@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
@@ -0,0 +1,329 @@
1
+ "use strict";
2
+
3
+ const path = require("node:path");
4
+ const { isDeepStrictEqual } = require("node:util");
5
+
6
+ const { normalizeBody, relationKey, relationParts, sourceIdentity } = require("./candidates");
7
+ const {
8
+ MAX_EFFECT_ITEMS,
9
+ MAX_EFFECT_TEXT,
10
+ byteLength,
11
+ hasOwn,
12
+ isPlainObject,
13
+ sortedUnique,
14
+ } = require("./shared");
15
+
16
+ function boundedEffectList(values, project) {
17
+ const normalized = project ? values.map(project) : sortedUnique(values).map(boundedEffectText);
18
+ return {
19
+ values: normalized.slice(0, MAX_EFFECT_ITEMS),
20
+ omitted: Math.max(0, normalized.length - MAX_EFFECT_ITEMS),
21
+ };
22
+ }
23
+
24
+ function boundedEffectText(value) {
25
+ const text = String(value || "");
26
+ return text.length > MAX_EFFECT_TEXT ? `${text.slice(0, MAX_EFFECT_TEXT - 1)}…` : text;
27
+ }
28
+
29
+ function relationEffectValue(value) {
30
+ const parts = relationParts(value);
31
+ const result = {
32
+ type: boundedEffectText(parts.type),
33
+ target: boundedEffectText(parts.target),
34
+ };
35
+ if (isPlainObject(value) && hasOwn(value, "label")) {
36
+ result.label = boundedEffectText(value.label);
37
+ }
38
+ if (isPlainObject(value) && hasOwn(value, "description")) {
39
+ result.description = boundedEffectText(value.description);
40
+ }
41
+ return result;
42
+ }
43
+
44
+ function collectionEffects(before, after, identity, project) {
45
+ const previous = new Map((before || []).map((value) => [identity(value), value]));
46
+ const next = new Map((after || []).map((value) => [identity(value), value]));
47
+ const added = Array.from(next.keys())
48
+ .filter((key) => !previous.has(key))
49
+ .sort();
50
+ const removed = Array.from(previous.keys())
51
+ .filter((key) => !next.has(key))
52
+ .sort();
53
+ const updated = Array.from(next.keys())
54
+ .filter((key) => previous.has(key) && !isDeepStrictEqual(previous.get(key), next.get(key)))
55
+ .sort();
56
+ const effectList = (keys, values) =>
57
+ boundedEffectList(project ? keys.map((key) => values.get(key)) : keys, project);
58
+ return {
59
+ added: effectList(added, next),
60
+ removed: effectList(removed, previous),
61
+ updated: effectList(updated, next),
62
+ };
63
+ }
64
+
65
+ function metadataEffects(before, after) {
66
+ const excluded = new Set(["tags", "sources", "relations", "generated"]);
67
+ const keys = sortedUnique(Object.keys(before || {}).concat(Object.keys(after || {}))).filter(
68
+ (key) => !excluded.has(key),
69
+ );
70
+ return {
71
+ set: boundedEffectList(
72
+ keys.filter((key) => hasOwn(after, key) && !isDeepStrictEqual(before[key], after[key])),
73
+ ),
74
+ removed: boundedEffectList(keys.filter((key) => hasOwn(before, key) && !hasOwn(after, key))),
75
+ };
76
+ }
77
+
78
+ function effectsForCandidate(candidate) {
79
+ const before = candidate.op === "update" ? candidate.originalFrontmatter : {};
80
+ const after = candidate.frontmatter;
81
+ const tags = collectionEffects(before.tags, after.tags, (value) => String(value));
82
+ const sources = collectionEffects(before.sources, after.sources, sourceIdentity);
83
+ const relations = collectionEffects(
84
+ before.relations,
85
+ after.relations,
86
+ relationKey,
87
+ relationEffectValue,
88
+ );
89
+ const metadata = metadataEffects(before, after);
90
+ const bodyChanged =
91
+ candidate.op === "create"
92
+ ? true
93
+ : normalizeBody(candidate.originalBody) !== normalizeBody(candidate.body);
94
+ const changedFields = [];
95
+ if (bodyChanged) changedFields.push("body");
96
+ const hasEffect = (group) => group.values.length || group.omitted;
97
+ if (hasEffect(tags.added) || hasEffect(tags.removed) || hasEffect(tags.updated))
98
+ changedFields.push("tags");
99
+ if (hasEffect(sources.added) || hasEffect(sources.removed) || hasEffect(sources.updated))
100
+ changedFields.push("sources");
101
+ if (hasEffect(relations.added) || hasEffect(relations.removed) || hasEffect(relations.updated))
102
+ changedFields.push("relations");
103
+ if (hasEffect(metadata.set) || hasEffect(metadata.removed)) changedFields.push("metadata");
104
+ return {
105
+ changedFields,
106
+ bodyChanged,
107
+ tags,
108
+ sources,
109
+ relations,
110
+ metadata,
111
+ beforeRevision: candidate.baseRevision,
112
+ afterRevision: candidate.publishedRevision,
113
+ bytesBefore: candidate.originalText === undefined ? 0 : byteLength(candidate.originalText),
114
+ bytesAfter: byteLength(candidate.markdown),
115
+ };
116
+ }
117
+
118
+ function policyCode(message) {
119
+ const text = String(message || "");
120
+ if (/generated|generator/i.test(text)) return "generated_owner_protected";
121
+ if (/Attested Computation|computation contract/i.test(text))
122
+ return "computation_authoring_prohibited";
123
+ if (/excluded by the bundle policy/i.test(text)) return "excluded_target";
124
+ if (/no effective changes/i.test(text)) return "no_effective_changes";
125
+ if (/same concept more than once/i.test(text)) return "duplicate_batch_target";
126
+ if (/already exists/i.test(text)) return "target_exists";
127
+ if (/unknown valid OKF concept/i.test(text)) return "concept_not_found";
128
+ if (/server-managed/i.test(text)) return "managed_metadata_protected";
129
+ if (/1 through \d+ operations/i.test(text)) return "invalid_batch_size";
130
+ if (
131
+ /outside|travers|safe relative|unsafe segment|reserved index|reserved .*file|Markdown file|Markdown path/i.test(
132
+ text,
133
+ )
134
+ )
135
+ return "unsafe_target_path";
136
+ if (/worktree must be completely clean/i.test(text)) return "git_worktree_dirty";
137
+ if (/Git filter attributes|repository-configured filters/i.test(text))
138
+ return "git_filter_attribute_unsupported";
139
+ if (/assume-unchanged|skip-worktree|Git index flags/i.test(text))
140
+ return "git_index_flag_unsupported";
141
+ if (/detached HEAD|symbolic branch|checked-out Git ref/i.test(text))
142
+ return "git_head_ref_unsupported";
143
+ if (/Git user\.(name|email)/i.test(text)) return "git_identity_missing";
144
+ if (/must have an existing HEAD/i.test(text)) return "git_head_missing";
145
+ if (/commit message/i.test(text)) return "invalid_commit_message";
146
+ return "authoring_policy_rejected";
147
+ }
148
+
149
+ function policyValidation(error) {
150
+ const message = error && error.message ? error.message : String(error);
151
+ const code = (error && error.code) || policyCode(message);
152
+ const details = error && error.details;
153
+ const diagnostic = {
154
+ code,
155
+ severity: "error",
156
+ layer: "authoring",
157
+ message,
158
+ ...(details !== undefined ? { details } : {}),
159
+ };
160
+ return {
161
+ valid: false,
162
+ conformant: false,
163
+ validForProject: false,
164
+ diagnostics: [diagnostic],
165
+ errors: [{ code, message, ...(details !== undefined ? { details } : {}) }],
166
+ warnings: [],
167
+ };
168
+ }
169
+
170
+ function targetReceipt(store, bundle, candidates, gitPreflight) {
171
+ const bundleRoot = store.resolveWritableBundleRoot(bundle);
172
+ const projectRoot = store.projectRoot ? path.resolve(store.projectRoot) : bundleRoot;
173
+ return {
174
+ bundle: bundle.id,
175
+ bundleRoot,
176
+ projectRoot,
177
+ repositoryRoot:
178
+ gitPreflight && gitPreflight.repositoryRoot ? gitPreflight.repositoryRoot : null,
179
+ absolutePaths: candidates.map((candidate) => candidate.target.absolutePath),
180
+ };
181
+ }
182
+
183
+ function candidateSummaries(candidates) {
184
+ return candidates.map((candidate) => ({
185
+ op: candidate.op,
186
+ bundle: candidate.bundle,
187
+ path: candidate.path,
188
+ absolutePath: candidate.target.absolutePath,
189
+ uri: candidate.uri,
190
+ title: candidate.title,
191
+ baseRevision: candidate.baseRevision,
192
+ candidateRevision: candidate.publishedRevision,
193
+ effects: effectsForCandidate(candidate),
194
+ }));
195
+ }
196
+
197
+ function durabilityReceipt(git, filesChanged, stateOverride) {
198
+ const persistence =
199
+ git && git.persistence ? git.persistence : filesChanged ? "working_tree" : "none";
200
+ return {
201
+ state:
202
+ stateOverride ||
203
+ (filesChanged
204
+ ? git && ["committed", "observed_committed"].includes(git.commitState)
205
+ ? "git_committed"
206
+ : git && git.commitState === "unknown"
207
+ ? "commit_state_unknown"
208
+ : "filesystem_published_uncommitted"
209
+ : "not_persisted"),
210
+ filesChanged: Boolean(filesChanged),
211
+ persistence,
212
+ committed: git && hasOwn(git, "committed") ? git.committed : false,
213
+ commitState: git && git.commitState ? git.commitState : "not_requested",
214
+ affectedIndexState: git && git.affectedIndexState ? git.affectedIndexState : "not_inspected",
215
+ indexState: git && git.indexState ? git.indexState : "not_inspected",
216
+ crashDurable: false,
217
+ };
218
+ }
219
+
220
+ function snapshotReceipt(plan) {
221
+ return {
222
+ checkedAt: plan.generated.at,
223
+ timeOfCheck: true,
224
+ generatedBy: plan.generated.by,
225
+ graphValidation: "future_overlay",
226
+ };
227
+ }
228
+
229
+ function preconditionsReceipt(plan) {
230
+ return {
231
+ allSatisfied: Boolean(plan.validation.valid && plan.gitPreflight.ready),
232
+ revisions: plan.candidates.map((candidate) => ({
233
+ path: candidate.path,
234
+ absolutePath: candidate.target.absolutePath,
235
+ baseRevision: candidate.baseRevision,
236
+ candidateRevision: candidate.publishedRevision,
237
+ })),
238
+ git: {
239
+ enabled: plan.gitPreflight.enabled,
240
+ ready: plan.gitPreflight.ready,
241
+ repositoryStatus: plan.gitPreflight.repositoryStatus,
242
+ repositoryRoot: plan.gitPreflight.repositoryRoot,
243
+ headBefore: plan.gitPreflight.headBefore,
244
+ headRef: plan.gitPreflight.headRef,
245
+ worktreeClean: plan.gitPreflight.worktreeClean,
246
+ identityConfigured: plan.gitPreflight.identityConfigured,
247
+ diagnostics: plan.gitPreflight.diagnostics,
248
+ },
249
+ };
250
+ }
251
+
252
+ // Present only when the service enforces a write policy, so receipts of a
253
+ // server without one are unchanged.
254
+ function policyReceipt(plan) {
255
+ return plan.policy ? { policyViolations: plan.policy.violations } : {};
256
+ }
257
+
258
+ // The receipt of a batch rolled back before publication: for a failure, one
259
+ // whose files could not all be put back; without one, a batch whose
260
+ // persisted state failed validation (rolled back completely or not).
261
+ function rollbackReceipt(plan, rollback, error) {
262
+ const complete = !error && rollback.complete;
263
+ return {
264
+ applied: false,
265
+ readyToApply: false,
266
+ filesChanged: !complete,
267
+ status: complete ? "rolled_back" : "rollback_conflict",
268
+ snapshot: snapshotReceipt(plan),
269
+ preconditions: preconditionsReceipt(plan),
270
+ generated: plan.generated,
271
+ target: plan.target,
272
+ durability: durabilityReceipt(
273
+ null,
274
+ !complete,
275
+ complete ? "rolled_back" : "partial_filesystem_state",
276
+ ),
277
+ changes: plan.changes,
278
+ validation: plan.validation,
279
+ ...policyReceipt(plan),
280
+ rollback,
281
+ ...(error ? { error: error.message ? error.message : String(error) } : {}),
282
+ };
283
+ }
284
+
285
+ function validationReceipt(plan) {
286
+ const git = {
287
+ enabled: plan.gitPreflight.enabled,
288
+ repository: Boolean(plan.gitPreflight.repository),
289
+ repositoryRoot: plan.gitPreflight.repositoryRoot,
290
+ repositoryStatus: plan.gitPreflight.repositoryStatus,
291
+ ready: plan.gitPreflight.ready,
292
+ headBefore: plan.gitPreflight.headBefore,
293
+ headRef: plan.gitPreflight.headRef,
294
+ worktreeClean: plan.gitPreflight.worktreeClean,
295
+ identityConfigured: plan.gitPreflight.identityConfigured,
296
+ diagnostics: plan.gitPreflight.diagnostics,
297
+ commitState: "not_attempted",
298
+ persistence: "none",
299
+ };
300
+ const readyToApply = Boolean(plan.validation.valid && plan.gitPreflight.ready);
301
+ return {
302
+ valid: plan.validation.valid,
303
+ readyToApply,
304
+ applied: false,
305
+ filesChanged: false,
306
+ status: !plan.validation.valid ? "invalid" : readyToApply ? "ready" : "blocked",
307
+ snapshot: snapshotReceipt(plan),
308
+ preconditions: preconditionsReceipt(plan),
309
+ generated: plan.generated,
310
+ target: plan.target,
311
+ durability: durabilityReceipt(git, false),
312
+ changes: plan.changes,
313
+ validation: plan.validation,
314
+ ...policyReceipt(plan),
315
+ git,
316
+ };
317
+ }
318
+
319
+ module.exports = {
320
+ candidateSummaries,
321
+ durabilityReceipt,
322
+ policyReceipt,
323
+ policyValidation,
324
+ preconditionsReceipt,
325
+ rollbackReceipt,
326
+ snapshotReceipt,
327
+ targetReceipt,
328
+ validationReceipt,
329
+ };
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ // Frontmatter and concept Markdown rendering (split from src/authoring.js,
4
+ // plan Q-1); src/authoring.js re-exports both names for compatibility.
5
+
6
+ const path = require("node:path");
7
+ const yaml = require("js-yaml");
8
+
9
+ function renderFrontmatter(frontmatter) {
10
+ const values = Object.fromEntries(
11
+ Object.entries(frontmatter || {}).filter((entry) => entry[1] !== undefined),
12
+ );
13
+ return yaml
14
+ .dump(values, {
15
+ schema: yaml.CORE_SCHEMA,
16
+ noRefs: true,
17
+ lineWidth: -1,
18
+ sortKeys: false,
19
+ })
20
+ .trimEnd();
21
+ }
22
+
23
+ function renderConceptMarkdown(input) {
24
+ const frontmatter = Object.assign({}, input?.frontmatter || {});
25
+ const body = String(input?.body || "")
26
+ .replace(/\r\n/g, "\n")
27
+ .trim();
28
+ return [
29
+ "---",
30
+ renderFrontmatter(frontmatter),
31
+ "---",
32
+ "",
33
+ body || `# ${frontmatter.title || path.posix.basename(input.path || "concept.md", ".md")}`,
34
+ "",
35
+ ].join("\n");
36
+ }
37
+
38
+ module.exports = { renderConceptMarkdown, renderFrontmatter };
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+
5
+ const MAX_EFFECT_ITEMS = 20;
6
+ const MAX_EFFECT_TEXT = 240;
7
+
8
+ class AuthoringPolicyError extends Error {
9
+ constructor(message, code, details) {
10
+ super(message);
11
+ this.name = "AuthoringPolicyError";
12
+ if (code) this.code = code;
13
+ if (details !== undefined) this.details = details;
14
+ }
15
+ }
16
+
17
+ class AuthoringOperationalError extends Error {
18
+ constructor(message) {
19
+ super(message);
20
+ this.name = "AuthoringOperationalError";
21
+ }
22
+ }
23
+
24
+ function isPlainObject(value) {
25
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
26
+ return false;
27
+ }
28
+ const prototype = Object.getPrototypeOf(value);
29
+ return prototype === Object.prototype || prototype === null;
30
+ }
31
+
32
+ function hasOwn(value, key) {
33
+ return Boolean(value && Object.prototype.hasOwnProperty.call(value, key));
34
+ }
35
+
36
+ function commandOutput(result) {
37
+ return String((result && (result.stderr || result.stdout)) || "")
38
+ .trim()
39
+ .slice(0, 4000);
40
+ }
41
+
42
+ function commandFailure(result, fallback) {
43
+ return commandOutput(result) || (result && result.error && result.error.message) || fallback;
44
+ }
45
+
46
+ function commandSucceeded(result) {
47
+ return Boolean(result && !result.error && result.status === 0);
48
+ }
49
+
50
+ function revisionFor(text) {
51
+ return `sha256:${crypto.createHash("sha256").update(text).digest("hex")}`;
52
+ }
53
+
54
+ function byteLength(text) {
55
+ return Buffer.byteLength(String(text || ""), "utf8");
56
+ }
57
+
58
+ function sortedUnique(values) {
59
+ return Array.from(new Set(values)).sort();
60
+ }
61
+
62
+ module.exports = {
63
+ AuthoringOperationalError,
64
+ AuthoringPolicyError,
65
+ MAX_EFFECT_ITEMS,
66
+ MAX_EFFECT_TEXT,
67
+ byteLength,
68
+ commandFailure,
69
+ commandOutput,
70
+ commandSucceeded,
71
+ hasOwn,
72
+ isPlainObject,
73
+ revisionFor,
74
+ sortedUnique,
75
+ };
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+
7
+ const { revisionFor } = require("./shared");
8
+
9
+ function temporaryPath(target) {
10
+ return path.join(
11
+ path.dirname(target),
12
+ `.${path.basename(target)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`,
13
+ );
14
+ }
15
+
16
+ function restoreFile(target, text, mode) {
17
+ const temporary = temporaryPath(target);
18
+ try {
19
+ fs.writeFileSync(temporary, text, { encoding: "utf8", flag: "wx" });
20
+ if (mode !== null && mode !== undefined) {
21
+ fs.chmodSync(temporary, mode);
22
+ }
23
+ fs.renameSync(temporary, target);
24
+ } finally {
25
+ if (fs.existsSync(temporary)) {
26
+ fs.unlinkSync(temporary);
27
+ }
28
+ }
29
+ }
30
+
31
+ function ensureParentDirectories(store, candidate, createdDirectories) {
32
+ const bundleRoot = store.resolveWritableBundleRoot(store.getBundle(candidate.bundle));
33
+ const parent = path.dirname(candidate.target.absolutePath);
34
+ const relative = path.relative(bundleRoot, parent);
35
+ let current = bundleRoot;
36
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
37
+ current = path.join(current, segment);
38
+ if (fs.existsSync(current)) {
39
+ const stat = fs.lstatSync(current);
40
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
41
+ throw new Error(`Concept parent is not a safe directory: ${current}`);
42
+ }
43
+ continue;
44
+ }
45
+ fs.mkdirSync(current);
46
+ createdDirectories.push(current);
47
+ }
48
+ }
49
+
50
+ function cleanupDirectories(createdDirectories) {
51
+ createdDirectories
52
+ .slice()
53
+ .sort((left, right) => right.length - left.length)
54
+ .forEach((directory) => {
55
+ try {
56
+ fs.rmdirSync(directory);
57
+ } catch (error) {
58
+ if (!error || !["ENOENT", "ENOTEMPTY"].includes(error.code)) {
59
+ throw error;
60
+ }
61
+ }
62
+ });
63
+ }
64
+
65
+ function stageCandidates(store, candidates) {
66
+ const staged = [];
67
+ const createdDirectories = [];
68
+ try {
69
+ candidates.forEach((candidate) => {
70
+ ensureParentDirectories(store, candidate, createdDirectories);
71
+ const temporary = temporaryPath(candidate.target.absolutePath);
72
+ fs.writeFileSync(temporary, candidate.markdown, { encoding: "utf8", flag: "wx" });
73
+ const stagedCandidate = Object.assign({}, candidate, { temporary });
74
+ staged.push(stagedCandidate);
75
+ if (candidate.op === "update") {
76
+ fs.chmodSync(temporary, candidate.originalMode);
77
+ }
78
+ });
79
+ return { staged, createdDirectories };
80
+ } catch (error) {
81
+ staged.forEach((entry) => {
82
+ if (fs.existsSync(entry.temporary)) fs.unlinkSync(entry.temporary);
83
+ });
84
+ cleanupDirectories(createdDirectories);
85
+ throw error;
86
+ }
87
+ }
88
+
89
+ function assertRevisions(staged) {
90
+ staged.forEach((candidate) => {
91
+ const exists = fs.existsSync(candidate.target.absolutePath);
92
+ if (candidate.op === "create" && exists) {
93
+ throw new Error(`Concept file appeared during batch preparation: ${candidate.path}`);
94
+ }
95
+ if (candidate.op === "update") {
96
+ if (!exists) {
97
+ throw new Error(`Concept file disappeared during batch preparation: ${candidate.path}`);
98
+ }
99
+ const currentRevision = revisionFor(fs.readFileSync(candidate.target.absolutePath));
100
+ if (currentRevision !== candidate.baseRevision) {
101
+ throw new Error(`Concept changed during batch preparation: ${candidate.path}`);
102
+ }
103
+ }
104
+ });
105
+ }
106
+
107
+ function inspectPublishedTarget(candidate) {
108
+ try {
109
+ const stat = fs.lstatSync(candidate.target.absolutePath);
110
+ if (stat.isSymbolicLink() || !stat.isFile()) {
111
+ return { state: "non_regular", revision: null };
112
+ }
113
+ return {
114
+ state: "regular",
115
+ revision: revisionFor(fs.readFileSync(candidate.target.absolutePath)),
116
+ };
117
+ } catch (error) {
118
+ if (error && error.code === "ENOENT") {
119
+ return { state: "missing", revision: null };
120
+ }
121
+ throw error;
122
+ }
123
+ }
124
+
125
+ function rollbackCandidate(candidate) {
126
+ const inspected = inspectPublishedTarget(candidate);
127
+ const receipt = {
128
+ op: candidate.op,
129
+ path: candidate.path,
130
+ absolutePath: candidate.target.absolutePath,
131
+ expectedPublishedRevision: candidate.publishedRevision,
132
+ observedRevision: inspected.revision,
133
+ };
134
+ if (candidate.op === "create" && inspected.state === "missing") {
135
+ return Object.assign(receipt, { status: "already_absent", restored: true });
136
+ }
137
+ if (inspected.state !== "regular" || inspected.revision !== candidate.publishedRevision) {
138
+ return Object.assign(receipt, {
139
+ status: "conflict",
140
+ restored: false,
141
+ observedState: inspected.state,
142
+ });
143
+ }
144
+ if (candidate.op === "create") {
145
+ fs.unlinkSync(candidate.target.absolutePath);
146
+ return Object.assign(receipt, { status: "removed", restored: true });
147
+ }
148
+ restoreFile(candidate.target.absolutePath, candidate.originalText, candidate.originalMode);
149
+ const restored = inspectPublishedTarget(candidate);
150
+ if (restored.state !== "regular" || restored.revision !== candidate.baseRevision) {
151
+ return Object.assign(receipt, {
152
+ status: "restore_verification_failed",
153
+ restored: false,
154
+ restoredRevision: restored.revision,
155
+ });
156
+ }
157
+ return Object.assign(receipt, {
158
+ status: "restored",
159
+ restored: true,
160
+ restoredRevision: restored.revision,
161
+ });
162
+ }
163
+
164
+ function rollback(applied, staged, createdDirectories) {
165
+ const failures = [];
166
+ const outcomes = [];
167
+ staged.forEach((candidate) => {
168
+ if (fs.existsSync(candidate.temporary)) {
169
+ try {
170
+ fs.unlinkSync(candidate.temporary);
171
+ } catch (error) {
172
+ failures.push(error);
173
+ }
174
+ }
175
+ });
176
+ applied
177
+ .slice()
178
+ .reverse()
179
+ .forEach((candidate) => {
180
+ try {
181
+ outcomes.push(rollbackCandidate(candidate));
182
+ } catch (error) {
183
+ const failure = {
184
+ op: candidate.op,
185
+ path: candidate.path,
186
+ absolutePath: candidate.target.absolutePath,
187
+ status: "error",
188
+ restored: false,
189
+ error: error && error.message ? error.message : String(error),
190
+ };
191
+ outcomes.push(failure);
192
+ failures.push(failure);
193
+ }
194
+ });
195
+ try {
196
+ cleanupDirectories(createdDirectories || []);
197
+ } catch (error) {
198
+ failures.push({
199
+ status: "directory_cleanup_error",
200
+ error: error && error.message ? error.message : String(error),
201
+ });
202
+ }
203
+ const conflicts = outcomes.filter((outcome) => !outcome.restored);
204
+ return {
205
+ complete: conflicts.length === 0 && failures.length === 0,
206
+ outcomes,
207
+ conflicts,
208
+ failures,
209
+ };
210
+ }
211
+
212
+ module.exports = {
213
+ assertRevisions,
214
+ rollback,
215
+ stageCandidates,
216
+ };