@mfdaves/okf-mcp 0.9.1 → 0.13.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +452 -26
  3. package/bin/okf-mcp.js +6 -1
  4. package/okf/okf-mcp/distribution/reference-bundle.md +10 -3
  5. package/okf/okf-mcp/index.md +2 -1
  6. package/okf/okf-mcp/interfaces/http-authoring-api.md +11 -2
  7. package/okf/okf-mcp/interfaces/mcp-http.md +64 -0
  8. package/okf/okf-mcp/interfaces/mcp-tools.md +25 -6
  9. package/okf/okf-mcp/overview/okf-mcp.md +16 -6
  10. package/okf/okf-mcp/policies/authoring-safety.md +28 -5
  11. package/okf/okf-mcp/runtime/indexer.md +14 -1
  12. package/okf/okf-mcp/runtime/mcp-server.md +16 -8
  13. package/okf/okf-mcp/specs/producer-api.md +16 -2
  14. package/package.json +17 -5
  15. package/server.json +38 -2
  16. package/src/assets.js +165 -73
  17. package/src/authoring/candidates.js +434 -0
  18. package/src/authoring/git-preflight.js +225 -0
  19. package/src/authoring/git-publish.js +783 -0
  20. package/src/authoring/live.js +757 -0
  21. package/src/authoring/paths.js +112 -0
  22. package/src/authoring/policy-hook.js +221 -0
  23. package/src/authoring/proposal-policy.js +159 -0
  24. package/src/authoring/receipts.js +373 -0
  25. package/src/authoring/render.js +38 -0
  26. package/src/authoring/shared.js +75 -0
  27. package/src/authoring/staging.js +216 -0
  28. package/src/authoring.js +386 -287
  29. package/src/cache/files.js +147 -0
  30. package/src/cache/lock.js +201 -0
  31. package/src/cache/paths.js +197 -0
  32. package/src/cache/store.js +703 -0
  33. package/src/catalog-text.js +19 -0
  34. package/src/cli/commands.js +448 -0
  35. package/src/cli/http-options.js +193 -0
  36. package/src/cli/options.js +554 -0
  37. package/src/cli/usage.js +96 -0
  38. package/src/cli.js +18 -932
  39. package/src/computation.js +99 -61
  40. package/src/context/assemble.js +567 -0
  41. package/src/context/cli-options.js +88 -0
  42. package/src/context/score.js +234 -0
  43. package/src/context/sections.js +274 -0
  44. package/src/embed/interface.js +160 -0
  45. package/src/embed/openai.js +715 -0
  46. package/src/embed/prepare.js +182 -0
  47. package/src/embed/units.js +96 -0
  48. package/src/error-details.js +53 -0
  49. package/src/git-source.js +112 -52
  50. package/src/graph.js +95 -37
  51. package/src/http-server.js +36 -17
  52. package/src/index.js +15 -0
  53. package/src/indexer/assemble.js +566 -0
  54. package/src/indexer/build.js +290 -0
  55. package/src/indexer/cache.js +81 -0
  56. package/src/indexer/edges.js +430 -0
  57. package/src/indexer/index.js +44 -0
  58. package/src/indexer/paths.js +178 -0
  59. package/src/indexer/resolve.js +282 -0
  60. package/src/indexer/update.js +720 -0
  61. package/src/indexer.js +3 -1068
  62. package/src/live-authoring.js +4 -2329
  63. package/src/markdown.js +21 -16
  64. package/src/mcp/auth.js +409 -0
  65. package/src/mcp/http.js +317 -0
  66. package/src/mcp/principal.js +59 -0
  67. package/src/mcp/registry.js +356 -0
  68. package/src/mcp/resources.js +45 -0
  69. package/src/mcp/server.js +567 -0
  70. package/src/mcp/tools/catalog.js +247 -0
  71. package/src/mcp/tools/computation.js +83 -0
  72. package/src/mcp/tools/context.js +133 -0
  73. package/src/mcp/tools/graph.js +167 -0
  74. package/src/mcp/tools/live-authoring.js +316 -0
  75. package/src/mcp/tools/migration.js +86 -0
  76. package/src/mcp/tools/producers.js +79 -0
  77. package/src/mcp/tools/proposals.js +225 -0
  78. package/src/mcp/tools/provenance.js +87 -0
  79. package/src/mcp/tools/remote.js +79 -0
  80. package/src/mcp/tools/search.js +242 -0
  81. package/src/mcp-server.js +3 -1611
  82. package/src/migration.js +431 -253
  83. package/src/parser.js +245 -130
  84. package/src/plugins.js +71 -48
  85. package/src/policy/write-policy.js +713 -0
  86. package/src/producer-publisher.js +202 -78
  87. package/src/producers.js +311 -103
  88. package/src/project.js +346 -93
  89. package/src/remote.js +96 -61
  90. package/src/search/cli-options.js +107 -0
  91. package/src/search/confidence.js +61 -0
  92. package/src/search/dense.js +304 -0
  93. package/src/search/embedding-cli.js +57 -0
  94. package/src/search/embedding-config.js +217 -0
  95. package/src/search/fusion.js +249 -0
  96. package/src/search/hybrid.js +526 -0
  97. package/src/search/languages.js +200 -0
  98. package/src/search/lexical.js +695 -0
  99. package/src/search/query.js +620 -0
  100. package/src/search/stem/among.js +43 -0
  101. package/src/search/stem/base-stemmer.js +311 -0
  102. package/src/search/stem/en-regions.js +456 -0
  103. package/src/search/stem/en-suffixes.js +664 -0
  104. package/src/search/stem/en-tables.js +176 -0
  105. package/src/search/stem/en.js +238 -0
  106. package/src/search/stem/it-regions.js +459 -0
  107. package/src/search/stem/it-suffixes.js +471 -0
  108. package/src/search/stem/it-tables.js +257 -0
  109. package/src/search/stem/it.js +155 -0
  110. package/src/search-index.js +2 -81
  111. package/src/search.js +2 -252
  112. package/src/store.js +134 -81
  113. package/src/tool-packs.js +346 -0
  114. package/src/v02.js +301 -105
  115. package/src/validation.js +24 -20
package/src/authoring.js CHANGED
@@ -3,7 +3,6 @@
3
3
  const path = require("path");
4
4
  const fs = require("fs");
5
5
  const { isDeepStrictEqual } = require("node:util");
6
- const yaml = require("js-yaml");
7
6
  const { parseMarkdownText, normalizeSlashes } = require("./parser");
8
7
  const {
9
8
  bundleExcludesPath,
@@ -12,152 +11,52 @@ const {
12
11
  resolveLinkPath,
13
12
  semanticReferences,
14
13
  } = require("./indexer");
14
+ const { deriveConceptPathSuggestion, normalizeConceptPath, slug } = require("./authoring/paths");
15
+ const { resolveWritePolicy } = require("./authoring/policy-hook");
15
16
  const {
16
- isExternalReference,
17
- isLocalAssetReference,
18
- resolveBundleAssetPath,
19
- } = require("./assets");
17
+ checkProposal,
18
+ prepareAcceptance,
19
+ refuseMigration,
20
+ refuseUpdate,
21
+ } = require("./authoring/proposal-policy");
22
+ const { renderConceptMarkdown, renderFrontmatter } = require("./authoring/render");
23
+ const { isExternalReference, isLocalAssetReference, resolveBundleAssetPath } = require("./assets");
24
+ const { undeclaredRelationTypeMessage } = require("./catalog-text");
20
25
  const { buildV02MigrationPlan, checkV02Migration } = require("./migration");
21
26
  const { validateIndex } = require("./validation");
22
27
 
23
- const COMPUTATION_FIELDS = new Set(["runtime", "parameters", "computation", "executor", "attester"]);
24
-
25
- function slug(value, fallback) {
26
- const text = String(value || fallback || "concept").trim().toLowerCase();
27
- return text
28
- .replace(/[^a-z0-9]+/g, "-")
29
- .replace(/^-+|-+$/g, "") || String(fallback || "concept");
30
- }
28
+ const COMPUTATION_FIELDS = new Set([
29
+ "runtime",
30
+ "parameters",
31
+ "computation",
32
+ "executor",
33
+ "attester",
34
+ ]);
31
35
 
32
36
  function isConfiguredGeneratorOutput(project, absolutePath) {
33
37
  if (!project || !project.root || !absolutePath) return false;
34
38
  const pluginOutput = (project.plugins || []).some((plugin) => {
35
39
  if (!plugin || !plugin.output) return false;
36
40
  const relative = path.relative(path.resolve(project.root, String(plugin.output)), absolutePath);
37
- return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
41
+ return (
42
+ relative === "" ||
43
+ (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative))
44
+ );
38
45
  });
39
46
  if (pluginOutput) return true;
40
- const managedBundles = new Set((project.producers || []).map((producer) => producer && producer.bundle));
47
+ const managedBundles = new Set(
48
+ (project.producers || []).map((producer) => producer && producer.bundle),
49
+ );
41
50
  return (project.bundles || []).some((bundle) => {
42
51
  if (!bundle || !managedBundles.has(bundle.id)) return false;
43
52
  const relative = path.relative(path.resolve(bundle.root), absolutePath);
44
- return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
53
+ return (
54
+ relative === "" ||
55
+ (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative))
56
+ );
45
57
  });
46
58
  }
47
59
 
48
- function normalizeConceptPath(value) {
49
- const raw = normalizeSlashes(String(value || "").trim());
50
- if (!raw) {
51
- throw new Error("Concept path is required.");
52
- }
53
- if (raw.startsWith("/") || /^[A-Za-z]:\//.test(raw) || /[\u0000-\u001f\u007f]/.test(raw)) {
54
- throw new Error("Concept path must be a safe relative path.");
55
- }
56
- const rawParts = raw.split("/");
57
- if (rawParts.some((part) => !part || part === "." || part === ".." || part.startsWith("."))) {
58
- throw new Error("Concept path must be a safe relative path without empty, hidden, dot, or parent segments.");
59
- }
60
- if (rawParts.slice(0, -1).some((part) => part.toLowerCase().endsWith(".md"))) {
61
- throw new Error("Concept path cannot place a Markdown file inside another Markdown path.");
62
- }
63
- const normalized = path.posix.normalize(raw);
64
- if (!normalized || normalized === "." || normalized.startsWith("../") || normalized === "..") {
65
- throw new Error("Concept path must stay inside the bundle.");
66
- }
67
- if (normalized.split("/").some((part) => !part || part === "." || part === "..")) {
68
- throw new Error("Concept path contains an unsafe segment.");
69
- }
70
- if (!normalized.toLowerCase().endsWith(".md")) {
71
- throw new Error("Concept path must end with .md.");
72
- }
73
- const base = path.posix.basename(normalized).toLowerCase();
74
- if (base === "index.md" || base === "log.md") {
75
- throw new Error("Concept path cannot be a reserved index.md or log.md file.");
76
- }
77
- return normalized;
78
- }
79
-
80
- function deriveConceptPathSuggestion(index, bundle, input) {
81
- const rawPrefix = input && input.prefix
82
- ? normalizeSlashes(String(input.prefix).trim())
83
- : "";
84
- if (rawPrefix.startsWith("/") || /^[A-Za-z]:\//.test(rawPrefix)) {
85
- throw new Error("Path prefix must be a safe relative path inside the bundle.");
86
- }
87
- const prefix = rawPrefix.replace(/\/+$/g, "");
88
- if (prefix) {
89
- normalizeConceptPath(`${prefix}/placeholder.md`);
90
- }
91
- const type = String((input && input.type) || "").trim();
92
- const typePart = type === "Attested Computation"
93
- ? "computations"
94
- : slug(type, "concept");
95
- const titlePart = slug(input && input.title, typePart);
96
- let parent = prefix ? `${prefix}/${typePart}` : typePart;
97
- let strategy = prefix ? "explicit_prefix" : "type_slug";
98
- let evidence = { matchingConcepts: 0, dominantDirectoryCount: 0, dominantDirectoryRatio: 0 };
99
-
100
- if (type !== "Attested Computation" && index) {
101
- const matching = findConceptMatches(index, {
102
- bundle: bundle.id,
103
- type,
104
- pathPrefix: prefix,
105
- });
106
- const counts = new Map();
107
- matching.forEach((document) => {
108
- const directory = path.posix.dirname(document.path);
109
- const normalizedDirectory = directory === "." ? "" : directory;
110
- counts.set(normalizedDirectory, (counts.get(normalizedDirectory) || 0) + 1);
111
- });
112
- const dominant = Array.from(counts.entries()).sort((left, right) => (
113
- right[1] - left[1] || left[0].localeCompare(right[0])
114
- ))[0];
115
- const dominantCount = dominant ? dominant[1] : 0;
116
- const ratio = matching.length ? dominantCount / matching.length : 0;
117
- evidence = {
118
- matchingConcepts: matching.length,
119
- dominantDirectoryCount: dominantCount,
120
- dominantDirectoryRatio: Number(ratio.toFixed(3)),
121
- };
122
- if (dominant && dominantCount >= 2 && ratio >= 0.6) {
123
- parent = dominant[0];
124
- strategy = "dominant_same_type_directory";
125
- evidence.dominantDirectory = dominant[0] || ".";
126
- }
127
- }
128
-
129
- return {
130
- path: normalizeConceptPath([parent, `${titlePart}.md`].filter(Boolean).join("/")),
131
- strategy,
132
- evidence,
133
- };
134
- }
135
-
136
- function renderFrontmatter(frontmatter) {
137
- const values = Object.fromEntries(
138
- Object.entries(frontmatter || {}).filter((entry) => entry[1] !== undefined),
139
- );
140
- return yaml.dump(values, {
141
- schema: yaml.CORE_SCHEMA,
142
- noRefs: true,
143
- lineWidth: -1,
144
- sortKeys: false,
145
- }).trimEnd();
146
- }
147
-
148
- function renderConceptMarkdown(input) {
149
- const frontmatter = Object.assign({}, input && input.frontmatter ? input.frontmatter : {});
150
- const body = String((input && input.body) || "").replace(/\r\n/g, "\n").trim();
151
- return [
152
- "---",
153
- renderFrontmatter(frontmatter),
154
- "---",
155
- "",
156
- body || `# ${frontmatter.title || path.posix.basename(input.path || "concept.md", ".md")}`,
157
- "",
158
- ].join("\n");
159
- }
160
-
161
60
  function relationFrom(value, doc) {
162
61
  if (typeof value === "string") {
163
62
  const parts = value.trim().split(/\s+/);
@@ -179,8 +78,17 @@ function relationFrom(value, doc) {
179
78
  }
180
79
 
181
80
  class ConceptAuthoringService {
182
- constructor(store) {
81
+ constructor(store, options) {
183
82
  this.store = store;
83
+ // Trusted host configuration only (B-5): the write policy (writePolicy
84
+ // in okf.project.yaml, or a parsed --policy) and the actor proposals are
85
+ // attributed to. Tool and HTTP arguments can name neither.
86
+ this.writePolicy = resolveWritePolicy(options, store);
87
+ this.actor = options?.actor || null;
88
+ }
89
+
90
+ attribution() {
91
+ return this.actor ? { proposedBy: this.actor } : {};
184
92
  }
185
93
 
186
94
  getBundle(id) {
@@ -191,9 +99,11 @@ class ConceptAuthoringService {
191
99
  ? bundles[0]
192
100
  : null;
193
101
  if (!bundle) {
194
- throw new Error(id
195
- ? `Unknown writable OKF bundle: ${id}`
196
- : "A bundle id is required unless exactly one writable OKF root is configured.");
102
+ throw new Error(
103
+ id
104
+ ? `Unknown writable OKF bundle: ${id}`
105
+ : "A bundle id is required unless exactly one writable OKF root is configured.",
106
+ );
197
107
  }
198
108
  return bundle;
199
109
  }
@@ -211,9 +121,11 @@ class ConceptAuthoringService {
211
121
  const matches = titleMatches.slice(0, 5).map((doc) => conceptMatchSummary(doc));
212
122
  const available = !fs.existsSync(target.absolutePath);
213
123
  const only = matches.length === 1 && matches[0];
214
- const generatorOwned = only && (only.generatedFile
215
- || only.generatedBy && only.generatedBy.startsWith("process:")
216
- || isConfiguredGeneratorOutput(this.store.project, titleMatches[0].absolutePath));
124
+ const generatorOwned =
125
+ only &&
126
+ (only.generatedFile ||
127
+ (only.generatedBy && only.generatedBy.startsWith("process:")) ||
128
+ isConfiguredGeneratorOutput(this.store.project, titleMatches[0].absolutePath));
217
129
  return {
218
130
  bundle: bundle.id,
219
131
  path: suggestion.path,
@@ -225,9 +137,14 @@ class ConceptAuthoringService {
225
137
  titleMatchesOmitted: Math.max(0, titleMatches.length - matches.length),
226
138
  ...(matches.length === 1 ? { existingConcept: matches[0] } : {}),
227
139
  recommendedOperation: titleMatches.length
228
- ? titleMatches.length > 1 ? "review_matches"
229
- : generatorOwned ? "change_generator" : "update"
230
- : available ? "create" : "inspect_existing",
140
+ ? titleMatches.length > 1
141
+ ? "review_matches"
142
+ : generatorOwned
143
+ ? "change_generator"
144
+ : "update"
145
+ : available
146
+ ? "create"
147
+ : "inspect_existing",
231
148
  strategy: suggestion.strategy,
232
149
  evidence: suggestion.evidence,
233
150
  };
@@ -238,7 +155,11 @@ class ConceptAuthoringService {
238
155
  const bundleId = bundle.id;
239
156
  const conceptPath = normalizeConceptPath(input && input.path);
240
157
  const frontmatter = Object.assign({}, input && input.frontmatter ? input.frontmatter : {});
241
- const markdown = renderConceptMarkdown({ path: conceptPath, frontmatter, body: input && input.body });
158
+ const markdown = renderConceptMarkdown({
159
+ path: conceptPath,
160
+ frontmatter,
161
+ body: input && input.body,
162
+ });
242
163
  const index = this.store.getIndex();
243
164
  const replace = options && options.replace;
244
165
  const errors = [];
@@ -247,26 +168,30 @@ class ConceptAuthoringService {
247
168
 
248
169
  function isReplacedConcept(existing) {
249
170
  return Boolean(
250
- replace
251
- && existing
252
- && existing.bundle === replace.bundle
253
- && existing.path === replace.path,
171
+ replace && existing && existing.bundle === replace.bundle && existing.path === replace.path,
254
172
  );
255
173
  }
256
174
 
257
175
  try {
258
176
  doc = parseMarkdownText(bundle, conceptPath, markdown, `${bundle.root}/${conceptPath}`);
259
177
  } catch (error) {
260
- errors.push({ code: "parse_error", bundle: bundleId, path: conceptPath, message: error.message });
178
+ errors.push({
179
+ code: "parse_error",
180
+ bundle: bundleId,
181
+ path: conceptPath,
182
+ message: error.message,
183
+ });
261
184
  return { valid: false, bundle: bundleId, path: conceptPath, markdown, errors, warnings };
262
185
  }
263
186
 
264
187
  doc.warnings.forEach((warning) => {
265
188
  const entry = Object.assign({ bundle: bundleId }, warning);
266
- if (entry.code === "missing_type"
267
- || entry.code === "missing_frontmatter"
268
- || entry.code === "invalid_id"
269
- || entry.layer === "v0.2") {
189
+ if (
190
+ entry.code === "missing_type" ||
191
+ entry.code === "missing_frontmatter" ||
192
+ entry.code === "invalid_id" ||
193
+ entry.layer === "v0.2"
194
+ ) {
270
195
  errors.push(entry);
271
196
  } else {
272
197
  warnings.push(entry);
@@ -275,16 +200,35 @@ class ConceptAuthoringService {
275
200
 
276
201
  const existingAtPath = index.byUri.get(doc.pathUri);
277
202
  if (existingAtPath && !isReplacedConcept(existingAtPath)) {
278
- errors.push({ code: "duplicate_uri", bundle: bundleId, path: conceptPath, uri: doc.pathUri, message: "Concept path already exists." });
203
+ errors.push({
204
+ code: "duplicate_uri",
205
+ bundle: bundleId,
206
+ path: conceptPath,
207
+ uri: doc.pathUri,
208
+ message: "Concept path already exists.",
209
+ });
279
210
  }
280
211
  const existingAtUri = index.byUri.get(doc.uri);
281
212
  if (existingAtUri && !isReplacedConcept(existingAtUri)) {
282
- errors.push({ code: "duplicate_uri", bundle: bundleId, path: conceptPath, uri: doc.uri, message: "Canonical Concept ID already exists." });
213
+ errors.push({
214
+ code: "duplicate_uri",
215
+ bundle: bundleId,
216
+ path: conceptPath,
217
+ uri: doc.uri,
218
+ message: "Canonical Concept ID already exists.",
219
+ });
283
220
  }
284
221
  if (doc.customId) {
285
222
  const existingAtCustomId = index.byUri.get(doc.customId);
286
223
  if (existingAtCustomId && !isReplacedConcept(existingAtCustomId)) {
287
- errors.push({ code: "duplicate_uri", alias: true, bundle: bundleId, path: conceptPath, uri: doc.customId, message: "Custom id alias already exists." });
224
+ errors.push({
225
+ code: "duplicate_uri",
226
+ alias: true,
227
+ bundle: bundleId,
228
+ path: conceptPath,
229
+ uri: doc.customId,
230
+ message: "Custom id alias already exists.",
231
+ });
288
232
  }
289
233
  }
290
234
  if (doc.type === "Attested Computation" && !(options && options.allowComputation)) {
@@ -302,14 +246,27 @@ class ConceptAuthoringService {
302
246
  return;
303
247
  }
304
248
  if (resolved.outsideRoot) {
305
- warnings.push({ code: "link_outside_root", bundle: bundleId, path: doc.path, href: link.href, message: "Markdown link resolves outside bundle root." });
249
+ warnings.push({
250
+ code: "link_outside_root",
251
+ bundle: bundleId,
252
+ path: doc.path,
253
+ href: link.href,
254
+ message: "Markdown link resolves outside bundle root.",
255
+ });
306
256
  return;
307
257
  }
308
258
  const targetPathUri = `okf://${bundleId}/${resolved.path}`;
309
259
  const target = index.byPathUri && index.byPathUri.get(targetPathUri);
310
260
  const targetExists = Boolean(target && target.pathUri === targetPathUri);
311
261
  if (!targetExists && resolved.uri !== doc.uri && resolved.uri !== doc.pathUri) {
312
- 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." };
262
+ const entry = {
263
+ code: "broken_link",
264
+ bundle: bundleId,
265
+ path: doc.path,
266
+ href: link.href,
267
+ target: resolved.path,
268
+ message: "Markdown link target does not exist in bundle.",
269
+ };
313
270
  if (this.store.strictLinks) {
314
271
  errors.push(entry);
315
272
  } else {
@@ -319,7 +276,9 @@ class ConceptAuthoringService {
319
276
  });
320
277
 
321
278
  semanticReferences(doc).forEach((reference) => {
322
- const selfTarget = [doc.uri, doc.pathUri, doc.customId].filter(Boolean).includes(reference.value);
279
+ const selfTarget = [doc.uri, doc.pathUri, doc.customId]
280
+ .filter(Boolean)
281
+ .includes(reference.value);
323
282
  if (reference.value.startsWith("okf://")) {
324
283
  const target = index.byUri.get(reference.value);
325
284
  if (!selfTarget && (!target || target.reserved || !target.valid)) {
@@ -338,8 +297,9 @@ class ConceptAuthoringService {
338
297
  if (isExternalReference(reference.value)) {
339
298
  return;
340
299
  }
341
- const computationDependency = doc.type === "Attested Computation"
342
- && ["computation", "executor", "attester"].includes(reference.kind);
300
+ const computationDependency =
301
+ doc.type === "Attested Computation" &&
302
+ ["computation", "executor", "attester"].includes(reference.kind);
343
303
  if (computationDependency && options && options.allowComputation) {
344
304
  return;
345
305
  }
@@ -379,38 +339,60 @@ class ConceptAuthoringService {
379
339
  });
380
340
 
381
341
  const relationTypes = new Set(this.store.getRelationTypes().map(String));
382
- doc.relations.map((relation) => relationFrom(relation, doc)).forEach((relation) => {
383
- const type = String(relation.type || "related_to");
384
- const targetUri = String(relation.target || "").trim();
385
- if (!targetUri) {
386
- errors.push({ code: "missing_relation_target", bundle: bundleId, path: doc.path, relationType: type, message: "Relation has no target." });
387
- return;
388
- }
389
- const safeCustomType = /^[A-Za-z0-9_.-]+$/.test(type);
390
- if (!relationTypes.has(type) && !(this.store.allowCustomRelationTypes && safeCustomType)) {
391
- errors.push({ code: "invalid_relation_type", bundle: bundleId, path: doc.path, relationType: type, message: `Unsupported relation type: ${type}` });
392
- }
393
- let target = index.byUri.get(targetUri);
394
- let internalTarget = targetUri.startsWith("okf://");
395
- if (!target && !/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(targetUri)) {
396
- internalTarget = true;
397
- const resolved = resolveLinkPath(bundle, doc.path, targetUri, index.byPathUri);
398
- if (resolved && !resolved.outsideRoot) {
399
- const pathUri = `okf://${bundleId}/${resolved.path}`;
400
- target = index.byPathUri.get(pathUri);
401
- if (!target && !path.posix.extname(resolved.path)) {
402
- target = index.byPathUri.get(`${pathUri}.md`);
342
+ doc.relations
343
+ .map((relation) => relationFrom(relation, doc))
344
+ .forEach((relation, position) => {
345
+ const type = String(relation.type || "related_to");
346
+ const targetUri = String(relation.target || "").trim();
347
+ if (!targetUri) {
348
+ errors.push({
349
+ code: "missing_relation_target",
350
+ bundle: bundleId,
351
+ path: doc.path,
352
+ relationType: type,
353
+ message: "Relation has no target.",
354
+ });
355
+ return;
356
+ }
357
+ const safeCustomType = /^[A-Za-z0-9_.-]+$/.test(type);
358
+ if (!relationTypes.has(type) && !(this.store.allowCustomRelationTypes && safeCustomType)) {
359
+ errors.push({
360
+ code: "invalid_relation_type",
361
+ bundle: bundleId,
362
+ path: doc.path,
363
+ relationType: type,
364
+ message: undeclaredRelationTypeMessage(doc.path, position),
365
+ });
366
+ }
367
+ let target = index.byUri.get(targetUri);
368
+ let internalTarget = targetUri.startsWith("okf://");
369
+ if (!target && !/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(targetUri)) {
370
+ internalTarget = true;
371
+ const resolved = resolveLinkPath(bundle, doc.path, targetUri, index.byPathUri);
372
+ if (resolved && !resolved.outsideRoot) {
373
+ const pathUri = `okf://${bundleId}/${resolved.path}`;
374
+ target = index.byPathUri.get(pathUri);
375
+ if (!target && !path.posix.extname(resolved.path)) {
376
+ target = index.byPathUri.get(`${pathUri}.md`);
377
+ }
403
378
  }
404
379
  }
405
- }
406
- const selfTarget = targetUri === doc.uri || targetUri === doc.pathUri || targetUri === doc.customId
407
- || (target && target.uri === doc.uri);
408
- if (internalTarget
409
- && !selfTarget
410
- && (!target || target.reserved || !target.valid)) {
411
- errors.push({ code: "broken_relation", bundle: bundleId, path: doc.path, target: targetUri, relationType: type, message: "Relation target does not resolve to a valid concept." });
412
- }
413
- });
380
+ const selfTarget =
381
+ targetUri === doc.uri ||
382
+ targetUri === doc.pathUri ||
383
+ targetUri === doc.customId ||
384
+ (target && target.uri === doc.uri);
385
+ if (internalTarget && !selfTarget && (!target || target.reserved || !target.valid)) {
386
+ errors.push({
387
+ code: "broken_relation",
388
+ bundle: bundleId,
389
+ path: doc.path,
390
+ target: targetUri,
391
+ relationType: type,
392
+ message: "Relation target does not resolve to a valid concept.",
393
+ });
394
+ }
395
+ });
414
396
 
415
397
  return {
416
398
  valid: errors.length === 0,
@@ -440,20 +422,24 @@ class ConceptAuthoringService {
440
422
  }
441
423
 
442
424
  async proposeConcept(input) {
443
- const validation = this.validateConcept(input || {});
444
- if (!validation.valid) {
445
- return { created: false, validation };
425
+ const checked = checkProposal(this, "create", input || {}, (candidate) =>
426
+ this.validateConcept(candidate),
427
+ );
428
+ if (checked.refused) {
429
+ return checked.refused;
446
430
  }
431
+ const { request, validation } = checked;
447
432
  const proposal = await this.store.saveProposal({
448
433
  op: "create",
449
434
  bundle: validation.bundle,
450
435
  path: validation.path,
451
- frontmatter: Object.assign({}, input.frontmatter || {}),
452
- body: String(input.body || ""),
436
+ frontmatter: Object.assign({}, request.frontmatter || {}),
437
+ body: String(request.body || ""),
453
438
  markdown: validation.markdown,
454
- message: input.message || "",
455
- migrationId: input.migrationId || null,
439
+ message: request.message || "",
440
+ migrationId: request.migrationId || null,
456
441
  validation,
442
+ ...this.attribution(),
457
443
  });
458
444
  return { created: true, proposal };
459
445
  }
@@ -471,25 +457,28 @@ class ConceptAuthoringService {
471
457
  validateUpdateCandidate(input, existing) {
472
458
  const existingComputation = existing.type === "Attested Computation";
473
459
  const candidateFrontmatter = input.frontmatter || {};
474
- const computationContractChanged = existingComputation && (
475
- candidateFrontmatter.type !== existing.frontmatter.type
476
- || String(input.body || "") !== String(existing.body || "")
477
- || Array.from(COMPUTATION_FIELDS).some((field) => (
478
- !isDeepStrictEqual(candidateFrontmatter[field], existing.frontmatter[field])
479
- ))
480
- );
481
- const validation = this.validateConcept({
482
- bundle: existing.bundle,
483
- path: existing.path,
484
- frontmatter: candidateFrontmatter,
485
- body: input.body,
486
- }, {
487
- allowComputation: existingComputation && !computationContractChanged,
488
- replace: {
460
+ const computationContractChanged =
461
+ existingComputation &&
462
+ (candidateFrontmatter.type !== existing.frontmatter.type ||
463
+ String(input.body || "") !== String(existing.body || "") ||
464
+ Array.from(COMPUTATION_FIELDS).some(
465
+ (field) => !isDeepStrictEqual(candidateFrontmatter[field], existing.frontmatter[field]),
466
+ ));
467
+ const validation = this.validateConcept(
468
+ {
489
469
  bundle: existing.bundle,
490
470
  path: existing.path,
471
+ frontmatter: candidateFrontmatter,
472
+ body: input.body,
491
473
  },
492
- });
474
+ {
475
+ allowComputation: existingComputation && !computationContractChanged,
476
+ replace: {
477
+ bundle: existing.bundle,
478
+ path: existing.path,
479
+ },
480
+ },
481
+ );
493
482
  if (computationContractChanged) {
494
483
  validation.errors.push({
495
484
  code: "immutable_computation_contract",
@@ -534,26 +523,35 @@ class ConceptAuthoringService {
534
523
  if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
535
524
  throw new Error("frontmatter must be an object when provided.");
536
525
  }
537
- const removeKeys = input && input.removeFrontmatterKeys === undefined
538
- ? []
539
- : input.removeFrontmatterKeys;
540
- if (!Array.isArray(removeKeys) || removeKeys.some((key) => typeof key !== "string" || !key.trim())) {
526
+ const removeKeys =
527
+ input && input.removeFrontmatterKeys === undefined ? [] : input.removeFrontmatterKeys;
528
+ if (
529
+ !Array.isArray(removeKeys) ||
530
+ removeKeys.some((key) => typeof key !== "string" || !key.trim())
531
+ ) {
541
532
  throw new Error("removeFrontmatterKeys must be an array of non-empty strings.");
542
533
  }
543
534
  if (removeKeys.includes("id")) {
544
535
  throw new Error("Concept updates cannot remove the existing concept id.");
545
536
  }
546
537
  const hasBody = Boolean(input && Object.prototype.hasOwnProperty.call(input, "body"));
547
- const touchesComputationContract = Object.keys(patch).some((key) => COMPUTATION_FIELDS.has(key))
548
- || removeKeys.some((key) => COMPUTATION_FIELDS.has(key))
549
- || (Object.prototype.hasOwnProperty.call(patch, "type") && patch.type !== existing.type)
550
- || (existing.type === "Attested Computation" && hasBody);
551
- if (patch.type === "Attested Computation" && existing.type !== "Attested Computation"
552
- || touchesComputationContract) {
553
- throw new Error("Generic updates cannot create or modify Attested Computation contracts or code.");
538
+ const touchesComputationContract =
539
+ Object.keys(patch).some((key) => COMPUTATION_FIELDS.has(key)) ||
540
+ removeKeys.some((key) => COMPUTATION_FIELDS.has(key)) ||
541
+ (Object.prototype.hasOwnProperty.call(patch, "type") && patch.type !== existing.type) ||
542
+ (existing.type === "Attested Computation" && hasBody);
543
+ if (
544
+ (patch.type === "Attested Computation" && existing.type !== "Attested Computation") ||
545
+ touchesComputationContract
546
+ ) {
547
+ throw new Error(
548
+ "Generic updates cannot create or modify Attested Computation contracts or code.",
549
+ );
554
550
  }
555
551
  if (!Object.keys(patch).length && !removeKeys.length && !hasBody) {
556
- throw new Error("okf_propose_update requires a frontmatter change, a removed key, or a body replacement.");
552
+ throw new Error(
553
+ "okf_propose_update requires a frontmatter change, a removed key, or a body replacement.",
554
+ );
557
555
  }
558
556
  const frontmatter = Object.assign({}, existing.frontmatter, patch);
559
557
  removeKeys.forEach((key) => {
@@ -564,6 +562,10 @@ class ConceptAuthoringService {
564
562
  if (!validation.valid) {
565
563
  return { created: false, op: "update", validation };
566
564
  }
565
+ const refusedUpdate = refuseUpdate(this, validation, existing, frontmatter);
566
+ if (refusedUpdate) {
567
+ return refusedUpdate;
568
+ }
567
569
  const proposal = await this.store.saveProposal({
568
570
  op: "update",
569
571
  targetUri: existing.uri,
@@ -577,6 +579,7 @@ class ConceptAuthoringService {
577
579
  message: input.message || "",
578
580
  migrationId: input.migrationId || null,
579
581
  validation,
582
+ ...this.attribution(),
580
583
  });
581
584
  return { created: true, op: "update", proposal };
582
585
  }
@@ -607,7 +610,9 @@ class ConceptAuthoringService {
607
610
  }
608
611
  const content = fs.readFileSync(target.absolutePath);
609
612
  if (content.length > 1024 * 1024) {
610
- throw new Error(`Referenced ${field} dependency exceeded the 1 MiB review limit while being read.`);
613
+ throw new Error(
614
+ `Referenced ${field} dependency exceeded the 1 MiB review limit while being read.`,
615
+ );
611
616
  }
612
617
  const bundleId = dependencyBundle || candidate.bundle;
613
618
  const key = `${field}\u0000${bundleId}\u0000${target.relativePath}`;
@@ -620,8 +625,17 @@ class ConceptAuthoringService {
620
625
  });
621
626
  };
622
627
  assetFiles.forEach((asset, index) => {
623
- if (!asset || typeof asset !== "object" || Array.isArray(asset) || typeof asset.content !== "string") {
624
- validation.errors.push({ code: "invalid_computation_asset", index, message: "Computation asset entries require path and text content." });
628
+ if (
629
+ !asset ||
630
+ typeof asset !== "object" ||
631
+ Array.isArray(asset) ||
632
+ typeof asset.content !== "string"
633
+ ) {
634
+ validation.errors.push({
635
+ code: "invalid_computation_asset",
636
+ index,
637
+ message: "Computation asset entries require path and text content.",
638
+ });
625
639
  return;
626
640
  }
627
641
  try {
@@ -634,7 +648,12 @@ class ConceptAuthoringService {
634
648
  }
635
649
  normalizedAssetFiles.push({ path: target.relativePath, content: asset.content });
636
650
  } catch (error) {
637
- validation.errors.push({ code: "invalid_computation_asset_path", index, path: asset.path, message: error.message });
651
+ validation.errors.push({
652
+ code: "invalid_computation_asset_path",
653
+ index,
654
+ path: asset.path,
655
+ message: error.message,
656
+ });
638
657
  }
639
658
  });
640
659
  const computation = validation.signals && validation.signals.computation;
@@ -644,7 +663,11 @@ class ConceptAuthoringService {
644
663
  ? path.posix.normalize(rawPath.slice(1))
645
664
  : path.posix.normalize(path.posix.join(path.posix.dirname(validation.path), rawPath));
646
665
  if (resolvedPath.startsWith("../") || resolvedPath === "..") {
647
- validation.errors.push({ code: "computation_asset_outside_root", path: rawPath, message: "Computation file resolves outside the bundle." });
666
+ validation.errors.push({
667
+ code: "computation_asset_outside_root",
668
+ path: rawPath,
669
+ message: "Computation file resolves outside the bundle.",
670
+ });
648
671
  } else if (resolvedPath === validation.path || resolvedPath.toLowerCase().endsWith(".md")) {
649
672
  validation.errors.push({
650
673
  code: "invalid_computation_asset_target",
@@ -653,23 +676,42 @@ class ConceptAuthoringService {
653
676
  });
654
677
  } else {
655
678
  const proposed = normalizedAssetFiles.filter((asset) => asset.path === resolvedPath);
656
- if (normalizedAssetFiles.length && (proposed.length !== 1 || normalizedAssetFiles.length !== 1)) {
657
- validation.errors.push({ code: "computation_asset_mismatch", path: rawPath, message: "The coordinated proposal may contain only the declared computation file." });
679
+ if (
680
+ normalizedAssetFiles.length &&
681
+ (proposed.length !== 1 || normalizedAssetFiles.length !== 1)
682
+ ) {
683
+ validation.errors.push({
684
+ code: "computation_asset_mismatch",
685
+ path: rawPath,
686
+ message: "The coordinated proposal may contain only the declared computation file.",
687
+ });
658
688
  }
659
689
  if (!proposed.length) {
660
690
  try {
661
691
  const existing = this.store.resolveBundleFile(candidate.bundle, resolvedPath);
662
- if (!fs.existsSync(existing.absolutePath) || !fs.statSync(existing.absolutePath).isFile()) {
663
- throw new Error("Declared computation file does not exist and was not included in the proposal.");
692
+ if (
693
+ !fs.existsSync(existing.absolutePath) ||
694
+ !fs.statSync(existing.absolutePath).isFile()
695
+ ) {
696
+ throw new Error(
697
+ "Declared computation file does not exist and was not included in the proposal.",
698
+ );
664
699
  }
665
700
  recordDependency("computation", existing, candidate.bundle);
666
701
  } catch (error) {
667
- validation.errors.push({ code: "missing_computation_asset", path: rawPath, message: error.message });
702
+ validation.errors.push({
703
+ code: "missing_computation_asset",
704
+ path: rawPath,
705
+ message: error.message,
706
+ });
668
707
  }
669
708
  }
670
709
  }
671
710
  } else if (normalizedAssetFiles.length) {
672
- validation.errors.push({ code: "unexpected_computation_asset", message: "Inline computations cannot include an external computation asset." });
711
+ validation.errors.push({
712
+ code: "unexpected_computation_asset",
713
+ message: "Inline computations cannot include an external computation asset.",
714
+ });
673
715
  }
674
716
  const dependencyIndex = this.store.getIndex();
675
717
  ["executor", "attester"].forEach((field) => {
@@ -680,7 +722,12 @@ class ConceptAuthoringService {
680
722
  if (value.startsWith("okf://")) {
681
723
  const selfUris = [validation.uri, validation.pathUri, validation.customId].filter(Boolean);
682
724
  const targetDocument = dependencyIndex.byUri.get(value);
683
- if (selfUris.includes(value) || !targetDocument || targetDocument.reserved || !targetDocument.valid) {
725
+ if (
726
+ selfUris.includes(value) ||
727
+ !targetDocument ||
728
+ targetDocument.reserved ||
729
+ !targetDocument.valid
730
+ ) {
684
731
  validation.errors.push({
685
732
  code: `invalid_${field}_concept`,
686
733
  field: `${field}.resource`,
@@ -693,7 +740,12 @@ class ConceptAuthoringService {
693
740
  const target = this.store.resolveBundleFile(targetDocument.bundle, targetDocument.path);
694
741
  recordDependency(field, target, targetDocument.bundle);
695
742
  } catch (error) {
696
- validation.errors.push({ code: `missing_${field}_asset`, field: `${field}.resource`, path: value, message: error.message });
743
+ validation.errors.push({
744
+ code: `missing_${field}_asset`,
745
+ field: `${field}.resource`,
746
+ path: value,
747
+ message: error.message,
748
+ });
697
749
  }
698
750
  return;
699
751
  }
@@ -709,44 +761,58 @@ class ConceptAuthoringService {
709
761
  throw new Error(`${field} resource does not exist.`);
710
762
  }
711
763
  if (resolvedPath.toLowerCase().endsWith(".md")) {
712
- const targetDocument = dependencyIndex.byPathUri.get(`okf://${candidate.bundle}/${resolvedPath}`);
764
+ const targetDocument = dependencyIndex.byPathUri.get(
765
+ `okf://${candidate.bundle}/${resolvedPath}`,
766
+ );
713
767
  if (!targetDocument || targetDocument.reserved || !targetDocument.valid) {
714
- throw new Error(`${field} Markdown resource must resolve to a valid non-reserved concept.`);
768
+ throw new Error(
769
+ `${field} Markdown resource must resolve to a valid non-reserved concept.`,
770
+ );
715
771
  }
716
772
  }
717
773
  recordDependency(field, target, candidate.bundle);
718
774
  } catch (error) {
719
- validation.errors.push({ code: `missing_${field}_asset`, field: `${field}.resource`, path: value, message: error.message });
775
+ validation.errors.push({
776
+ code: `missing_${field}_asset`,
777
+ field: `${field}.resource`,
778
+ path: value,
779
+ message: error.message,
780
+ });
720
781
  }
721
782
  });
722
783
  validation.assetFiles = normalizedAssetFiles;
723
- validation.dependencyRevisions = Array.from(dependencyRevisions.values()).sort((left, right) => (
724
- `${left.field}\u0000${left.bundle}\u0000${left.path}`.localeCompare(`${right.field}\u0000${right.bundle}\u0000${right.path}`)
725
- ));
784
+ validation.dependencyRevisions = Array.from(dependencyRevisions.values()).sort((left, right) =>
785
+ `${left.field}\u0000${left.bundle}\u0000${left.path}`.localeCompare(
786
+ `${right.field}\u0000${right.bundle}\u0000${right.path}`,
787
+ ),
788
+ );
726
789
  validation.valid = validation.errors.length === 0;
727
790
  return validation;
728
791
  }
729
792
 
730
793
  async proposeAttestedComputation(input) {
731
- const validation = this.validateAttestedComputation(input || {}, {
732
- assetFiles: input && input.computationPath
733
- ? [{ path: input.computationPath, content: String(input.computationContent || "") }]
734
- : [],
735
- });
736
- if (!validation.valid) {
737
- return { created: false, validation };
794
+ const assetFiles = input?.computationPath
795
+ ? [{ path: input.computationPath, content: String(input.computationContent || "") }]
796
+ : [];
797
+ const checked = checkProposal(this, "create_computation", input || {}, (candidate) =>
798
+ this.validateAttestedComputation(candidate, { assetFiles }),
799
+ );
800
+ if (checked.refused) {
801
+ return checked.refused;
738
802
  }
803
+ const { request, validation } = checked;
739
804
  const proposal = await this.store.saveProposal({
740
805
  op: "create_computation",
741
806
  bundle: validation.bundle,
742
807
  path: validation.path,
743
- frontmatter: Object.assign({}, input.frontmatter || {}),
744
- body: String(input.body || ""),
808
+ frontmatter: Object.assign({}, request.frontmatter || {}),
809
+ body: String(request.body || ""),
745
810
  markdown: validation.markdown,
746
811
  assetFiles: validation.assetFiles,
747
812
  dependencyRevisions: validation.dependencyRevisions,
748
- message: input.message || "",
813
+ message: request.message || "",
749
814
  validation,
815
+ ...this.attribution(),
750
816
  });
751
817
  return { created: true, proposal };
752
818
  }
@@ -759,40 +825,53 @@ class ConceptAuthoringService {
759
825
  doc = parseMarkdownText(bundle, "index.md", proposal.markdown, `${bundle.root}/index.md`);
760
826
  errors.push.apply(errors, doc.conformanceDiagnostics || []);
761
827
  } catch (error) {
762
- errors.push({ code: "parse_error", bundle: bundle.id, path: "index.md", message: error.message });
828
+ errors.push({
829
+ code: "parse_error",
830
+ bundle: bundle.id,
831
+ path: "index.md",
832
+ message: error.message,
833
+ });
763
834
  }
764
835
  const currentIndex = this.store.getIndex();
765
- const currentRoot = currentIndex.documents.find((entry) => (
766
- entry.bundle === proposal.bundle && entry.path === "index.md"
767
- ));
768
- const expectedMarkdown = currentRoot ? [
769
- "---",
770
- renderFrontmatter({ okf_version: "0.2" }),
771
- "---",
772
- "",
773
- String(currentRoot.body || "").replace(/^\s+/, ""),
774
- ].join("\n") : null;
775
- if (!doc
776
- || doc.frontmatter.okf_version !== "0.2"
777
- || !proposal.frontmatter
778
- || proposal.frontmatter.okf_version !== "0.2"
779
- || Object.keys(proposal.frontmatter).some((key) => key !== "okf_version")
780
- || proposal.body !== (currentRoot && currentRoot.body)
781
- || proposal.markdown !== expectedMarkdown) {
836
+ const currentRoot = currentIndex.documents.find(
837
+ (entry) => entry.bundle === proposal.bundle && entry.path === "index.md",
838
+ );
839
+ const expectedMarkdown = currentRoot
840
+ ? [
841
+ "---",
842
+ renderFrontmatter({ okf_version: "0.2" }),
843
+ "---",
844
+ "",
845
+ String(currentRoot.body || "").replace(/^\s+/, ""),
846
+ ].join("\n")
847
+ : null;
848
+ if (
849
+ !doc ||
850
+ doc.frontmatter.okf_version !== "0.2" ||
851
+ !proposal.frontmatter ||
852
+ proposal.frontmatter.okf_version !== "0.2" ||
853
+ Object.keys(proposal.frontmatter).some((key) => key !== "okf_version") ||
854
+ proposal.body !== (currentRoot && currentRoot.body) ||
855
+ proposal.markdown !== expectedMarkdown
856
+ ) {
782
857
  errors.push({
783
858
  code: "invalid_migration_version_declaration",
784
859
  bundle: bundle.id,
785
860
  path: "index.md",
786
- message: "Migration index acceptance may only add the exact okf_version: 0.2 declaration to the unchanged current root body.",
861
+ message:
862
+ "Migration index acceptance may only add the exact okf_version: 0.2 declaration to the unchanged current root body.",
787
863
  });
788
864
  }
789
865
  const report = checkV02Migration(currentIndex, { bundle: proposal.bundle });
790
866
  errors.push.apply(errors, report.blockers || []);
791
867
  const projectValidation = validateIndex(currentIndex, proposal.bundle);
792
868
  if (!projectValidation.validForProject) {
793
- errors.push.apply(errors, projectValidation.diagnostics.filter((entry) => (
794
- entry.invalidatesProject || entry.severity === "error"
795
- )));
869
+ errors.push.apply(
870
+ errors,
871
+ projectValidation.diagnostics.filter(
872
+ (entry) => entry.invalidatesProject || entry.severity === "error",
873
+ ),
874
+ );
796
875
  }
797
876
  return { valid: errors.length === 0, errors, report, projectValidation, concept: doc || null };
798
877
  }
@@ -814,6 +893,10 @@ class ConceptAuthoringService {
814
893
  if (childValidations.some((validation) => !validation.valid)) {
815
894
  return { created: false, plan: Object.assign({}, plan, { childValidations }) };
816
895
  }
896
+ const refusedMigration = refuseMigration(this, bundleId, plan);
897
+ if (refusedMigration) {
898
+ return refusedMigration;
899
+ }
817
900
  let manifest;
818
901
  const children = [];
819
902
  try {
@@ -824,21 +907,28 @@ class ConceptAuthoringService {
824
907
  childProposalIds: [],
825
908
  });
826
909
  for (const step of plan.conceptProposals) {
827
- const result = await this.proposeUpdate(Object.assign({}, step.arguments, {
828
- migrationId: manifest.id,
829
- message: `${step.arguments.message} Migration ${manifest.id}. ${normalizedInput.message || ""}`.trim(),
830
- }));
910
+ const result = await this.proposeUpdate(
911
+ Object.assign({}, step.arguments, {
912
+ migrationId: manifest.id,
913
+ message:
914
+ `${step.arguments.message} Migration ${manifest.id}. ${normalizedInput.message || ""}`.trim(),
915
+ }),
916
+ );
831
917
  if (!result.created) {
832
918
  throw new Error(`Failed to create migration child proposal for ${step.target.uri}.`);
833
919
  }
834
920
  children.push(result.proposal);
835
- manifest = await this.store.saveMigrationManifest(Object.assign({}, manifest, {
836
- childProposalIds: children.map((proposal) => proposal.id),
837
- plan,
838
- }));
921
+ manifest = await this.store.saveMigrationManifest(
922
+ Object.assign({}, manifest, {
923
+ childProposalIds: children.map((proposal) => proposal.id),
924
+ plan,
925
+ }),
926
+ );
839
927
  }
840
928
  if (plan.versionDeclaration) {
841
- const root = index.documents.find((doc) => doc.bundle === bundleId && doc.path === "index.md");
929
+ const root = index.documents.find(
930
+ (doc) => doc.bundle === bundleId && doc.path === "index.md",
931
+ );
842
932
  if (!root) {
843
933
  throw new Error("Bundle root index.md is required for the v0.2 declaration proposal.");
844
934
  }
@@ -864,13 +954,16 @@ class ConceptAuthoringService {
864
954
  validation,
865
955
  migrationId: manifest.id,
866
956
  prerequisites: children.map((proposal) => proposal.id),
957
+ ...this.attribution(),
867
958
  });
868
959
  children.push(proposal);
869
960
  }
870
- manifest = await this.store.saveMigrationManifest(Object.assign({}, manifest, {
871
- childProposalIds: children.map((proposal) => proposal.id),
872
- plan,
873
- }));
961
+ manifest = await this.store.saveMigrationManifest(
962
+ Object.assign({}, manifest, {
963
+ childProposalIds: children.map((proposal) => proposal.id),
964
+ plan,
965
+ }),
966
+ );
874
967
  return { created: true, manifest, proposals: children };
875
968
  } catch (error) {
876
969
  children.forEach((proposal) => this.store.removeProposal(proposal.id));
@@ -889,8 +982,14 @@ class ConceptAuthoringService {
889
982
  return this.store.getProposal(input && input.proposalId);
890
983
  }
891
984
 
985
+ // A stored proposal is judged again before acceptance writes anything,
986
+ // against the actor recorded on it, else the accepting one (plan W-1).
892
987
  async acceptProposal(input) {
893
- return this.store.acceptProposal(input && input.proposalId, this, {
988
+ const { refused, acceptor } = await prepareAcceptance(this, input?.proposalId);
989
+ if (refused) {
990
+ return refused;
991
+ }
992
+ return this.store.acceptProposal(input && input.proposalId, acceptor, {
894
993
  allowComputation: Boolean(input && input.allowComputation),
895
994
  });
896
995
  }