@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,776 @@
1
+ "use strict";
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 gitPreflight = require("./git-preflight");
10
+ const {
11
+ AuthoringPolicyError,
12
+ commandFailure,
13
+ commandSucceeded,
14
+ hasOwn,
15
+ revisionFor,
16
+ sortedUnique,
17
+ } = require("./shared");
18
+
19
+ class GitPublisher {
20
+ constructor(options) {
21
+ const config = options || {};
22
+ this.gitCommit = Boolean(config.gitCommit);
23
+ this.spawnSync = config.spawnSync || nodeSpawnSync;
24
+ }
25
+
26
+ runGit(directory, args, options) {
27
+ const environment = Object.assign({}, process.env);
28
+ Object.keys(environment)
29
+ .filter((key) => key.startsWith("GIT_"))
30
+ .forEach((key) => {
31
+ delete environment[key];
32
+ });
33
+ if (options && options.environment) {
34
+ Object.assign(environment, options.environment);
35
+ }
36
+ environment.GIT_LITERAL_PATHSPECS = "1";
37
+ environment.GIT_TERMINAL_PROMPT = "0";
38
+ environment.GIT_PAGER = "cat";
39
+ environment.GIT_NO_REPLACE_OBJECTS = "1";
40
+ if (options && options.readOnly) {
41
+ environment.GIT_OPTIONAL_LOCKS = "0";
42
+ }
43
+ const spawnOptions = {
44
+ encoding: "utf8",
45
+ shell: false,
46
+ maxBuffer: 8 * 1024 * 1024,
47
+ timeout: 15000,
48
+ env: environment,
49
+ };
50
+ if (options && hasOwn(options, "input")) {
51
+ spawnOptions.input = options.input;
52
+ }
53
+ try {
54
+ return this.spawnSync(
55
+ "git",
56
+ [
57
+ "-C",
58
+ directory,
59
+ "-c",
60
+ "core.hooksPath=/dev/null",
61
+ "-c",
62
+ "core.fsmonitor=false",
63
+ "-c",
64
+ "commit.gpgSign=false",
65
+ "-c",
66
+ "diff.external=",
67
+ ].concat(args),
68
+ spawnOptions,
69
+ );
70
+ } catch (error) {
71
+ return { status: null, stdout: "", stderr: "", error };
72
+ }
73
+ }
74
+
75
+ readGitValue(repository, args, options) {
76
+ const result = this.runGit(repository, args, options);
77
+ return commandSucceeded(result) ? String(result.stdout || "").trim() : null;
78
+ }
79
+
80
+ prepareGit(bundle, candidates) {
81
+ return gitPreflight.prepareGit(this, bundle, candidates);
82
+ }
83
+
84
+ repositoryFiles(preflight, candidates) {
85
+ const files = sortedUnique(
86
+ candidates.map((candidate) =>
87
+ path.relative(preflight.repository, candidate.target.absolutePath).replace(/\\/g, "/"),
88
+ ),
89
+ );
90
+ if (
91
+ files.some(
92
+ (file) => !file || file === ".." || file.startsWith("../") || path.isAbsolute(file),
93
+ )
94
+ ) {
95
+ throw new AuthoringPolicyError(
96
+ "An affected concept path is outside the detected Git repository.",
97
+ );
98
+ }
99
+ return files;
100
+ }
101
+
102
+ inspectGitState(repository, revision, files) {
103
+ const affected = this.runGit(
104
+ repository,
105
+ ["diff", "--no-ext-diff", "--cached", "--quiet", revision, "--"].concat(files),
106
+ );
107
+ const global = this.runGit(repository, [
108
+ "diff",
109
+ "--no-ext-diff",
110
+ "--cached",
111
+ "--quiet",
112
+ revision,
113
+ "--",
114
+ ]);
115
+ const worktree = this.runGit(
116
+ repository,
117
+ ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--"].concat(files),
118
+ );
119
+ const state = (result) => {
120
+ if (result && !result.error && result.status === 0) return "clean";
121
+ if (result && !result.error && result.status === 1) return "dirty";
122
+ return "unknown";
123
+ };
124
+ return {
125
+ affectedIndexState: state(affected),
126
+ indexState: state(global),
127
+ affectedWorktreeState: !commandSucceeded(worktree)
128
+ ? "unknown"
129
+ : String(worktree.stdout || "")
130
+ .split("\0")
131
+ .filter(Boolean)
132
+ .some((entry) => entry.startsWith("??") || (entry.length > 1 && entry[1] !== " "))
133
+ ? "dirty"
134
+ : "clean",
135
+ };
136
+ }
137
+
138
+ classifyCommit(preflight, expectedTree) {
139
+ const headAfter = this.readGitValue(preflight.repository, [
140
+ "rev-parse",
141
+ "--verify",
142
+ preflight.headRef || "HEAD",
143
+ ]);
144
+ if (!headAfter) {
145
+ return { commitState: "unknown", committed: null, headAfter: null };
146
+ }
147
+ if (headAfter === preflight.headBefore) {
148
+ return { commitState: "not_committed", committed: false, headAfter };
149
+ }
150
+ const treeAfter = this.readGitValue(preflight.repository, ["rev-parse", `${headAfter}^{tree}`]);
151
+ const parentAfter = this.readGitValue(preflight.repository, ["rev-parse", `${headAfter}^`]);
152
+ if (expectedTree && treeAfter === expectedTree && parentAfter === preflight.headBefore) {
153
+ return {
154
+ commitState: "committed",
155
+ committed: true,
156
+ commitSha: headAfter,
157
+ headAfter,
158
+ treeAfter,
159
+ };
160
+ }
161
+ return {
162
+ commitState: "unknown",
163
+ committed: null,
164
+ headAfter,
165
+ treeAfter,
166
+ parentAfter,
167
+ };
168
+ }
169
+
170
+ inspectPublishedTargets(candidates) {
171
+ const checks = candidates.map((candidate) => {
172
+ try {
173
+ const stat = fs.lstatSync(candidate.target.absolutePath);
174
+ if (!stat.isFile() || stat.isSymbolicLink()) {
175
+ return {
176
+ path: candidate.path,
177
+ absolutePath: candidate.target.absolutePath,
178
+ expectedRevision: candidate.publishedRevision,
179
+ observedState: "non_regular",
180
+ observedRevision: null,
181
+ matches: false,
182
+ };
183
+ }
184
+ const observedRevision = revisionFor(fs.readFileSync(candidate.target.absolutePath));
185
+ return {
186
+ path: candidate.path,
187
+ absolutePath: candidate.target.absolutePath,
188
+ expectedRevision: candidate.publishedRevision,
189
+ observedState: "regular",
190
+ observedRevision,
191
+ matches: observedRevision === candidate.publishedRevision,
192
+ };
193
+ } catch (error) {
194
+ return {
195
+ path: candidate.path,
196
+ absolutePath: candidate.target.absolutePath,
197
+ expectedRevision: candidate.publishedRevision,
198
+ observedState: error && error.code === "ENOENT" ? "missing" : "unavailable",
199
+ observedRevision: null,
200
+ matches: false,
201
+ };
202
+ }
203
+ });
204
+ const conflicts = checks.filter((check) => !check.matches);
205
+ return {
206
+ targetState: conflicts.length ? "conflict" : "matching",
207
+ validatedFilesPresent: conflicts.length === 0,
208
+ targetChecks: checks,
209
+ targetConflicts: conflicts,
210
+ };
211
+ }
212
+
213
+ synchronizeCommittedIndex(preflight, classification, files) {
214
+ const currentHeadRef = this.readGitValue(preflight.repository, ["symbolic-ref", "-q", "HEAD"]);
215
+ if (!preflight.headRef || currentHeadRef !== preflight.headRef) {
216
+ const inspected = this.inspectGitState(preflight.repository, classification.headAfter, files);
217
+ return Object.assign(
218
+ {
219
+ indexSynchronization: "skipped_checkout_changed",
220
+ checkoutState: "changed",
221
+ currentHeadRef,
222
+ indexSynchronizationError:
223
+ "The checked-out Git ref changed before affected index paths could be synchronized.",
224
+ },
225
+ inspected,
226
+ );
227
+ }
228
+ const indexPath = this.gitIndexPath(preflight.repository);
229
+ const headPath = this.gitControlPath(preflight.repository, "HEAD");
230
+ const branchPath = preflight.headRef
231
+ ? this.gitControlPath(preflight.repository, preflight.headRef)
232
+ : null;
233
+ if (!indexPath || !headPath || !branchPath) {
234
+ const inspected = this.inspectGitState(preflight.repository, classification.headAfter, files);
235
+ return Object.assign(
236
+ {
237
+ indexSynchronization: "skipped_index_unavailable",
238
+ indexSynchronizationError: "Could not resolve the Git index path.",
239
+ },
240
+ inspected,
241
+ );
242
+ }
243
+ const lockPath = `${indexPath}.lock`;
244
+ const headLockPath = `${headPath}.lock`;
245
+ const branchLockPath = `${branchPath}.lock`;
246
+ let lockDescriptor = null;
247
+ let lockOwned = false;
248
+ let headLockDescriptor = null;
249
+ let headLockOwned = false;
250
+ let branchLockDescriptor = null;
251
+ let branchLockOwned = false;
252
+ let attemptedLock = "index";
253
+ let published = false;
254
+ try {
255
+ const indexStat = fs.statSync(indexPath);
256
+ lockDescriptor = fs.openSync(lockPath, "wx", indexStat.mode & 0o777);
257
+ lockOwned = true;
258
+ fs.writeFileSync(lockDescriptor, fs.readFileSync(indexPath));
259
+ fs.closeSync(lockDescriptor);
260
+ lockDescriptor = null;
261
+ attemptedLock = "checkout";
262
+ headLockDescriptor = fs.openSync(headLockPath, "wx", 0o666);
263
+ headLockOwned = true;
264
+ fs.closeSync(headLockDescriptor);
265
+ headLockDescriptor = null;
266
+ attemptedLock = "branch";
267
+ branchLockDescriptor = fs.openSync(branchLockPath, "wx", 0o666);
268
+ branchLockOwned = true;
269
+ fs.closeSync(branchLockDescriptor);
270
+ branchLockDescriptor = null;
271
+ const lockedHeadRef = this.readGitValue(preflight.repository, ["symbolic-ref", "-q", "HEAD"]);
272
+ const lockedBranchHead = this.readGitValue(preflight.repository, [
273
+ "rev-parse",
274
+ "--verify",
275
+ preflight.headRef,
276
+ ]);
277
+ if (lockedHeadRef !== preflight.headRef || lockedBranchHead !== classification.headAfter) {
278
+ return {
279
+ indexSynchronization: "skipped_checkout_changed",
280
+ checkoutState: "changed",
281
+ currentHeadRef: lockedHeadRef,
282
+ currentBranchHead: lockedBranchHead,
283
+ indexSynchronizationError:
284
+ "The checked-out Git ref or its commit changed before affected index paths could be synchronized.",
285
+ affectedIndexState: "unknown",
286
+ indexState: "unknown",
287
+ affectedWorktreeState: "unknown",
288
+ };
289
+ }
290
+ const lockedIndex = { environment: { GIT_INDEX_FILE: lockPath } };
291
+ const candidateIndexChanged = this.runGit(
292
+ preflight.repository,
293
+ ["diff", "--no-ext-diff", "--cached", "--quiet", preflight.headBefore, "--"].concat(files),
294
+ lockedIndex,
295
+ );
296
+ if (!commandSucceeded(candidateIndexChanged)) {
297
+ const inspected = this.inspectGitState(
298
+ preflight.repository,
299
+ classification.headAfter,
300
+ files,
301
+ );
302
+ return Object.assign(
303
+ {
304
+ indexSynchronization:
305
+ candidateIndexChanged &&
306
+ !candidateIndexChanged.error &&
307
+ candidateIndexChanged.status === 1
308
+ ? "skipped_affected_index_changed"
309
+ : "skipped_index_unavailable",
310
+ indexSynchronizationError:
311
+ candidateIndexChanged &&
312
+ !candidateIndexChanged.error &&
313
+ candidateIndexChanged.status === 1
314
+ ? "Affected Git index entries changed after preflight and were preserved."
315
+ : commandFailure(
316
+ candidateIndexChanged,
317
+ "Could not verify affected Git index entries.",
318
+ ),
319
+ },
320
+ inspected,
321
+ );
322
+ }
323
+ const reset = this.runGit(
324
+ preflight.repository,
325
+ ["reset", "--quiet", classification.headAfter, "--"].concat(files),
326
+ lockedIndex,
327
+ );
328
+ if (!commandSucceeded(reset)) {
329
+ const inspected = this.inspectGitState(
330
+ preflight.repository,
331
+ classification.headAfter,
332
+ files,
333
+ );
334
+ return Object.assign(
335
+ {
336
+ indexSynchronization: "failed",
337
+ indexSynchronizationError: commandFailure(
338
+ reset,
339
+ "Could not synchronize committed index paths.",
340
+ ),
341
+ },
342
+ inspected,
343
+ );
344
+ }
345
+ const verified = this.runGit(
346
+ preflight.repository,
347
+ ["diff", "--no-ext-diff", "--cached", "--quiet", classification.headAfter, "--"].concat(
348
+ files,
349
+ ),
350
+ lockedIndex,
351
+ );
352
+ if (!commandSucceeded(verified)) {
353
+ const inspected = this.inspectGitState(
354
+ preflight.repository,
355
+ classification.headAfter,
356
+ files,
357
+ );
358
+ return Object.assign(
359
+ {
360
+ indexSynchronization: "failed_verification",
361
+ indexSynchronizationError: commandFailure(
362
+ verified,
363
+ "Synchronized index verification failed.",
364
+ ),
365
+ },
366
+ inspected,
367
+ );
368
+ }
369
+ fs.renameSync(lockPath, indexPath);
370
+ published = true;
371
+ return Object.assign(
372
+ {
373
+ indexSynchronization: "synchronized",
374
+ },
375
+ this.inspectGitState(preflight.repository, classification.headAfter, files),
376
+ );
377
+ } catch (error) {
378
+ const inspected = this.inspectGitState(preflight.repository, classification.headAfter, files);
379
+ return Object.assign(
380
+ {
381
+ indexSynchronization:
382
+ error && error.code === "EEXIST"
383
+ ? attemptedLock === "index"
384
+ ? "skipped_index_locked"
385
+ : attemptedLock === "checkout"
386
+ ? "skipped_checkout_locked"
387
+ : "skipped_branch_locked"
388
+ : "failed",
389
+ indexSynchronizationError:
390
+ error && error.code === "EEXIST"
391
+ ? `The Git ${attemptedLock} state is locked by another writer; its state was preserved.`
392
+ : error && error.message
393
+ ? error.message
394
+ : String(error),
395
+ },
396
+ inspected,
397
+ );
398
+ } finally {
399
+ if (lockDescriptor !== null) {
400
+ try {
401
+ fs.closeSync(lockDescriptor);
402
+ } catch {
403
+ // Best-effort descriptor cleanup after a failed synchronization.
404
+ }
405
+ }
406
+ if (headLockDescriptor !== null) {
407
+ try {
408
+ fs.closeSync(headLockDescriptor);
409
+ } catch {
410
+ // Best-effort descriptor cleanup after a failed synchronization.
411
+ }
412
+ }
413
+ if (branchLockDescriptor !== null) {
414
+ try {
415
+ fs.closeSync(branchLockDescriptor);
416
+ } catch {
417
+ // Best-effort descriptor cleanup after a failed synchronization.
418
+ }
419
+ }
420
+ if (lockOwned && !published) {
421
+ for (const target of [lockPath, `${lockPath}.lock`]) {
422
+ try {
423
+ fs.unlinkSync(target);
424
+ } catch (error) {
425
+ if (!error || error.code !== "ENOENT") {
426
+ // The index itself remains untouched; the receipt reports synchronization failure.
427
+ }
428
+ }
429
+ }
430
+ }
431
+ for (const [owned, target] of [
432
+ [branchLockOwned, branchLockPath],
433
+ [headLockOwned, headLockPath],
434
+ ]) {
435
+ if (!owned) continue;
436
+ try {
437
+ fs.unlinkSync(target);
438
+ } catch (error) {
439
+ if (!error || error.code !== "ENOENT") {
440
+ // The receipt already reports the synchronization outcome.
441
+ }
442
+ }
443
+ }
444
+ }
445
+ }
446
+
447
+ finalizeGitFailure(preflight, files, failure, expectedTree, candidates) {
448
+ const classification = this.classifyCommit(preflight, expectedTree);
449
+ if (classification.committed === true) {
450
+ const synchronized = this.synchronizeCommittedIndex(preflight, classification, files);
451
+ const targets = this.inspectPublishedTargets(candidates);
452
+ return Object.assign(
453
+ {},
454
+ classification,
455
+ {
456
+ enabled: true,
457
+ repository: true,
458
+ repositoryRoot: preflight.repository,
459
+ commitState: "observed_committed",
460
+ persistence: "git_commit",
461
+ warning: commandFailure(failure, "Git reported failure after the commit became visible."),
462
+ },
463
+ synchronized,
464
+ targets,
465
+ );
466
+ }
467
+ if (classification.committed === false) {
468
+ const inspected = this.inspectGitState(preflight.repository, preflight.headBefore, files);
469
+ const targets = this.inspectPublishedTargets(candidates);
470
+ return Object.assign(
471
+ {
472
+ enabled: true,
473
+ repository: true,
474
+ repositoryRoot: preflight.repository,
475
+ committed: false,
476
+ commitState: "not_committed",
477
+ persistence: targets.validatedFilesPresent ? "working_tree" : "unknown",
478
+ error: commandFailure(failure, "Git commit failed"),
479
+ },
480
+ classification,
481
+ inspected,
482
+ targets,
483
+ );
484
+ }
485
+ const inspected = classification.headAfter
486
+ ? this.inspectGitState(preflight.repository, classification.headAfter, files)
487
+ : { affectedIndexState: "unknown", indexState: "unknown", affectedWorktreeState: "unknown" };
488
+ const targets = this.inspectPublishedTargets(candidates);
489
+ return Object.assign(
490
+ {
491
+ enabled: true,
492
+ repository: true,
493
+ repositoryRoot: preflight.repository,
494
+ committed: null,
495
+ commitState: "unknown",
496
+ persistence: "unknown",
497
+ error: commandFailure(failure, "Git commit outcome could not be determined"),
498
+ },
499
+ classification,
500
+ inspected,
501
+ targets,
502
+ );
503
+ }
504
+
505
+ gitControlPath(repository, name) {
506
+ const controlPath = this.readGitValue(repository, ["rev-parse", "--git-path", name], {
507
+ readOnly: true,
508
+ });
509
+ if (!controlPath) {
510
+ return null;
511
+ }
512
+ return path.isAbsolute(controlPath) ? controlPath : path.resolve(repository, controlPath);
513
+ }
514
+
515
+ gitIndexPath(repository) {
516
+ return this.gitControlPath(repository, "index");
517
+ }
518
+
519
+ temporaryGitIndex(repository) {
520
+ const absoluteIndex = this.gitIndexPath(repository);
521
+ return absoluteIndex
522
+ ? `${absoluteIndex}.okf-${process.pid}-${crypto.randomBytes(8).toString("hex")}`
523
+ : null;
524
+ }
525
+
526
+ removeTemporaryGitIndex(indexPath) {
527
+ [indexPath, `${indexPath}.lock`].forEach((target) => {
528
+ try {
529
+ fs.unlinkSync(target);
530
+ } catch (error) {
531
+ if (!error || error.code !== "ENOENT") {
532
+ // A leftover isolated index is inert and must not obscure the commit result.
533
+ }
534
+ }
535
+ });
536
+ }
537
+
538
+ buildValidatedGitTree(preflight, candidates, files) {
539
+ const indexPath = this.temporaryGitIndex(preflight.repository);
540
+ if (!indexPath) {
541
+ return { failure: { status: 1, stderr: "Could not allocate an isolated Git index." } };
542
+ }
543
+ const isolated = { environment: { GIT_INDEX_FILE: indexPath } };
544
+ try {
545
+ const seeded = this.runGit(
546
+ preflight.repository,
547
+ ["read-tree", preflight.headBefore],
548
+ isolated,
549
+ );
550
+ if (!commandSucceeded(seeded)) {
551
+ return { failure: seeded };
552
+ }
553
+ for (const candidate of candidates) {
554
+ const hashed = this.runGit(preflight.repository, ["hash-object", "-w", "--stdin"], {
555
+ input: candidate.markdown,
556
+ });
557
+ if (!commandSucceeded(hashed)) {
558
+ return { failure: hashed };
559
+ }
560
+ const objectId = String(hashed.stdout || "").trim();
561
+ let mode = "100644";
562
+ if (candidate.op === "update") {
563
+ const relativePath = path
564
+ .relative(preflight.repository, candidate.target.absolutePath)
565
+ .replace(/\\/g, "/");
566
+ const seededEntry = this.runGit(
567
+ preflight.repository,
568
+ ["ls-files", "-s", "-z", "--", relativePath],
569
+ isolated,
570
+ );
571
+ if (!commandSucceeded(seededEntry)) {
572
+ return { failure: seededEntry };
573
+ }
574
+ const match = String(seededEntry.stdout || "").match(/^([0-7]{6})\s/);
575
+ if (!match) {
576
+ return {
577
+ failure: {
578
+ status: 1,
579
+ stderr: `Could not preserve the pinned Git tree mode for ${relativePath}.`,
580
+ },
581
+ };
582
+ }
583
+ mode = match[1];
584
+ }
585
+ const updated = this.runGit(
586
+ preflight.repository,
587
+ [
588
+ "update-index",
589
+ "--add",
590
+ "--cacheinfo",
591
+ mode,
592
+ objectId,
593
+ path.relative(preflight.repository, candidate.target.absolutePath).replace(/\\/g, "/"),
594
+ ],
595
+ isolated,
596
+ );
597
+ if (!commandSucceeded(updated)) {
598
+ return { failure: updated };
599
+ }
600
+ }
601
+ const written = this.runGit(preflight.repository, ["write-tree"], isolated);
602
+ if (!commandSucceeded(written)) {
603
+ return { failure: written };
604
+ }
605
+ const expectedTree = String(written.stdout || "").trim();
606
+ const changed = this.runGit(preflight.repository, [
607
+ "diff",
608
+ "--no-ext-diff",
609
+ "--name-only",
610
+ "-z",
611
+ preflight.headBefore,
612
+ expectedTree,
613
+ "--",
614
+ ]);
615
+ const changedFiles = commandSucceeded(changed)
616
+ ? String(changed.stdout || "")
617
+ .split("\0")
618
+ .filter(Boolean)
619
+ .sort()
620
+ : null;
621
+ if (!changedFiles || !isDeepStrictEqual(changedFiles, files.slice().sort())) {
622
+ return {
623
+ expectedTree,
624
+ failure: {
625
+ status: 1,
626
+ stderr: commandSucceeded(changed)
627
+ ? "The isolated Git tree did not exactly match the validated OKF batch paths."
628
+ : commandFailure(changed, "Could not inspect the isolated Git tree."),
629
+ },
630
+ };
631
+ }
632
+ return { expectedTree };
633
+ } finally {
634
+ this.removeTemporaryGitIndex(indexPath);
635
+ }
636
+ }
637
+
638
+ commitGit(preflight, candidates, message) {
639
+ if (!preflight.enabled) {
640
+ return {
641
+ enabled: false,
642
+ committed: false,
643
+ commitState: "not_requested",
644
+ repository: Boolean(preflight.repository),
645
+ repositoryRoot: preflight.repository,
646
+ persistence: "working_tree",
647
+ };
648
+ }
649
+ if (!preflight.repository) {
650
+ return {
651
+ enabled: true,
652
+ repository: false,
653
+ repositoryRoot: null,
654
+ committed: false,
655
+ commitState: "not_repository",
656
+ persistence: "working_tree",
657
+ reason: "not_git_repository",
658
+ };
659
+ }
660
+ const files = this.repositoryFiles(preflight, candidates);
661
+ let expectedTree = null;
662
+ try {
663
+ const initialTargets = this.inspectPublishedTargets(candidates);
664
+ if (!initialTargets.validatedFilesPresent) {
665
+ return this.finalizeGitFailure(
666
+ preflight,
667
+ files,
668
+ {
669
+ status: 1,
670
+ stderr: "A published concept changed before the Git commit tree was built.",
671
+ },
672
+ null,
673
+ candidates,
674
+ );
675
+ }
676
+ const built = this.buildValidatedGitTree(preflight, candidates, files);
677
+ expectedTree = built.expectedTree || null;
678
+ if (built.failure) {
679
+ return this.finalizeGitFailure(preflight, files, built.failure, expectedTree, candidates);
680
+ }
681
+ const verifiedTargets = this.inspectPublishedTargets(candidates);
682
+ const headRefStillBefore = this.readGitValue(preflight.repository, [
683
+ "symbolic-ref",
684
+ "-q",
685
+ "HEAD",
686
+ ]);
687
+ const refStillBefore = this.readGitValue(preflight.repository, [
688
+ "rev-parse",
689
+ "--verify",
690
+ preflight.headRef,
691
+ ]);
692
+ if (
693
+ !verifiedTargets.validatedFilesPresent ||
694
+ headRefStillBefore !== preflight.headRef ||
695
+ refStillBefore !== preflight.headBefore
696
+ ) {
697
+ return this.finalizeGitFailure(
698
+ preflight,
699
+ files,
700
+ {
701
+ status: 1,
702
+ stderr: !verifiedTargets.validatedFilesPresent
703
+ ? "A published concept changed before the Git ref update."
704
+ : "The checked-out Git ref changed before the validated commit could be published.",
705
+ },
706
+ expectedTree,
707
+ candidates,
708
+ );
709
+ }
710
+ const committed = this.runGit(preflight.repository, [
711
+ "commit-tree",
712
+ expectedTree,
713
+ "-p",
714
+ preflight.headBefore,
715
+ "-m",
716
+ message,
717
+ ]);
718
+ if (!commandSucceeded(committed)) {
719
+ return this.finalizeGitFailure(preflight, files, committed, expectedTree, candidates);
720
+ }
721
+ const commitSha = String(committed.stdout || "").trim();
722
+ const finalTargets = this.inspectPublishedTargets(candidates);
723
+ if (!finalTargets.validatedFilesPresent) {
724
+ return this.finalizeGitFailure(
725
+ preflight,
726
+ files,
727
+ {
728
+ status: 1,
729
+ stderr: "A published concept changed before the validated commit was published.",
730
+ },
731
+ expectedTree,
732
+ candidates,
733
+ );
734
+ }
735
+ const updated = this.runGit(preflight.repository, [
736
+ "update-ref",
737
+ "-m",
738
+ "okf-mcp live authoring",
739
+ preflight.headRef,
740
+ commitSha,
741
+ preflight.headBefore,
742
+ ]);
743
+ const classification = this.classifyCommit(preflight, expectedTree);
744
+ if (!commandSucceeded(updated) || classification.committed !== true) {
745
+ return this.finalizeGitFailure(preflight, files, updated, expectedTree, candidates);
746
+ }
747
+ const synchronized = this.synchronizeCommittedIndex(preflight, classification, files);
748
+ const targets = this.inspectPublishedTargets(candidates);
749
+ return Object.assign(
750
+ {
751
+ enabled: true,
752
+ repository: true,
753
+ repositoryRoot: preflight.repository,
754
+ committed: true,
755
+ commitState: "committed",
756
+ persistence: "git_commit",
757
+ },
758
+ classification,
759
+ synchronized,
760
+ targets,
761
+ );
762
+ } catch (error) {
763
+ return this.finalizeGitFailure(
764
+ preflight,
765
+ files,
766
+ { status: null, stdout: "", stderr: "", error },
767
+ expectedTree,
768
+ candidates,
769
+ );
770
+ }
771
+ }
772
+ }
773
+
774
+ module.exports = {
775
+ GitPublisher,
776
+ };