@mfdaves/okf-mcp 0.9.1 → 0.12.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 (97) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +172 -17
  3. package/bin/okf-mcp.js +6 -1
  4. package/okf/okf-mcp/policies/authoring-safety.md +11 -1
  5. package/package.json +17 -5
  6. package/server.json +2 -2
  7. package/src/assets.js +165 -73
  8. package/src/authoring/candidates.js +391 -0
  9. package/src/authoring/git-preflight.js +225 -0
  10. package/src/authoring/git-publish.js +776 -0
  11. package/src/authoring/live.js +789 -0
  12. package/src/authoring/paths.js +112 -0
  13. package/src/authoring/policy-hook.js +221 -0
  14. package/src/authoring/proposal-policy.js +137 -0
  15. package/src/authoring/receipts.js +329 -0
  16. package/src/authoring/render.js +38 -0
  17. package/src/authoring/shared.js +75 -0
  18. package/src/authoring/staging.js +216 -0
  19. package/src/authoring.js +386 -287
  20. package/src/cache/files.js +147 -0
  21. package/src/cache/lock.js +201 -0
  22. package/src/cache/paths.js +197 -0
  23. package/src/cache/store.js +703 -0
  24. package/src/catalog-text.js +19 -0
  25. package/src/cli.js +184 -151
  26. package/src/computation.js +99 -61
  27. package/src/context/assemble.js +567 -0
  28. package/src/context/cli-options.js +88 -0
  29. package/src/context/score.js +234 -0
  30. package/src/context/sections.js +274 -0
  31. package/src/embed/interface.js +160 -0
  32. package/src/embed/openai.js +715 -0
  33. package/src/embed/prepare.js +182 -0
  34. package/src/embed/units.js +96 -0
  35. package/src/git-source.js +112 -52
  36. package/src/graph.js +95 -37
  37. package/src/http-server.js +36 -17
  38. package/src/index.js +15 -0
  39. package/src/indexer/assemble.js +566 -0
  40. package/src/indexer/build.js +290 -0
  41. package/src/indexer/cache.js +81 -0
  42. package/src/indexer/edges.js +430 -0
  43. package/src/indexer/index.js +44 -0
  44. package/src/indexer/paths.js +178 -0
  45. package/src/indexer/resolve.js +282 -0
  46. package/src/indexer/update.js +720 -0
  47. package/src/indexer.js +3 -1068
  48. package/src/live-authoring.js +4 -2329
  49. package/src/markdown.js +21 -16
  50. package/src/mcp/registry.js +328 -0
  51. package/src/mcp/resources.js +45 -0
  52. package/src/mcp/server.js +472 -0
  53. package/src/mcp/tools/catalog.js +244 -0
  54. package/src/mcp/tools/computation.js +83 -0
  55. package/src/mcp/tools/context.js +133 -0
  56. package/src/mcp/tools/graph.js +167 -0
  57. package/src/mcp/tools/live-authoring.js +316 -0
  58. package/src/mcp/tools/migration.js +86 -0
  59. package/src/mcp/tools/producers.js +79 -0
  60. package/src/mcp/tools/proposals.js +213 -0
  61. package/src/mcp/tools/provenance.js +87 -0
  62. package/src/mcp/tools/remote.js +79 -0
  63. package/src/mcp/tools/search.js +242 -0
  64. package/src/mcp-server.js +3 -1611
  65. package/src/migration.js +431 -253
  66. package/src/parser.js +245 -130
  67. package/src/plugins.js +71 -48
  68. package/src/policy/write-policy.js +713 -0
  69. package/src/producer-publisher.js +195 -77
  70. package/src/producers.js +265 -101
  71. package/src/project.js +277 -93
  72. package/src/remote.js +96 -61
  73. package/src/search/cli-options.js +107 -0
  74. package/src/search/confidence.js +61 -0
  75. package/src/search/dense.js +304 -0
  76. package/src/search/embedding-cli.js +57 -0
  77. package/src/search/embedding-config.js +217 -0
  78. package/src/search/fusion.js +249 -0
  79. package/src/search/hybrid.js +526 -0
  80. package/src/search/languages.js +200 -0
  81. package/src/search/lexical.js +695 -0
  82. package/src/search/query.js +620 -0
  83. package/src/search/stem/among.js +43 -0
  84. package/src/search/stem/base-stemmer.js +311 -0
  85. package/src/search/stem/en-regions.js +456 -0
  86. package/src/search/stem/en-suffixes.js +664 -0
  87. package/src/search/stem/en-tables.js +176 -0
  88. package/src/search/stem/en.js +238 -0
  89. package/src/search/stem/it-regions.js +459 -0
  90. package/src/search/stem/it-suffixes.js +471 -0
  91. package/src/search/stem/it-tables.js +257 -0
  92. package/src/search/stem/it.js +155 -0
  93. package/src/search-index.js +2 -81
  94. package/src/search.js +2 -252
  95. package/src/store.js +134 -81
  96. package/src/v02.js +301 -105
  97. package/src/validation.js +24 -20
@@ -1,2331 +1,6 @@
1
1
  "use strict";
2
2
 
3
- const crypto = require("node:crypto");
4
- const fs = require("node:fs");
5
- const path = require("node:path");
6
- const { spawnSync: nodeSpawnSync } = require("node:child_process");
7
- const { isDeepStrictEqual } = require("node:util");
8
-
9
- const {
10
- deriveConceptPathSuggestion,
11
- isConfiguredGeneratorOutput,
12
- normalizeConceptPath,
13
- renderConceptMarkdown,
14
- } = require("./authoring");
15
- const {
16
- attachProject,
17
- buildIndex,
18
- bundleAllowsPath,
19
- conceptIsGeneratedFile,
20
- conceptMatchSummary,
21
- normalizeConceptTitle,
22
- recoverConceptLocator,
23
- resolveConcept,
24
- validateIndex,
25
- } = require("./indexer");
26
- const { validActor } = require("./v02");
27
-
28
- const MAX_CHANGES = 100;
29
- const MAX_COMMIT_MESSAGE_BYTES = 1024;
30
- const MAX_EFFECT_ITEMS = 20;
31
- const MAX_EFFECT_TEXT = 240;
32
- const MANAGED_METADATA_KEYS = new Set([
33
- "id",
34
- "type",
35
- "title",
36
- "description",
37
- "tags",
38
- "sources",
39
- "relations",
40
- "generated",
41
- "generated_file",
42
- "generatedFile",
43
- "runtime",
44
- "parameters",
45
- "computation",
46
- "executor",
47
- "attester",
48
- ]);
49
-
50
- class AuthoringPolicyError extends Error {
51
- constructor(message, code, details) {
52
- super(message);
53
- this.name = "AuthoringPolicyError";
54
- if (code) this.code = code;
55
- if (details !== undefined) this.details = details;
56
- }
57
- }
58
-
59
- class AuthoringOperationalError extends Error {
60
- constructor(message) {
61
- super(message);
62
- this.name = "AuthoringOperationalError";
63
- }
64
- }
65
-
66
- function isPlainObject(value) {
67
- if (!value || typeof value !== "object" || Array.isArray(value)) {
68
- return false;
69
- }
70
- const prototype = Object.getPrototypeOf(value);
71
- return prototype === Object.prototype || prototype === null;
72
- }
73
-
74
- function hasOwn(value, key) {
75
- return Boolean(value && Object.prototype.hasOwnProperty.call(value, key));
76
- }
77
-
78
- function nonEmptyString(value, field) {
79
- if (typeof value !== "string" || !value.trim()) {
80
- throw new Error(`${field} must be a non-empty string.`);
81
- }
82
- return value.trim();
83
- }
84
-
85
- function normalizeBody(value) {
86
- return String(value || "").replace(/\r\n/g, "\n").trim();
87
- }
88
-
89
- function canonicalValue(value) {
90
- if (Array.isArray(value)) {
91
- return value.map(canonicalValue);
92
- }
93
- if (isPlainObject(value)) {
94
- return Object.fromEntries(
95
- Object.keys(value).sort().map((key) => [key, canonicalValue(value[key])]),
96
- );
97
- }
98
- return value;
99
- }
100
-
101
- function exactKey(value) {
102
- return JSON.stringify(canonicalValue(value));
103
- }
104
-
105
- function uniqueStrings(values, field) {
106
- if (values === undefined) {
107
- return [];
108
- }
109
- if (!Array.isArray(values)) {
110
- throw new Error(`${field} must be an array.`);
111
- }
112
- const seen = new Set();
113
- const normalized = [];
114
- values.forEach((value, index) => {
115
- const item = nonEmptyString(value, `${field}[${index}]`);
116
- if (!seen.has(item)) {
117
- seen.add(item);
118
- normalized.push(item);
119
- }
120
- });
121
- return normalized;
122
- }
123
-
124
- function normalizeSource(value, field) {
125
- if (typeof value === "string") {
126
- return { resource: nonEmptyString(value, field) };
127
- }
128
- if (!isPlainObject(value)) {
129
- throw new Error(`${field} must be a resource string or source object.`);
130
- }
131
- return Object.assign({}, value);
132
- }
133
-
134
- function sourceIdentity(source) {
135
- if (typeof source === "string" && source.trim()) {
136
- return `resource:${source.trim()}`;
137
- }
138
- if (isPlainObject(source) && typeof source.id === "string" && source.id.trim()) {
139
- return `id:${source.id.trim()}`;
140
- }
141
- if (isPlainObject(source) && typeof source.resource === "string" && source.resource.trim()) {
142
- return `resource:${source.resource.trim()}`;
143
- }
144
- return `exact:${exactKey(source)}`;
145
- }
146
-
147
- function sourceMatches(source, selector) {
148
- const sourceId = isPlainObject(source) && typeof source.id === "string"
149
- ? source.id.trim()
150
- : "";
151
- const sourceResource = typeof source === "string"
152
- ? source.trim()
153
- : isPlainObject(source) && typeof source.resource === "string"
154
- ? source.resource.trim()
155
- : "";
156
- if (typeof selector === "string") {
157
- const value = selector.trim();
158
- return sourceId === value || sourceResource === value;
159
- }
160
- if (!isPlainObject(selector)) {
161
- return false;
162
- }
163
- if (typeof selector.id === "string" && selector.id.trim()) {
164
- return sourceId === selector.id.trim();
165
- }
166
- if (typeof selector.resource === "string" && selector.resource.trim()) {
167
- return sourceResource === selector.resource.trim();
168
- }
169
- return false;
170
- }
171
-
172
- function validateSourceSelector(selector, field) {
173
- if (typeof selector === "string") {
174
- nonEmptyString(selector, field);
175
- return;
176
- }
177
- if (!isPlainObject(selector)) {
178
- throw new Error(`${field} must select a source by id or resource.`);
179
- }
180
- const hasId = typeof selector.id === "string" && selector.id.trim();
181
- const hasResource = typeof selector.resource === "string" && selector.resource.trim();
182
- if (!hasId && !hasResource) {
183
- throw new Error(`${field} must select a source by id or resource.`);
184
- }
185
- }
186
-
187
- function applySourcePatch(existing, patch, field) {
188
- if (!isPlainObject(patch)) {
189
- throw new Error(`${field} must be an object containing add and/or remove arrays.`);
190
- }
191
- const remove = patch.remove === undefined ? [] : patch.remove;
192
- if (!Array.isArray(remove)) {
193
- throw new Error(`${field}.remove must be an array.`);
194
- }
195
- remove.forEach((selector, index) => validateSourceSelector(selector, `${field}.remove[${index}]`));
196
- let result = Array.isArray(existing) ? existing.slice() : [];
197
- result = result.filter((source) => !remove.some((selector) => sourceMatches(source, selector)));
198
- const additions = patch.add === undefined ? [] : patch.add;
199
- if (!Array.isArray(additions)) {
200
- throw new Error(`${field}.add must be an array.`);
201
- }
202
- additions.map((source, index) => normalizeSource(source, `${field}.add[${index}]`)).forEach((source) => {
203
- const identity = sourceIdentity(source);
204
- const existingIndex = result.findIndex((candidate) => sourceIdentity(candidate) === identity);
205
- if (existingIndex === -1) {
206
- result.push(source);
207
- } else if (!isDeepStrictEqual(result[existingIndex], source)) {
208
- result[existingIndex] = source;
209
- }
210
- });
211
- const seen = new Set();
212
- return result.filter((source) => {
213
- const identity = sourceIdentity(source);
214
- if (seen.has(identity)) {
215
- return false;
216
- }
217
- seen.add(identity);
218
- return true;
219
- });
220
- }
221
-
222
- function relationParts(value) {
223
- if (typeof value === "string") {
224
- const parts = value.trim().split(/\s+/);
225
- return {
226
- type: parts.length > 1 ? parts.shift() : "related_to",
227
- target: parts.join(" ") || value.trim(),
228
- };
229
- }
230
- if (isPlainObject(value)) {
231
- return {
232
- type: String(value.type || value.kind || "related_to").trim(),
233
- target: String(value.target || value.to || "").trim(),
234
- };
235
- }
236
- return { type: "", target: "" };
237
- }
238
-
239
- function relationKey(value) {
240
- const relation = relationParts(value);
241
- return `${relation.type}\u0000${relation.target}`;
242
- }
243
-
244
- function normalizeRelation(value, field) {
245
- if (!isPlainObject(value)) {
246
- throw new Error(`${field} must be an object.`);
247
- }
248
- const type = nonEmptyString(value.type, `${field}.type`);
249
- const target = nonEmptyString(value.target, `${field}.target`);
250
- const relation = { type, target };
251
- if (hasOwn(value, "label")) {
252
- relation.label = String(value.label);
253
- }
254
- if (hasOwn(value, "description")) {
255
- relation.description = String(value.description);
256
- }
257
- return relation;
258
- }
259
-
260
- function applyRelationPatch(existing, patch, field) {
261
- if (!isPlainObject(patch)) {
262
- throw new Error(`${field} must be an object containing add and/or remove arrays.`);
263
- }
264
- const remove = patch.remove === undefined ? [] : patch.remove;
265
- if (!Array.isArray(remove)) {
266
- throw new Error(`${field}.remove must be an array.`);
267
- }
268
- const removeKeys = new Set(remove.map((relation, index) => (
269
- relationKey(normalizeRelation(relation, `${field}.remove[${index}]`))
270
- )));
271
- let result = (Array.isArray(existing) ? existing : [])
272
- .filter((relation) => !removeKeys.has(relationKey(relation)));
273
- const additions = patch.add === undefined ? [] : patch.add;
274
- if (!Array.isArray(additions)) {
275
- throw new Error(`${field}.add must be an array.`);
276
- }
277
- additions.map((relation, index) => normalizeRelation(relation, `${field}.add[${index}]`)).forEach((relation) => {
278
- const key = relationKey(relation);
279
- const existingIndex = result.findIndex((candidate) => relationKey(candidate) === key);
280
- if (existingIndex === -1) {
281
- result.push(relation);
282
- } else if (!isDeepStrictEqual(result[existingIndex], relation)) {
283
- result[existingIndex] = relation;
284
- }
285
- });
286
- const seen = new Set();
287
- return result.filter((relation) => {
288
- const key = relationKey(relation);
289
- if (seen.has(key)) {
290
- return false;
291
- }
292
- seen.add(key);
293
- return true;
294
- });
295
- }
296
-
297
- function applyTagPatch(existing, patch, field) {
298
- if (!isPlainObject(patch)) {
299
- throw new Error(`${field} must be an object containing add and/or remove arrays.`);
300
- }
301
- const additions = uniqueStrings(patch.add, `${field}.add`);
302
- const removals = new Set(uniqueStrings(patch.remove, `${field}.remove`));
303
- const seen = new Set();
304
- return (Array.isArray(existing) ? existing : [])
305
- .filter((tag) => !removals.has(tag))
306
- .concat(additions)
307
- .filter((tag) => {
308
- if (seen.has(tag)) {
309
- return false;
310
- }
311
- seen.add(tag);
312
- return true;
313
- });
314
- }
315
-
316
- function validateMetadata(metadata, field) {
317
- if (metadata === undefined) {
318
- return {};
319
- }
320
- if (!isPlainObject(metadata)) {
321
- throw new Error(`${field} must be an object.`);
322
- }
323
- Object.keys(metadata).forEach((key) => {
324
- if (MANAGED_METADATA_KEYS.has(key)) {
325
- throw new Error(`${field}.${key} is server-managed; use its dedicated field instead.`);
326
- }
327
- });
328
- return Object.assign({}, metadata);
329
- }
330
-
331
- function validateRemovalKeys(keys, field) {
332
- const values = uniqueStrings(keys, field);
333
- values.forEach((key) => {
334
- if (MANAGED_METADATA_KEYS.has(key)) {
335
- throw new Error(`${field} cannot remove server-managed field: ${key}`);
336
- }
337
- });
338
- return values;
339
- }
340
-
341
- function actorValue(value) {
342
- const actor = nonEmptyString(value, "actor");
343
- if (!validActor(actor)) {
344
- throw new Error("actor must use human:<id>, process:<id>, or provider/model syntax.");
345
- }
346
- return actor;
347
- }
348
-
349
- function generatedOwners(document) {
350
- const owners = [];
351
- const generated = document && document.frontmatter && document.frontmatter.generated;
352
- if (isPlainObject(generated) && typeof generated.by === "string") {
353
- owners.push(generated.by);
354
- }
355
- const normalized = document && document.signals && document.signals.generated;
356
- if (isPlainObject(normalized) && typeof normalized.by === "string") {
357
- owners.push(normalized.by);
358
- }
359
- return owners;
360
- }
361
-
362
- function commandOutput(result) {
363
- return String((result && (result.stderr || result.stdout)) || "").trim().slice(0, 4000);
364
- }
365
-
366
- function commandFailure(result, fallback) {
367
- return commandOutput(result)
368
- || (result && result.error && result.error.message)
369
- || fallback;
370
- }
371
-
372
- function commandSucceeded(result) {
373
- return Boolean(result && !result.error && result.status === 0);
374
- }
375
-
376
- function revisionFor(text) {
377
- return `sha256:${crypto.createHash("sha256").update(text).digest("hex")}`;
378
- }
379
-
380
- function byteLength(text) {
381
- return Buffer.byteLength(String(text || ""), "utf8");
382
- }
383
-
384
- function sortedUnique(values) {
385
- return Array.from(new Set(values)).sort();
386
- }
387
-
388
- function boundedEffectList(values, project) {
389
- const normalized = project
390
- ? values.map(project)
391
- : sortedUnique(values).map(boundedEffectText);
392
- return {
393
- values: normalized.slice(0, MAX_EFFECT_ITEMS),
394
- omitted: Math.max(0, normalized.length - MAX_EFFECT_ITEMS),
395
- };
396
- }
397
-
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) {
419
- const previous = new Map((before || []).map((value) => [identity(value), value]));
420
- const next = new Map((after || []).map((value) => [identity(value), value]));
421
- const added = Array.from(next.keys()).filter((key) => !previous.has(key)).sort();
422
- const removed = Array.from(previous.keys()).filter((key) => !next.has(key)).sort();
423
- const updated = Array.from(next.keys()).filter((key) => (
424
- previous.has(key) && !isDeepStrictEqual(previous.get(key), next.get(key))
425
- )).sort();
426
- const effectList = (keys, values) => boundedEffectList(
427
- project ? keys.map((key) => values.get(key)) : keys,
428
- project,
429
- );
430
- return {
431
- added: effectList(added, next),
432
- removed: effectList(removed, previous),
433
- updated: effectList(updated, next),
434
- };
435
- }
436
-
437
- function metadataEffects(before, after) {
438
- const excluded = new Set(["tags", "sources", "relations", "generated"]);
439
- const keys = sortedUnique(Object.keys(before || {}).concat(Object.keys(after || {})))
440
- .filter((key) => !excluded.has(key));
441
- return {
442
- set: boundedEffectList(keys.filter((key) => hasOwn(after, key) && !isDeepStrictEqual(before[key], after[key]))),
443
- removed: boundedEffectList(keys.filter((key) => hasOwn(before, key) && !hasOwn(after, key))),
444
- };
445
- }
446
-
447
- function effectsForCandidate(candidate) {
448
- const before = candidate.op === "update" ? candidate.originalFrontmatter : {};
449
- const after = candidate.frontmatter;
450
- const tags = collectionEffects(before.tags, after.tags, (value) => String(value));
451
- const sources = collectionEffects(before.sources, after.sources, sourceIdentity);
452
- const relations = collectionEffects(before.relations, after.relations, relationKey, relationEffectValue);
453
- const metadata = metadataEffects(before, after);
454
- const bodyChanged = candidate.op === "create"
455
- ? true
456
- : normalizeBody(candidate.originalBody) !== normalizeBody(candidate.body);
457
- const changedFields = [];
458
- if (bodyChanged) changedFields.push("body");
459
- const hasEffect = (group) => group.values.length || group.omitted;
460
- if (hasEffect(tags.added) || hasEffect(tags.removed) || hasEffect(tags.updated)) changedFields.push("tags");
461
- if (hasEffect(sources.added) || hasEffect(sources.removed) || hasEffect(sources.updated)) changedFields.push("sources");
462
- if (hasEffect(relations.added) || hasEffect(relations.removed) || hasEffect(relations.updated)) changedFields.push("relations");
463
- if (hasEffect(metadata.set) || hasEffect(metadata.removed)) changedFields.push("metadata");
464
- return {
465
- changedFields,
466
- bodyChanged,
467
- tags,
468
- sources,
469
- relations,
470
- metadata,
471
- beforeRevision: candidate.baseRevision,
472
- afterRevision: candidate.publishedRevision,
473
- bytesBefore: candidate.originalText === undefined ? 0 : byteLength(candidate.originalText),
474
- bytesAfter: byteLength(candidate.markdown),
475
- };
476
- }
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
-
519
- function policyCode(message) {
520
- const text = String(message || "");
521
- if (/generated|generator/i.test(text)) return "generated_owner_protected";
522
- if (/Attested Computation|computation contract/i.test(text)) return "computation_authoring_prohibited";
523
- if (/excluded by the bundle policy/i.test(text)) return "excluded_target";
524
- if (/no effective changes/i.test(text)) return "no_effective_changes";
525
- if (/same concept more than once/i.test(text)) return "duplicate_batch_target";
526
- if (/already exists/i.test(text)) return "target_exists";
527
- if (/unknown valid OKF concept/i.test(text)) return "concept_not_found";
528
- if (/server-managed/i.test(text)) return "managed_metadata_protected";
529
- if (/1 through \d+ operations/i.test(text)) return "invalid_batch_size";
530
- if (/outside|travers|safe relative|unsafe segment|reserved index|reserved .*file|Markdown file|Markdown path/i.test(text)) return "unsafe_target_path";
531
- if (/worktree must be completely clean/i.test(text)) return "git_worktree_dirty";
532
- if (/Git filter attributes|repository-configured filters/i.test(text)) return "git_filter_attribute_unsupported";
533
- if (/assume-unchanged|skip-worktree|Git index flags/i.test(text)) return "git_index_flag_unsupported";
534
- if (/detached HEAD|symbolic branch|checked-out Git ref/i.test(text)) return "git_head_ref_unsupported";
535
- if (/Git user\.(name|email)/i.test(text)) return "git_identity_missing";
536
- if (/must have an existing HEAD/i.test(text)) return "git_head_missing";
537
- if (/commit message/i.test(text)) return "invalid_commit_message";
538
- return "authoring_policy_rejected";
539
- }
540
-
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
- };
552
- return {
553
- valid: false,
554
- conformant: false,
555
- validForProject: false,
556
- diagnostics: [diagnostic],
557
- errors: [{ code, message, ...(details !== undefined ? { details } : {}) }],
558
- warnings: [],
559
- };
560
- }
561
-
562
- function temporaryPath(target) {
563
- return path.join(
564
- path.dirname(target),
565
- `.${path.basename(target)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`,
566
- );
567
- }
568
-
569
- function restoreFile(target, text, mode) {
570
- const temporary = temporaryPath(target);
571
- try {
572
- fs.writeFileSync(temporary, text, { encoding: "utf8", flag: "wx" });
573
- if (mode !== null && mode !== undefined) {
574
- fs.chmodSync(temporary, mode);
575
- }
576
- fs.renameSync(temporary, target);
577
- } finally {
578
- if (fs.existsSync(temporary)) {
579
- fs.unlinkSync(temporary);
580
- }
581
- }
582
- }
583
-
584
- class LiveAuthoringService {
585
- constructor(store, options) {
586
- const config = options || {};
587
- this.store = store;
588
- this.actor = actorValue(config.actor);
589
- this.gitCommit = Boolean(config.gitCommit);
590
- this.spawnSync = config.spawnSync || nodeSpawnSync;
591
- this.now = config.now || (() => new Date());
592
- }
593
-
594
- getBundle(id) {
595
- const bundles = this.store.getBundles();
596
- const bundle = id
597
- ? bundles.find((entry) => entry.id === id)
598
- : bundles.length === 1
599
- ? bundles[0]
600
- : null;
601
- if (!bundle) {
602
- throw new Error(id
603
- ? `Unknown writable OKF bundle: ${id}`
604
- : "A bundle id is required unless exactly one writable OKF root is configured.");
605
- }
606
- return bundle;
607
- }
608
-
609
- buildIndex(additionalBundles, documentOverrides) {
610
- const index = buildIndex(this.store.getBundles().concat(additionalBundles || []), {
611
- relationTypes: this.store.getRelationTypes(),
612
- strictLinks: this.store.strictLinks,
613
- allowCustomRelationTypes: this.store.allowCustomRelationTypes,
614
- documentOverrides,
615
- });
616
- return this.store.project ? attachProject(index, this.store.project) : index;
617
- }
618
-
619
- assertWritableTarget(bundle, conceptPath, existing) {
620
- const target = this.store.resolveConceptFile(bundle.id, conceptPath);
621
- if (isConfiguredGeneratorOutput(this.store.project, target.absolutePath)) {
622
- throw new Error(`Concept is inside a configured generator output and must be changed through its generator: ${conceptPath}`);
623
- }
624
- if (existing && conceptIsManaged(existing, this.store.project)) {
625
- throw new Error(`Generated concept must be changed through its generator: ${existing.uri}`);
626
- }
627
- return target;
628
- }
629
-
630
- createCandidate(change, bundle, currentIndex, generated) {
631
- const type = nonEmptyString(change.type, "changes[].type");
632
- if (type === "Attested Computation") {
633
- throw new Error("Live concept authoring cannot create Attested Computation contracts.");
634
- }
635
- const title = nonEmptyString(change.title, "changes[].title");
636
- const conceptPath = normalizeConceptPath(
637
- change.path || deriveConceptPathSuggestion(currentIndex, bundle, { type, title }).path,
638
- );
639
- if (!bundleAllowsPath(bundle, conceptPath)) {
640
- throw new Error(`Concept path is excluded by the bundle policy: ${conceptPath}`);
641
- }
642
- const target = this.assertWritableTarget(bundle, conceptPath, null);
643
- if (fs.existsSync(target.absolutePath)) {
644
- throw new Error(`Concept file already exists: ${conceptPath}`);
645
- }
646
- const metadata = validateMetadata(change.metadata, "changes[].metadata");
647
- const frontmatter = Object.assign({ type, title }, metadata);
648
- if (hasOwn(change, "description")) {
649
- frontmatter.description = String(change.description);
650
- }
651
- const tags = uniqueStrings(change.tags, "changes[].tags");
652
- if (change.sources !== undefined && !Array.isArray(change.sources)) {
653
- throw new Error("changes[].sources must be an array.");
654
- }
655
- if (change.relations !== undefined && !Array.isArray(change.relations)) {
656
- throw new Error("changes[].relations must be an array.");
657
- }
658
- const sources = (change.sources || [])
659
- .map((source, index) => normalizeSource(source, `changes[].sources[${index}]`));
660
- const relations = (change.relations || [])
661
- .map((relation, index) => normalizeRelation(relation, `changes[].relations[${index}]`));
662
- if (tags.length) frontmatter.tags = tags;
663
- if (sources.length) frontmatter.sources = applySourcePatch([], { add: sources }, "changes[].sources");
664
- if (relations.length) frontmatter.relations = applyRelationPatch([], { add: relations }, "changes[].relations");
665
- frontmatter.generated = generated;
666
- const body = hasOwn(change, "body") ? String(change.body || "") : `# ${title}`;
667
- const markdown = renderConceptMarkdown({ path: conceptPath, frontmatter, body });
668
- return {
669
- op: "create",
670
- bundle: bundle.id,
671
- path: conceptPath,
672
- uri: `okf://${bundle.id}/${conceptPath.replace(/\.md$/i, "")}`,
673
- title,
674
- frontmatter,
675
- body,
676
- markdown,
677
- target,
678
- baseRevision: null,
679
- publishedRevision: revisionFor(markdown),
680
- originalFrontmatter: {},
681
- originalBody: "",
682
- };
683
- }
684
-
685
- updateCandidate(change, bundle, currentIndex, generated) {
686
- const uri = nonEmptyString(change.uri, "changes[].uri");
687
- const existing = resolveConcept(currentIndex, uri);
688
- if (!existing || !existing.valid || existing.reserved) {
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
- );
695
- }
696
- if (existing.bundle !== bundle.id) {
697
- throw new Error(`All changes must target writable bundle ${bundle.id}: ${uri}`);
698
- }
699
- if (existing.type === "Attested Computation") {
700
- throw new Error("Live concept authoring cannot modify Attested Computation contracts or code.");
701
- }
702
- const target = this.assertWritableTarget(bundle, existing.path, existing);
703
- const originalText = fs.readFileSync(target.absolutePath, "utf8");
704
- const originalMode = fs.statSync(target.absolutePath).mode;
705
- const indexedRevision = revisionFor(existing.text);
706
- const diskRevision = revisionFor(originalText);
707
- if (indexedRevision !== diskRevision) {
708
- throw new Error(`Concept changed after it was indexed; retry the update: ${existing.uri}`);
709
- }
710
- const frontmatter = Object.assign({}, existing.frontmatter);
711
- Object.assign(frontmatter, validateMetadata(change.metadata, "changes[].metadata"));
712
- validateRemovalKeys(change.removeMetadataKeys, "changes[].removeMetadataKeys").forEach((key) => {
713
- delete frontmatter[key];
714
- });
715
- if (hasOwn(change, "title")) {
716
- frontmatter.title = nonEmptyString(change.title, "changes[].title");
717
- }
718
- if (hasOwn(change, "description")) {
719
- frontmatter.description = String(change.description);
720
- }
721
- if (hasOwn(change, "tags")) {
722
- frontmatter.tags = applyTagPatch(frontmatter.tags, change.tags, "changes[].tags");
723
- }
724
- if (hasOwn(change, "sources")) {
725
- frontmatter.sources = applySourcePatch(frontmatter.sources, change.sources, "changes[].sources");
726
- }
727
- if (hasOwn(change, "relations")) {
728
- frontmatter.relations = applyRelationPatch(frontmatter.relations, change.relations, "changes[].relations");
729
- }
730
- const body = hasOwn(change, "body") ? String(change.body || "") : existing.body;
731
- if (isDeepStrictEqual(frontmatter, existing.frontmatter)
732
- && normalizeBody(body) === normalizeBody(existing.body)) {
733
- throw new Error(`Update has no effective changes: ${existing.uri}`);
734
- }
735
- frontmatter.generated = Object.assign(
736
- {},
737
- isPlainObject(existing.frontmatter.generated) ? existing.frontmatter.generated : {},
738
- generated,
739
- );
740
- const markdown = renderConceptMarkdown({ path: existing.path, frontmatter, body });
741
- return {
742
- op: "update",
743
- bundle: bundle.id,
744
- path: existing.path,
745
- uri: existing.uri,
746
- title: frontmatter.title || existing.title,
747
- frontmatter,
748
- body,
749
- markdown,
750
- target,
751
- baseRevision: diskRevision,
752
- publishedRevision: revisionFor(markdown),
753
- originalText,
754
- originalMode,
755
- originalFrontmatter: Object.assign({}, existing.frontmatter),
756
- originalBody: existing.body,
757
- };
758
- }
759
-
760
- validationResult(index, candidates) {
761
- const validation = validateIndex(index);
762
- const candidateDiagnostics = [];
763
- candidates.forEach((candidate) => {
764
- const document = index.byPathUri.get(`okf://${candidate.bundle}/${candidate.path}`);
765
- if (!document || document.reserved || !document.valid) {
766
- candidateDiagnostics.push({
767
- code: "candidate_not_indexed",
768
- severity: "error",
769
- layer: "project",
770
- bundle: candidate.bundle,
771
- path: candidate.path,
772
- message: "Candidate did not become a valid concept in the future graph.",
773
- });
774
- return;
775
- }
776
- (document.warnings || []).filter((entry) => entry.layer === "v0.2").forEach((entry) => {
777
- candidateDiagnostics.push(Object.assign({}, entry, {
778
- severity: "error",
779
- bundle: candidate.bundle,
780
- path: candidate.path,
781
- }));
782
- });
783
- });
784
- const diagnostics = validation.diagnostics.concat(candidateDiagnostics);
785
- return {
786
- valid: validation.valid && candidateDiagnostics.length === 0,
787
- conformant: validation.conformant,
788
- validForProject: validation.validForProject && candidateDiagnostics.length === 0,
789
- diagnostics,
790
- errors: validation.errors,
791
- warnings: validation.warnings,
792
- };
793
- }
794
-
795
- runGit(directory, args, options) {
796
- const environment = Object.assign({}, process.env);
797
- Object.keys(environment).filter((key) => key.startsWith("GIT_")).forEach((key) => {
798
- delete environment[key];
799
- });
800
- if (options && options.environment) {
801
- Object.assign(environment, options.environment);
802
- }
803
- environment.GIT_LITERAL_PATHSPECS = "1";
804
- environment.GIT_TERMINAL_PROMPT = "0";
805
- environment.GIT_PAGER = "cat";
806
- environment.GIT_NO_REPLACE_OBJECTS = "1";
807
- if (options && options.readOnly) {
808
- environment.GIT_OPTIONAL_LOCKS = "0";
809
- }
810
- const spawnOptions = {
811
- encoding: "utf8",
812
- shell: false,
813
- maxBuffer: 8 * 1024 * 1024,
814
- timeout: 15000,
815
- env: environment,
816
- };
817
- if (options && hasOwn(options, "input")) {
818
- spawnOptions.input = options.input;
819
- }
820
- try {
821
- return this.spawnSync("git", [
822
- "-C",
823
- directory,
824
- "-c",
825
- "core.hooksPath=/dev/null",
826
- "-c",
827
- "core.fsmonitor=false",
828
- "-c",
829
- "commit.gpgSign=false",
830
- "-c",
831
- "diff.external=",
832
- ].concat(args), spawnOptions);
833
- } catch (error) {
834
- return { status: null, stdout: "", stderr: "", error };
835
- }
836
- }
837
-
838
- readGitValue(repository, args, options) {
839
- const result = this.runGit(repository, args, options);
840
- return commandSucceeded(result) ? String(result.stdout || "").trim() : null;
841
- }
842
-
843
- activeGitFilterAttributes(repository, candidates) {
844
- const tracked = this.runGit(repository, ["ls-files", "-z"], { readOnly: true });
845
- if (!commandSucceeded(tracked)) {
846
- throw new AuthoringOperationalError(
847
- `Could not inspect tracked Git paths: ${commandFailure(tracked, "git ls-files failed")}`,
848
- );
849
- }
850
- const paths = sortedUnique(
851
- String(tracked.stdout || "").split("\0").filter(Boolean)
852
- .concat(this.repositoryFiles({ repository }, candidates)),
853
- );
854
- const active = [];
855
- for (let offset = 0; offset < paths.length; offset += 200) {
856
- const chunk = paths.slice(offset, offset + 200);
857
- const inspected = this.runGit(
858
- repository,
859
- ["check-attr", "-z", "--all", "--"].concat(chunk),
860
- { readOnly: true },
861
- );
862
- if (!commandSucceeded(inspected)) {
863
- throw new AuthoringOperationalError(
864
- `Could not inspect Git filter attributes: ${commandFailure(inspected, "git check-attr failed")}`,
865
- );
866
- }
867
- const values = String(inspected.stdout || "").split("\0");
868
- for (let index = 0; index + 2 < values.length; index += 3) {
869
- const attribute = values[index + 1];
870
- if (attribute === "filter") {
871
- active.push({ path: values[index], filter: values[index + 2] || "set" });
872
- }
873
- }
874
- }
875
- return active;
876
- }
877
-
878
- unsupportedGitIndexFlags(repository) {
879
- const inspected = this.runGit(repository, ["ls-files", "-v", "-z"], { readOnly: true });
880
- if (!commandSucceeded(inspected)) {
881
- throw new AuthoringOperationalError(
882
- `Could not inspect Git index flags: ${commandFailure(inspected, "git ls-files failed")}`,
883
- );
884
- }
885
- return String(inspected.stdout || "").split("\0").filter(Boolean).flatMap((entry) => {
886
- const tag = entry[0] || "";
887
- const flagged = tag === "S" || (/[a-z]/.test(tag) && tag === tag.toLowerCase());
888
- if (!flagged) {
889
- return [];
890
- }
891
- return [{
892
- path: entry.slice(2),
893
- flag: tag === "S" ? "skip-worktree" : "assume-unchanged",
894
- }];
895
- });
896
- }
897
-
898
- prepareGit(bundle, candidates) {
899
- const preflight = {
900
- enabled: this.gitCommit,
901
- repository: null,
902
- repositoryStatus: this.gitCommit ? "not_git_repository" : "not_inspected",
903
- repositoryRoot: null,
904
- headBefore: null,
905
- headRef: null,
906
- worktreeClean: null,
907
- identityConfigured: null,
908
- ready: !this.gitCommit,
909
- diagnostics: [],
910
- };
911
- if (!this.gitCommit) {
912
- return preflight;
913
- }
914
- const discovered = this.runGit(bundle.root, ["rev-parse", "--show-toplevel"], { readOnly: true });
915
- if (discovered.error) {
916
- if (this.gitCommit) {
917
- throw new AuthoringOperationalError(`Git executable is unavailable: ${discovered.error.message}`);
918
- }
919
- return Object.assign(preflight, {
920
- repositoryStatus: "unavailable",
921
- inspectionError: discovered.error.message,
922
- });
923
- }
924
- if (discovered.status !== 0) {
925
- const detail = commandOutput(discovered);
926
- if (/not a git repository/i.test(detail)) {
927
- preflight.ready = true;
928
- return preflight;
929
- }
930
- if (this.gitCommit) {
931
- throw new AuthoringOperationalError(`Could not inspect Git repository: ${detail || `git exited ${discovered.status}`}`);
932
- }
933
- return Object.assign(preflight, {
934
- repositoryStatus: "inspection_failed",
935
- inspectionError: detail || `git exited ${discovered.status}`,
936
- });
937
- }
938
- const repository = path.resolve(String(discovered.stdout || "").trim());
939
- preflight.repository = repository;
940
- preflight.repositoryRoot = repository;
941
- preflight.repositoryStatus = "detected";
942
- const symbolicHead = this.runGit(
943
- repository,
944
- ["symbolic-ref", "-q", "HEAD"],
945
- { readOnly: true },
946
- );
947
- if (symbolicHead.error || (symbolicHead.status !== 0 && symbolicHead.status !== 1)) {
948
- throw new AuthoringOperationalError(
949
- `Could not inspect the checked-out Git ref: ${commandFailure(symbolicHead, "git symbolic-ref failed")}`,
950
- );
951
- }
952
- const headRef = commandSucceeded(symbolicHead)
953
- ? String(symbolicHead.stdout || "").trim()
954
- : null;
955
- preflight.headRef = headRef;
956
- const headBefore = this.readGitValue(
957
- repository,
958
- ["rev-parse", "--verify", headRef || "HEAD"],
959
- { readOnly: true },
960
- );
961
- preflight.headBefore = headBefore;
962
- const missingIdentity = [];
963
- for (const key of ["user.name", "user.email"]) {
964
- const configured = this.runGit(repository, ["config", "--get", key], { readOnly: true });
965
- if (configured && configured.error) {
966
- throw new AuthoringOperationalError(
967
- `Could not inspect Git ${key}: ${configured.error.message}`,
968
- );
969
- }
970
- if (configured && configured.status !== 0 && configured.status !== 1) {
971
- throw new AuthoringOperationalError(
972
- `Could not inspect Git ${key}: ${commandFailure(configured, `git config exited ${configured.status}`)}`,
973
- );
974
- }
975
- if (!commandSucceeded(configured) || !String(configured.stdout || "").trim()) {
976
- missingIdentity.push(key);
977
- }
978
- }
979
- preflight.identityConfigured = missingIdentity.length === 0;
980
- const unsupportedIndexFlags = this.unsupportedGitIndexFlags(repository);
981
- preflight.unsupportedIndexFlags = unsupportedIndexFlags.slice(0, MAX_EFFECT_ITEMS);
982
- const activeFilters = this.activeGitFilterAttributes(repository, candidates);
983
- preflight.activeFilterAttributes = activeFilters.slice(0, MAX_EFFECT_ITEMS);
984
- if (!activeFilters.length && !unsupportedIndexFlags.length) {
985
- const status = this.runGit(
986
- repository,
987
- ["status", "--porcelain=v1", "--untracked-files=all"],
988
- { readOnly: true },
989
- );
990
- if (!commandSucceeded(status)) {
991
- throw new AuthoringOperationalError(
992
- `Could not inspect Git status: ${commandFailure(status, "git status failed")}`,
993
- );
994
- }
995
- preflight.worktreeClean = !String(status.stdout || "").trim();
996
- }
997
- preflight.ready = !this.gitCommit || Boolean(
998
- headBefore
999
- && headRef
1000
- && preflight.worktreeClean
1001
- && preflight.identityConfigured
1002
- && !activeFilters.length
1003
- && !unsupportedIndexFlags.length,
1004
- );
1005
- if (this.gitCommit && !headBefore) {
1006
- preflight.diagnostics.push({
1007
- code: "git_head_missing",
1008
- message: "Git repository must have an existing HEAD before an automatic OKF commit.",
1009
- });
1010
- }
1011
- if (this.gitCommit && headBefore && !headRef) {
1012
- preflight.diagnostics.push({
1013
- code: "git_detached_head_unsupported",
1014
- message: "Automatic OKF commits require a checked-out symbolic branch; detached HEAD is not supported.",
1015
- });
1016
- }
1017
- if (this.gitCommit && preflight.worktreeClean === false) {
1018
- preflight.diagnostics.push({
1019
- code: "git_worktree_dirty",
1020
- message: "Git worktree must be completely clean before an automatic OKF commit.",
1021
- });
1022
- }
1023
- if (this.gitCommit && missingIdentity.length) {
1024
- preflight.diagnostics.push({
1025
- code: "git_identity_missing",
1026
- message: `Git ${missingIdentity[0]} must be configured before an automatic OKF commit.`,
1027
- });
1028
- }
1029
- if (this.gitCommit && activeFilters.length) {
1030
- preflight.diagnostics.push({
1031
- code: "git_filter_attribute_unsupported",
1032
- message: "Automatic OKF commits reject active Git filter attributes so validation cannot execute repository-configured filters and committed bytes remain exact.",
1033
- paths: activeFilters.slice(0, MAX_EFFECT_ITEMS),
1034
- omitted: Math.max(0, activeFilters.length - MAX_EFFECT_ITEMS),
1035
- });
1036
- }
1037
- if (this.gitCommit && unsupportedIndexFlags.length) {
1038
- preflight.diagnostics.push({
1039
- code: "git_index_flag_unsupported",
1040
- message: "Automatic OKF commits reject assume-unchanged and skip-worktree Git index flags because they can hide user changes from clean-worktree inspection.",
1041
- paths: unsupportedIndexFlags.slice(0, MAX_EFFECT_ITEMS),
1042
- omitted: Math.max(0, unsupportedIndexFlags.length - MAX_EFFECT_ITEMS),
1043
- });
1044
- }
1045
- return preflight;
1046
- }
1047
-
1048
- repositoryFiles(preflight, candidates) {
1049
- const files = sortedUnique(candidates.map((candidate) => (
1050
- path.relative(preflight.repository, candidate.target.absolutePath).replace(/\\/g, "/")
1051
- )));
1052
- if (files.some((file) => !file || file === ".." || file.startsWith("../") || path.isAbsolute(file))) {
1053
- throw new AuthoringPolicyError("An affected concept path is outside the detected Git repository.");
1054
- }
1055
- return files;
1056
- }
1057
-
1058
- inspectGitState(repository, revision, files) {
1059
- const affected = this.runGit(repository, [
1060
- "diff", "--no-ext-diff", "--cached", "--quiet", revision, "--",
1061
- ].concat(files));
1062
- const global = this.runGit(repository, [
1063
- "diff", "--no-ext-diff", "--cached", "--quiet", revision, "--",
1064
- ]);
1065
- const worktree = this.runGit(repository, [
1066
- "status", "--porcelain=v1", "-z", "--untracked-files=all", "--",
1067
- ].concat(files));
1068
- const state = (result) => {
1069
- if (result && !result.error && result.status === 0) return "clean";
1070
- if (result && !result.error && result.status === 1) return "dirty";
1071
- return "unknown";
1072
- };
1073
- return {
1074
- affectedIndexState: state(affected),
1075
- indexState: state(global),
1076
- affectedWorktreeState: !commandSucceeded(worktree)
1077
- ? "unknown"
1078
- : String(worktree.stdout || "").split("\0").filter(Boolean).some((entry) => (
1079
- entry.startsWith("??") || entry.length > 1 && entry[1] !== " "
1080
- )) ? "dirty" : "clean",
1081
- };
1082
- }
1083
-
1084
- classifyCommit(preflight, expectedTree) {
1085
- const headAfter = this.readGitValue(
1086
- preflight.repository,
1087
- ["rev-parse", "--verify", preflight.headRef || "HEAD"],
1088
- );
1089
- if (!headAfter) {
1090
- return { commitState: "unknown", committed: null, headAfter: null };
1091
- }
1092
- if (headAfter === preflight.headBefore) {
1093
- return { commitState: "not_committed", committed: false, headAfter };
1094
- }
1095
- const treeAfter = this.readGitValue(preflight.repository, ["rev-parse", `${headAfter}^{tree}`]);
1096
- const parentAfter = this.readGitValue(preflight.repository, ["rev-parse", `${headAfter}^`]);
1097
- if (expectedTree && treeAfter === expectedTree && parentAfter === preflight.headBefore) {
1098
- return {
1099
- commitState: "committed",
1100
- committed: true,
1101
- commitSha: headAfter,
1102
- headAfter,
1103
- treeAfter,
1104
- };
1105
- }
1106
- return {
1107
- commitState: "unknown",
1108
- committed: null,
1109
- headAfter,
1110
- treeAfter,
1111
- parentAfter,
1112
- };
1113
- }
1114
-
1115
- inspectPublishedTargets(candidates) {
1116
- const checks = candidates.map((candidate) => {
1117
- try {
1118
- const stat = fs.lstatSync(candidate.target.absolutePath);
1119
- if (!stat.isFile() || stat.isSymbolicLink()) {
1120
- return {
1121
- path: candidate.path,
1122
- absolutePath: candidate.target.absolutePath,
1123
- expectedRevision: candidate.publishedRevision,
1124
- observedState: "non_regular",
1125
- observedRevision: null,
1126
- matches: false,
1127
- };
1128
- }
1129
- const observedRevision = revisionFor(fs.readFileSync(candidate.target.absolutePath));
1130
- return {
1131
- path: candidate.path,
1132
- absolutePath: candidate.target.absolutePath,
1133
- expectedRevision: candidate.publishedRevision,
1134
- observedState: "regular",
1135
- observedRevision,
1136
- matches: observedRevision === candidate.publishedRevision,
1137
- };
1138
- } catch (error) {
1139
- return {
1140
- path: candidate.path,
1141
- absolutePath: candidate.target.absolutePath,
1142
- expectedRevision: candidate.publishedRevision,
1143
- observedState: error && error.code === "ENOENT" ? "missing" : "unavailable",
1144
- observedRevision: null,
1145
- matches: false,
1146
- };
1147
- }
1148
- });
1149
- const conflicts = checks.filter((check) => !check.matches);
1150
- return {
1151
- targetState: conflicts.length ? "conflict" : "matching",
1152
- validatedFilesPresent: conflicts.length === 0,
1153
- targetChecks: checks,
1154
- targetConflicts: conflicts,
1155
- };
1156
- }
1157
-
1158
- synchronizeCommittedIndex(preflight, classification, files) {
1159
- const currentHeadRef = this.readGitValue(
1160
- preflight.repository,
1161
- ["symbolic-ref", "-q", "HEAD"],
1162
- );
1163
- if (!preflight.headRef || currentHeadRef !== preflight.headRef) {
1164
- const inspected = this.inspectGitState(
1165
- preflight.repository,
1166
- classification.headAfter,
1167
- files,
1168
- );
1169
- return Object.assign({
1170
- indexSynchronization: "skipped_checkout_changed",
1171
- checkoutState: "changed",
1172
- currentHeadRef,
1173
- indexSynchronizationError: "The checked-out Git ref changed before affected index paths could be synchronized.",
1174
- }, inspected);
1175
- }
1176
- const indexPath = this.gitIndexPath(preflight.repository);
1177
- const headPath = this.gitControlPath(preflight.repository, "HEAD");
1178
- const branchPath = preflight.headRef
1179
- ? this.gitControlPath(preflight.repository, preflight.headRef)
1180
- : null;
1181
- if (!indexPath || !headPath || !branchPath) {
1182
- const inspected = this.inspectGitState(
1183
- preflight.repository,
1184
- classification.headAfter,
1185
- files,
1186
- );
1187
- return Object.assign({
1188
- indexSynchronization: "skipped_index_unavailable",
1189
- indexSynchronizationError: "Could not resolve the Git index path.",
1190
- }, inspected);
1191
- }
1192
- const lockPath = `${indexPath}.lock`;
1193
- const headLockPath = `${headPath}.lock`;
1194
- const branchLockPath = `${branchPath}.lock`;
1195
- let lockDescriptor = null;
1196
- let lockOwned = false;
1197
- let headLockDescriptor = null;
1198
- let headLockOwned = false;
1199
- let branchLockDescriptor = null;
1200
- let branchLockOwned = false;
1201
- let attemptedLock = "index";
1202
- let published = false;
1203
- try {
1204
- const indexStat = fs.statSync(indexPath);
1205
- lockDescriptor = fs.openSync(lockPath, "wx", indexStat.mode & 0o777);
1206
- lockOwned = true;
1207
- fs.writeFileSync(lockDescriptor, fs.readFileSync(indexPath));
1208
- fs.closeSync(lockDescriptor);
1209
- lockDescriptor = null;
1210
- attemptedLock = "checkout";
1211
- headLockDescriptor = fs.openSync(headLockPath, "wx", 0o666);
1212
- headLockOwned = true;
1213
- fs.closeSync(headLockDescriptor);
1214
- headLockDescriptor = null;
1215
- attemptedLock = "branch";
1216
- branchLockDescriptor = fs.openSync(branchLockPath, "wx", 0o666);
1217
- branchLockOwned = true;
1218
- fs.closeSync(branchLockDescriptor);
1219
- branchLockDescriptor = null;
1220
- const lockedHeadRef = this.readGitValue(
1221
- preflight.repository,
1222
- ["symbolic-ref", "-q", "HEAD"],
1223
- );
1224
- const lockedBranchHead = this.readGitValue(
1225
- preflight.repository,
1226
- ["rev-parse", "--verify", preflight.headRef],
1227
- );
1228
- if (lockedHeadRef !== preflight.headRef
1229
- || lockedBranchHead !== classification.headAfter) {
1230
- return {
1231
- indexSynchronization: "skipped_checkout_changed",
1232
- checkoutState: "changed",
1233
- currentHeadRef: lockedHeadRef,
1234
- currentBranchHead: lockedBranchHead,
1235
- indexSynchronizationError: "The checked-out Git ref or its commit changed before affected index paths could be synchronized.",
1236
- affectedIndexState: "unknown",
1237
- indexState: "unknown",
1238
- affectedWorktreeState: "unknown",
1239
- };
1240
- }
1241
- const lockedIndex = { environment: { GIT_INDEX_FILE: lockPath } };
1242
- const candidateIndexChanged = this.runGit(preflight.repository, [
1243
- "diff", "--no-ext-diff", "--cached", "--quiet", preflight.headBefore, "--",
1244
- ].concat(files), lockedIndex);
1245
- if (!commandSucceeded(candidateIndexChanged)) {
1246
- const inspected = this.inspectGitState(
1247
- preflight.repository,
1248
- classification.headAfter,
1249
- files,
1250
- );
1251
- return Object.assign({
1252
- indexSynchronization: candidateIndexChanged && !candidateIndexChanged.error
1253
- && candidateIndexChanged.status === 1
1254
- ? "skipped_affected_index_changed"
1255
- : "skipped_index_unavailable",
1256
- indexSynchronizationError: candidateIndexChanged && !candidateIndexChanged.error
1257
- && candidateIndexChanged.status === 1
1258
- ? "Affected Git index entries changed after preflight and were preserved."
1259
- : commandFailure(candidateIndexChanged, "Could not verify affected Git index entries."),
1260
- }, inspected);
1261
- }
1262
- const reset = this.runGit(preflight.repository, [
1263
- "reset", "--quiet", classification.headAfter, "--",
1264
- ].concat(files), lockedIndex);
1265
- if (!commandSucceeded(reset)) {
1266
- const inspected = this.inspectGitState(
1267
- preflight.repository,
1268
- classification.headAfter,
1269
- files,
1270
- );
1271
- return Object.assign({
1272
- indexSynchronization: "failed",
1273
- indexSynchronizationError: commandFailure(reset, "Could not synchronize committed index paths."),
1274
- }, inspected);
1275
- }
1276
- const verified = this.runGit(preflight.repository, [
1277
- "diff", "--no-ext-diff", "--cached", "--quiet", classification.headAfter, "--",
1278
- ].concat(files), lockedIndex);
1279
- if (!commandSucceeded(verified)) {
1280
- const inspected = this.inspectGitState(
1281
- preflight.repository,
1282
- classification.headAfter,
1283
- files,
1284
- );
1285
- return Object.assign({
1286
- indexSynchronization: "failed_verification",
1287
- indexSynchronizationError: commandFailure(verified, "Synchronized index verification failed."),
1288
- }, inspected);
1289
- }
1290
- fs.renameSync(lockPath, indexPath);
1291
- published = true;
1292
- return Object.assign({
1293
- indexSynchronization: "synchronized",
1294
- }, this.inspectGitState(preflight.repository, classification.headAfter, files));
1295
- } catch (error) {
1296
- const inspected = this.inspectGitState(
1297
- preflight.repository,
1298
- classification.headAfter,
1299
- files,
1300
- );
1301
- return Object.assign({
1302
- indexSynchronization: error && error.code === "EEXIST"
1303
- ? attemptedLock === "index"
1304
- ? "skipped_index_locked"
1305
- : attemptedLock === "checkout"
1306
- ? "skipped_checkout_locked"
1307
- : "skipped_branch_locked"
1308
- : "failed",
1309
- indexSynchronizationError: error && error.code === "EEXIST"
1310
- ? `The Git ${attemptedLock} state is locked by another writer; its state was preserved.`
1311
- : error && error.message ? error.message : String(error),
1312
- }, inspected);
1313
- } finally {
1314
- if (lockDescriptor !== null) {
1315
- try {
1316
- fs.closeSync(lockDescriptor);
1317
- } catch {
1318
- // Best-effort descriptor cleanup after a failed synchronization.
1319
- }
1320
- }
1321
- if (headLockDescriptor !== null) {
1322
- try {
1323
- fs.closeSync(headLockDescriptor);
1324
- } catch {
1325
- // Best-effort descriptor cleanup after a failed synchronization.
1326
- }
1327
- }
1328
- if (branchLockDescriptor !== null) {
1329
- try {
1330
- fs.closeSync(branchLockDescriptor);
1331
- } catch {
1332
- // Best-effort descriptor cleanup after a failed synchronization.
1333
- }
1334
- }
1335
- if (lockOwned && !published) {
1336
- for (const target of [lockPath, `${lockPath}.lock`]) {
1337
- try {
1338
- fs.unlinkSync(target);
1339
- } catch (error) {
1340
- if (!error || error.code !== "ENOENT") {
1341
- // The index itself remains untouched; the receipt reports synchronization failure.
1342
- }
1343
- }
1344
- }
1345
- }
1346
- for (const [owned, target] of [
1347
- [branchLockOwned, branchLockPath],
1348
- [headLockOwned, headLockPath],
1349
- ]) {
1350
- if (!owned) continue;
1351
- try {
1352
- fs.unlinkSync(target);
1353
- } catch (error) {
1354
- if (!error || error.code !== "ENOENT") {
1355
- // The receipt already reports the synchronization outcome.
1356
- }
1357
- }
1358
- }
1359
- }
1360
- }
1361
-
1362
- finalizeGitFailure(preflight, files, failure, expectedTree, candidates) {
1363
- const classification = this.classifyCommit(preflight, expectedTree);
1364
- if (classification.committed === true) {
1365
- const synchronized = this.synchronizeCommittedIndex(preflight, classification, files);
1366
- const targets = this.inspectPublishedTargets(candidates);
1367
- return Object.assign({}, classification, {
1368
- enabled: true,
1369
- repository: true,
1370
- repositoryRoot: preflight.repository,
1371
- commitState: "observed_committed",
1372
- persistence: "git_commit",
1373
- warning: commandFailure(failure, "Git reported failure after the commit became visible."),
1374
- }, synchronized, targets);
1375
- }
1376
- if (classification.committed === false) {
1377
- const inspected = this.inspectGitState(preflight.repository, preflight.headBefore, files);
1378
- const targets = this.inspectPublishedTargets(candidates);
1379
- return Object.assign({
1380
- enabled: true,
1381
- repository: true,
1382
- repositoryRoot: preflight.repository,
1383
- committed: false,
1384
- commitState: "not_committed",
1385
- persistence: targets.validatedFilesPresent ? "working_tree" : "unknown",
1386
- error: commandFailure(failure, "Git commit failed"),
1387
- }, classification, inspected, targets);
1388
- }
1389
- const inspected = classification.headAfter
1390
- ? this.inspectGitState(preflight.repository, classification.headAfter, files)
1391
- : { affectedIndexState: "unknown", indexState: "unknown", affectedWorktreeState: "unknown" };
1392
- const targets = this.inspectPublishedTargets(candidates);
1393
- return Object.assign({
1394
- enabled: true,
1395
- repository: true,
1396
- repositoryRoot: preflight.repository,
1397
- committed: null,
1398
- commitState: "unknown",
1399
- persistence: "unknown",
1400
- error: commandFailure(failure, "Git commit outcome could not be determined"),
1401
- }, classification, inspected, targets);
1402
- }
1403
-
1404
- gitControlPath(repository, name) {
1405
- const controlPath = this.readGitValue(
1406
- repository,
1407
- ["rev-parse", "--git-path", name],
1408
- { readOnly: true },
1409
- );
1410
- if (!controlPath) {
1411
- return null;
1412
- }
1413
- return path.isAbsolute(controlPath)
1414
- ? controlPath
1415
- : path.resolve(repository, controlPath);
1416
- }
1417
-
1418
- gitIndexPath(repository) {
1419
- return this.gitControlPath(repository, "index");
1420
- }
1421
-
1422
- temporaryGitIndex(repository) {
1423
- const absoluteIndex = this.gitIndexPath(repository);
1424
- return absoluteIndex
1425
- ? `${absoluteIndex}.okf-${process.pid}-${crypto.randomBytes(8).toString("hex")}`
1426
- : null;
1427
- }
1428
-
1429
- removeTemporaryGitIndex(indexPath) {
1430
- [indexPath, `${indexPath}.lock`].forEach((target) => {
1431
- try {
1432
- fs.unlinkSync(target);
1433
- } catch (error) {
1434
- if (!error || error.code !== "ENOENT") {
1435
- // A leftover isolated index is inert and must not obscure the commit result.
1436
- }
1437
- }
1438
- });
1439
- }
1440
-
1441
- buildValidatedGitTree(preflight, candidates, files) {
1442
- const indexPath = this.temporaryGitIndex(preflight.repository);
1443
- if (!indexPath) {
1444
- return { failure: { status: 1, stderr: "Could not allocate an isolated Git index." } };
1445
- }
1446
- const isolated = { environment: { GIT_INDEX_FILE: indexPath } };
1447
- try {
1448
- const seeded = this.runGit(
1449
- preflight.repository,
1450
- ["read-tree", preflight.headBefore],
1451
- isolated,
1452
- );
1453
- if (!commandSucceeded(seeded)) {
1454
- return { failure: seeded };
1455
- }
1456
- for (const candidate of candidates) {
1457
- const hashed = this.runGit(
1458
- preflight.repository,
1459
- ["hash-object", "-w", "--stdin"],
1460
- { input: candidate.markdown },
1461
- );
1462
- if (!commandSucceeded(hashed)) {
1463
- return { failure: hashed };
1464
- }
1465
- const objectId = String(hashed.stdout || "").trim();
1466
- let mode = "100644";
1467
- if (candidate.op === "update") {
1468
- const relativePath = path.relative(
1469
- preflight.repository,
1470
- candidate.target.absolutePath,
1471
- ).replace(/\\/g, "/");
1472
- const seededEntry = this.runGit(preflight.repository, [
1473
- "ls-files", "-s", "-z", "--", relativePath,
1474
- ], isolated);
1475
- if (!commandSucceeded(seededEntry)) {
1476
- return { failure: seededEntry };
1477
- }
1478
- const match = String(seededEntry.stdout || "").match(/^([0-7]{6})\s/);
1479
- if (!match) {
1480
- return {
1481
- failure: {
1482
- status: 1,
1483
- stderr: `Could not preserve the pinned Git tree mode for ${relativePath}.`,
1484
- },
1485
- };
1486
- }
1487
- mode = match[1];
1488
- }
1489
- const updated = this.runGit(preflight.repository, [
1490
- "update-index",
1491
- "--add",
1492
- "--cacheinfo",
1493
- mode,
1494
- objectId,
1495
- path.relative(preflight.repository, candidate.target.absolutePath).replace(/\\/g, "/"),
1496
- ], isolated);
1497
- if (!commandSucceeded(updated)) {
1498
- return { failure: updated };
1499
- }
1500
- }
1501
- const written = this.runGit(preflight.repository, ["write-tree"], isolated);
1502
- if (!commandSucceeded(written)) {
1503
- return { failure: written };
1504
- }
1505
- const expectedTree = String(written.stdout || "").trim();
1506
- const changed = this.runGit(preflight.repository, [
1507
- "diff", "--no-ext-diff", "--name-only", "-z",
1508
- preflight.headBefore, expectedTree, "--",
1509
- ]);
1510
- const changedFiles = commandSucceeded(changed)
1511
- ? String(changed.stdout || "").split("\0").filter(Boolean).sort()
1512
- : null;
1513
- if (!changedFiles || !isDeepStrictEqual(changedFiles, files.slice().sort())) {
1514
- return {
1515
- expectedTree,
1516
- failure: {
1517
- status: 1,
1518
- stderr: commandSucceeded(changed)
1519
- ? "The isolated Git tree did not exactly match the validated OKF batch paths."
1520
- : commandFailure(changed, "Could not inspect the isolated Git tree."),
1521
- },
1522
- };
1523
- }
1524
- return { expectedTree };
1525
- } finally {
1526
- this.removeTemporaryGitIndex(indexPath);
1527
- }
1528
- }
1529
-
1530
- commitGit(preflight, candidates, message) {
1531
- if (!preflight.enabled) {
1532
- return {
1533
- enabled: false,
1534
- committed: false,
1535
- commitState: "not_requested",
1536
- repository: Boolean(preflight.repository),
1537
- repositoryRoot: preflight.repository,
1538
- persistence: "working_tree",
1539
- };
1540
- }
1541
- if (!preflight.repository) {
1542
- return {
1543
- enabled: true,
1544
- repository: false,
1545
- repositoryRoot: null,
1546
- committed: false,
1547
- commitState: "not_repository",
1548
- persistence: "working_tree",
1549
- reason: "not_git_repository",
1550
- };
1551
- }
1552
- const files = this.repositoryFiles(preflight, candidates);
1553
- let expectedTree = null;
1554
- try {
1555
- const initialTargets = this.inspectPublishedTargets(candidates);
1556
- if (!initialTargets.validatedFilesPresent) {
1557
- return this.finalizeGitFailure(preflight, files, {
1558
- status: 1,
1559
- stderr: "A published concept changed before the Git commit tree was built.",
1560
- }, null, candidates);
1561
- }
1562
- const built = this.buildValidatedGitTree(preflight, candidates, files);
1563
- expectedTree = built.expectedTree || null;
1564
- if (built.failure) {
1565
- return this.finalizeGitFailure(
1566
- preflight,
1567
- files,
1568
- built.failure,
1569
- expectedTree,
1570
- candidates,
1571
- );
1572
- }
1573
- const verifiedTargets = this.inspectPublishedTargets(candidates);
1574
- const headRefStillBefore = this.readGitValue(
1575
- preflight.repository,
1576
- ["symbolic-ref", "-q", "HEAD"],
1577
- );
1578
- const refStillBefore = this.readGitValue(
1579
- preflight.repository,
1580
- ["rev-parse", "--verify", preflight.headRef],
1581
- );
1582
- if (!verifiedTargets.validatedFilesPresent
1583
- || headRefStillBefore !== preflight.headRef
1584
- || refStillBefore !== preflight.headBefore) {
1585
- return this.finalizeGitFailure(preflight, files, {
1586
- status: 1,
1587
- stderr: !verifiedTargets.validatedFilesPresent
1588
- ? "A published concept changed before the Git ref update."
1589
- : "The checked-out Git ref changed before the validated commit could be published.",
1590
- }, expectedTree, candidates);
1591
- }
1592
- const committed = this.runGit(preflight.repository, [
1593
- "commit-tree", expectedTree, "-p", preflight.headBefore, "-m", message,
1594
- ]);
1595
- if (!commandSucceeded(committed)) {
1596
- return this.finalizeGitFailure(
1597
- preflight,
1598
- files,
1599
- committed,
1600
- expectedTree,
1601
- candidates,
1602
- );
1603
- }
1604
- const commitSha = String(committed.stdout || "").trim();
1605
- const finalTargets = this.inspectPublishedTargets(candidates);
1606
- if (!finalTargets.validatedFilesPresent) {
1607
- return this.finalizeGitFailure(preflight, files, {
1608
- status: 1,
1609
- stderr: "A published concept changed before the validated commit was published.",
1610
- }, expectedTree, candidates);
1611
- }
1612
- const updated = this.runGit(preflight.repository, [
1613
- "update-ref", "-m", "okf-mcp live authoring",
1614
- preflight.headRef, commitSha, preflight.headBefore,
1615
- ]);
1616
- const classification = this.classifyCommit(preflight, expectedTree);
1617
- if (!commandSucceeded(updated) || classification.committed !== true) {
1618
- return this.finalizeGitFailure(
1619
- preflight,
1620
- files,
1621
- updated,
1622
- expectedTree,
1623
- candidates,
1624
- );
1625
- }
1626
- const synchronized = this.synchronizeCommittedIndex(preflight, classification, files);
1627
- const targets = this.inspectPublishedTargets(candidates);
1628
- return Object.assign({
1629
- enabled: true,
1630
- repository: true,
1631
- repositoryRoot: preflight.repository,
1632
- committed: true,
1633
- commitState: "committed",
1634
- persistence: "git_commit",
1635
- }, classification, synchronized, targets);
1636
- } catch (error) {
1637
- return this.finalizeGitFailure(
1638
- preflight,
1639
- files,
1640
- { status: null, stdout: "", stderr: "", error },
1641
- expectedTree,
1642
- candidates,
1643
- );
1644
- }
1645
- }
1646
-
1647
- defaultMessage(candidates) {
1648
- if (candidates.length === 1) {
1649
- return `docs(okf): ${candidates[0].op === "create" ? "add" : "update"} ${candidates[0].title}`;
1650
- }
1651
- return `docs(okf): apply ${candidates.length} concept changes`;
1652
- }
1653
-
1654
- commitMessage(input, candidates) {
1655
- if (hasOwn(input, "message") && typeof input.message !== "string") {
1656
- throw new AuthoringPolicyError("Git commit message must be a string.");
1657
- }
1658
- const supplied = hasOwn(input, "message") ? input.message.trim() : "";
1659
- const message = supplied || this.defaultMessage(candidates);
1660
- if (message.includes("\0")) {
1661
- throw new AuthoringPolicyError("Git commit message cannot contain NUL characters.");
1662
- }
1663
- if (byteLength(message) > MAX_COMMIT_MESSAGE_BYTES) {
1664
- throw new AuthoringPolicyError(
1665
- `Git commit message must not exceed ${MAX_COMMIT_MESSAGE_BYTES} UTF-8 bytes.`,
1666
- );
1667
- }
1668
- return message;
1669
- }
1670
-
1671
- ensureParentDirectories(candidate, createdDirectories) {
1672
- const bundleRoot = this.store.resolveWritableBundleRoot(this.store.getBundle(candidate.bundle));
1673
- const parent = path.dirname(candidate.target.absolutePath);
1674
- const relative = path.relative(bundleRoot, parent);
1675
- let current = bundleRoot;
1676
- for (const segment of relative.split(path.sep).filter(Boolean)) {
1677
- current = path.join(current, segment);
1678
- if (fs.existsSync(current)) {
1679
- const stat = fs.lstatSync(current);
1680
- if (stat.isSymbolicLink() || !stat.isDirectory()) {
1681
- throw new Error(`Concept parent is not a safe directory: ${current}`);
1682
- }
1683
- continue;
1684
- }
1685
- fs.mkdirSync(current);
1686
- createdDirectories.push(current);
1687
- }
1688
- }
1689
-
1690
- cleanupDirectories(createdDirectories) {
1691
- createdDirectories.slice().sort((left, right) => right.length - left.length).forEach((directory) => {
1692
- try {
1693
- fs.rmdirSync(directory);
1694
- } catch (error) {
1695
- if (!error || !["ENOENT", "ENOTEMPTY"].includes(error.code)) {
1696
- throw error;
1697
- }
1698
- }
1699
- });
1700
- }
1701
-
1702
- stageCandidates(candidates) {
1703
- const staged = [];
1704
- const createdDirectories = [];
1705
- try {
1706
- candidates.forEach((candidate) => {
1707
- this.ensureParentDirectories(candidate, createdDirectories);
1708
- const temporary = temporaryPath(candidate.target.absolutePath);
1709
- fs.writeFileSync(temporary, candidate.markdown, { encoding: "utf8", flag: "wx" });
1710
- const stagedCandidate = Object.assign({}, candidate, { temporary });
1711
- staged.push(stagedCandidate);
1712
- if (candidate.op === "update") {
1713
- fs.chmodSync(temporary, candidate.originalMode);
1714
- }
1715
- });
1716
- return { staged, createdDirectories };
1717
- } catch (error) {
1718
- staged.forEach((entry) => {
1719
- if (fs.existsSync(entry.temporary)) fs.unlinkSync(entry.temporary);
1720
- });
1721
- this.cleanupDirectories(createdDirectories);
1722
- throw error;
1723
- }
1724
- }
1725
-
1726
- assertRevisions(staged) {
1727
- staged.forEach((candidate) => {
1728
- const exists = fs.existsSync(candidate.target.absolutePath);
1729
- if (candidate.op === "create" && exists) {
1730
- throw new Error(`Concept file appeared during batch preparation: ${candidate.path}`);
1731
- }
1732
- if (candidate.op === "update") {
1733
- if (!exists) {
1734
- throw new Error(`Concept file disappeared during batch preparation: ${candidate.path}`);
1735
- }
1736
- const currentRevision = revisionFor(fs.readFileSync(candidate.target.absolutePath));
1737
- if (currentRevision !== candidate.baseRevision) {
1738
- throw new Error(`Concept changed during batch preparation: ${candidate.path}`);
1739
- }
1740
- }
1741
- });
1742
- }
1743
-
1744
- inspectPublishedTarget(candidate) {
1745
- try {
1746
- const stat = fs.lstatSync(candidate.target.absolutePath);
1747
- if (stat.isSymbolicLink() || !stat.isFile()) {
1748
- return { state: "non_regular", revision: null };
1749
- }
1750
- return {
1751
- state: "regular",
1752
- revision: revisionFor(fs.readFileSync(candidate.target.absolutePath)),
1753
- };
1754
- } catch (error) {
1755
- if (error && error.code === "ENOENT") {
1756
- return { state: "missing", revision: null };
1757
- }
1758
- throw error;
1759
- }
1760
- }
1761
-
1762
- rollbackCandidate(candidate) {
1763
- const inspected = this.inspectPublishedTarget(candidate);
1764
- const receipt = {
1765
- op: candidate.op,
1766
- path: candidate.path,
1767
- absolutePath: candidate.target.absolutePath,
1768
- expectedPublishedRevision: candidate.publishedRevision,
1769
- observedRevision: inspected.revision,
1770
- };
1771
- if (candidate.op === "create" && inspected.state === "missing") {
1772
- return Object.assign(receipt, { status: "already_absent", restored: true });
1773
- }
1774
- if (inspected.state !== "regular" || inspected.revision !== candidate.publishedRevision) {
1775
- return Object.assign(receipt, {
1776
- status: "conflict",
1777
- restored: false,
1778
- observedState: inspected.state,
1779
- });
1780
- }
1781
- if (candidate.op === "create") {
1782
- fs.unlinkSync(candidate.target.absolutePath);
1783
- return Object.assign(receipt, { status: "removed", restored: true });
1784
- }
1785
- restoreFile(candidate.target.absolutePath, candidate.originalText, candidate.originalMode);
1786
- const restored = this.inspectPublishedTarget(candidate);
1787
- if (restored.state !== "regular" || restored.revision !== candidate.baseRevision) {
1788
- return Object.assign(receipt, {
1789
- status: "restore_verification_failed",
1790
- restored: false,
1791
- restoredRevision: restored.revision,
1792
- });
1793
- }
1794
- return Object.assign(receipt, {
1795
- status: "restored",
1796
- restored: true,
1797
- restoredRevision: restored.revision,
1798
- });
1799
- }
1800
-
1801
- rollback(applied, staged, createdDirectories) {
1802
- const failures = [];
1803
- const outcomes = [];
1804
- staged.forEach((candidate) => {
1805
- if (fs.existsSync(candidate.temporary)) {
1806
- try {
1807
- fs.unlinkSync(candidate.temporary);
1808
- } catch (error) {
1809
- failures.push(error);
1810
- }
1811
- }
1812
- });
1813
- applied.slice().reverse().forEach((candidate) => {
1814
- try {
1815
- outcomes.push(this.rollbackCandidate(candidate));
1816
- } catch (error) {
1817
- const failure = {
1818
- op: candidate.op,
1819
- path: candidate.path,
1820
- absolutePath: candidate.target.absolutePath,
1821
- status: "error",
1822
- restored: false,
1823
- error: error && error.message ? error.message : String(error),
1824
- };
1825
- outcomes.push(failure);
1826
- failures.push(failure);
1827
- }
1828
- });
1829
- try {
1830
- this.cleanupDirectories(createdDirectories || []);
1831
- } catch (error) {
1832
- failures.push({
1833
- status: "directory_cleanup_error",
1834
- error: error && error.message ? error.message : String(error),
1835
- });
1836
- }
1837
- const conflicts = outcomes.filter((outcome) => !outcome.restored);
1838
- return {
1839
- complete: conflicts.length === 0 && failures.length === 0,
1840
- outcomes,
1841
- conflicts,
1842
- failures,
1843
- };
1844
- }
1845
-
1846
- generatedStamp() {
1847
- const timestampValue = this.now();
1848
- return {
1849
- by: this.actor,
1850
- at: timestampValue instanceof Date
1851
- ? timestampValue.toISOString()
1852
- : new Date(timestampValue).toISOString(),
1853
- };
1854
- }
1855
-
1856
- targetReceipt(bundle, candidates, gitPreflight) {
1857
- const bundleRoot = this.store.resolveWritableBundleRoot(bundle);
1858
- const projectRoot = this.store.projectRoot
1859
- ? path.resolve(this.store.projectRoot)
1860
- : bundleRoot;
1861
- return {
1862
- bundle: bundle.id,
1863
- bundleRoot,
1864
- projectRoot,
1865
- repositoryRoot: gitPreflight && gitPreflight.repositoryRoot
1866
- ? gitPreflight.repositoryRoot
1867
- : null,
1868
- absolutePaths: candidates.map((candidate) => candidate.target.absolutePath),
1869
- };
1870
- }
1871
-
1872
- candidateSummaries(candidates) {
1873
- return candidates.map((candidate) => ({
1874
- op: candidate.op,
1875
- bundle: candidate.bundle,
1876
- path: candidate.path,
1877
- absolutePath: candidate.target.absolutePath,
1878
- uri: candidate.uri,
1879
- title: candidate.title,
1880
- baseRevision: candidate.baseRevision,
1881
- candidateRevision: candidate.publishedRevision,
1882
- effects: effectsForCandidate(candidate),
1883
- }));
1884
- }
1885
-
1886
- durabilityReceipt(git, filesChanged, stateOverride) {
1887
- const persistence = git && git.persistence
1888
- ? git.persistence
1889
- : filesChanged ? "working_tree" : "none";
1890
- return {
1891
- state: stateOverride || (filesChanged
1892
- ? git && ["committed", "observed_committed"].includes(git.commitState)
1893
- ? "git_committed"
1894
- : git && git.commitState === "unknown"
1895
- ? "commit_state_unknown"
1896
- : "filesystem_published_uncommitted"
1897
- : "not_persisted"),
1898
- filesChanged: Boolean(filesChanged),
1899
- persistence,
1900
- committed: git && hasOwn(git, "committed") ? git.committed : false,
1901
- commitState: git && git.commitState ? git.commitState : "not_requested",
1902
- affectedIndexState: git && git.affectedIndexState ? git.affectedIndexState : "not_inspected",
1903
- indexState: git && git.indexState ? git.indexState : "not_inspected",
1904
- crashDurable: false,
1905
- };
1906
- }
1907
-
1908
- snapshotReceipt(plan) {
1909
- return {
1910
- checkedAt: plan.generated.at,
1911
- timeOfCheck: true,
1912
- generatedBy: plan.generated.by,
1913
- graphValidation: "future_overlay",
1914
- };
1915
- }
1916
-
1917
- preconditionsReceipt(plan) {
1918
- return {
1919
- allSatisfied: Boolean(plan.validation.valid && plan.gitPreflight.ready),
1920
- revisions: plan.candidates.map((candidate) => ({
1921
- path: candidate.path,
1922
- absolutePath: candidate.target.absolutePath,
1923
- baseRevision: candidate.baseRevision,
1924
- candidateRevision: candidate.publishedRevision,
1925
- })),
1926
- git: {
1927
- enabled: plan.gitPreflight.enabled,
1928
- ready: plan.gitPreflight.ready,
1929
- repositoryStatus: plan.gitPreflight.repositoryStatus,
1930
- repositoryRoot: plan.gitPreflight.repositoryRoot,
1931
- headBefore: plan.gitPreflight.headBefore,
1932
- headRef: plan.gitPreflight.headRef,
1933
- worktreeClean: plan.gitPreflight.worktreeClean,
1934
- identityConfigured: plan.gitPreflight.identityConfigured,
1935
- diagnostics: plan.gitPreflight.diagnostics,
1936
- },
1937
- };
1938
- }
1939
-
1940
- planChanges(input, context) {
1941
- if (!isPlainObject(input)) {
1942
- throw new AuthoringPolicyError("okf_apply_changes requires an object argument.");
1943
- }
1944
- if (!Array.isArray(input.changes) || input.changes.length < 1 || input.changes.length > MAX_CHANGES) {
1945
- throw new AuthoringPolicyError(`changes must contain from 1 through ${MAX_CHANGES} operations.`);
1946
- }
1947
- let bundle;
1948
- try {
1949
- bundle = this.getBundle(input.bundle);
1950
- } catch (error) {
1951
- if (error && error.code) throw error;
1952
- throw new AuthoringPolicyError(error && error.message ? error.message : String(error));
1953
- }
1954
- const generated = this.generatedStamp();
1955
- const additionalBundles = context && Array.isArray(context.additionalBundles)
1956
- ? context.additionalBundles
1957
- : [];
1958
- const currentIndex = this.buildIndex(additionalBundles);
1959
- const candidates = input.changes.map((change, index) => {
1960
- if (!isPlainObject(change)) {
1961
- throw new AuthoringPolicyError(`changes[${index}] must be an object.`);
1962
- }
1963
- try {
1964
- if (change.op === "create") {
1965
- return this.createCandidate(change, bundle, currentIndex, generated);
1966
- }
1967
- if (change.op === "update") {
1968
- return this.updateCandidate(change, bundle, currentIndex, generated);
1969
- }
1970
- throw new AuthoringPolicyError(`changes[${index}].op must be create or update.`);
1971
- } catch (error) {
1972
- if (error instanceof AuthoringPolicyError || error instanceof AuthoringOperationalError) {
1973
- throw error;
1974
- }
1975
- if (error && error.code) throw error;
1976
- throw new AuthoringPolicyError(error && error.message ? error.message : String(error));
1977
- }
1978
- });
1979
- const targetPaths = new Set();
1980
- candidates.forEach((candidate) => {
1981
- const key = path.resolve(candidate.target.absolutePath);
1982
- if (targetPaths.has(key)) {
1983
- throw new AuthoringPolicyError(`A batch cannot target the same concept more than once: ${candidate.path}`);
1984
- }
1985
- targetPaths.add(key);
1986
- });
1987
- const absoluteTargets = Array.from(targetPaths);
1988
- for (let left = 0; left < absoluteTargets.length; left += 1) {
1989
- for (let right = left + 1; right < absoluteTargets.length; right += 1) {
1990
- if (absoluteTargets[left].startsWith(`${absoluteTargets[right]}${path.sep}`)
1991
- || absoluteTargets[right].startsWith(`${absoluteTargets[left]}${path.sep}`)) {
1992
- throw new AuthoringPolicyError(
1993
- "A batch cannot place one concept path underneath another concept file path.",
1994
- );
1995
- }
1996
- }
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
- }
2023
- const message = this.commitMessage(input, candidates);
2024
- const overrides = new Map(candidates.map((candidate) => [
2025
- `${candidate.bundle}\u0000${candidate.path}`,
2026
- candidate.markdown,
2027
- ]));
2028
- const validation = this.validationResult(
2029
- this.buildIndex(additionalBundles, overrides),
2030
- candidates,
2031
- );
2032
- const gitPreflight = this.prepareGit(bundle, candidates);
2033
- return {
2034
- input,
2035
- bundle,
2036
- generated,
2037
- additionalBundles,
2038
- candidates,
2039
- message,
2040
- validation,
2041
- gitPreflight,
2042
- target: this.targetReceipt(bundle, candidates, gitPreflight),
2043
- changes: this.candidateSummaries(candidates),
2044
- };
2045
- }
2046
-
2047
- validationReceipt(plan) {
2048
- const git = {
2049
- enabled: plan.gitPreflight.enabled,
2050
- repository: Boolean(plan.gitPreflight.repository),
2051
- repositoryRoot: plan.gitPreflight.repositoryRoot,
2052
- repositoryStatus: plan.gitPreflight.repositoryStatus,
2053
- ready: plan.gitPreflight.ready,
2054
- headBefore: plan.gitPreflight.headBefore,
2055
- headRef: plan.gitPreflight.headRef,
2056
- worktreeClean: plan.gitPreflight.worktreeClean,
2057
- identityConfigured: plan.gitPreflight.identityConfigured,
2058
- diagnostics: plan.gitPreflight.diagnostics,
2059
- commitState: "not_attempted",
2060
- persistence: "none",
2061
- };
2062
- const readyToApply = Boolean(plan.validation.valid && plan.gitPreflight.ready);
2063
- return {
2064
- valid: plan.validation.valid,
2065
- readyToApply,
2066
- applied: false,
2067
- filesChanged: false,
2068
- status: !plan.validation.valid ? "invalid" : readyToApply ? "ready" : "blocked",
2069
- snapshot: this.snapshotReceipt(plan),
2070
- preconditions: this.preconditionsReceipt(plan),
2071
- generated: plan.generated,
2072
- target: plan.target,
2073
- durability: this.durabilityReceipt(git, false),
2074
- changes: plan.changes,
2075
- validation: plan.validation,
2076
- git,
2077
- };
2078
- }
2079
-
2080
- invalidValidationReceipt(error) {
2081
- const validation = policyValidation(error);
2082
- const generated = this.generatedStamp();
2083
- return {
2084
- valid: false,
2085
- readyToApply: false,
2086
- applied: false,
2087
- filesChanged: false,
2088
- status: "invalid",
2089
- snapshot: {
2090
- checkedAt: generated.at,
2091
- timeOfCheck: true,
2092
- generatedBy: generated.by,
2093
- graphValidation: "not_run",
2094
- },
2095
- preconditions: {
2096
- allSatisfied: false,
2097
- revisions: [],
2098
- git: {
2099
- enabled: this.gitCommit,
2100
- ready: false,
2101
- repositoryStatus: "not_inspected",
2102
- repositoryRoot: null,
2103
- diagnostics: [],
2104
- },
2105
- },
2106
- generated,
2107
- durability: this.durabilityReceipt(null, false),
2108
- changes: [],
2109
- validation,
2110
- ...(error && error.code ? { code: error.code } : {}),
2111
- ...(error && error.details !== undefined ? { details: error.details } : {}),
2112
- git: {
2113
- enabled: this.gitCommit,
2114
- repository: false,
2115
- repositoryRoot: null,
2116
- repositoryStatus: "not_inspected",
2117
- commitState: "not_attempted",
2118
- persistence: "none",
2119
- },
2120
- };
2121
- }
2122
-
2123
- async validateChanges(input, context) {
2124
- return this.store.withWriteLock(() => {
2125
- try {
2126
- return this.validationReceipt(this.planChanges(input, context));
2127
- } catch (error) {
2128
- if (!(error instanceof AuthoringPolicyError)) {
2129
- throw error;
2130
- }
2131
- return this.invalidValidationReceipt(error);
2132
- }
2133
- });
2134
- }
2135
-
2136
- async applyChanges(input, context) {
2137
- return this.store.withWriteLock(() => this.applyChangesUnlocked(input, context));
2138
- }
2139
-
2140
- async applyChangesUnlocked(input, context) {
2141
- const plan = this.planChanges(input, context);
2142
- if (!plan.validation.valid) {
2143
- return {
2144
- applied: false,
2145
- readyToApply: false,
2146
- filesChanged: false,
2147
- status: "rejected",
2148
- snapshot: this.snapshotReceipt(plan),
2149
- preconditions: this.preconditionsReceipt(plan),
2150
- generated: plan.generated,
2151
- target: plan.target,
2152
- durability: this.durabilityReceipt(null, false),
2153
- changes: plan.changes,
2154
- validation: plan.validation,
2155
- git: {
2156
- enabled: plan.gitPreflight.enabled,
2157
- repository: Boolean(plan.gitPreflight.repository),
2158
- repositoryRoot: plan.gitPreflight.repositoryRoot,
2159
- repositoryStatus: plan.gitPreflight.repositoryStatus,
2160
- commitState: "not_attempted",
2161
- persistence: "none",
2162
- },
2163
- };
2164
- }
2165
- if (!plan.gitPreflight.ready) {
2166
- const blocker = plan.gitPreflight.diagnostics[0];
2167
- throw new AuthoringPolicyError(blocker
2168
- ? blocker.message
2169
- : "Configured Git preconditions do not currently allow automatic apply.");
2170
- }
2171
- const transaction = this.stageCandidates(plan.candidates);
2172
- const staged = transaction.staged;
2173
- const applied = [];
2174
- try {
2175
- this.assertRevisions(staged);
2176
- staged.forEach((candidate) => {
2177
- if (candidate.op === "create") {
2178
- fs.linkSync(candidate.temporary, candidate.target.absolutePath);
2179
- applied.push(candidate);
2180
- fs.unlinkSync(candidate.temporary);
2181
- } else {
2182
- const currentRevision = revisionFor(fs.readFileSync(candidate.target.absolutePath));
2183
- if (currentRevision !== candidate.baseRevision) {
2184
- throw new Error(`Concept changed immediately before publication: ${candidate.path}`);
2185
- }
2186
- fs.renameSync(candidate.temporary, candidate.target.absolutePath);
2187
- applied.push(candidate);
2188
- }
2189
- });
2190
- } catch (error) {
2191
- const rollback = this.rollback(applied, staged, transaction.createdDirectories);
2192
- if (!rollback.complete) {
2193
- return {
2194
- applied: false,
2195
- readyToApply: false,
2196
- filesChanged: true,
2197
- status: "rollback_conflict",
2198
- snapshot: this.snapshotReceipt(plan),
2199
- preconditions: this.preconditionsReceipt(plan),
2200
- generated: plan.generated,
2201
- target: plan.target,
2202
- durability: this.durabilityReceipt(null, true, "partial_filesystem_state"),
2203
- changes: plan.changes,
2204
- validation: plan.validation,
2205
- rollback,
2206
- error: error && error.message ? error.message : String(error),
2207
- };
2208
- }
2209
- throw error;
2210
- }
2211
- let persistedValidation;
2212
- try {
2213
- persistedValidation = this.validationResult(
2214
- this.buildIndex(plan.additionalBundles),
2215
- plan.candidates,
2216
- );
2217
- } catch (error) {
2218
- const rollback = this.rollback(applied, staged, transaction.createdDirectories);
2219
- if (!rollback.complete) {
2220
- return {
2221
- applied: false,
2222
- readyToApply: false,
2223
- filesChanged: true,
2224
- status: "rollback_conflict",
2225
- snapshot: this.snapshotReceipt(plan),
2226
- preconditions: this.preconditionsReceipt(plan),
2227
- generated: plan.generated,
2228
- target: plan.target,
2229
- durability: this.durabilityReceipt(null, true, "partial_filesystem_state"),
2230
- changes: plan.changes,
2231
- validation: plan.validation,
2232
- rollback,
2233
- error: error && error.message ? error.message : String(error),
2234
- };
2235
- }
2236
- throw error;
2237
- }
2238
- if (!persistedValidation.valid) {
2239
- const rollback = this.rollback(applied, staged, transaction.createdDirectories);
2240
- return {
2241
- applied: false,
2242
- readyToApply: false,
2243
- filesChanged: !rollback.complete,
2244
- status: rollback.complete ? "rolled_back" : "rollback_conflict",
2245
- snapshot: this.snapshotReceipt(plan),
2246
- preconditions: this.preconditionsReceipt(plan),
2247
- generated: plan.generated,
2248
- target: plan.target,
2249
- durability: this.durabilityReceipt(
2250
- null,
2251
- !rollback.complete,
2252
- rollback.complete ? "rolled_back" : "partial_filesystem_state",
2253
- ),
2254
- changes: plan.changes,
2255
- validation: persistedValidation,
2256
- rollback,
2257
- };
2258
- }
2259
- let git;
2260
- try {
2261
- git = this.commitGit(plan.gitPreflight, plan.candidates, plan.message);
2262
- } catch (error) {
2263
- git = {
2264
- enabled: plan.gitPreflight.enabled,
2265
- repository: Boolean(plan.gitPreflight.repository),
2266
- repositoryRoot: plan.gitPreflight.repositoryRoot,
2267
- committed: null,
2268
- commitState: "unknown",
2269
- persistence: "unknown",
2270
- error: error && error.message ? error.message : String(error),
2271
- };
2272
- }
2273
- if (git.targetState === "conflict") {
2274
- let currentValidation = persistedValidation;
2275
- try {
2276
- currentValidation = this.validationResult(
2277
- this.buildIndex(plan.additionalBundles),
2278
- [],
2279
- );
2280
- } catch {
2281
- // Preserve the last complete validation receipt when the conflicting state is unreadable.
2282
- }
2283
- if (git.committed !== true) {
2284
- return {
2285
- applied: false,
2286
- readyToApply: false,
2287
- filesChanged: true,
2288
- status: "post_publication_conflict",
2289
- snapshot: this.snapshotReceipt(plan),
2290
- preconditions: this.preconditionsReceipt(plan),
2291
- generated: plan.generated,
2292
- target: plan.target,
2293
- durability: this.durabilityReceipt(git, true, "partial_filesystem_state"),
2294
- changes: plan.changes,
2295
- validation: currentValidation,
2296
- git,
2297
- error: git.error || "Validated concept bytes were replaced before Git persistence completed.",
2298
- };
2299
- }
2300
- persistedValidation = currentValidation;
2301
- }
2302
- const status = git.commitState === "unknown"
2303
- ? "applied_commit_unknown"
2304
- : git.committed === true && git.targetState === "conflict"
2305
- ? "applied_worktree_diverged"
2306
- : git.enabled && git.repository && !git.committed
2307
- ? "applied_uncommitted"
2308
- : "applied";
2309
- return {
2310
- applied: true,
2311
- readyToApply: git.targetState !== "conflict",
2312
- filesChanged: true,
2313
- status,
2314
- snapshot: this.snapshotReceipt(plan),
2315
- preconditions: this.preconditionsReceipt(plan),
2316
- generated: plan.generated,
2317
- target: plan.target,
2318
- durability: this.durabilityReceipt(git, true),
2319
- changes: plan.changes,
2320
- validation: persistedValidation,
2321
- git,
2322
- };
2323
- }
2324
- }
2325
-
2326
- module.exports = {
2327
- LiveAuthoringService,
2328
- MAX_CHANGES,
2329
- MAX_COMMIT_MESSAGE_BYTES,
2330
- MANAGED_METADATA_KEYS,
2331
- };
3
+ // Compatibility shim: live authoring moved to src/authoring/ in 0.10. Deep
4
+ // requires of this path keep working; new code should require
5
+ // "./authoring/live".
6
+ module.exports = require("./authoring/live");