@mfdaves/okf-mcp 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,7 +35,7 @@ Node 22 or newer is required.
35
35
  Install from the GitHub release:
36
36
 
37
37
  ```bash
38
- git clone --branch v0.7.0 https://github.com/mfdaves/okf-mcp.git
38
+ git clone --branch v0.8.0 https://github.com/mfdaves/okf-mcp.git
39
39
  cd okf-mcp
40
40
  npm ci
41
41
  node bin/okf-mcp.js --root ./path/to/okf validate
@@ -44,14 +44,14 @@ node bin/okf-mcp.js --root ./path/to/okf validate
44
44
  Pin the published version for reproducible use:
45
45
 
46
46
  ```bash
47
- npx -y @mfdaves/okf-mcp@0.7.0 --version
48
- npx -y @mfdaves/okf-mcp@0.7.0 --root ./path/to/okf validate
47
+ npx -y @mfdaves/okf-mcp@0.8.0 --version
48
+ npx -y @mfdaves/okf-mcp@0.8.0 --root ./path/to/okf validate
49
49
  ```
50
50
 
51
51
  For a persistent installation:
52
52
 
53
53
  ```bash
54
- npm install --global @mfdaves/okf-mcp@0.7.0
54
+ npm install --global @mfdaves/okf-mcp@0.8.0
55
55
 
56
56
  okf --version
57
57
  okf --root ./path/to/okf validate
@@ -95,7 +95,7 @@ okf --root okf/bundles/okf-mcp concept overview/okf-mcp
95
95
  Load the reference bundle directly from this release:
96
96
 
97
97
  ```bash
98
- okf --remote-bundle okf-mcp=https://github.com/mfdaves/okf-mcp/tree/v0.7.0/okf/bundles/okf-mcp --inspect
98
+ okf --remote-bundle okf-mcp=https://github.com/mfdaves/okf-mcp/tree/v0.8.0/okf/bundles/okf-mcp --inspect
99
99
  ```
100
100
 
101
101
  The `@mfdaves/okf-mcp` npm package includes both `okf.project.yaml` and the
@@ -182,7 +182,7 @@ Example client configuration:
182
182
  "command": "npx",
183
183
  "args": [
184
184
  "-y",
185
- "@mfdaves/okf-mcp@0.7.0",
185
+ "@mfdaves/okf-mcp@0.8.0",
186
186
  "--root",
187
187
  "/absolute/path/to/okf",
188
188
  "mcp"
@@ -201,7 +201,7 @@ Project config mode, with read-only project helpers but without proposal mutatio
201
201
  "command": "npx",
202
202
  "args": [
203
203
  "-y",
204
- "@mfdaves/okf-mcp@0.7.0",
204
+ "@mfdaves/okf-mcp@0.8.0",
205
205
  "--project",
206
206
  "/absolute/path/to/repo/okf.project.yaml",
207
207
  "mcp"
@@ -239,7 +239,7 @@ Concept IDs are their bundle-relative Markdown paths with `.md` removed. This ex
239
239
  okf://<bundle-id>/<extensionless-concept-id>
240
240
  ```
241
241
 
242
- The former `.md` URI and a valid custom `id` remain compatibility lookup aliases. A bare Concept ID resolves only when unique across loaded bundles; `okf://` remains deterministic for federated workspaces. Reserved `index.md` and `log.md` resources retain their filenames because they are not concepts.
242
+ The former `.md` URI and a valid custom `id` remain compatibility lookup aliases. A bare Concept ID resolves only when unique across loaded bundles. For standalone aggregate catalogs, a URI-shaped portable path such as `okf://services/queue.md` also resolves when `services/queue` is globally unique and `services` is not a loaded bundle id. Exact canonical URIs always win; a known-bundle miss or ambiguous portable path stays unresolved. Reserved `index.md` and `log.md` resources retain their filenames because they are not concepts.
243
243
 
244
244
  The `id`, `aliases`, and typed `relations` fields below are `okf-mcp` extensions. The standard v0.2 identity remains path-derived:
245
245
 
@@ -327,7 +327,7 @@ okf --root /path/to/catalog \
327
327
  - `validate_project`
328
328
  - `export_graph`
329
329
 
330
- Most MCP tools are read-only over the current index. `load_remote_bundle` mutates only the server's in-memory index by fetching a public GitHub tree; it does not write files.
330
+ Most MCP tools are read-only over the current index. `load_remote_bundle` mutates only the server's in-memory index by fetching a public GitHub tree; it does not write files. Concept listing and search default to compact summaries; pass `detail: "full"` when navigation metadata, signals, ranking, or snippets are required. Relationship paths are deduplicated by node sequence even when parallel edge kinds connect the same concepts.
331
331
 
332
332
  Every MCP tool includes a purpose-specific description, descriptions for its input parameters, and standard annotations covering read-only behavior, destructive behavior, idempotency, and external access.
333
333
 
@@ -382,9 +382,9 @@ The agent sees one read-only batch validator and one destructive apply tool. It
382
382
  }
383
383
  ```
384
384
 
385
- Create paths are optional. The server first uses a strong dominant directory convention from existing concepts of the same type, then falls back to deterministic type/title slugs. `okf_suggest_concept_path` reports the strategy, evidence, availability, canonical URI, and absolute filename. Updates identify an existing `uri`; scalar fields replace existing values, while `tags`, `sources`, and `relations` use explicit `add`/`remove` patches. `metadata` carries extension frontmatter but cannot override identity, generation, collection, or computation fields. Paths and URIs are immutable during update: moving a concept changes its portable identity and remains a separate, intentionally unsupported operation.
385
+ Create paths are optional. The server first uses a strong dominant directory convention from existing same-type concepts within the requested prefix, then falls back to deterministic type/title slugs. `okf_suggest_concept_path` reports the strategy, evidence, path availability, and same-type/title matches so an available filename is not mistaken for a safe duplicate. Updates identify an existing `uri`; stale locators return bounded likely replacements, while scalar fields replace existing values and `tags`, `sources`, and `relations` use explicit `add`/`remove` patches. `metadata` carries extension frontmatter but cannot override identity, generation, collection, or computation fields. Paths and URIs are immutable during update: moving a concept changes its portable identity and remains a separate, intentionally unsupported operation.
386
386
 
387
- Every 1–100 item batch is validated as one future graph, so concepts created together can reference one another. Call `okf_validate_changes` with the complete intended batch to receive a time-of-check preview without writing files. Validation and apply share the same planner; apply repeats every check under the writer queue because revisions and Git state can change after a preview. Results include compact semantic effects, canonical and absolute targets, source revisions, graph diagnostics, Git preconditions, and an explicit durability state without echoing full bodies.
387
+ Every 1–100 item batch is validated as one future graph, so concepts created together can reference one another and same-type/title conflicts are detected across creates and updates. Call `okf_validate_changes` with the complete intended batch to receive a time-of-check preview without writing files. Validation and apply share the same planner; apply repeats every check under the writer queue because revisions and Git state can change after a preview. Compact receipts are the v0.8 default; pass `detail: "full"` for the v0.7 planning layout. Effects expose structured relations and keep server-managed generation provenance separate from substantive `changedFields`.
388
388
 
389
389
  The server writes nothing unless every candidate is valid, revision checks still match, and every target stays inside one writable bundle. Process-generated documents, generator output directories, hidden/control-plane paths such as `.git/**`, reserved files, and Attested Computation contracts are not live-write targets. Rollback checks revisions immediately before each restore and reports detected replacements as a partial `rollback_conflict`. That protection is best effort under the documented single-external-writer requirement; it is not a cross-process compare-and-swap guarantee.
390
390
 
@@ -543,6 +543,7 @@ Use `list_remote_bundles` to inspect what was loaded.
543
543
  - `hasSources`
544
544
  - `runtime` and `attestationReady`
545
545
  - `generatedBy` and `verifiedBy`
546
+ - `detail` (`compact` by default, or `full`)
546
547
  - `limit`
547
548
  - `offset`
548
549
 
@@ -551,7 +552,7 @@ listing filters. Text search tokenizes case-insensitively and requires every
551
552
  query term, regardless of order. BM25+ ranks title, type, tags, aliases,
552
553
  description, path, and body matches; frontmatter remains available through
553
554
  exact structured filters but is not copied into the text index. Scores are
554
- relative within a result set and are not a stable cross-version scale.
555
+ relative within a result set and are not a stable cross-version scale. Compact results contain only `uri`, `title`, `type`, and `description`; title, type, and description are bounded, while full results remain lossless.
555
556
 
556
557
  Queries are bounded to 512 characters and 16 terms. Prefix expansion, fuzzy
557
558
  matching, stemming, and stop-word removal are intentionally disabled so code
@@ -561,6 +562,8 @@ frontmatter filters support exact scalar matching and array-contains
561
562
  matching. `relationType` selects concepts with an outgoing relation of that
562
563
  type.
563
564
 
565
+ The SDK regression suite also budgets a neutral four-step research path from actual serialized MCP text. It uses UTF-8 bytes divided by four as a deterministic estimate, not an exact model tokenizer or billing count, and guards both an absolute compact budget and a compact/full ratio.
566
+
564
567
  Example:
565
568
 
566
569
  ```json
@@ -595,7 +598,7 @@ For navigation convenience, okf-mcp resolves links to a nested bundle directory
595
598
  `index.md` when there is no exact document target. This applies to local and
596
599
  remote bundles and to candidate validation during proposal authoring.
597
600
 
598
- Graph tools return compact JSON:
601
+ Graph tools return bounded JSON:
599
602
 
600
603
  ```json
601
604
  {
@@ -29,9 +29,9 @@ relations:
29
29
 
30
30
  The MCP interface groups tools by intent.
31
31
 
32
- Discovery tools list bundles, concepts, types, tags, custom relation types, standard edge kinds, and loaded remote bundles. `get_concept` accepts a portable Concept ID or compatibility locator and returns raw frontmatter and body plus normalized v0.2 signals, referenced-asset metadata, and declared Git-source availability. Search uses a process-local MiniSearch BM25+ index and filters lifecycle, trust, freshness at a deterministic date, source presence, generator or verifier actors, runtime, and static attestation readiness.
32
+ Discovery tools list bundles, concepts, types, tags, custom relation types, standard edge kinds, and loaded remote bundles. `get_concept` accepts a canonical URI, unique portable Concept ID, or URI-shaped portable compatibility locator and returns raw frontmatter and body plus normalized v0.2 signals, referenced-asset metadata, and declared Git-source availability. Missing stale locators return bounded likely replacements without silently following them. Search uses a process-local MiniSearch BM25+ index and filters lifecycle, trust, freshness at a deterministic date, source presence, generator or verifier actors, runtime, and static attestation readiness.
33
33
 
34
- Graph tools return bounded graphs, neighbors, subgraphs, paths, summaries, provenance traces, and rendered exports. They can filter semantic edge kinds and optionally include inert asset nodes or unfetched external leaves. Extensionless canonical, `.md`, and custom-id aliases are accepted for lookup.
34
+ Graph tools return bounded graphs, neighbors, subgraphs, paths, summaries, provenance traces, and rendered exports. They can filter semantic edge kinds and optionally include inert asset nodes or unfetched external leaves. Identical node paths from parallel edge kinds are returned once.
35
35
 
36
36
  Validation tools inspect bundles, projects, and candidate concepts without writing. They report OKF conformance separately from project validity. Remote loading fetches a public GitHub tree into the in-memory index.
37
37
 
@@ -41,7 +41,7 @@ Static computation tools inspect contracts, read indexed assets, prepare paramet
41
41
 
42
42
  An explicit local root or project workspace exposes candidate validation, path suggestion, and proposal inspection. Normal proposal mutations require `--authoring`; the coordinated computation proposal additionally requires `--allow-computation-authoring`. `--write --actor <actor>` exposes read-only `okf_validate_changes` plus destructive `okf_apply_changes`, both accepting the same structured create/update batch grammar without requiring agents to compose YAML. Runtime calls to `load_remote_bundle` require `--allow-remote-tool`.
43
43
 
44
- `okf_validate_changes` and `okf_apply_changes` plan 1–100 operations as one future graph, including cross-batch and loaded-remote references. Validation returns a non-durable time-of-check receipt. Apply repeats planning under the process-local writer queue, stamps one server-owned `generated.at` with the configured `generated.by`, publishes the complete local batch, validates persisted state, and refreshes the index. Receipts expose bounded semantic effects, absolute targets, revisions, graph diagnostics, Git preconditions, and durability without echoing full bodies.
44
+ `okf_validate_changes` and `okf_apply_changes` plan 1–100 operations as one future graph, including cross-batch and loaded-remote references plus same-type/title conflicts. Validation returns a non-durable time-of-check receipt. Apply repeats planning under the process-local writer queue, stamps one server-owned `generated.at` with the configured `generated.by`, publishes the complete local batch, validates persisted state, and refreshes the index. Compact receipts are the default; `detail: "full"` retains the richer planning layout. Relation effects are structured, and generated provenance is separate from substantive changed fields.
45
45
 
46
46
  Optional `--git-commit` policy rejects filter declarations and hidden `assume-unchanged`/`skip-worktree` index flags, disables replace-object resolution, pins the checked-out symbolic branch, constructs an isolated index from validated bytes, and publishes its exact tree with a compare-and-swap ref update from a clean worktree. The shared index is not used to assemble the commit, so unrelated concurrently staged paths cannot enter it; only affected index paths are synchronized after publication. Determinate failures preserve matching valid working-tree files. Ambiguous outcomes, checkout changes, target replacements, and best-effort revision-checked rollback conflicts are reported explicitly; the tool never pushes.
47
47
 
@@ -49,4 +49,4 @@ Every tool supplies a purpose-specific description, descriptions for all input p
49
49
 
50
50
  The official MCP SDK validates tool arguments against the advertised schema without coercion. Unknown or disabled tools are rejected by SDK dispatch. Argument-schema failures and expected validation, storage, network, read-only, and proposal-conflict failures from enabled tools are returned as tool results with `isError: true`. A validation operation that successfully reports invalid OKF remains a successful tool result.
51
51
 
52
- `search_concepts` and the optional text query on `list_concepts` require every case-insensitive query term, regardless of order. They rank title, type, tags, aliases, description, path, and body while keeping arbitrary frontmatter as an exact structured filter. Queries are bounded to 512 characters and 16 terms; fuzzy, prefix, stemming, and stop-word expansion are not applied. Scores are relative retrieval scores rather than a stable public scale. Relation-type filtering selects concepts with an outgoing relation of the requested type.
52
+ `search_concepts` and the optional text query on `list_concepts` require every case-insensitive query term, regardless of order. They rank title, type, tags, aliases, description, path, and body while keeping arbitrary frontmatter as an exact structured filter. Compact MCP results expose the URI plus bounded title, type, and description; `detail: "full"` returns navigation metadata, signals, ranking, and snippets. Queries are bounded to 512 characters and 16 terms; fuzzy, prefix, stemming, and stop-word expansion are not applied. Scores are relative retrieval scores rather than a stable public scale. Relation-type filtering selects concepts with an outgoing relation of the requested type.
@@ -35,7 +35,7 @@ Authoring is allowed for an explicit local `--root` or local roots declared by `
35
35
 
36
36
  Concept paths must be safe relative `.md` paths inside the selected bundle. Absolute paths, parent traversal, hidden/control-plane segments such as `.git`, case-insensitive reserved `index.md` and `log.md` targets, Markdown-file ancestor segments, symbolic-link traversal, and non-directory parents are rejected.
37
37
 
38
- New concepts cannot reuse a canonical Concept ID or compatibility alias. Updates are bound to the existing bundle and path and cannot change the custom-id alias.
38
+ New concepts cannot reuse a canonical Concept ID or compatibility alias, and a batch cannot increase same-type/title ambiguity. Updates are bound to the existing bundle and path and cannot change the custom-id alias. Move/rename remains unsupported because it changes portable identity and requires a future graph tombstone plus lossless inbound-reference rewriting.
39
39
 
40
40
  Candidates must satisfy the concept format, configured relation vocabulary, and internal target integrity. External schemes such as `repo://` are allowed as opaque references.
41
41
 
@@ -21,7 +21,7 @@ relations:
21
21
 
22
22
  An OKF concept is a UTF-8 Markdown file with YAML frontmatter. A non-empty string `type` is required. Standard v0.2 metadata families include `resource`, `sources`, `usage_window`, `generated`, `verified`, `status`, `stale_after`, and the Attested Computation contract. The Markdown body carries the durable explanation.
23
23
 
24
- The standard Concept ID is the bundle-relative path with `.md` removed. okf-mcp also creates the workspace-scoped locator `okf://<bundle>/<concept-id>` for MCP resources and federated lookup; it is not the portable OKF identity. The former `.md` URI remains a compatibility alias. The optional `id`, `aliases`, and typed `relations` fields are `okf-mcp` extensions; a valid custom `id` is an additional alias rather than a replacement for the standard identity.
24
+ The standard Concept ID is the bundle-relative path with `.md` removed. okf-mcp also creates the workspace-scoped locator `okf://<bundle>/<concept-id>` for MCP resources and federated lookup; it is not the portable OKF identity. The former `.md` URI remains a compatibility alias. A URI-shaped portable path is accepted only when its apparent authority is not a loaded bundle and the complete portable ID is globally unique; canonical identity always takes precedence. The optional `id`, `aliases`, and typed `relations` fields are `okf-mcp` extensions; a valid custom `id` is an additional alias rather than a replacement for the standard identity.
25
25
 
26
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
27
 
@@ -29,7 +29,7 @@ A reviewer then inspects the proposal and either accepts or rejects it. Acceptan
29
29
 
30
30
  Invalid candidates never become proposals. A proposal that becomes invalid before acceptance remains inspectable and returns the current validation result.
31
31
 
32
- For a trusted client approval boundary, `--write --actor <actor>` exposes read-only `okf_validate_changes` and destructive `okf_apply_changes`. Agents submit structured concept fields rather than YAML. The server derives optional paths from strong same-type directory conventions or deterministic slugs, patches tags/sources/relations, stamps one generation actor and time, and validates the complete future graph. A validation receipt is a non-durable time-of-check preview; apply repeats the checks before publication. Optional Git policy pins the checked-out symbolic branch, builds one exact isolated tree from validated bytes, and compare-and-swap publishes it without pushing.
32
+ For a trusted client approval boundary, `--write --actor <actor>` exposes read-only `okf_validate_changes` and destructive `okf_apply_changes`. Agents submit structured concept fields rather than YAML. The server derives optional paths from strong prefix-scoped same-type conventions or deterministic slugs, rejects future same-type/title conflicts, patches tags/sources/relations, stamps one generation actor and time, and validates the complete future graph. A validation receipt is a non-durable time-of-check preview; apply repeats the checks before publication. Compact receipts are the default and full receipts remain available explicitly. Optional Git policy pins the checked-out symbolic branch, builds one exact isolated tree from validated bytes, and compare-and-swap publishes it without pushing.
33
33
 
34
34
  Direct writes do not replace generator ownership or computation review. Process-generated concepts, configured generator outputs, and Attested Computation contracts remain outside this workflow.
35
35
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mfdaves/okf-mcp",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Local-first Open Knowledge Format validator, graph index, CLI, and MCP stdio server.",
5
5
  "homepage": "https://github.com/mfdaves/okf-mcp#readme",
6
6
  "repository": {
package/server.json CHANGED
@@ -8,12 +8,12 @@
8
8
  "source": "github"
9
9
  },
10
10
  "websiteUrl": "https://github.com/mfdaves/okf-mcp#readme",
11
- "version": "0.7.0",
11
+ "version": "0.8.0",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "npm",
15
15
  "identifier": "@mfdaves/okf-mcp",
16
- "version": "0.7.0",
16
+ "version": "0.8.0",
17
17
  "transport": {
18
18
  "type": "stdio"
19
19
  },
package/src/authoring.js CHANGED
@@ -7,6 +7,8 @@ const yaml = require("js-yaml");
7
7
  const { parseMarkdownText, normalizeSlashes } = require("./parser");
8
8
  const {
9
9
  bundleExcludesPath,
10
+ conceptMatchSummary,
11
+ findConceptMatches,
10
12
  resolveLinkPath,
11
13
  semanticReferences,
12
14
  } = require("./indexer");
@@ -27,6 +29,14 @@ function slug(value, fallback) {
27
29
  .replace(/^-+|-+$/g, "") || String(fallback || "concept");
28
30
  }
29
31
 
32
+ function isConfiguredGeneratorOutput(project, absolutePath) {
33
+ return Boolean(project && project.root && absolutePath && (project.plugins || []).some((plugin) => {
34
+ if (!plugin || !plugin.output) return false;
35
+ const relative = path.relative(path.resolve(project.root, String(plugin.output)), absolutePath);
36
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
37
+ }));
38
+ }
39
+
30
40
  function normalizeConceptPath(value) {
31
41
  const raw = normalizeSlashes(String(value || "").trim());
32
42
  if (!raw) {
@@ -79,15 +89,12 @@ function deriveConceptPathSuggestion(index, bundle, input) {
79
89
  let strategy = prefix ? "explicit_prefix" : "type_slug";
80
90
  let evidence = { matchingConcepts: 0, dominantDirectoryCount: 0, dominantDirectoryRatio: 0 };
81
91
 
82
- if (!prefix && type !== "Attested Computation" && index && Array.isArray(index.documents)) {
83
- const matching = index.documents.filter((document) => (
84
- document
85
- && document.bundle === bundle.id
86
- && document.valid
87
- && !document.reserved
88
- && document.type === type
89
- && typeof document.path === "string"
90
- ));
92
+ if (type !== "Attested Computation" && index) {
93
+ const matching = findConceptMatches(index, {
94
+ bundle: bundle.id,
95
+ type,
96
+ pathPrefix: prefix,
97
+ });
91
98
  const counts = new Map();
92
99
  matching.forEach((document) => {
93
100
  const directory = path.posix.dirname(document.path);
@@ -185,14 +192,34 @@ class ConceptAuthoringService {
185
192
 
186
193
  suggestConceptPath(input) {
187
194
  const bundle = this.getBundle(input && input.bundle);
188
- const suggestion = deriveConceptPathSuggestion(this.store.getIndex(), bundle, input || {});
195
+ const index = this.store.getIndex();
196
+ const suggestion = deriveConceptPathSuggestion(index, bundle, input || {});
189
197
  const target = this.store.resolveConceptFile(bundle.id, suggestion.path);
198
+ const titleMatches = findConceptMatches(index, {
199
+ bundle: bundle.id,
200
+ type: input && input.type,
201
+ title: input && input.title,
202
+ });
203
+ const matches = titleMatches.slice(0, 5).map((doc) => conceptMatchSummary(doc));
204
+ const available = !fs.existsSync(target.absolutePath);
205
+ const only = matches.length === 1 && matches[0];
206
+ const generatorOwned = only && (only.generatedFile
207
+ || only.generatedBy && only.generatedBy.startsWith("process:")
208
+ || isConfiguredGeneratorOutput(this.store.project, titleMatches[0].absolutePath));
190
209
  return {
191
210
  bundle: bundle.id,
192
211
  path: suggestion.path,
193
212
  uri: `okf://${bundle.id}/${suggestion.path.replace(/\.md$/i, "")}`,
194
213
  absolutePath: target.absolutePath,
195
- available: !fs.existsSync(target.absolutePath),
214
+ available,
215
+ creatable: available && titleMatches.length === 0,
216
+ titleMatches: matches,
217
+ titleMatchesOmitted: Math.max(0, titleMatches.length - matches.length),
218
+ ...(matches.length === 1 ? { existingConcept: matches[0] } : {}),
219
+ recommendedOperation: titleMatches.length
220
+ ? titleMatches.length > 1 ? "review_matches"
221
+ : generatorOwned ? "change_generator" : "update"
222
+ : available ? "create" : "inspect_existing",
196
223
  strategy: suggestion.strategy,
197
224
  evidence: suggestion.evidence,
198
225
  };
@@ -868,6 +895,7 @@ class ConceptAuthoringService {
868
895
  module.exports = {
869
896
  ConceptAuthoringService,
870
897
  deriveConceptPathSuggestion,
898
+ isConfiguredGeneratorOutput,
871
899
  normalizeConceptPath,
872
900
  renderConceptMarkdown,
873
901
  renderFrontmatter,
package/src/graph.js CHANGED
@@ -180,9 +180,9 @@ function findPaths(index, source, target, maxPaths, options) {
180
180
  const adjacency = new Map();
181
181
  index.edges.filter((edge) => !edge.broken && edgeAllowed(edge, options)).forEach((edge) => {
182
182
  if (!adjacency.has(edge.source)) {
183
- adjacency.set(edge.source, []);
183
+ adjacency.set(edge.source, new Set());
184
184
  }
185
- adjacency.get(edge.source).push(edge.target);
185
+ adjacency.get(edge.source).add(edge.target);
186
186
  });
187
187
  const queue = [[canonicalSource]];
188
188
  const paths = [];
package/src/indexer.js CHANGED
@@ -171,23 +171,169 @@ function registerPortableConceptId(map, ambiguous, key, document) {
171
171
  map.set(normalized, document);
172
172
  }
173
173
 
174
+ function portableConceptKeys(value) {
175
+ const normalized = normalizeSlashes(String(value || ""))
176
+ .replace(/^\/+/, "")
177
+ .split("#")[0];
178
+ if (!normalized) return [];
179
+ return normalized.toLowerCase().endsWith(".md")
180
+ ? [normalized, normalized.slice(0, -3)]
181
+ : [normalized, `${normalized}.md`];
182
+ }
183
+
184
+ function portableConceptMatches(index, value) {
185
+ for (const key of portableConceptKeys(value)) {
186
+ const matches = (index.documents || []).filter((doc) => doc.conceptId === key || doc.path === key);
187
+ if (matches.length) {
188
+ return matches.sort((left, right) => left.uri.localeCompare(right.uri));
189
+ }
190
+ }
191
+ return [];
192
+ }
193
+
174
194
  function resolveConcept(index, locator) {
175
195
  const raw = String(locator || "").trim();
176
196
  if (!raw || !index) {
177
197
  return null;
178
198
  }
179
- const byUri = index.byUri && index.byUri.get(raw);
199
+ const fragmentless = normalizeSlashes(raw).split("#")[0];
200
+ const byUri = index.byUri && (index.byUri.get(raw) || index.byUri.get(fragmentless));
180
201
  if (byUri) {
181
202
  return byUri;
182
203
  }
183
- const normalized = normalizeSlashes(raw).replace(/^\/+/, "").split("#")[0];
184
- if (!normalized || !index.byConceptId) {
204
+ if ((index.ambiguousAliases || new Set()).has(raw)
205
+ || (index.ambiguousAliases || new Set()).has(fragmentless)) {
185
206
  return null;
186
207
  }
187
- return index.byConceptId.get(normalized)
188
- || index.byConceptId.get(normalized.replace(/\.md$/i, ""))
189
- || index.byConceptId.get(`${normalized}.md`)
190
- || null;
208
+ const uriMatch = fragmentless.match(/^okf:\/\/([^/]+)\/(.+)$/);
209
+ if (fragmentless.startsWith("okf://")) {
210
+ if (!uriMatch || (index.bundles || []).some((bundle) => bundle.id === uriMatch[1])) {
211
+ return null;
212
+ }
213
+ }
214
+ for (const key of portableConceptKeys(uriMatch ? `${uriMatch[1]}/${uriMatch[2]}` : fragmentless)) {
215
+ if ((index.ambiguousConceptIds || new Set()).has(key)) return null;
216
+ const owner = index.byConceptId && index.byConceptId.get(key);
217
+ if (owner) return owner;
218
+ }
219
+ return null;
220
+ }
221
+
222
+ function normalizeConceptTitle(value) {
223
+ return String(value || "").normalize("NFKC").trim().replace(/\s+/gu, " ").toLowerCase();
224
+ }
225
+
226
+ function conceptTitleSlug(value) {
227
+ return normalizeConceptTitle(value)
228
+ .replace(/[^a-z0-9]+/g, "-")
229
+ .replace(/^-+|-+$/g, "");
230
+ }
231
+
232
+ function conceptIsGeneratedFile(doc) {
233
+ const frontmatter = doc && doc.frontmatter || {};
234
+ return Boolean(doc && (doc.generatedFile === true || doc.isGenerated === true)
235
+ || frontmatter.generated_file === true || frontmatter.generatedFile === true);
236
+ }
237
+
238
+ function conceptMatchSummary(doc, matchReasons) {
239
+ const generated = doc && doc.signals && doc.signals.generated;
240
+ return {
241
+ uri: doc.uri,
242
+ bundle: doc.bundle,
243
+ path: doc.path,
244
+ conceptId: doc.conceptId || doc.path.replace(/\.md$/i, ""),
245
+ type: doc.type || doc.frontmatter && doc.frontmatter.type,
246
+ title: doc.title,
247
+ generatedBy: generated && generated.by || null,
248
+ ...(conceptIsGeneratedFile(doc) ? { generatedFile: true } : {}),
249
+ ...(matchReasons && matchReasons.length ? { matchReasons } : {}),
250
+ };
251
+ }
252
+
253
+ function findConceptMatches(index, options) {
254
+ const config = options || {};
255
+ const title = config.title === undefined ? null : normalizeConceptTitle(config.title);
256
+ const prefix = normalizeSlashes(String(config.pathPrefix || "")).replace(/^\/+|\/+$/g, "");
257
+ const documents = index && Array.isArray(index.concepts)
258
+ ? index.concepts
259
+ : index && Array.isArray(index.documents) ? index.documents : [];
260
+ return documents
261
+ .filter((doc) => (
262
+ doc && doc.valid !== false && !doc.reserved
263
+ && typeof doc.path === "string"
264
+ && (!config.bundle || doc.bundle === config.bundle)
265
+ && (!config.type || doc.type === config.type)
266
+ && (title === null || normalizeConceptTitle(doc.title) === title)
267
+ && (!prefix || doc.path === prefix || doc.path.startsWith(`${prefix}/`))
268
+ ))
269
+ .sort((left, right) => left.path.localeCompare(right.path) || left.uri.localeCompare(right.uri));
270
+ }
271
+
272
+ function recoveryReceipt(locator, entries, limit, allowRetry, forcedAmbiguity) {
273
+ const maximum = Math.max(1, Math.min(Number(limit || 5), 20));
274
+ const candidates = entries.slice(0, maximum)
275
+ .map((entry) => conceptMatchSummary(entry.doc, entry.reasons));
276
+ const actionable = entries.length === 1 && entries[0].doc.valid && !entries[0].doc.reserved;
277
+ return {
278
+ status: forcedAmbiguity || entries.length > 1 ? "ambiguous"
279
+ : actionable ? "replacement_found" : "not_found",
280
+ requestedLocator: locator,
281
+ candidates,
282
+ omitted: Math.max(0, entries.length - candidates.length),
283
+ ...(allowRetry && !forcedAmbiguity && actionable
284
+ ? { retryWith: { uri: entries[0].doc.uri } } : {}),
285
+ };
286
+ }
287
+
288
+ function recoverConceptLocator(index, locator, options) {
289
+ const config = options || {};
290
+ const raw = normalizeSlashes(String(locator || "").trim()).split("#")[0];
291
+ const uriMatch = raw.match(/^okf:\/\/([^/]+)\/(.+)$/);
292
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(raw) && !uriMatch) {
293
+ return { status: "not_found", requestedLocator: raw, candidates: [], omitted: 0 };
294
+ }
295
+ const knownBundle = uriMatch && (index.bundles || []).some((entry) => entry.id === uriMatch[1]);
296
+ const bundle = knownBundle ? uriMatch[1] : config.bundle || "";
297
+ const portablePath = (uriMatch && knownBundle
298
+ ? uriMatch[2]
299
+ : raw.replace(/^okf:\/\//, ""))
300
+ .replace(/^\/+/, "");
301
+ const aliasOwners = (index.documents || []).filter((doc) => (
302
+ (index.ambiguousAliases || new Set()).has(raw) && (doc.uriAliases || []).includes(raw)
303
+ )).sort((left, right) => left.uri.localeCompare(right.uri));
304
+ const exact = aliasOwners.length ? aliasOwners : knownBundle ? [] : portableConceptMatches(index, portablePath);
305
+ if (exact.length) {
306
+ const portableAmbiguous = portableConceptKeys(portablePath)
307
+ .some((key) => (index.ambiguousConceptIds || new Set()).has(key));
308
+ return recoveryReceipt(raw, exact.map((doc) => ({
309
+ doc, reasons: [aliasOwners.length ? "uri_alias" : "portable_id"],
310
+ })), config.limit, !aliasOwners.length && !portableAmbiguous,
311
+ aliasOwners.length > 0 || portableAmbiguous);
312
+ }
313
+ const requestedPath = portablePath.replace(/\.md$/i, "");
314
+ const requestedBase = path.posix.basename(requestedPath).toLowerCase();
315
+ const requestedSlug = conceptTitleSlug(requestedBase);
316
+ const ranked = [];
317
+ if (!requestedSlug) return recoveryReceipt(raw, [], config.limit, false);
318
+ findConceptMatches(index, { bundle }).forEach((doc) => {
319
+ const base = path.posix.basename(doc.conceptId || doc.path.replace(/\.md$/i, "")).toLowerCase();
320
+ const reasons = [];
321
+ if (base === requestedBase) reasons.push("path_basename");
322
+ if (conceptTitleSlug(doc.title) === requestedSlug) reasons.push("title_slug");
323
+ if ((doc.aliases || []).some((alias) => conceptTitleSlug(alias) === requestedSlug)) reasons.push("alias");
324
+ if (!reasons.length) return;
325
+ ranked.push({
326
+ doc,
327
+ reasons,
328
+ score: (reasons.includes("path_basename") ? 4 : 0)
329
+ + (reasons.includes("title_slug") ? 2 : 0)
330
+ + (reasons.includes("alias") ? 1 : 0),
331
+ });
332
+ });
333
+ ranked.sort((left, right) => right.score - left.score
334
+ || left.doc.path.localeCompare(right.doc.path)
335
+ || left.doc.uri.localeCompare(right.doc.uri));
336
+ return recoveryReceipt(raw, ranked, config.limit, true);
191
337
  }
192
338
 
193
339
  function resolveIndexedLink(bundleId, resolved, href, documentsByPath) {
@@ -900,10 +1046,15 @@ module.exports = {
900
1046
  attachProject,
901
1047
  conceptSummary,
902
1048
  conceptSignals,
1049
+ conceptIsGeneratedFile,
1050
+ conceptMatchSummary,
903
1051
  bundleAllowsPath,
904
1052
  bundleExcludesPath,
1053
+ findConceptMatches,
905
1054
  loadProjectBundles,
1055
+ normalizeConceptTitle,
906
1056
  parseBundleArg,
1057
+ recoverConceptLocator,
907
1058
  resolveLinkPath,
908
1059
  resolveConcept,
909
1060
  semanticReferences,
@@ -8,6 +8,7 @@ const { isDeepStrictEqual } = require("node:util");
8
8
 
9
9
  const {
10
10
  deriveConceptPathSuggestion,
11
+ isConfiguredGeneratorOutput,
11
12
  normalizeConceptPath,
12
13
  renderConceptMarkdown,
13
14
  } = require("./authoring");
@@ -15,6 +16,10 @@ const {
15
16
  attachProject,
16
17
  buildIndex,
17
18
  bundleAllowsPath,
19
+ conceptIsGeneratedFile,
20
+ conceptMatchSummary,
21
+ normalizeConceptTitle,
22
+ recoverConceptLocator,
18
23
  resolveConcept,
19
24
  validateIndex,
20
25
  } = require("./indexer");
@@ -43,9 +48,11 @@ const MANAGED_METADATA_KEYS = new Set([
43
48
  ]);
44
49
 
45
50
  class AuthoringPolicyError extends Error {
46
- constructor(message) {
51
+ constructor(message, code, details) {
47
52
  super(message);
48
53
  this.name = "AuthoringPolicyError";
54
+ if (code) this.code = code;
55
+ if (details !== undefined) this.details = details;
49
56
  }
50
57
  }
51
58
 
@@ -339,11 +346,6 @@ function actorValue(value) {
339
346
  return actor;
340
347
  }
341
348
 
342
- function isInside(root, candidate) {
343
- const relative = path.relative(path.resolve(root), path.resolve(candidate));
344
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
345
- }
346
-
347
349
  function generatedOwners(document) {
348
350
  const owners = [];
349
351
  const generated = document && document.frontmatter && document.frontmatter.generated;
@@ -383,18 +385,37 @@ function sortedUnique(values) {
383
385
  return Array.from(new Set(values)).sort();
384
386
  }
385
387
 
386
- function boundedEffectList(values) {
387
- const normalized = sortedUnique(values).map((value) => {
388
- const text = String(value);
389
- return text.length > MAX_EFFECT_TEXT ? `${text.slice(0, MAX_EFFECT_TEXT - 1)}…` : text;
390
- });
388
+ function boundedEffectList(values, project) {
389
+ const normalized = project
390
+ ? values.map(project)
391
+ : sortedUnique(values).map(boundedEffectText);
391
392
  return {
392
393
  values: normalized.slice(0, MAX_EFFECT_ITEMS),
393
394
  omitted: Math.max(0, normalized.length - MAX_EFFECT_ITEMS),
394
395
  };
395
396
  }
396
397
 
397
- function collectionEffects(before, after, identity) {
398
+ function boundedEffectText(value) {
399
+ const text = String(value || "");
400
+ return text.length > MAX_EFFECT_TEXT ? `${text.slice(0, MAX_EFFECT_TEXT - 1)}…` : text;
401
+ }
402
+
403
+ function relationEffectValue(value) {
404
+ const parts = relationParts(value);
405
+ const result = {
406
+ type: boundedEffectText(parts.type),
407
+ target: boundedEffectText(parts.target),
408
+ };
409
+ if (isPlainObject(value) && hasOwn(value, "label")) {
410
+ result.label = boundedEffectText(value.label);
411
+ }
412
+ if (isPlainObject(value) && hasOwn(value, "description")) {
413
+ result.description = boundedEffectText(value.description);
414
+ }
415
+ return result;
416
+ }
417
+
418
+ function collectionEffects(before, after, identity, project) {
398
419
  const previous = new Map((before || []).map((value) => [identity(value), value]));
399
420
  const next = new Map((after || []).map((value) => [identity(value), value]));
400
421
  const added = Array.from(next.keys()).filter((key) => !previous.has(key)).sort();
@@ -402,10 +423,14 @@ function collectionEffects(before, after, identity) {
402
423
  const updated = Array.from(next.keys()).filter((key) => (
403
424
  previous.has(key) && !isDeepStrictEqual(previous.get(key), next.get(key))
404
425
  )).sort();
426
+ const effectList = (keys, values) => boundedEffectList(
427
+ project ? keys.map((key) => values.get(key)) : keys,
428
+ project,
429
+ );
405
430
  return {
406
- added: boundedEffectList(added),
407
- removed: boundedEffectList(removed),
408
- updated: boundedEffectList(updated),
431
+ added: effectList(added, next),
432
+ removed: effectList(removed, previous),
433
+ updated: effectList(updated, next),
409
434
  };
410
435
  }
411
436
 
@@ -424,7 +449,7 @@ function effectsForCandidate(candidate) {
424
449
  const after = candidate.frontmatter;
425
450
  const tags = collectionEffects(before.tags, after.tags, (value) => String(value));
426
451
  const sources = collectionEffects(before.sources, after.sources, sourceIdentity);
427
- const relations = collectionEffects(before.relations, after.relations, relationKey);
452
+ const relations = collectionEffects(before.relations, after.relations, relationKey, relationEffectValue);
428
453
  const metadata = metadataEffects(before, after);
429
454
  const bodyChanged = candidate.op === "create"
430
455
  ? true
@@ -436,7 +461,6 @@ function effectsForCandidate(candidate) {
436
461
  if (hasEffect(sources.added) || hasEffect(sources.removed) || hasEffect(sources.updated)) changedFields.push("sources");
437
462
  if (hasEffect(relations.added) || hasEffect(relations.removed) || hasEffect(relations.updated)) changedFields.push("relations");
438
463
  if (hasEffect(metadata.set) || hasEffect(metadata.removed)) changedFields.push("metadata");
439
- if (!isDeepStrictEqual(before.generated, after.generated)) changedFields.push("generated");
440
464
  return {
441
465
  changedFields,
442
466
  bodyChanged,
@@ -451,6 +475,47 @@ function effectsForCandidate(candidate) {
451
475
  };
452
476
  }
453
477
 
478
+ function semanticConceptKey(type, title) {
479
+ return `${String(type || "")}\u0000${normalizeConceptTitle(title)}`;
480
+ }
481
+
482
+ function conceptIsManaged(doc, project) {
483
+ return conceptIsGeneratedFile(doc)
484
+ || generatedOwners(doc).some((owner) => owner.startsWith("process:"))
485
+ || isConfiguredGeneratorOutput(project, doc && doc.absolutePath);
486
+ }
487
+
488
+ function conceptConflictDetails(matches, project) {
489
+ const candidates = matches.slice(0, 5).map((doc) => conceptMatchSummary(doc));
490
+ const only = candidates.length === 1 ? candidates[0] : null;
491
+ const generated = matches.length === 1 && conceptIsManaged(matches[0], project);
492
+ const updateable = only && !generated && only.type !== "Attested Computation";
493
+ return {
494
+ reason: "same_type_title",
495
+ candidates,
496
+ omitted: Math.max(0, matches.length - candidates.length),
497
+ recommendedOperation: updateable ? "update" : generated ? "change_generator" : "review",
498
+ ...(updateable ? { retryWith: { op: "update", uri: only.uri } } : {}),
499
+ };
500
+ }
501
+
502
+ function staleUpdateDetails(index, uri, bundle, project) {
503
+ const recovery = recoverConceptLocator(index, uri, { bundle, limit: 5 });
504
+ const only = recovery.candidates.length === 1 ? recovery.candidates[0] : null;
505
+ const matched = only && resolveConcept(index, only.uri);
506
+ if (only && (conceptIsManaged(matched, project)
507
+ || only.type === "Attested Computation")) {
508
+ delete recovery.retryWith;
509
+ recovery.recommendedOperation = only.type === "Attested Computation"
510
+ ? "review_computation_owner"
511
+ : "change_generator";
512
+ } else if (recovery.retryWith) {
513
+ recovery.retryWith.op = "update";
514
+ recovery.recommendedOperation = "update";
515
+ }
516
+ return { recovery };
517
+ }
518
+
454
519
  function policyCode(message) {
455
520
  const text = String(message || "");
456
521
  if (/generated|generator/i.test(text)) return "generated_owner_protected";
@@ -473,19 +538,23 @@ function policyCode(message) {
473
538
  return "authoring_policy_rejected";
474
539
  }
475
540
 
476
- function policyValidation(message) {
477
- const code = policyCode(message);
541
+ function policyValidation(error) {
542
+ const message = error && error.message ? error.message : String(error);
543
+ const code = error && error.code || policyCode(message);
544
+ const details = error && error.details;
545
+ const diagnostic = {
546
+ code,
547
+ severity: "error",
548
+ layer: "authoring",
549
+ message,
550
+ ...(details !== undefined ? { details } : {}),
551
+ };
478
552
  return {
479
553
  valid: false,
480
554
  conformant: false,
481
555
  validForProject: false,
482
- diagnostics: [{
483
- code,
484
- severity: "error",
485
- layer: "authoring",
486
- message,
487
- }],
488
- errors: [{ code, message }],
556
+ diagnostics: [diagnostic],
557
+ errors: [{ code, message, ...(details !== undefined ? { details } : {}) }],
489
558
  warnings: [],
490
559
  };
491
560
  }
@@ -547,32 +616,13 @@ class LiveAuthoringService {
547
616
  return this.store.project ? attachProject(index, this.store.project) : index;
548
617
  }
549
618
 
550
- generatedOutputDirectories() {
551
- const project = this.store.project;
552
- if (!project || !project.root) {
553
- return [];
554
- }
555
- return (project.plugins || [])
556
- .filter((plugin) => plugin && plugin.output)
557
- .map((plugin) => path.resolve(project.root, String(plugin.output)));
558
- }
559
-
560
619
  assertWritableTarget(bundle, conceptPath, existing) {
561
620
  const target = this.store.resolveConceptFile(bundle.id, conceptPath);
562
- if (this.generatedOutputDirectories().some((output) => isInside(output, target.absolutePath))) {
621
+ if (isConfiguredGeneratorOutput(this.store.project, target.absolutePath)) {
563
622
  throw new Error(`Concept is inside a configured generator output and must be changed through its generator: ${conceptPath}`);
564
623
  }
565
- if (existing) {
566
- const frontmatter = existing.frontmatter || {};
567
- if (existing.generatedFile === true
568
- || existing.isGenerated === true
569
- || frontmatter.generated_file === true
570
- || frontmatter.generatedFile === true) {
571
- throw new Error(`Generated concept must be changed through its generator: ${existing.uri}`);
572
- }
573
- if (generatedOwners(existing).some((owner) => owner.startsWith("process:"))) {
574
- throw new Error(`Process-generated concept must be changed through its generator: ${existing.uri}`);
575
- }
624
+ if (existing && conceptIsManaged(existing, this.store.project)) {
625
+ throw new Error(`Generated concept must be changed through its generator: ${existing.uri}`);
576
626
  }
577
627
  return target;
578
628
  }
@@ -636,7 +686,12 @@ class LiveAuthoringService {
636
686
  const uri = nonEmptyString(change.uri, "changes[].uri");
637
687
  const existing = resolveConcept(currentIndex, uri);
638
688
  if (!existing || !existing.valid || existing.reserved) {
639
- throw new Error(`Unknown valid OKF concept: ${uri}`);
689
+ const details = staleUpdateDetails(currentIndex, uri, bundle.id, this.store.project);
690
+ throw new AuthoringPolicyError(
691
+ `Unknown valid OKF concept: ${uri}`,
692
+ details.recovery.status === "ambiguous" ? "concept_locator_ambiguous" : "concept_not_found",
693
+ details,
694
+ );
640
695
  }
641
696
  if (existing.bundle !== bundle.id) {
642
697
  throw new Error(`All changes must target writable bundle ${bundle.id}: ${uri}`);
@@ -1940,6 +1995,31 @@ class LiveAuthoringService {
1940
1995
  }
1941
1996
  }
1942
1997
  }
1998
+ const currentConcepts = currentIndex.concepts.filter((doc) => doc.bundle === bundle.id);
1999
+ const replacedPaths = new Set(candidates.filter((entry) => entry.op === "update").map((entry) => entry.path));
2000
+ const finalConcepts = currentConcepts.filter((doc) => !replacedPaths.has(doc.path)).concat(candidates);
2001
+ for (const candidate of candidates) {
2002
+ const key = semanticConceptKey(candidate.frontmatter.type, candidate.title);
2003
+ const before = currentConcepts.filter((doc) => semanticConceptKey(doc.type, doc.title) === key);
2004
+ const after = finalConcepts.filter((doc) => (
2005
+ semanticConceptKey(doc.type || doc.frontmatter.type, doc.title) === key
2006
+ ));
2007
+ if (after.length <= Math.max(1, before.length)) continue;
2008
+ const existing = after.filter((doc) => !candidates.includes(doc));
2009
+ const details = candidate.op === "create" && existing.length === 1 && after.length === 2
2010
+ ? conceptConflictDetails(existing, this.store.project)
2011
+ : {
2012
+ reason: before.length ? "same_type_title" : "same_batch_type_title",
2013
+ candidates: after.slice(0, 5).map((doc) => conceptMatchSummary(doc)),
2014
+ omitted: Math.max(0, after.length - 5),
2015
+ recommendedOperation: "merge_batch_changes",
2016
+ };
2017
+ throw new AuthoringPolicyError(
2018
+ `The batch would leave more than one ${candidate.frontmatter.type} titled "${candidate.title}".`,
2019
+ "concept_already_exists",
2020
+ details,
2021
+ );
2022
+ }
1943
2023
  const message = this.commitMessage(input, candidates);
1944
2024
  const overrides = new Map(candidates.map((candidate) => [
1945
2025
  `${candidate.bundle}\u0000${candidate.path}`,
@@ -1998,7 +2078,7 @@ class LiveAuthoringService {
1998
2078
  }
1999
2079
 
2000
2080
  invalidValidationReceipt(error) {
2001
- const validation = policyValidation(error && error.message ? error.message : String(error));
2081
+ const validation = policyValidation(error);
2002
2082
  const generated = this.generatedStamp();
2003
2083
  return {
2004
2084
  valid: false,
@@ -2027,6 +2107,8 @@ class LiveAuthoringService {
2027
2107
  durability: this.durabilityReceipt(null, false),
2028
2108
  changes: [],
2029
2109
  validation,
2110
+ ...(error && error.code ? { code: error.code } : {}),
2111
+ ...(error && error.details !== undefined ? { details: error.details } : {}),
2030
2112
  git: {
2031
2113
  enabled: this.gitCommit,
2032
2114
  repository: false,
package/src/mcp-server.js CHANGED
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
 
3
+ const fs = require("node:fs");
3
4
  const path = require("path");
4
5
  const {
5
6
  McpServer,
@@ -14,6 +15,7 @@ const {
14
15
  conceptSignals,
15
16
  conceptSummary,
16
17
  loadProjectBundles,
18
+ recoverConceptLocator,
17
19
  resolveConcept,
18
20
  validateIndex,
19
21
  } = require("./indexer");
@@ -127,6 +129,10 @@ function objectParameter(description, extra) {
127
129
  }, extra || {});
128
130
  }
129
131
 
132
+ function detailParameter(description) {
133
+ return stringParameter(description, { enum: ["compact", "full"], default: "compact" });
134
+ }
135
+
130
136
  function relationParameter(description) {
131
137
  return {
132
138
  type: "object",
@@ -227,6 +233,7 @@ const LIVE_CHANGES_DESCRIPTION = [
227
233
 
228
234
  const LIVE_CHANGE_TOOL_PROPERTIES = {
229
235
  bundle: nonEmptyStringParameter("Writable bundle id; optional when exactly one local root is configured."),
236
+ detail: detailParameter("Receipt detail level; compact removes repeated planning fields while full preserves the v0.7 receipt layout."),
230
237
  message: stringParameter("Optional Git commit summary when automatic commits are enabled.", {
231
238
  maxLength: MAX_COMMIT_MESSAGE_BYTES,
232
239
  }),
@@ -244,10 +251,11 @@ const LIVE_CHANGE_EFFECTS_OUTPUT = {
244
251
  description: "Compact structured summary of the fields changed by this operation.",
245
252
  additionalProperties: true,
246
253
  properties: {
254
+ changedFields: stringArrayParameter("Substantive concept fields changed, excluding server-managed generation provenance."),
247
255
  bodyChanged: optionalBooleanParameter("Whether the Markdown body changed."),
248
256
  tags: objectParameter("Tags added and removed by the operation."),
249
257
  sources: objectParameter("Sources added and removed by the operation."),
250
- relations: objectParameter("Relations added and removed by the operation."),
258
+ relations: objectParameter("Added, removed, and updated relation values as structured { type, target, label?, description? } objects."),
251
259
  metadata: objectParameter("Metadata fields set and removed by the operation."),
252
260
  },
253
261
  };
@@ -263,6 +271,11 @@ const LIVE_CHANGE_SUMMARY_OUTPUT = {
263
271
  absolutePath: stringParameter("Absolute target concept filename."),
264
272
  uri: stringParameter("Canonical concept URI."),
265
273
  title: stringParameter("Resulting concept title."),
274
+ baseRevision: {
275
+ description: "Source revision before the operation; null for creates.",
276
+ oneOf: [{ type: "string" }, { type: "null" }],
277
+ },
278
+ candidateRevision: stringParameter("Revision of the validated candidate bytes."),
266
279
  effects: LIVE_CHANGE_EFFECTS_OUTPUT,
267
280
  },
268
281
  };
@@ -271,8 +284,8 @@ const LIVE_CHANGE_OUTPUT_PROPERTIES = {
271
284
  status: stringParameter("Validation or application outcome."),
272
285
  readyToApply: optionalBooleanParameter("Whether policy, graph, revision, and configured Git preconditions currently allow apply."),
273
286
  filesChanged: optionalBooleanParameter("Whether filesystem changes remain when the request returns."),
274
- snapshot: objectParameter("Time-of-check metadata for this planning result."),
275
- preconditions: objectParameter("Revision and Git preconditions checked for the batch."),
287
+ snapshot: objectParameter("Full-receipt time-of-check metadata for this planning result."),
288
+ preconditions: objectParameter("Full-receipt revision and Git preconditions checked for the batch."),
276
289
  generated: objectParameter("Server-owned generation actor and timestamp."),
277
290
  target: objectParameter("Absolute bundle, repository, and affected-file locations."),
278
291
  durability: objectParameter("Working-tree and automatic-commit durability state."),
@@ -331,6 +344,7 @@ const TOOL_DEFINITIONS = {
331
344
  bundle: nonEmptyStringParameter("Limit results to this bundle id."),
332
345
  type: nonEmptyStringParameter("Limit results to this exact concept type."),
333
346
  tag: nonEmptyStringParameter("Limit results to concepts containing this tag."),
347
+ detail: detailParameter("Compact returns only URI, title, type, and description; full includes navigation metadata and signals."),
334
348
  limit: integerParameter("Maximum number of concepts to return.", 1, 250, 25),
335
349
  offset: integerParameter("Number of matching concepts to skip before returning results.", 0, undefined, 0),
336
350
  },
@@ -377,6 +391,7 @@ const TOOL_DEFINITIONS = {
377
391
  attestationReady: optionalBooleanParameter("Require static Attested Computation readiness."),
378
392
  generatedBy: nonEmptyStringParameter("Limit results to this generator actor."),
379
393
  verifiedBy: nonEmptyStringParameter("Limit results to concepts verified by this actor."),
394
+ detail: detailParameter("Compact returns only URI, title, type, and description; full includes ranking, navigation metadata, and signals."),
380
395
  limit: integerParameter("Maximum number of concepts to return.", 1, 250, 25),
381
396
  offset: integerParameter("Number of matching concepts to skip before returning results.", 0, undefined, 0),
382
397
  },
@@ -743,6 +758,45 @@ function jsonContent(value, options) {
743
758
  return result;
744
759
  }
745
760
 
761
+ function liveRequest(args) {
762
+ const input = Object.assign({}, args || {});
763
+ const detail = input.detail || "compact";
764
+ delete input.detail;
765
+ return { input, detail };
766
+ }
767
+
768
+ function projectLiveReceipt(receipt, detail) {
769
+ if (detail === "full") return receipt;
770
+ const compact = structuredClone(receipt);
771
+ const preconditionGit = compact.preconditions && compact.preconditions.git;
772
+ if (preconditionGit || compact.git) {
773
+ compact.git = Object.assign({}, preconditionGit || {}, compact.git || {});
774
+ }
775
+ delete compact.snapshot;
776
+ delete compact.preconditions;
777
+ if (compact.target) delete compact.target.absolutePaths;
778
+ if (compact.durability) delete compact.durability.filesChanged;
779
+ (compact.changes || []).forEach((change) => {
780
+ delete change.bundle;
781
+ const effects = change.effects;
782
+ if (!effects) return;
783
+ ["beforeRevision", "afterRevision", "bytesBefore", "bytesAfter"].forEach((key) => delete effects[key]);
784
+ if (effects.bodyChanged === false) delete effects.bodyChanged;
785
+ ["tags", "sources", "relations", "metadata"].forEach((name) => {
786
+ const group = effects[name];
787
+ if (!group) return;
788
+ Object.keys(group).forEach((key) => {
789
+ const list = group[key];
790
+ if (!list || !Array.isArray(list.values)) return;
791
+ if (!list.omitted) delete list.omitted;
792
+ if (!list.values.length && !list.omitted) delete group[key];
793
+ });
794
+ if (!Object.keys(group).length) delete effects[name];
795
+ });
796
+ });
797
+ return compact;
798
+ }
799
+
746
800
  function toolEnabled(state, name) {
747
801
  if (PROJECT_HELPER_TOOL_NAMES.has(name)) {
748
802
  return Boolean(state && state.authoringService);
@@ -850,7 +904,7 @@ function readResource(index, uri) {
850
904
  }
851
905
 
852
906
  function listConcepts(index, args) {
853
- const options = Object.assign({}, args || {});
907
+ const options = Object.assign({ detail: "compact" }, args || {});
854
908
  if (options.type && !options.types) {
855
909
  options.types = [options.type];
856
910
  }
@@ -860,15 +914,27 @@ function listConcepts(index, args) {
860
914
  return searchConcepts(index, options);
861
915
  }
862
916
 
863
- function getConcept(index, args, repositoryMappings) {
864
- const locator = args && (args.id || args.uri)
917
+ function conceptLocator(args) {
918
+ return args && (args.id || args.uri)
865
919
  ? (args.id || args.uri)
866
920
  : args && args.bundle && args.path
867
921
  ? `okf://${args.bundle}/${args.path}`
868
922
  : null;
923
+ }
924
+
925
+ function getConcept(index, args, repositoryMappings) {
926
+ const locator = conceptLocator(args);
869
927
  const doc = resolveConcept(index, locator);
870
928
  if (!doc) {
871
- throw new ToolExecutionError(`Unknown OKF concept URI or ID: ${locator || "<missing>"}`);
929
+ const recovery = recoverConceptLocator(index, locator, {
930
+ bundle: args && args.bundle,
931
+ limit: 5,
932
+ });
933
+ throw new ToolExecutionError(
934
+ `Unknown OKF concept URI or ID: ${locator || "<missing>"}`,
935
+ recovery.status === "ambiguous" ? "concept_locator_ambiguous" : "concept_not_found",
936
+ { recovery },
937
+ );
872
938
  }
873
939
  if (!doc.valid || doc.reserved) {
874
940
  throw new ToolExecutionError(`Locator is not a valid OKF concept: ${locator}`);
@@ -893,6 +959,18 @@ function getConcept(index, args, repositoryMappings) {
893
959
  });
894
960
  }
895
961
 
962
+ function conceptIndexIsStale(index, args) {
963
+ const doc = resolveConcept(index, conceptLocator(args));
964
+ if (!doc) return true;
965
+ const bundle = (index.bundles || []).find((entry) => entry.id === doc.bundle);
966
+ if (!bundle || bundle.remote) return false;
967
+ try {
968
+ return !fs.lstatSync(doc.absolutePath).isFile();
969
+ } catch (_error) {
970
+ return true;
971
+ }
972
+ }
973
+
896
974
  function listTypes(index) {
897
975
  const counts = {};
898
976
  index.concepts.forEach((doc) => {
@@ -999,10 +1077,11 @@ async function callTool(state, name, args) {
999
1077
  case "list_concepts":
1000
1078
  return jsonContent(listConcepts(index, args));
1001
1079
  case "get_concept":
1002
- return jsonContent(getConcept(index, args, state.repositoryMappings));
1080
+ if (conceptIndexIsStale(index, args)) rebuildStateIndex(state);
1081
+ return jsonContent(getConcept(state.index, args, state.repositoryMappings));
1003
1082
  case "search_concepts":
1004
1083
  return jsonContent(await expectedToolOperation(
1005
- () => searchConcepts(index, args),
1084
+ () => searchConcepts(index, Object.assign({ detail: "compact" }, args)),
1006
1085
  { translateTypeError: true },
1007
1086
  ));
1008
1087
  case "list_types":
@@ -1145,8 +1224,9 @@ async function callTool(state, name, args) {
1145
1224
  () => requireAuthoring(state).rejectProposal(args),
1146
1225
  ));
1147
1226
  case "okf_validate_changes": {
1227
+ const request = liveRequest(args);
1148
1228
  const result = await expectedToolOperation(
1149
- () => requireLiveAuthoring(state).validateChanges(args, {
1229
+ () => requireLiveAuthoring(state).validateChanges(request.input, {
1150
1230
  additionalBundles: state.remoteBundles,
1151
1231
  }),
1152
1232
  { translateTypeError: true },
@@ -1154,11 +1234,12 @@ async function callTool(state, name, args) {
1154
1234
  if (result.applied || result.filesChanged) {
1155
1235
  rebuildStateIndex(state);
1156
1236
  }
1157
- return jsonContent(result, { structured: true });
1237
+ return jsonContent(projectLiveReceipt(result, request.detail), { structured: true });
1158
1238
  }
1159
1239
  case "okf_apply_changes": {
1240
+ const request = liveRequest(args);
1160
1241
  const result = await expectedToolOperation(
1161
- () => requireLiveAuthoring(state).applyChanges(args, {
1242
+ () => requireLiveAuthoring(state).applyChanges(request.input, {
1162
1243
  additionalBundles: state.remoteBundles,
1163
1244
  }),
1164
1245
  { translateTypeError: true },
@@ -1166,7 +1247,7 @@ async function callTool(state, name, args) {
1166
1247
  if (result.applied || result.filesChanged) {
1167
1248
  rebuildStateIndex(state);
1168
1249
  }
1169
- return jsonContent(result, {
1250
+ return jsonContent(projectLiveReceipt(result, request.detail), {
1170
1251
  structured: true,
1171
1252
  isError: result.applied === false,
1172
1253
  });
package/src/search.js CHANGED
@@ -5,10 +5,26 @@ const { normalizeV02Signals } = require("./v02");
5
5
  const { resolveConcept } = require("./indexer");
6
6
  const { normalizeSearchQuery, prepareSearchIndex } = require("./search-index");
7
7
 
8
+ const MAX_COMPACT_TEXT = 500;
9
+
8
10
  function lower(value) {
9
11
  return String(value || "").toLowerCase();
10
12
  }
11
13
 
14
+ function compactText(value) {
15
+ const text = String(value || "");
16
+ return text.length > MAX_COMPACT_TEXT ? `${text.slice(0, MAX_COMPACT_TEXT - 1)}…` : text;
17
+ }
18
+
19
+ function compactConceptSummary(doc) {
20
+ return {
21
+ uri: doc.uri,
22
+ title: compactText(doc.title),
23
+ type: compactText(doc.type),
24
+ description: compactText(doc.description),
25
+ };
26
+ }
27
+
12
28
  function asArray(value) {
13
29
  if (value === undefined || value === null) {
14
30
  return [];
@@ -205,6 +221,9 @@ function searchConcepts(index, options) {
205
221
  results.sort((a, b) => compareDocs(a.doc, b.doc));
206
222
  }
207
223
  const page = results.slice(offset, offset + limit).map((entry) => {
224
+ if (config.detail === "compact") {
225
+ return compactConceptSummary(entry.doc);
226
+ }
208
227
  const summary = conceptSummary(entry.doc);
209
228
  if (config.asOf) {
210
229
  const signals = signalsForDoc(entry.doc, config.asOf);