@mfdaves/okf-mcp 0.3.3-rc.1 → 0.5.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.
Files changed (40) hide show
  1. package/.agents/skills/okf-v02-migration/SKILL.md +37 -0
  2. package/.agents/skills/okf-v02-migration/agents/openai.yaml +6 -0
  3. package/.agents/skills/okf-v02-migration/references/field-mapping.md +26 -0
  4. package/README.md +192 -78
  5. package/okf/bundles/okf-mcp/distribution/reference-bundle.md +2 -2
  6. package/okf/bundles/okf-mcp/index.md +7 -0
  7. package/okf/bundles/okf-mcp/interfaces/http-authoring-api.md +2 -2
  8. package/okf/bundles/okf-mcp/interfaces/mcp-tools.md +8 -4
  9. package/okf/bundles/okf-mcp/overview/okf-mcp.md +2 -2
  10. package/okf/bundles/okf-mcp/policies/authoring-safety.md +5 -3
  11. package/okf/bundles/okf-mcp/runtime/file-concept-store.md +7 -5
  12. package/okf/bundles/okf-mcp/runtime/indexer.md +6 -4
  13. package/okf/bundles/okf-mcp/runtime/mcp-server.md +6 -6
  14. package/okf/bundles/okf-mcp/specs/attested-computation.md +24 -0
  15. package/okf/bundles/okf-mcp/specs/concept-format.md +5 -3
  16. package/okf/bundles/okf-mcp/specs/git-sources.md +23 -0
  17. package/okf/bundles/okf-mcp/workflows/v02-migration.md +24 -0
  18. package/package.json +9 -3
  19. package/server.json +5 -5
  20. package/src/assets.js +469 -0
  21. package/src/authoring.js +492 -20
  22. package/src/cli.js +467 -37
  23. package/src/computation.js +366 -0
  24. package/src/git-source.js +551 -0
  25. package/src/graph.js +71 -18
  26. package/src/http-server.js +8 -1
  27. package/src/index.js +5 -0
  28. package/src/indexer.js +428 -24
  29. package/src/markdown.js +129 -0
  30. package/src/mcp-server.js +447 -313
  31. package/src/migration.js +687 -0
  32. package/src/parser.js +135 -54
  33. package/src/plugins.js +30 -50
  34. package/src/project.js +74 -17
  35. package/src/remote.js +232 -17
  36. package/src/search.js +69 -6
  37. package/src/store.js +421 -25
  38. package/src/v02.js +545 -0
  39. package/src/validation.js +13 -2
  40. package/src/mcp-protocol.js +0 -283
package/src/authoring.js CHANGED
@@ -1,9 +1,24 @@
1
1
  "use strict";
2
2
 
3
3
  const path = require("path");
4
+ const fs = require("fs");
5
+ const { isDeepStrictEqual } = require("node:util");
4
6
  const yaml = require("js-yaml");
5
7
  const { parseMarkdownText, normalizeSlashes } = require("./parser");
6
- const { resolveLinkPath } = require("./indexer");
8
+ const {
9
+ bundleExcludesPath,
10
+ resolveLinkPath,
11
+ semanticReferences,
12
+ } = require("./indexer");
13
+ const {
14
+ isExternalReference,
15
+ isLocalAssetReference,
16
+ resolveBundleAssetPath,
17
+ } = require("./assets");
18
+ const { buildV02MigrationPlan, checkV02Migration } = require("./migration");
19
+ const { validateIndex } = require("./validation");
20
+
21
+ const COMPUTATION_FIELDS = new Set(["runtime", "parameters", "computation", "executor", "attester"]);
7
22
 
8
23
  function slug(value, fallback) {
9
24
  const text = String(value || fallback || "concept").trim().toLowerCase();
@@ -30,7 +45,7 @@ function normalizeConceptPath(value) {
30
45
  if (!normalized.toLowerCase().endsWith(".md")) {
31
46
  throw new Error("Concept path must end with .md.");
32
47
  }
33
- const base = path.posix.basename(normalized).toLowerCase();
48
+ const base = path.posix.basename(normalized);
34
49
  if (base === "index.md" || base === "log.md") {
35
50
  throw new Error("Concept path cannot be a reserved index.md or log.md file.");
36
51
  }
@@ -88,32 +103,39 @@ class ConceptAuthoringService {
88
103
  }
89
104
 
90
105
  getBundle(id) {
91
- const bundle = this.store.getBundles().find((entry) => entry.id === id);
106
+ const bundles = this.store.getBundles().filter((entry) => !entry.remote);
107
+ const bundle = id
108
+ ? bundles.find((entry) => entry.id === id)
109
+ : bundles.length === 1
110
+ ? bundles[0]
111
+ : null;
92
112
  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}`);
113
+ throw new Error(id
114
+ ? `Unknown writable OKF bundle: ${id}`
115
+ : "A bundle id is required unless exactly one writable OKF root is configured.");
97
116
  }
98
117
  return bundle;
99
118
  }
100
119
 
101
120
  suggestConceptPath(input) {
121
+ const bundle = this.getBundle(input && input.bundle);
102
122
  const prefix = input && input.prefix ? normalizeSlashes(String(input.prefix)).replace(/^\/+|\/+$/g, "") : "";
103
123
  if (prefix && (prefix === "." || prefix.startsWith("../") || prefix.includes("/../"))) {
104
124
  throw new Error("Path prefix must stay inside the bundle.");
105
125
  }
106
- const typePart = slug(input && input.type, "concept");
126
+ const typePart = input && input.type === "Attested Computation"
127
+ ? "computations"
128
+ : slug(input && input.type, "concept");
107
129
  const titlePart = slug(input && input.title, typePart);
108
130
  return {
109
- bundle: input && input.bundle,
131
+ bundle: bundle.id,
110
132
  path: normalizeConceptPath([prefix, typePart, `${titlePart}.md`].filter(Boolean).join("/")),
111
133
  };
112
134
  }
113
135
 
114
136
  validateConcept(input, options) {
115
- const bundleId = input && input.bundle;
116
- const bundle = this.getBundle(bundleId);
137
+ const bundle = this.getBundle(input && input.bundle);
138
+ const bundleId = bundle.id;
117
139
  const conceptPath = normalizeConceptPath(input && input.path);
118
140
  const frontmatter = Object.assign({}, input && input.frontmatter ? input.frontmatter : {});
119
141
  const markdown = renderConceptMarkdown({ path: conceptPath, frontmatter, body: input && input.body });
@@ -141,7 +163,10 @@ class ConceptAuthoringService {
141
163
 
142
164
  doc.warnings.forEach((warning) => {
143
165
  const entry = Object.assign({ bundle: bundleId }, warning);
144
- if (entry.code === "missing_type" || entry.code === "missing_frontmatter" || entry.code === "invalid_id") {
166
+ if (entry.code === "missing_type"
167
+ || entry.code === "missing_frontmatter"
168
+ || entry.code === "invalid_id"
169
+ || entry.layer === "v0.2") {
145
170
  errors.push(entry);
146
171
  } else {
147
172
  warnings.push(entry);
@@ -153,8 +178,22 @@ class ConceptAuthoringService {
153
178
  errors.push({ code: "duplicate_uri", bundle: bundleId, path: conceptPath, uri: doc.pathUri, message: "Concept path already exists." });
154
179
  }
155
180
  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." });
181
+ if (existingAtUri && !isReplacedConcept(existingAtUri)) {
182
+ errors.push({ code: "duplicate_uri", bundle: bundleId, path: conceptPath, uri: doc.uri, message: "Canonical Concept ID already exists." });
183
+ }
184
+ if (doc.customId) {
185
+ const existingAtCustomId = index.byUri.get(doc.customId);
186
+ if (existingAtCustomId && !isReplacedConcept(existingAtCustomId)) {
187
+ errors.push({ code: "duplicate_uri", alias: true, bundle: bundleId, path: conceptPath, uri: doc.customId, message: "Custom id alias already exists." });
188
+ }
189
+ }
190
+ if (doc.type === "Attested Computation" && !(options && options.allowComputation)) {
191
+ errors.push({
192
+ code: "computation_authoring_requires_capability",
193
+ bundle: bundleId,
194
+ path: conceptPath,
195
+ message: "Attested Computation contracts require the gated computation proposal tool.",
196
+ });
158
197
  }
159
198
 
160
199
  doc.links.forEach((link) => {
@@ -170,7 +209,72 @@ class ConceptAuthoringService {
170
209
  const target = index.byPathUri && index.byPathUri.get(targetPathUri);
171
210
  const targetExists = Boolean(target && target.pathUri === targetPathUri);
172
211
  if (!targetExists && resolved.uri !== doc.uri && resolved.uri !== doc.pathUri) {
173
- 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." });
212
+ const entry = { code: "broken_link", bundle: bundleId, path: doc.path, href: link.href, target: resolved.path, message: "Markdown link target does not exist in bundle." };
213
+ if (this.store.strictLinks) {
214
+ errors.push(entry);
215
+ } else {
216
+ warnings.push(entry);
217
+ }
218
+ }
219
+ });
220
+
221
+ semanticReferences(doc).forEach((reference) => {
222
+ const selfTarget = [doc.uri, doc.pathUri, doc.customId].filter(Boolean).includes(reference.value);
223
+ if (reference.value.startsWith("okf://")) {
224
+ const target = index.byUri.get(reference.value);
225
+ if (!selfTarget && (!target || target.reserved || !target.valid)) {
226
+ errors.push({
227
+ code: "broken_semantic_reference",
228
+ bundle: bundleId,
229
+ path: doc.path,
230
+ field: reference.field,
231
+ target: reference.value,
232
+ edgeKind: reference.kind,
233
+ message: "Standard OKF semantic reference does not resolve to a valid concept.",
234
+ });
235
+ }
236
+ return;
237
+ }
238
+ if (isExternalReference(reference.value)) {
239
+ return;
240
+ }
241
+ const computationDependency = doc.type === "Attested Computation"
242
+ && ["computation", "executor", "attester"].includes(reference.kind);
243
+ if (computationDependency && options && options.allowComputation) {
244
+ return;
245
+ }
246
+ const explicitLocal = isLocalAssetReference(reference.value, {
247
+ allowBare: reference.kind !== "source",
248
+ });
249
+ if (!explicitLocal) {
250
+ return;
251
+ }
252
+ try {
253
+ const resolved = resolveBundleAssetPath(bundle.root, doc.path, reference.value);
254
+ if (resolved.path.toLowerCase().endsWith(".md")) {
255
+ const target = index.byPathUri.get(`okf://${bundleId}/${resolved.path}`);
256
+ if (!target || target.reserved || !target.valid) {
257
+ throw new Error("Local Markdown reference does not resolve to a valid concept.");
258
+ }
259
+ } else {
260
+ if (bundleExcludesPath(bundle, resolved.path)) {
261
+ throw new Error("Local asset reference is excluded by the bundle policy.");
262
+ }
263
+ const target = this.store.resolveBundleFile(bundleId, resolved.path);
264
+ if (!fs.existsSync(target.absolutePath) || !fs.statSync(target.absolutePath).isFile()) {
265
+ throw new Error("Local asset reference does not resolve to an existing regular file.");
266
+ }
267
+ }
268
+ } catch (error) {
269
+ errors.push({
270
+ code: "broken_semantic_reference",
271
+ bundle: bundleId,
272
+ path: doc.path,
273
+ field: reference.field,
274
+ target: reference.value,
275
+ edgeKind: reference.kind,
276
+ message: error.message,
277
+ });
174
278
  }
175
279
  });
176
280
 
@@ -182,11 +286,29 @@ class ConceptAuthoringService {
182
286
  errors.push({ code: "missing_relation_target", bundle: bundleId, path: doc.path, relationType: type, message: "Relation has no target." });
183
287
  return;
184
288
  }
185
- if (!relationTypes.has(type)) {
289
+ const safeCustomType = /^[A-Za-z0-9_.-]+$/.test(type);
290
+ if (!relationTypes.has(type) && !(this.store.allowCustomRelationTypes && safeCustomType)) {
186
291
  errors.push({ code: "invalid_relation_type", bundle: bundleId, path: doc.path, relationType: type, message: `Unsupported relation type: ${type}` });
187
292
  }
188
- if (targetUri.startsWith("okf://") && !index.byUri.has(targetUri) && targetUri !== doc.uri && targetUri !== doc.pathUri) {
189
- errors.push({ code: "broken_relation", bundle: bundleId, path: doc.path, target: targetUri, relationType: type, message: "Relation target does not exist." });
293
+ let target = index.byUri.get(targetUri);
294
+ let internalTarget = targetUri.startsWith("okf://");
295
+ if (!target && !/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(targetUri)) {
296
+ internalTarget = true;
297
+ const resolved = resolveLinkPath(bundle, doc.path, targetUri, index.byPathUri);
298
+ if (resolved && !resolved.outsideRoot) {
299
+ const pathUri = `okf://${bundleId}/${resolved.path}`;
300
+ target = index.byPathUri.get(pathUri);
301
+ if (!target && !path.posix.extname(resolved.path)) {
302
+ target = index.byPathUri.get(`${pathUri}.md`);
303
+ }
304
+ }
305
+ }
306
+ const selfTarget = targetUri === doc.uri || targetUri === doc.pathUri || targetUri === doc.customId
307
+ || (target && target.uri === doc.uri);
308
+ if (internalTarget
309
+ && !selfTarget
310
+ && (!target || target.reserved || !target.valid)) {
311
+ errors.push({ code: "broken_relation", bundle: bundleId, path: doc.path, target: targetUri, relationType: type, message: "Relation target does not resolve to a valid concept." });
190
312
  }
191
313
  });
192
314
 
@@ -196,16 +318,22 @@ class ConceptAuthoringService {
196
318
  path: conceptPath,
197
319
  uri: doc.uri,
198
320
  pathUri: doc.pathUri,
321
+ conceptId: doc.conceptId,
322
+ customId: doc.customId,
199
323
  markdown,
200
324
  concept: {
201
325
  uri: doc.uri,
202
326
  pathUri: doc.pathUri,
327
+ conceptId: doc.conceptId,
328
+ customId: doc.customId,
203
329
  type: doc.type,
204
330
  title: doc.title,
205
331
  description: doc.description,
206
332
  tags: doc.tags,
207
333
  aliases: doc.aliases,
334
+ signals: doc.signals,
208
335
  },
336
+ signals: doc.signals,
209
337
  errors,
210
338
  warnings,
211
339
  };
@@ -224,6 +352,7 @@ class ConceptAuthoringService {
224
352
  body: String(input.body || ""),
225
353
  markdown: validation.markdown,
226
354
  message: input.message || "",
355
+ migrationId: input.migrationId || null,
227
356
  validation,
228
357
  });
229
358
  return { created: true, proposal };
@@ -240,17 +369,37 @@ class ConceptAuthoringService {
240
369
  }
241
370
 
242
371
  validateUpdateCandidate(input, existing) {
372
+ const existingComputation = existing.type === "Attested Computation";
373
+ const candidateFrontmatter = input.frontmatter || {};
374
+ const computationContractChanged = existingComputation && (
375
+ candidateFrontmatter.type !== existing.frontmatter.type
376
+ || String(input.body || "") !== String(existing.body || "")
377
+ || Array.from(COMPUTATION_FIELDS).some((field) => (
378
+ !isDeepStrictEqual(candidateFrontmatter[field], existing.frontmatter[field])
379
+ ))
380
+ );
243
381
  const validation = this.validateConcept({
244
382
  bundle: existing.bundle,
245
383
  path: existing.path,
246
- frontmatter: input.frontmatter,
384
+ frontmatter: candidateFrontmatter,
247
385
  body: input.body,
248
386
  }, {
387
+ allowComputation: existingComputation && !computationContractChanged,
249
388
  replace: {
250
389
  bundle: existing.bundle,
251
390
  path: existing.path,
252
391
  },
253
392
  });
393
+ if (computationContractChanged) {
394
+ validation.errors.push({
395
+ code: "immutable_computation_contract",
396
+ bundle: existing.bundle,
397
+ path: existing.path,
398
+ uri: existing.uri,
399
+ message: "Generic updates cannot change an existing Attested Computation contract or body.",
400
+ });
401
+ validation.valid = false;
402
+ }
254
403
  if (validation.uri !== existing.uri) {
255
404
  validation.errors.push({
256
405
  code: "immutable_uri",
@@ -261,6 +410,17 @@ class ConceptAuthoringService {
261
410
  });
262
411
  validation.valid = false;
263
412
  }
413
+ if (validation.customId !== existing.customId) {
414
+ validation.errors.push({
415
+ code: "immutable_uri",
416
+ detailCode: "immutable_custom_id_alias",
417
+ bundle: existing.bundle,
418
+ path: existing.path,
419
+ uri: validation.customId,
420
+ message: "Concept updates cannot change the existing custom id alias.",
421
+ });
422
+ validation.valid = false;
423
+ }
264
424
  return validation;
265
425
  }
266
426
 
@@ -284,6 +444,14 @@ class ConceptAuthoringService {
284
444
  throw new Error("Concept updates cannot remove the existing concept id.");
285
445
  }
286
446
  const hasBody = Boolean(input && Object.prototype.hasOwnProperty.call(input, "body"));
447
+ const touchesComputationContract = Object.keys(patch).some((key) => COMPUTATION_FIELDS.has(key))
448
+ || removeKeys.some((key) => COMPUTATION_FIELDS.has(key))
449
+ || (Object.prototype.hasOwnProperty.call(patch, "type") && patch.type !== existing.type)
450
+ || (existing.type === "Attested Computation" && hasBody);
451
+ if (patch.type === "Attested Computation" && existing.type !== "Attested Computation"
452
+ || touchesComputationContract) {
453
+ throw new Error("Generic updates cannot create or modify Attested Computation contracts or code.");
454
+ }
287
455
  if (!Object.keys(patch).length && !removeKeys.length && !hasBody) {
288
456
  throw new Error("okf_propose_update requires a frontmatter change, a removed key, or a body replacement.");
289
457
  }
@@ -307,11 +475,312 @@ class ConceptAuthoringService {
307
475
  body,
308
476
  markdown: validation.markdown,
309
477
  message: input.message || "",
478
+ migrationId: input.migrationId || null,
310
479
  validation,
311
480
  });
312
481
  return { created: true, op: "update", proposal };
313
482
  }
314
483
 
484
+ validateAttestedComputation(input, options) {
485
+ const bundle = this.getBundle(input && input.bundle);
486
+ const candidate = Object.assign({}, input || {}, { bundle: bundle.id });
487
+ const assetFiles = Array.isArray(options && options.assetFiles) ? options.assetFiles : [];
488
+ const validation = this.validateConcept(candidate, { allowComputation: true });
489
+ if (!validation.concept || validation.concept.type !== "Attested Computation") {
490
+ validation.errors.push({
491
+ code: "invalid_computation_type",
492
+ bundle: candidate.bundle,
493
+ path: candidate.path,
494
+ message: "Atomic computation proposals require type: Attested Computation.",
495
+ });
496
+ }
497
+ const frontmatter = candidate.frontmatter || {};
498
+ const normalizedAssetFiles = [];
499
+ const dependencyRevisions = new Map();
500
+ const recordDependency = (field, target, dependencyBundle) => {
501
+ const stat = fs.statSync(target.absolutePath);
502
+ if (!stat.isFile()) {
503
+ throw new Error(`Referenced ${field} dependency is not a regular file.`);
504
+ }
505
+ if (stat.size > 1024 * 1024) {
506
+ throw new Error(`Referenced ${field} dependency exceeds the 1 MiB review limit.`);
507
+ }
508
+ const content = fs.readFileSync(target.absolutePath);
509
+ if (content.length > 1024 * 1024) {
510
+ throw new Error(`Referenced ${field} dependency exceeded the 1 MiB review limit while being read.`);
511
+ }
512
+ const bundleId = dependencyBundle || candidate.bundle;
513
+ const key = `${field}\u0000${bundleId}\u0000${target.relativePath}`;
514
+ dependencyRevisions.set(key, {
515
+ field,
516
+ bundle: bundleId,
517
+ path: target.relativePath,
518
+ bytes: content.length,
519
+ revision: this.store.getContentRevision(content),
520
+ });
521
+ };
522
+ assetFiles.forEach((asset, index) => {
523
+ if (!asset || typeof asset !== "object" || Array.isArray(asset) || typeof asset.content !== "string") {
524
+ validation.errors.push({ code: "invalid_computation_asset", index, message: "Computation asset entries require path and text content." });
525
+ return;
526
+ }
527
+ try {
528
+ const target = this.store.resolveBundleFile(candidate.bundle, asset.path);
529
+ if (!asset.content.trim()) {
530
+ throw new Error("Computation asset content must be non-empty text.");
531
+ }
532
+ if (Buffer.byteLength(asset.content, "utf8") > 1024 * 1024) {
533
+ throw new Error("Computation asset exceeds the 1 MiB proposal limit.");
534
+ }
535
+ normalizedAssetFiles.push({ path: target.relativePath, content: asset.content });
536
+ } catch (error) {
537
+ validation.errors.push({ code: "invalid_computation_asset_path", index, path: asset.path, message: error.message });
538
+ }
539
+ });
540
+ const computation = validation.signals && validation.signals.computation;
541
+ if (computation && computation.computation && computation.computation.mode === "file") {
542
+ const rawPath = computation.computation.path;
543
+ const resolvedPath = rawPath.startsWith("/")
544
+ ? path.posix.normalize(rawPath.slice(1))
545
+ : path.posix.normalize(path.posix.join(path.posix.dirname(validation.path), rawPath));
546
+ if (resolvedPath.startsWith("../") || resolvedPath === "..") {
547
+ validation.errors.push({ code: "computation_asset_outside_root", path: rawPath, message: "Computation file resolves outside the bundle." });
548
+ } else if (resolvedPath === validation.path || resolvedPath.toLowerCase().endsWith(".md")) {
549
+ validation.errors.push({
550
+ code: "invalid_computation_asset_target",
551
+ path: rawPath,
552
+ message: "A file computation must target a distinct non-Markdown bundle asset.",
553
+ });
554
+ } else {
555
+ const proposed = normalizedAssetFiles.filter((asset) => asset.path === resolvedPath);
556
+ if (normalizedAssetFiles.length && (proposed.length !== 1 || normalizedAssetFiles.length !== 1)) {
557
+ validation.errors.push({ code: "computation_asset_mismatch", path: rawPath, message: "The coordinated proposal may contain only the declared computation file." });
558
+ }
559
+ if (!proposed.length) {
560
+ try {
561
+ const existing = this.store.resolveBundleFile(candidate.bundle, resolvedPath);
562
+ if (!fs.existsSync(existing.absolutePath) || !fs.statSync(existing.absolutePath).isFile()) {
563
+ throw new Error("Declared computation file does not exist and was not included in the proposal.");
564
+ }
565
+ recordDependency("computation", existing, candidate.bundle);
566
+ } catch (error) {
567
+ validation.errors.push({ code: "missing_computation_asset", path: rawPath, message: error.message });
568
+ }
569
+ }
570
+ }
571
+ } else if (normalizedAssetFiles.length) {
572
+ validation.errors.push({ code: "unexpected_computation_asset", message: "Inline computations cannot include an external computation asset." });
573
+ }
574
+ const dependencyIndex = this.store.getIndex();
575
+ ["executor", "attester"].forEach((field) => {
576
+ const value = frontmatter[field] && frontmatter[field].resource;
577
+ if (typeof value !== "string") {
578
+ return;
579
+ }
580
+ if (value.startsWith("okf://")) {
581
+ const selfUris = [validation.uri, validation.pathUri, validation.customId].filter(Boolean);
582
+ const targetDocument = dependencyIndex.byUri.get(value);
583
+ if (selfUris.includes(value) || !targetDocument || targetDocument.reserved || !targetDocument.valid) {
584
+ validation.errors.push({
585
+ code: `invalid_${field}_concept`,
586
+ field: `${field}.resource`,
587
+ path: value,
588
+ message: `${field} must reference an existing valid non-reserved concept.`,
589
+ });
590
+ return;
591
+ }
592
+ try {
593
+ const target = this.store.resolveBundleFile(targetDocument.bundle, targetDocument.path);
594
+ recordDependency(field, target, targetDocument.bundle);
595
+ } catch (error) {
596
+ validation.errors.push({ code: `missing_${field}_asset`, field: `${field}.resource`, path: value, message: error.message });
597
+ }
598
+ return;
599
+ }
600
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(value)) {
601
+ return;
602
+ }
603
+ const resolvedPath = value.startsWith("/")
604
+ ? path.posix.normalize(value.slice(1))
605
+ : path.posix.normalize(path.posix.join(path.posix.dirname(validation.path), value));
606
+ try {
607
+ const target = this.store.resolveBundleFile(candidate.bundle, resolvedPath);
608
+ if (!fs.existsSync(target.absolutePath) || !fs.statSync(target.absolutePath).isFile()) {
609
+ throw new Error(`${field} resource does not exist.`);
610
+ }
611
+ if (resolvedPath.toLowerCase().endsWith(".md")) {
612
+ const targetDocument = dependencyIndex.byPathUri.get(`okf://${candidate.bundle}/${resolvedPath}`);
613
+ if (!targetDocument || targetDocument.reserved || !targetDocument.valid) {
614
+ throw new Error(`${field} Markdown resource must resolve to a valid non-reserved concept.`);
615
+ }
616
+ }
617
+ recordDependency(field, target, candidate.bundle);
618
+ } catch (error) {
619
+ validation.errors.push({ code: `missing_${field}_asset`, field: `${field}.resource`, path: value, message: error.message });
620
+ }
621
+ });
622
+ validation.assetFiles = normalizedAssetFiles;
623
+ validation.dependencyRevisions = Array.from(dependencyRevisions.values()).sort((left, right) => (
624
+ `${left.field}\u0000${left.bundle}\u0000${left.path}`.localeCompare(`${right.field}\u0000${right.bundle}\u0000${right.path}`)
625
+ ));
626
+ validation.valid = validation.errors.length === 0;
627
+ return validation;
628
+ }
629
+
630
+ async proposeAttestedComputation(input) {
631
+ const validation = this.validateAttestedComputation(input || {}, {
632
+ assetFiles: input && input.computationPath
633
+ ? [{ path: input.computationPath, content: String(input.computationContent || "") }]
634
+ : [],
635
+ });
636
+ if (!validation.valid) {
637
+ return { created: false, validation };
638
+ }
639
+ const proposal = await this.store.saveProposal({
640
+ op: "create_computation",
641
+ bundle: validation.bundle,
642
+ path: validation.path,
643
+ frontmatter: Object.assign({}, input.frontmatter || {}),
644
+ body: String(input.body || ""),
645
+ markdown: validation.markdown,
646
+ assetFiles: validation.assetFiles,
647
+ dependencyRevisions: validation.dependencyRevisions,
648
+ message: input.message || "",
649
+ validation,
650
+ });
651
+ return { created: true, proposal };
652
+ }
653
+
654
+ validateReservedIndexMigration(proposal) {
655
+ const bundle = this.getBundle(proposal.bundle);
656
+ let doc;
657
+ const errors = [];
658
+ try {
659
+ doc = parseMarkdownText(bundle, "index.md", proposal.markdown, `${bundle.root}/index.md`);
660
+ errors.push.apply(errors, doc.conformanceDiagnostics || []);
661
+ } catch (error) {
662
+ errors.push({ code: "parse_error", bundle: bundle.id, path: "index.md", message: error.message });
663
+ }
664
+ const currentIndex = this.store.getIndex();
665
+ const currentRoot = currentIndex.documents.find((entry) => (
666
+ entry.bundle === proposal.bundle && entry.path === "index.md"
667
+ ));
668
+ const expectedMarkdown = currentRoot ? [
669
+ "---",
670
+ renderFrontmatter({ okf_version: "0.2" }),
671
+ "---",
672
+ "",
673
+ String(currentRoot.body || "").replace(/^\s+/, ""),
674
+ ].join("\n") : null;
675
+ if (!doc
676
+ || doc.frontmatter.okf_version !== "0.2"
677
+ || !proposal.frontmatter
678
+ || proposal.frontmatter.okf_version !== "0.2"
679
+ || Object.keys(proposal.frontmatter).some((key) => key !== "okf_version")
680
+ || proposal.body !== (currentRoot && currentRoot.body)
681
+ || proposal.markdown !== expectedMarkdown) {
682
+ errors.push({
683
+ code: "invalid_migration_version_declaration",
684
+ bundle: bundle.id,
685
+ path: "index.md",
686
+ message: "Migration index acceptance may only add the exact okf_version: 0.2 declaration to the unchanged current root body.",
687
+ });
688
+ }
689
+ const report = checkV02Migration(currentIndex, { bundle: proposal.bundle });
690
+ errors.push.apply(errors, report.blockers || []);
691
+ const projectValidation = validateIndex(currentIndex, proposal.bundle);
692
+ if (!projectValidation.validForProject) {
693
+ errors.push.apply(errors, projectValidation.diagnostics.filter((entry) => (
694
+ entry.invalidatesProject || entry.severity === "error"
695
+ )));
696
+ }
697
+ return { valid: errors.length === 0, errors, report, projectValidation, concept: doc || null };
698
+ }
699
+
700
+ async proposeV02Migration(input) {
701
+ const bundle = this.getBundle(input && input.bundle);
702
+ const bundleId = bundle.id;
703
+ const normalizedInput = Object.assign({}, input || {}, { bundle: bundleId });
704
+ const index = this.store.getIndex();
705
+ const plan = buildV02MigrationPlan(index, normalizedInput);
706
+ if (!plan.ready) {
707
+ return { created: false, plan };
708
+ }
709
+ const childValidations = plan.conceptProposals.map((step) => {
710
+ const existing = this.resolveConcept(step.target.uri);
711
+ const frontmatter = Object.assign({}, existing.frontmatter, step.arguments.frontmatter);
712
+ return this.validateUpdateCandidate({ frontmatter, body: existing.body }, existing);
713
+ });
714
+ if (childValidations.some((validation) => !validation.valid)) {
715
+ return { created: false, plan: Object.assign({}, plan, { childValidations }) };
716
+ }
717
+ let manifest;
718
+ const children = [];
719
+ try {
720
+ manifest = await this.store.saveMigrationManifest({
721
+ bundle: bundleId,
722
+ targetVersion: "0.2",
723
+ plan,
724
+ childProposalIds: [],
725
+ });
726
+ for (const step of plan.conceptProposals) {
727
+ const result = await this.proposeUpdate(Object.assign({}, step.arguments, {
728
+ migrationId: manifest.id,
729
+ message: `${step.arguments.message} Migration ${manifest.id}. ${normalizedInput.message || ""}`.trim(),
730
+ }));
731
+ if (!result.created) {
732
+ throw new Error(`Failed to create migration child proposal for ${step.target.uri}.`);
733
+ }
734
+ children.push(result.proposal);
735
+ manifest = await this.store.saveMigrationManifest(Object.assign({}, manifest, {
736
+ childProposalIds: children.map((proposal) => proposal.id),
737
+ plan,
738
+ }));
739
+ }
740
+ if (plan.versionDeclaration) {
741
+ const root = index.documents.find((doc) => doc.bundle === bundleId && doc.path === "index.md");
742
+ if (!root) {
743
+ throw new Error("Bundle root index.md is required for the v0.2 declaration proposal.");
744
+ }
745
+ const markdown = [
746
+ "---",
747
+ renderFrontmatter({ okf_version: "0.2" }),
748
+ "---",
749
+ "",
750
+ String(root.body || "").replace(/^\s+/, ""),
751
+ ].join("\n");
752
+ const validation = { valid: true, bundle: bundleId, path: "index.md", markdown };
753
+ const proposal = await this.store.saveProposal({
754
+ op: "migration_index",
755
+ bundle: bundleId,
756
+ path: "index.md",
757
+ targetUri: root.uri,
758
+ targetPathUri: root.pathUri,
759
+ baseRevision: this.store.getContentRevision(root.text),
760
+ frontmatter: { okf_version: "0.2" },
761
+ body: root.body,
762
+ markdown,
763
+ message: `Declare OKF v0.2 after migration ${manifest.id} child proposals are accepted and validated.`,
764
+ validation,
765
+ migrationId: manifest.id,
766
+ prerequisites: children.map((proposal) => proposal.id),
767
+ });
768
+ children.push(proposal);
769
+ }
770
+ manifest = await this.store.saveMigrationManifest(Object.assign({}, manifest, {
771
+ childProposalIds: children.map((proposal) => proposal.id),
772
+ plan,
773
+ }));
774
+ return { created: true, manifest, proposals: children };
775
+ } catch (error) {
776
+ children.forEach((proposal) => this.store.removeProposal(proposal.id));
777
+ if (manifest) {
778
+ this.store.removeMigrationManifest(manifest.id);
779
+ }
780
+ throw error;
781
+ }
782
+ }
783
+
315
784
  async listProposals(input) {
316
785
  return this.store.listProposals(input || {});
317
786
  }
@@ -321,7 +790,9 @@ class ConceptAuthoringService {
321
790
  }
322
791
 
323
792
  async acceptProposal(input) {
324
- return this.store.acceptProposal(input && input.proposalId, this);
793
+ return this.store.acceptProposal(input && input.proposalId, this, {
794
+ allowComputation: Boolean(input && input.allowComputation),
795
+ });
325
796
  }
326
797
 
327
798
  async rejectProposal(input) {
@@ -333,5 +804,6 @@ module.exports = {
333
804
  ConceptAuthoringService,
334
805
  normalizeConceptPath,
335
806
  renderConceptMarkdown,
807
+ renderFrontmatter,
336
808
  slug,
337
809
  };