@mfdaves/okf-mcp 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,11 @@ const path = require("node:path");
6
6
  const { spawnSync: nodeSpawnSync } = require("node:child_process");
7
7
  const { isDeepStrictEqual } = require("node:util");
8
8
 
9
- const { normalizeConceptPath, renderConceptMarkdown, slug } = require("./authoring");
9
+ const {
10
+ deriveConceptPathSuggestion,
11
+ normalizeConceptPath,
12
+ renderConceptMarkdown,
13
+ } = require("./authoring");
10
14
  const {
11
15
  attachProject,
12
16
  buildIndex,
@@ -17,6 +21,9 @@ const {
17
21
  const { validActor } = require("./v02");
18
22
 
19
23
  const MAX_CHANGES = 100;
24
+ const MAX_COMMIT_MESSAGE_BYTES = 1024;
25
+ const MAX_EFFECT_ITEMS = 20;
26
+ const MAX_EFFECT_TEXT = 240;
20
27
  const MANAGED_METADATA_KEYS = new Set([
21
28
  "id",
22
29
  "type",
@@ -35,6 +42,20 @@ const MANAGED_METADATA_KEYS = new Set([
35
42
  "attester",
36
43
  ]);
37
44
 
45
+ class AuthoringPolicyError extends Error {
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = "AuthoringPolicyError";
49
+ }
50
+ }
51
+
52
+ class AuthoringOperationalError extends Error {
53
+ constructor(message) {
54
+ super(message);
55
+ this.name = "AuthoringOperationalError";
56
+ }
57
+ }
58
+
38
59
  function isPlainObject(value) {
39
60
  if (!value || typeof value !== "object" || Array.isArray(value)) {
40
61
  return false;
@@ -346,10 +367,129 @@ function commandFailure(result, fallback) {
346
367
  || fallback;
347
368
  }
348
369
 
370
+ function commandSucceeded(result) {
371
+ return Boolean(result && !result.error && result.status === 0);
372
+ }
373
+
349
374
  function revisionFor(text) {
350
375
  return `sha256:${crypto.createHash("sha256").update(text).digest("hex")}`;
351
376
  }
352
377
 
378
+ function byteLength(text) {
379
+ return Buffer.byteLength(String(text || ""), "utf8");
380
+ }
381
+
382
+ function sortedUnique(values) {
383
+ return Array.from(new Set(values)).sort();
384
+ }
385
+
386
+ function boundedEffectList(values) {
387
+ const normalized = sortedUnique(values).map((value) => {
388
+ const text = String(value);
389
+ return text.length > MAX_EFFECT_TEXT ? `${text.slice(0, MAX_EFFECT_TEXT - 1)}…` : text;
390
+ });
391
+ return {
392
+ values: normalized.slice(0, MAX_EFFECT_ITEMS),
393
+ omitted: Math.max(0, normalized.length - MAX_EFFECT_ITEMS),
394
+ };
395
+ }
396
+
397
+ function collectionEffects(before, after, identity) {
398
+ const previous = new Map((before || []).map((value) => [identity(value), value]));
399
+ const next = new Map((after || []).map((value) => [identity(value), value]));
400
+ const added = Array.from(next.keys()).filter((key) => !previous.has(key)).sort();
401
+ const removed = Array.from(previous.keys()).filter((key) => !next.has(key)).sort();
402
+ const updated = Array.from(next.keys()).filter((key) => (
403
+ previous.has(key) && !isDeepStrictEqual(previous.get(key), next.get(key))
404
+ )).sort();
405
+ return {
406
+ added: boundedEffectList(added),
407
+ removed: boundedEffectList(removed),
408
+ updated: boundedEffectList(updated),
409
+ };
410
+ }
411
+
412
+ function metadataEffects(before, after) {
413
+ const excluded = new Set(["tags", "sources", "relations", "generated"]);
414
+ const keys = sortedUnique(Object.keys(before || {}).concat(Object.keys(after || {})))
415
+ .filter((key) => !excluded.has(key));
416
+ return {
417
+ set: boundedEffectList(keys.filter((key) => hasOwn(after, key) && !isDeepStrictEqual(before[key], after[key]))),
418
+ removed: boundedEffectList(keys.filter((key) => hasOwn(before, key) && !hasOwn(after, key))),
419
+ };
420
+ }
421
+
422
+ function effectsForCandidate(candidate) {
423
+ const before = candidate.op === "update" ? candidate.originalFrontmatter : {};
424
+ const after = candidate.frontmatter;
425
+ const tags = collectionEffects(before.tags, after.tags, (value) => String(value));
426
+ const sources = collectionEffects(before.sources, after.sources, sourceIdentity);
427
+ const relations = collectionEffects(before.relations, after.relations, relationKey);
428
+ const metadata = metadataEffects(before, after);
429
+ const bodyChanged = candidate.op === "create"
430
+ ? true
431
+ : normalizeBody(candidate.originalBody) !== normalizeBody(candidate.body);
432
+ const changedFields = [];
433
+ if (bodyChanged) changedFields.push("body");
434
+ const hasEffect = (group) => group.values.length || group.omitted;
435
+ if (hasEffect(tags.added) || hasEffect(tags.removed) || hasEffect(tags.updated)) changedFields.push("tags");
436
+ if (hasEffect(sources.added) || hasEffect(sources.removed) || hasEffect(sources.updated)) changedFields.push("sources");
437
+ if (hasEffect(relations.added) || hasEffect(relations.removed) || hasEffect(relations.updated)) changedFields.push("relations");
438
+ if (hasEffect(metadata.set) || hasEffect(metadata.removed)) changedFields.push("metadata");
439
+ if (!isDeepStrictEqual(before.generated, after.generated)) changedFields.push("generated");
440
+ return {
441
+ changedFields,
442
+ bodyChanged,
443
+ tags,
444
+ sources,
445
+ relations,
446
+ metadata,
447
+ beforeRevision: candidate.baseRevision,
448
+ afterRevision: candidate.publishedRevision,
449
+ bytesBefore: candidate.originalText === undefined ? 0 : byteLength(candidate.originalText),
450
+ bytesAfter: byteLength(candidate.markdown),
451
+ };
452
+ }
453
+
454
+ function policyCode(message) {
455
+ const text = String(message || "");
456
+ if (/generated|generator/i.test(text)) return "generated_owner_protected";
457
+ if (/Attested Computation|computation contract/i.test(text)) return "computation_authoring_prohibited";
458
+ if (/excluded by the bundle policy/i.test(text)) return "excluded_target";
459
+ if (/no effective changes/i.test(text)) return "no_effective_changes";
460
+ if (/same concept more than once/i.test(text)) return "duplicate_batch_target";
461
+ if (/already exists/i.test(text)) return "target_exists";
462
+ if (/unknown valid OKF concept/i.test(text)) return "concept_not_found";
463
+ if (/server-managed/i.test(text)) return "managed_metadata_protected";
464
+ if (/1 through \d+ operations/i.test(text)) return "invalid_batch_size";
465
+ if (/outside|travers|safe relative|unsafe segment|reserved index|reserved .*file|Markdown file|Markdown path/i.test(text)) return "unsafe_target_path";
466
+ if (/worktree must be completely clean/i.test(text)) return "git_worktree_dirty";
467
+ if (/Git filter attributes|repository-configured filters/i.test(text)) return "git_filter_attribute_unsupported";
468
+ if (/assume-unchanged|skip-worktree|Git index flags/i.test(text)) return "git_index_flag_unsupported";
469
+ if (/detached HEAD|symbolic branch|checked-out Git ref/i.test(text)) return "git_head_ref_unsupported";
470
+ if (/Git user\.(name|email)/i.test(text)) return "git_identity_missing";
471
+ if (/must have an existing HEAD/i.test(text)) return "git_head_missing";
472
+ if (/commit message/i.test(text)) return "invalid_commit_message";
473
+ return "authoring_policy_rejected";
474
+ }
475
+
476
+ function policyValidation(message) {
477
+ const code = policyCode(message);
478
+ return {
479
+ valid: false,
480
+ conformant: false,
481
+ validForProject: false,
482
+ diagnostics: [{
483
+ code,
484
+ severity: "error",
485
+ layer: "authoring",
486
+ message,
487
+ }],
488
+ errors: [{ code, message }],
489
+ warnings: [],
490
+ };
491
+ }
492
+
353
493
  function temporaryPath(target) {
354
494
  return path.join(
355
495
  path.dirname(target),
@@ -437,14 +577,14 @@ class LiveAuthoringService {
437
577
  return target;
438
578
  }
439
579
 
440
- createCandidate(change, bundle, generated) {
580
+ createCandidate(change, bundle, currentIndex, generated) {
441
581
  const type = nonEmptyString(change.type, "changes[].type");
442
582
  if (type === "Attested Computation") {
443
583
  throw new Error("Live concept authoring cannot create Attested Computation contracts.");
444
584
  }
445
585
  const title = nonEmptyString(change.title, "changes[].title");
446
586
  const conceptPath = normalizeConceptPath(
447
- change.path || `${slug(type, "concept")}/${slug(title, "concept")}.md`,
587
+ change.path || deriveConceptPathSuggestion(currentIndex, bundle, { type, title }).path,
448
588
  );
449
589
  if (!bundleAllowsPath(bundle, conceptPath)) {
450
590
  throw new Error(`Concept path is excluded by the bundle policy: ${conceptPath}`);
@@ -486,6 +626,9 @@ class LiveAuthoringService {
486
626
  markdown,
487
627
  target,
488
628
  baseRevision: null,
629
+ publishedRevision: revisionFor(markdown),
630
+ originalFrontmatter: {},
631
+ originalBody: "",
489
632
  };
490
633
  }
491
634
 
@@ -551,8 +694,11 @@ class LiveAuthoringService {
551
694
  markdown,
552
695
  target,
553
696
  baseRevision: diskRevision,
697
+ publishedRevision: revisionFor(markdown),
554
698
  originalText,
555
699
  originalMode,
700
+ originalFrontmatter: Object.assign({}, existing.frontmatter),
701
+ originalBody: existing.body,
556
702
  };
557
703
  }
558
704
 
@@ -591,105 +737,856 @@ class LiveAuthoringService {
591
737
  };
592
738
  }
593
739
 
594
- runGit(directory, args) {
740
+ runGit(directory, args, options) {
595
741
  const environment = Object.assign({}, process.env);
596
742
  Object.keys(environment).filter((key) => key.startsWith("GIT_")).forEach((key) => {
597
743
  delete environment[key];
598
744
  });
745
+ if (options && options.environment) {
746
+ Object.assign(environment, options.environment);
747
+ }
599
748
  environment.GIT_LITERAL_PATHSPECS = "1";
600
749
  environment.GIT_TERMINAL_PROMPT = "0";
601
- return this.spawnSync("git", [
602
- "-C",
603
- directory,
604
- "-c",
605
- "core.hooksPath=/dev/null",
606
- "-c",
607
- "commit.gpgSign=false",
608
- ].concat(args), {
750
+ environment.GIT_PAGER = "cat";
751
+ environment.GIT_NO_REPLACE_OBJECTS = "1";
752
+ if (options && options.readOnly) {
753
+ environment.GIT_OPTIONAL_LOCKS = "0";
754
+ }
755
+ const spawnOptions = {
609
756
  encoding: "utf8",
610
757
  shell: false,
611
- maxBuffer: 1024 * 1024,
758
+ maxBuffer: 8 * 1024 * 1024,
612
759
  timeout: 15000,
613
760
  env: environment,
761
+ };
762
+ if (options && hasOwn(options, "input")) {
763
+ spawnOptions.input = options.input;
764
+ }
765
+ try {
766
+ return this.spawnSync("git", [
767
+ "-C",
768
+ directory,
769
+ "-c",
770
+ "core.hooksPath=/dev/null",
771
+ "-c",
772
+ "core.fsmonitor=false",
773
+ "-c",
774
+ "commit.gpgSign=false",
775
+ "-c",
776
+ "diff.external=",
777
+ ].concat(args), spawnOptions);
778
+ } catch (error) {
779
+ return { status: null, stdout: "", stderr: "", error };
780
+ }
781
+ }
782
+
783
+ readGitValue(repository, args, options) {
784
+ const result = this.runGit(repository, args, options);
785
+ return commandSucceeded(result) ? String(result.stdout || "").trim() : null;
786
+ }
787
+
788
+ activeGitFilterAttributes(repository, candidates) {
789
+ const tracked = this.runGit(repository, ["ls-files", "-z"], { readOnly: true });
790
+ if (!commandSucceeded(tracked)) {
791
+ throw new AuthoringOperationalError(
792
+ `Could not inspect tracked Git paths: ${commandFailure(tracked, "git ls-files failed")}`,
793
+ );
794
+ }
795
+ const paths = sortedUnique(
796
+ String(tracked.stdout || "").split("\0").filter(Boolean)
797
+ .concat(this.repositoryFiles({ repository }, candidates)),
798
+ );
799
+ const active = [];
800
+ for (let offset = 0; offset < paths.length; offset += 200) {
801
+ const chunk = paths.slice(offset, offset + 200);
802
+ const inspected = this.runGit(
803
+ repository,
804
+ ["check-attr", "-z", "--all", "--"].concat(chunk),
805
+ { readOnly: true },
806
+ );
807
+ if (!commandSucceeded(inspected)) {
808
+ throw new AuthoringOperationalError(
809
+ `Could not inspect Git filter attributes: ${commandFailure(inspected, "git check-attr failed")}`,
810
+ );
811
+ }
812
+ const values = String(inspected.stdout || "").split("\0");
813
+ for (let index = 0; index + 2 < values.length; index += 3) {
814
+ const attribute = values[index + 1];
815
+ if (attribute === "filter") {
816
+ active.push({ path: values[index], filter: values[index + 2] || "set" });
817
+ }
818
+ }
819
+ }
820
+ return active;
821
+ }
822
+
823
+ unsupportedGitIndexFlags(repository) {
824
+ const inspected = this.runGit(repository, ["ls-files", "-v", "-z"], { readOnly: true });
825
+ if (!commandSucceeded(inspected)) {
826
+ throw new AuthoringOperationalError(
827
+ `Could not inspect Git index flags: ${commandFailure(inspected, "git ls-files failed")}`,
828
+ );
829
+ }
830
+ return String(inspected.stdout || "").split("\0").filter(Boolean).flatMap((entry) => {
831
+ const tag = entry[0] || "";
832
+ const flagged = tag === "S" || (/[a-z]/.test(tag) && tag === tag.toLowerCase());
833
+ if (!flagged) {
834
+ return [];
835
+ }
836
+ return [{
837
+ path: entry.slice(2),
838
+ flag: tag === "S" ? "skip-worktree" : "assume-unchanged",
839
+ }];
614
840
  });
615
841
  }
616
842
 
617
- prepareGit(bundle) {
843
+ prepareGit(bundle, candidates) {
844
+ const preflight = {
845
+ enabled: this.gitCommit,
846
+ repository: null,
847
+ repositoryStatus: this.gitCommit ? "not_git_repository" : "not_inspected",
848
+ repositoryRoot: null,
849
+ headBefore: null,
850
+ headRef: null,
851
+ worktreeClean: null,
852
+ identityConfigured: null,
853
+ ready: !this.gitCommit,
854
+ diagnostics: [],
855
+ };
618
856
  if (!this.gitCommit) {
619
- return { enabled: false, repository: null };
857
+ return preflight;
620
858
  }
621
- const discovered = this.runGit(bundle.root, ["rev-parse", "--show-toplevel"]);
859
+ const discovered = this.runGit(bundle.root, ["rev-parse", "--show-toplevel"], { readOnly: true });
622
860
  if (discovered.error) {
623
- throw new Error(`Git executable is unavailable: ${discovered.error.message}`);
861
+ if (this.gitCommit) {
862
+ throw new AuthoringOperationalError(`Git executable is unavailable: ${discovered.error.message}`);
863
+ }
864
+ return Object.assign(preflight, {
865
+ repositoryStatus: "unavailable",
866
+ inspectionError: discovered.error.message,
867
+ });
624
868
  }
625
869
  if (discovered.status !== 0) {
626
870
  const detail = commandOutput(discovered);
627
871
  if (/not a git repository/i.test(detail)) {
628
- return { enabled: true, repository: null };
872
+ preflight.ready = true;
873
+ return preflight;
629
874
  }
630
- throw new Error(`Could not inspect Git repository: ${detail || `git exited ${discovered.status}`}`);
631
- }
632
- const repository = String(discovered.stdout || "").trim();
633
- const status = this.runGit(repository, ["status", "--porcelain=v1", "--untracked-files=all"]);
634
- if (status.error || status.status !== 0) {
635
- throw new Error(`Could not inspect Git status: ${commandFailure(status, "git status failed")}`);
875
+ if (this.gitCommit) {
876
+ throw new AuthoringOperationalError(`Could not inspect Git repository: ${detail || `git exited ${discovered.status}`}`);
877
+ }
878
+ return Object.assign(preflight, {
879
+ repositoryStatus: "inspection_failed",
880
+ inspectionError: detail || `git exited ${discovered.status}`,
881
+ });
636
882
  }
637
- if (String(status.stdout || "").trim()) {
638
- throw new Error("Git worktree must be completely clean before an automatic OKF commit.");
883
+ const repository = path.resolve(String(discovered.stdout || "").trim());
884
+ preflight.repository = repository;
885
+ preflight.repositoryRoot = repository;
886
+ preflight.repositoryStatus = "detected";
887
+ const symbolicHead = this.runGit(
888
+ repository,
889
+ ["symbolic-ref", "-q", "HEAD"],
890
+ { readOnly: true },
891
+ );
892
+ if (symbolicHead.error || (symbolicHead.status !== 0 && symbolicHead.status !== 1)) {
893
+ throw new AuthoringOperationalError(
894
+ `Could not inspect the checked-out Git ref: ${commandFailure(symbolicHead, "git symbolic-ref failed")}`,
895
+ );
639
896
  }
897
+ const headRef = commandSucceeded(symbolicHead)
898
+ ? String(symbolicHead.stdout || "").trim()
899
+ : null;
900
+ preflight.headRef = headRef;
901
+ const headBefore = this.readGitValue(
902
+ repository,
903
+ ["rev-parse", "--verify", headRef || "HEAD"],
904
+ { readOnly: true },
905
+ );
906
+ preflight.headBefore = headBefore;
907
+ const missingIdentity = [];
640
908
  for (const key of ["user.name", "user.email"]) {
641
- const configured = this.runGit(repository, ["config", "--get", key]);
642
- if (configured.error || configured.status !== 0 || !String(configured.stdout || "").trim()) {
643
- throw new Error(`Git ${key} must be configured before an automatic OKF commit.`);
909
+ const configured = this.runGit(repository, ["config", "--get", key], { readOnly: true });
910
+ if (configured && configured.error) {
911
+ throw new AuthoringOperationalError(
912
+ `Could not inspect Git ${key}: ${configured.error.message}`,
913
+ );
914
+ }
915
+ if (configured && configured.status !== 0 && configured.status !== 1) {
916
+ throw new AuthoringOperationalError(
917
+ `Could not inspect Git ${key}: ${commandFailure(configured, `git config exited ${configured.status}`)}`,
918
+ );
919
+ }
920
+ if (!commandSucceeded(configured) || !String(configured.stdout || "").trim()) {
921
+ missingIdentity.push(key);
644
922
  }
645
923
  }
646
- return { enabled: true, repository };
924
+ preflight.identityConfigured = missingIdentity.length === 0;
925
+ const unsupportedIndexFlags = this.unsupportedGitIndexFlags(repository);
926
+ preflight.unsupportedIndexFlags = unsupportedIndexFlags.slice(0, MAX_EFFECT_ITEMS);
927
+ const activeFilters = this.activeGitFilterAttributes(repository, candidates);
928
+ preflight.activeFilterAttributes = activeFilters.slice(0, MAX_EFFECT_ITEMS);
929
+ if (!activeFilters.length && !unsupportedIndexFlags.length) {
930
+ const status = this.runGit(
931
+ repository,
932
+ ["status", "--porcelain=v1", "--untracked-files=all"],
933
+ { readOnly: true },
934
+ );
935
+ if (!commandSucceeded(status)) {
936
+ throw new AuthoringOperationalError(
937
+ `Could not inspect Git status: ${commandFailure(status, "git status failed")}`,
938
+ );
939
+ }
940
+ preflight.worktreeClean = !String(status.stdout || "").trim();
941
+ }
942
+ preflight.ready = !this.gitCommit || Boolean(
943
+ headBefore
944
+ && headRef
945
+ && preflight.worktreeClean
946
+ && preflight.identityConfigured
947
+ && !activeFilters.length
948
+ && !unsupportedIndexFlags.length,
949
+ );
950
+ if (this.gitCommit && !headBefore) {
951
+ preflight.diagnostics.push({
952
+ code: "git_head_missing",
953
+ message: "Git repository must have an existing HEAD before an automatic OKF commit.",
954
+ });
955
+ }
956
+ if (this.gitCommit && headBefore && !headRef) {
957
+ preflight.diagnostics.push({
958
+ code: "git_detached_head_unsupported",
959
+ message: "Automatic OKF commits require a checked-out symbolic branch; detached HEAD is not supported.",
960
+ });
961
+ }
962
+ if (this.gitCommit && preflight.worktreeClean === false) {
963
+ preflight.diagnostics.push({
964
+ code: "git_worktree_dirty",
965
+ message: "Git worktree must be completely clean before an automatic OKF commit.",
966
+ });
967
+ }
968
+ if (this.gitCommit && missingIdentity.length) {
969
+ preflight.diagnostics.push({
970
+ code: "git_identity_missing",
971
+ message: `Git ${missingIdentity[0]} must be configured before an automatic OKF commit.`,
972
+ });
973
+ }
974
+ if (this.gitCommit && activeFilters.length) {
975
+ preflight.diagnostics.push({
976
+ code: "git_filter_attribute_unsupported",
977
+ message: "Automatic OKF commits reject active Git filter attributes so validation cannot execute repository-configured filters and committed bytes remain exact.",
978
+ paths: activeFilters.slice(0, MAX_EFFECT_ITEMS),
979
+ omitted: Math.max(0, activeFilters.length - MAX_EFFECT_ITEMS),
980
+ });
981
+ }
982
+ if (this.gitCommit && unsupportedIndexFlags.length) {
983
+ preflight.diagnostics.push({
984
+ code: "git_index_flag_unsupported",
985
+ message: "Automatic OKF commits reject assume-unchanged and skip-worktree Git index flags because they can hide user changes from clean-worktree inspection.",
986
+ paths: unsupportedIndexFlags.slice(0, MAX_EFFECT_ITEMS),
987
+ omitted: Math.max(0, unsupportedIndexFlags.length - MAX_EFFECT_ITEMS),
988
+ });
989
+ }
990
+ return preflight;
647
991
  }
648
992
 
649
- commitGit(preflight, candidates, message) {
650
- if (!preflight.enabled) {
651
- return { enabled: false, committed: false };
993
+ repositoryFiles(preflight, candidates) {
994
+ const files = sortedUnique(candidates.map((candidate) => (
995
+ path.relative(preflight.repository, candidate.target.absolutePath).replace(/\\/g, "/")
996
+ )));
997
+ if (files.some((file) => !file || file === ".." || file.startsWith("../") || path.isAbsolute(file))) {
998
+ throw new AuthoringPolicyError("An affected concept path is outside the detected Git repository.");
652
999
  }
653
- if (!preflight.repository) {
654
- return { enabled: true, repository: false, committed: false, reason: "not_git_repository" };
1000
+ return files;
1001
+ }
1002
+
1003
+ inspectGitState(repository, revision, files) {
1004
+ const affected = this.runGit(repository, [
1005
+ "diff", "--no-ext-diff", "--cached", "--quiet", revision, "--",
1006
+ ].concat(files));
1007
+ const global = this.runGit(repository, [
1008
+ "diff", "--no-ext-diff", "--cached", "--quiet", revision, "--",
1009
+ ]);
1010
+ const worktree = this.runGit(repository, [
1011
+ "status", "--porcelain=v1", "-z", "--untracked-files=all", "--",
1012
+ ].concat(files));
1013
+ const state = (result) => {
1014
+ if (result && !result.error && result.status === 0) return "clean";
1015
+ if (result && !result.error && result.status === 1) return "dirty";
1016
+ return "unknown";
1017
+ };
1018
+ return {
1019
+ affectedIndexState: state(affected),
1020
+ indexState: state(global),
1021
+ affectedWorktreeState: !commandSucceeded(worktree)
1022
+ ? "unknown"
1023
+ : String(worktree.stdout || "").split("\0").filter(Boolean).some((entry) => (
1024
+ entry.startsWith("??") || entry.length > 1 && entry[1] !== " "
1025
+ )) ? "dirty" : "clean",
1026
+ };
1027
+ }
1028
+
1029
+ classifyCommit(preflight, expectedTree) {
1030
+ const headAfter = this.readGitValue(
1031
+ preflight.repository,
1032
+ ["rev-parse", "--verify", preflight.headRef || "HEAD"],
1033
+ );
1034
+ if (!headAfter) {
1035
+ return { commitState: "unknown", committed: null, headAfter: null };
655
1036
  }
656
- const files = candidates.map((candidate) => (
657
- path.relative(preflight.repository, candidate.target.absolutePath).replace(/\\/g, "/")
658
- ));
659
- if (files.some((file) => !file || file === ".." || file.startsWith("../"))) {
1037
+ if (headAfter === preflight.headBefore) {
1038
+ return { commitState: "not_committed", committed: false, headAfter };
1039
+ }
1040
+ const treeAfter = this.readGitValue(preflight.repository, ["rev-parse", `${headAfter}^{tree}`]);
1041
+ const parentAfter = this.readGitValue(preflight.repository, ["rev-parse", `${headAfter}^`]);
1042
+ if (expectedTree && treeAfter === expectedTree && parentAfter === preflight.headBefore) {
660
1043
  return {
1044
+ commitState: "committed",
1045
+ committed: true,
1046
+ commitSha: headAfter,
1047
+ headAfter,
1048
+ treeAfter,
1049
+ };
1050
+ }
1051
+ return {
1052
+ commitState: "unknown",
1053
+ committed: null,
1054
+ headAfter,
1055
+ treeAfter,
1056
+ parentAfter,
1057
+ };
1058
+ }
1059
+
1060
+ inspectPublishedTargets(candidates) {
1061
+ const checks = candidates.map((candidate) => {
1062
+ try {
1063
+ const stat = fs.lstatSync(candidate.target.absolutePath);
1064
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1065
+ return {
1066
+ path: candidate.path,
1067
+ absolutePath: candidate.target.absolutePath,
1068
+ expectedRevision: candidate.publishedRevision,
1069
+ observedState: "non_regular",
1070
+ observedRevision: null,
1071
+ matches: false,
1072
+ };
1073
+ }
1074
+ const observedRevision = revisionFor(fs.readFileSync(candidate.target.absolutePath));
1075
+ return {
1076
+ path: candidate.path,
1077
+ absolutePath: candidate.target.absolutePath,
1078
+ expectedRevision: candidate.publishedRevision,
1079
+ observedState: "regular",
1080
+ observedRevision,
1081
+ matches: observedRevision === candidate.publishedRevision,
1082
+ };
1083
+ } catch (error) {
1084
+ return {
1085
+ path: candidate.path,
1086
+ absolutePath: candidate.target.absolutePath,
1087
+ expectedRevision: candidate.publishedRevision,
1088
+ observedState: error && error.code === "ENOENT" ? "missing" : "unavailable",
1089
+ observedRevision: null,
1090
+ matches: false,
1091
+ };
1092
+ }
1093
+ });
1094
+ const conflicts = checks.filter((check) => !check.matches);
1095
+ return {
1096
+ targetState: conflicts.length ? "conflict" : "matching",
1097
+ validatedFilesPresent: conflicts.length === 0,
1098
+ targetChecks: checks,
1099
+ targetConflicts: conflicts,
1100
+ };
1101
+ }
1102
+
1103
+ synchronizeCommittedIndex(preflight, classification, files) {
1104
+ const currentHeadRef = this.readGitValue(
1105
+ preflight.repository,
1106
+ ["symbolic-ref", "-q", "HEAD"],
1107
+ );
1108
+ if (!preflight.headRef || currentHeadRef !== preflight.headRef) {
1109
+ const inspected = this.inspectGitState(
1110
+ preflight.repository,
1111
+ classification.headAfter,
1112
+ files,
1113
+ );
1114
+ return Object.assign({
1115
+ indexSynchronization: "skipped_checkout_changed",
1116
+ checkoutState: "changed",
1117
+ currentHeadRef,
1118
+ indexSynchronizationError: "The checked-out Git ref changed before affected index paths could be synchronized.",
1119
+ }, inspected);
1120
+ }
1121
+ const indexPath = this.gitIndexPath(preflight.repository);
1122
+ const headPath = this.gitControlPath(preflight.repository, "HEAD");
1123
+ const branchPath = preflight.headRef
1124
+ ? this.gitControlPath(preflight.repository, preflight.headRef)
1125
+ : null;
1126
+ if (!indexPath || !headPath || !branchPath) {
1127
+ const inspected = this.inspectGitState(
1128
+ preflight.repository,
1129
+ classification.headAfter,
1130
+ files,
1131
+ );
1132
+ return Object.assign({
1133
+ indexSynchronization: "skipped_index_unavailable",
1134
+ indexSynchronizationError: "Could not resolve the Git index path.",
1135
+ }, inspected);
1136
+ }
1137
+ const lockPath = `${indexPath}.lock`;
1138
+ const headLockPath = `${headPath}.lock`;
1139
+ const branchLockPath = `${branchPath}.lock`;
1140
+ let lockDescriptor = null;
1141
+ let lockOwned = false;
1142
+ let headLockDescriptor = null;
1143
+ let headLockOwned = false;
1144
+ let branchLockDescriptor = null;
1145
+ let branchLockOwned = false;
1146
+ let attemptedLock = "index";
1147
+ let published = false;
1148
+ try {
1149
+ const indexStat = fs.statSync(indexPath);
1150
+ lockDescriptor = fs.openSync(lockPath, "wx", indexStat.mode & 0o777);
1151
+ lockOwned = true;
1152
+ fs.writeFileSync(lockDescriptor, fs.readFileSync(indexPath));
1153
+ fs.closeSync(lockDescriptor);
1154
+ lockDescriptor = null;
1155
+ attemptedLock = "checkout";
1156
+ headLockDescriptor = fs.openSync(headLockPath, "wx", 0o666);
1157
+ headLockOwned = true;
1158
+ fs.closeSync(headLockDescriptor);
1159
+ headLockDescriptor = null;
1160
+ attemptedLock = "branch";
1161
+ branchLockDescriptor = fs.openSync(branchLockPath, "wx", 0o666);
1162
+ branchLockOwned = true;
1163
+ fs.closeSync(branchLockDescriptor);
1164
+ branchLockDescriptor = null;
1165
+ const lockedHeadRef = this.readGitValue(
1166
+ preflight.repository,
1167
+ ["symbolic-ref", "-q", "HEAD"],
1168
+ );
1169
+ const lockedBranchHead = this.readGitValue(
1170
+ preflight.repository,
1171
+ ["rev-parse", "--verify", preflight.headRef],
1172
+ );
1173
+ if (lockedHeadRef !== preflight.headRef
1174
+ || lockedBranchHead !== classification.headAfter) {
1175
+ return {
1176
+ indexSynchronization: "skipped_checkout_changed",
1177
+ checkoutState: "changed",
1178
+ currentHeadRef: lockedHeadRef,
1179
+ currentBranchHead: lockedBranchHead,
1180
+ indexSynchronizationError: "The checked-out Git ref or its commit changed before affected index paths could be synchronized.",
1181
+ affectedIndexState: "unknown",
1182
+ indexState: "unknown",
1183
+ affectedWorktreeState: "unknown",
1184
+ };
1185
+ }
1186
+ const lockedIndex = { environment: { GIT_INDEX_FILE: lockPath } };
1187
+ const candidateIndexChanged = this.runGit(preflight.repository, [
1188
+ "diff", "--no-ext-diff", "--cached", "--quiet", preflight.headBefore, "--",
1189
+ ].concat(files), lockedIndex);
1190
+ if (!commandSucceeded(candidateIndexChanged)) {
1191
+ const inspected = this.inspectGitState(
1192
+ preflight.repository,
1193
+ classification.headAfter,
1194
+ files,
1195
+ );
1196
+ return Object.assign({
1197
+ indexSynchronization: candidateIndexChanged && !candidateIndexChanged.error
1198
+ && candidateIndexChanged.status === 1
1199
+ ? "skipped_affected_index_changed"
1200
+ : "skipped_index_unavailable",
1201
+ indexSynchronizationError: candidateIndexChanged && !candidateIndexChanged.error
1202
+ && candidateIndexChanged.status === 1
1203
+ ? "Affected Git index entries changed after preflight and were preserved."
1204
+ : commandFailure(candidateIndexChanged, "Could not verify affected Git index entries."),
1205
+ }, inspected);
1206
+ }
1207
+ const reset = this.runGit(preflight.repository, [
1208
+ "reset", "--quiet", classification.headAfter, "--",
1209
+ ].concat(files), lockedIndex);
1210
+ if (!commandSucceeded(reset)) {
1211
+ const inspected = this.inspectGitState(
1212
+ preflight.repository,
1213
+ classification.headAfter,
1214
+ files,
1215
+ );
1216
+ return Object.assign({
1217
+ indexSynchronization: "failed",
1218
+ indexSynchronizationError: commandFailure(reset, "Could not synchronize committed index paths."),
1219
+ }, inspected);
1220
+ }
1221
+ const verified = this.runGit(preflight.repository, [
1222
+ "diff", "--no-ext-diff", "--cached", "--quiet", classification.headAfter, "--",
1223
+ ].concat(files), lockedIndex);
1224
+ if (!commandSucceeded(verified)) {
1225
+ const inspected = this.inspectGitState(
1226
+ preflight.repository,
1227
+ classification.headAfter,
1228
+ files,
1229
+ );
1230
+ return Object.assign({
1231
+ indexSynchronization: "failed_verification",
1232
+ indexSynchronizationError: commandFailure(verified, "Synchronized index verification failed."),
1233
+ }, inspected);
1234
+ }
1235
+ fs.renameSync(lockPath, indexPath);
1236
+ published = true;
1237
+ return Object.assign({
1238
+ indexSynchronization: "synchronized",
1239
+ }, this.inspectGitState(preflight.repository, classification.headAfter, files));
1240
+ } catch (error) {
1241
+ const inspected = this.inspectGitState(
1242
+ preflight.repository,
1243
+ classification.headAfter,
1244
+ files,
1245
+ );
1246
+ return Object.assign({
1247
+ indexSynchronization: error && error.code === "EEXIST"
1248
+ ? attemptedLock === "index"
1249
+ ? "skipped_index_locked"
1250
+ : attemptedLock === "checkout"
1251
+ ? "skipped_checkout_locked"
1252
+ : "skipped_branch_locked"
1253
+ : "failed",
1254
+ indexSynchronizationError: error && error.code === "EEXIST"
1255
+ ? `The Git ${attemptedLock} state is locked by another writer; its state was preserved.`
1256
+ : error && error.message ? error.message : String(error),
1257
+ }, inspected);
1258
+ } finally {
1259
+ if (lockDescriptor !== null) {
1260
+ try {
1261
+ fs.closeSync(lockDescriptor);
1262
+ } catch {
1263
+ // Best-effort descriptor cleanup after a failed synchronization.
1264
+ }
1265
+ }
1266
+ if (headLockDescriptor !== null) {
1267
+ try {
1268
+ fs.closeSync(headLockDescriptor);
1269
+ } catch {
1270
+ // Best-effort descriptor cleanup after a failed synchronization.
1271
+ }
1272
+ }
1273
+ if (branchLockDescriptor !== null) {
1274
+ try {
1275
+ fs.closeSync(branchLockDescriptor);
1276
+ } catch {
1277
+ // Best-effort descriptor cleanup after a failed synchronization.
1278
+ }
1279
+ }
1280
+ if (lockOwned && !published) {
1281
+ for (const target of [lockPath, `${lockPath}.lock`]) {
1282
+ try {
1283
+ fs.unlinkSync(target);
1284
+ } catch (error) {
1285
+ if (!error || error.code !== "ENOENT") {
1286
+ // The index itself remains untouched; the receipt reports synchronization failure.
1287
+ }
1288
+ }
1289
+ }
1290
+ }
1291
+ for (const [owned, target] of [
1292
+ [branchLockOwned, branchLockPath],
1293
+ [headLockOwned, headLockPath],
1294
+ ]) {
1295
+ if (!owned) continue;
1296
+ try {
1297
+ fs.unlinkSync(target);
1298
+ } catch (error) {
1299
+ if (!error || error.code !== "ENOENT") {
1300
+ // The receipt already reports the synchronization outcome.
1301
+ }
1302
+ }
1303
+ }
1304
+ }
1305
+ }
1306
+
1307
+ finalizeGitFailure(preflight, files, failure, expectedTree, candidates) {
1308
+ const classification = this.classifyCommit(preflight, expectedTree);
1309
+ if (classification.committed === true) {
1310
+ const synchronized = this.synchronizeCommittedIndex(preflight, classification, files);
1311
+ const targets = this.inspectPublishedTargets(candidates);
1312
+ return Object.assign({}, classification, {
661
1313
  enabled: true,
662
1314
  repository: true,
663
- committed: false,
664
- error: "An affected concept path is outside the detected Git repository.",
665
- };
1315
+ repositoryRoot: preflight.repository,
1316
+ commitState: "observed_committed",
1317
+ persistence: "git_commit",
1318
+ warning: commandFailure(failure, "Git reported failure after the commit became visible."),
1319
+ }, synchronized, targets);
666
1320
  }
667
- const add = this.runGit(preflight.repository, ["add", "--"].concat(files));
668
- if (add.error || add.status !== 0) {
669
- return {
1321
+ if (classification.committed === false) {
1322
+ const inspected = this.inspectGitState(preflight.repository, preflight.headBefore, files);
1323
+ const targets = this.inspectPublishedTargets(candidates);
1324
+ return Object.assign({
670
1325
  enabled: true,
671
1326
  repository: true,
1327
+ repositoryRoot: preflight.repository,
672
1328
  committed: false,
673
- error: commandFailure(add, "git add failed"),
1329
+ commitState: "not_committed",
1330
+ persistence: targets.validatedFilesPresent ? "working_tree" : "unknown",
1331
+ error: commandFailure(failure, "Git commit failed"),
1332
+ }, classification, inspected, targets);
1333
+ }
1334
+ const inspected = classification.headAfter
1335
+ ? this.inspectGitState(preflight.repository, classification.headAfter, files)
1336
+ : { affectedIndexState: "unknown", indexState: "unknown", affectedWorktreeState: "unknown" };
1337
+ const targets = this.inspectPublishedTargets(candidates);
1338
+ return Object.assign({
1339
+ enabled: true,
1340
+ repository: true,
1341
+ repositoryRoot: preflight.repository,
1342
+ committed: null,
1343
+ commitState: "unknown",
1344
+ persistence: "unknown",
1345
+ error: commandFailure(failure, "Git commit outcome could not be determined"),
1346
+ }, classification, inspected, targets);
1347
+ }
1348
+
1349
+ gitControlPath(repository, name) {
1350
+ const controlPath = this.readGitValue(
1351
+ repository,
1352
+ ["rev-parse", "--git-path", name],
1353
+ { readOnly: true },
1354
+ );
1355
+ if (!controlPath) {
1356
+ return null;
1357
+ }
1358
+ return path.isAbsolute(controlPath)
1359
+ ? controlPath
1360
+ : path.resolve(repository, controlPath);
1361
+ }
1362
+
1363
+ gitIndexPath(repository) {
1364
+ return this.gitControlPath(repository, "index");
1365
+ }
1366
+
1367
+ temporaryGitIndex(repository) {
1368
+ const absoluteIndex = this.gitIndexPath(repository);
1369
+ return absoluteIndex
1370
+ ? `${absoluteIndex}.okf-${process.pid}-${crypto.randomBytes(8).toString("hex")}`
1371
+ : null;
1372
+ }
1373
+
1374
+ removeTemporaryGitIndex(indexPath) {
1375
+ [indexPath, `${indexPath}.lock`].forEach((target) => {
1376
+ try {
1377
+ fs.unlinkSync(target);
1378
+ } catch (error) {
1379
+ if (!error || error.code !== "ENOENT") {
1380
+ // A leftover isolated index is inert and must not obscure the commit result.
1381
+ }
1382
+ }
1383
+ });
1384
+ }
1385
+
1386
+ buildValidatedGitTree(preflight, candidates, files) {
1387
+ const indexPath = this.temporaryGitIndex(preflight.repository);
1388
+ if (!indexPath) {
1389
+ return { failure: { status: 1, stderr: "Could not allocate an isolated Git index." } };
1390
+ }
1391
+ const isolated = { environment: { GIT_INDEX_FILE: indexPath } };
1392
+ try {
1393
+ const seeded = this.runGit(
1394
+ preflight.repository,
1395
+ ["read-tree", preflight.headBefore],
1396
+ isolated,
1397
+ );
1398
+ if (!commandSucceeded(seeded)) {
1399
+ return { failure: seeded };
1400
+ }
1401
+ for (const candidate of candidates) {
1402
+ const hashed = this.runGit(
1403
+ preflight.repository,
1404
+ ["hash-object", "-w", "--stdin"],
1405
+ { input: candidate.markdown },
1406
+ );
1407
+ if (!commandSucceeded(hashed)) {
1408
+ return { failure: hashed };
1409
+ }
1410
+ const objectId = String(hashed.stdout || "").trim();
1411
+ let mode = "100644";
1412
+ if (candidate.op === "update") {
1413
+ const relativePath = path.relative(
1414
+ preflight.repository,
1415
+ candidate.target.absolutePath,
1416
+ ).replace(/\\/g, "/");
1417
+ const seededEntry = this.runGit(preflight.repository, [
1418
+ "ls-files", "-s", "-z", "--", relativePath,
1419
+ ], isolated);
1420
+ if (!commandSucceeded(seededEntry)) {
1421
+ return { failure: seededEntry };
1422
+ }
1423
+ const match = String(seededEntry.stdout || "").match(/^([0-7]{6})\s/);
1424
+ if (!match) {
1425
+ return {
1426
+ failure: {
1427
+ status: 1,
1428
+ stderr: `Could not preserve the pinned Git tree mode for ${relativePath}.`,
1429
+ },
1430
+ };
1431
+ }
1432
+ mode = match[1];
1433
+ }
1434
+ const updated = this.runGit(preflight.repository, [
1435
+ "update-index",
1436
+ "--add",
1437
+ "--cacheinfo",
1438
+ mode,
1439
+ objectId,
1440
+ path.relative(preflight.repository, candidate.target.absolutePath).replace(/\\/g, "/"),
1441
+ ], isolated);
1442
+ if (!commandSucceeded(updated)) {
1443
+ return { failure: updated };
1444
+ }
1445
+ }
1446
+ const written = this.runGit(preflight.repository, ["write-tree"], isolated);
1447
+ if (!commandSucceeded(written)) {
1448
+ return { failure: written };
1449
+ }
1450
+ const expectedTree = String(written.stdout || "").trim();
1451
+ const changed = this.runGit(preflight.repository, [
1452
+ "diff", "--no-ext-diff", "--name-only", "-z",
1453
+ preflight.headBefore, expectedTree, "--",
1454
+ ]);
1455
+ const changedFiles = commandSucceeded(changed)
1456
+ ? String(changed.stdout || "").split("\0").filter(Boolean).sort()
1457
+ : null;
1458
+ if (!changedFiles || !isDeepStrictEqual(changedFiles, files.slice().sort())) {
1459
+ return {
1460
+ expectedTree,
1461
+ failure: {
1462
+ status: 1,
1463
+ stderr: commandSucceeded(changed)
1464
+ ? "The isolated Git tree did not exactly match the validated OKF batch paths."
1465
+ : commandFailure(changed, "Could not inspect the isolated Git tree."),
1466
+ },
1467
+ };
1468
+ }
1469
+ return { expectedTree };
1470
+ } finally {
1471
+ this.removeTemporaryGitIndex(indexPath);
1472
+ }
1473
+ }
1474
+
1475
+ commitGit(preflight, candidates, message) {
1476
+ if (!preflight.enabled) {
1477
+ return {
1478
+ enabled: false,
1479
+ committed: false,
1480
+ commitState: "not_requested",
1481
+ repository: Boolean(preflight.repository),
1482
+ repositoryRoot: preflight.repository,
1483
+ persistence: "working_tree",
674
1484
  };
675
1485
  }
676
- const commit = this.runGit(preflight.repository, ["commit", "-m", message, "--"].concat(files));
677
- if (commit.error || commit.status !== 0) {
1486
+ if (!preflight.repository) {
678
1487
  return {
679
1488
  enabled: true,
680
- repository: true,
1489
+ repository: false,
1490
+ repositoryRoot: null,
681
1491
  committed: false,
682
- error: commandFailure(commit, "git commit failed"),
1492
+ commitState: "not_repository",
1493
+ persistence: "working_tree",
1494
+ reason: "not_git_repository",
683
1495
  };
684
1496
  }
685
- const revision = this.runGit(preflight.repository, ["rev-parse", "HEAD"]);
686
- return {
687
- enabled: true,
688
- repository: true,
689
- committed: true,
690
- commitSha: revision.status === 0 ? String(revision.stdout || "").trim() : null,
691
- ...(revision.status === 0 ? {} : { warning: commandFailure(revision, "Commit succeeded but its SHA could not be read.") }),
692
- };
1497
+ const files = this.repositoryFiles(preflight, candidates);
1498
+ let expectedTree = null;
1499
+ try {
1500
+ const initialTargets = this.inspectPublishedTargets(candidates);
1501
+ if (!initialTargets.validatedFilesPresent) {
1502
+ return this.finalizeGitFailure(preflight, files, {
1503
+ status: 1,
1504
+ stderr: "A published concept changed before the Git commit tree was built.",
1505
+ }, null, candidates);
1506
+ }
1507
+ const built = this.buildValidatedGitTree(preflight, candidates, files);
1508
+ expectedTree = built.expectedTree || null;
1509
+ if (built.failure) {
1510
+ return this.finalizeGitFailure(
1511
+ preflight,
1512
+ files,
1513
+ built.failure,
1514
+ expectedTree,
1515
+ candidates,
1516
+ );
1517
+ }
1518
+ const verifiedTargets = this.inspectPublishedTargets(candidates);
1519
+ const headRefStillBefore = this.readGitValue(
1520
+ preflight.repository,
1521
+ ["symbolic-ref", "-q", "HEAD"],
1522
+ );
1523
+ const refStillBefore = this.readGitValue(
1524
+ preflight.repository,
1525
+ ["rev-parse", "--verify", preflight.headRef],
1526
+ );
1527
+ if (!verifiedTargets.validatedFilesPresent
1528
+ || headRefStillBefore !== preflight.headRef
1529
+ || refStillBefore !== preflight.headBefore) {
1530
+ return this.finalizeGitFailure(preflight, files, {
1531
+ status: 1,
1532
+ stderr: !verifiedTargets.validatedFilesPresent
1533
+ ? "A published concept changed before the Git ref update."
1534
+ : "The checked-out Git ref changed before the validated commit could be published.",
1535
+ }, expectedTree, candidates);
1536
+ }
1537
+ const committed = this.runGit(preflight.repository, [
1538
+ "commit-tree", expectedTree, "-p", preflight.headBefore, "-m", message,
1539
+ ]);
1540
+ if (!commandSucceeded(committed)) {
1541
+ return this.finalizeGitFailure(
1542
+ preflight,
1543
+ files,
1544
+ committed,
1545
+ expectedTree,
1546
+ candidates,
1547
+ );
1548
+ }
1549
+ const commitSha = String(committed.stdout || "").trim();
1550
+ const finalTargets = this.inspectPublishedTargets(candidates);
1551
+ if (!finalTargets.validatedFilesPresent) {
1552
+ return this.finalizeGitFailure(preflight, files, {
1553
+ status: 1,
1554
+ stderr: "A published concept changed before the validated commit was published.",
1555
+ }, expectedTree, candidates);
1556
+ }
1557
+ const updated = this.runGit(preflight.repository, [
1558
+ "update-ref", "-m", "okf-mcp live authoring",
1559
+ preflight.headRef, commitSha, preflight.headBefore,
1560
+ ]);
1561
+ const classification = this.classifyCommit(preflight, expectedTree);
1562
+ if (!commandSucceeded(updated) || classification.committed !== true) {
1563
+ return this.finalizeGitFailure(
1564
+ preflight,
1565
+ files,
1566
+ updated,
1567
+ expectedTree,
1568
+ candidates,
1569
+ );
1570
+ }
1571
+ const synchronized = this.synchronizeCommittedIndex(preflight, classification, files);
1572
+ const targets = this.inspectPublishedTargets(candidates);
1573
+ return Object.assign({
1574
+ enabled: true,
1575
+ repository: true,
1576
+ repositoryRoot: preflight.repository,
1577
+ committed: true,
1578
+ commitState: "committed",
1579
+ persistence: "git_commit",
1580
+ }, classification, synchronized, targets);
1581
+ } catch (error) {
1582
+ return this.finalizeGitFailure(
1583
+ preflight,
1584
+ files,
1585
+ { status: null, stdout: "", stderr: "", error },
1586
+ expectedTree,
1587
+ candidates,
1588
+ );
1589
+ }
693
1590
  }
694
1591
 
695
1592
  defaultMessage(candidates) {
@@ -699,6 +1596,23 @@ class LiveAuthoringService {
699
1596
  return `docs(okf): apply ${candidates.length} concept changes`;
700
1597
  }
701
1598
 
1599
+ commitMessage(input, candidates) {
1600
+ if (hasOwn(input, "message") && typeof input.message !== "string") {
1601
+ throw new AuthoringPolicyError("Git commit message must be a string.");
1602
+ }
1603
+ const supplied = hasOwn(input, "message") ? input.message.trim() : "";
1604
+ const message = supplied || this.defaultMessage(candidates);
1605
+ if (message.includes("\0")) {
1606
+ throw new AuthoringPolicyError("Git commit message cannot contain NUL characters.");
1607
+ }
1608
+ if (byteLength(message) > MAX_COMMIT_MESSAGE_BYTES) {
1609
+ throw new AuthoringPolicyError(
1610
+ `Git commit message must not exceed ${MAX_COMMIT_MESSAGE_BYTES} UTF-8 bytes.`,
1611
+ );
1612
+ }
1613
+ return message;
1614
+ }
1615
+
702
1616
  ensureParentDirectories(candidate, createdDirectories) {
703
1617
  const bundleRoot = this.store.resolveWritableBundleRoot(this.store.getBundle(candidate.bundle));
704
1618
  const parent = path.dirname(candidate.target.absolutePath);
@@ -772,8 +1686,66 @@ class LiveAuthoringService {
772
1686
  });
773
1687
  }
774
1688
 
1689
+ inspectPublishedTarget(candidate) {
1690
+ try {
1691
+ const stat = fs.lstatSync(candidate.target.absolutePath);
1692
+ if (stat.isSymbolicLink() || !stat.isFile()) {
1693
+ return { state: "non_regular", revision: null };
1694
+ }
1695
+ return {
1696
+ state: "regular",
1697
+ revision: revisionFor(fs.readFileSync(candidate.target.absolutePath)),
1698
+ };
1699
+ } catch (error) {
1700
+ if (error && error.code === "ENOENT") {
1701
+ return { state: "missing", revision: null };
1702
+ }
1703
+ throw error;
1704
+ }
1705
+ }
1706
+
1707
+ rollbackCandidate(candidate) {
1708
+ const inspected = this.inspectPublishedTarget(candidate);
1709
+ const receipt = {
1710
+ op: candidate.op,
1711
+ path: candidate.path,
1712
+ absolutePath: candidate.target.absolutePath,
1713
+ expectedPublishedRevision: candidate.publishedRevision,
1714
+ observedRevision: inspected.revision,
1715
+ };
1716
+ if (candidate.op === "create" && inspected.state === "missing") {
1717
+ return Object.assign(receipt, { status: "already_absent", restored: true });
1718
+ }
1719
+ if (inspected.state !== "regular" || inspected.revision !== candidate.publishedRevision) {
1720
+ return Object.assign(receipt, {
1721
+ status: "conflict",
1722
+ restored: false,
1723
+ observedState: inspected.state,
1724
+ });
1725
+ }
1726
+ if (candidate.op === "create") {
1727
+ fs.unlinkSync(candidate.target.absolutePath);
1728
+ return Object.assign(receipt, { status: "removed", restored: true });
1729
+ }
1730
+ restoreFile(candidate.target.absolutePath, candidate.originalText, candidate.originalMode);
1731
+ const restored = this.inspectPublishedTarget(candidate);
1732
+ if (restored.state !== "regular" || restored.revision !== candidate.baseRevision) {
1733
+ return Object.assign(receipt, {
1734
+ status: "restore_verification_failed",
1735
+ restored: false,
1736
+ restoredRevision: restored.revision,
1737
+ });
1738
+ }
1739
+ return Object.assign(receipt, {
1740
+ status: "restored",
1741
+ restored: true,
1742
+ restoredRevision: restored.revision,
1743
+ });
1744
+ }
1745
+
775
1746
  rollback(applied, staged, createdDirectories) {
776
1747
  const failures = [];
1748
+ const outcomes = [];
777
1749
  staged.forEach((candidate) => {
778
1750
  if (fs.existsSync(candidate.temporary)) {
779
1751
  try {
@@ -785,84 +1757,336 @@ class LiveAuthoringService {
785
1757
  });
786
1758
  applied.slice().reverse().forEach((candidate) => {
787
1759
  try {
788
- if (candidate.op === "create") {
789
- if (fs.existsSync(candidate.target.absolutePath)) fs.unlinkSync(candidate.target.absolutePath);
790
- } else {
791
- restoreFile(candidate.target.absolutePath, candidate.originalText, candidate.originalMode);
792
- }
1760
+ outcomes.push(this.rollbackCandidate(candidate));
793
1761
  } catch (error) {
794
- failures.push(error);
1762
+ const failure = {
1763
+ op: candidate.op,
1764
+ path: candidate.path,
1765
+ absolutePath: candidate.target.absolutePath,
1766
+ status: "error",
1767
+ restored: false,
1768
+ error: error && error.message ? error.message : String(error),
1769
+ };
1770
+ outcomes.push(failure);
1771
+ failures.push(failure);
795
1772
  }
796
1773
  });
797
1774
  try {
798
1775
  this.cleanupDirectories(createdDirectories || []);
799
1776
  } catch (error) {
800
- failures.push(error);
801
- }
802
- if (failures.length) {
803
- throw new Error(`OKF batch rollback failed: ${failures[0].message}`);
1777
+ failures.push({
1778
+ status: "directory_cleanup_error",
1779
+ error: error && error.message ? error.message : String(error),
1780
+ });
804
1781
  }
1782
+ const conflicts = outcomes.filter((outcome) => !outcome.restored);
1783
+ return {
1784
+ complete: conflicts.length === 0 && failures.length === 0,
1785
+ outcomes,
1786
+ conflicts,
1787
+ failures,
1788
+ };
805
1789
  }
806
1790
 
807
- async applyChanges(input, context) {
808
- return this.store.withWriteLock(() => this.applyChangesUnlocked(input, context));
809
- }
810
-
811
- async applyChangesUnlocked(input, context) {
812
- if (!isPlainObject(input)) {
813
- throw new Error("okf_apply_changes requires an object argument.");
814
- }
815
- if (!Array.isArray(input.changes) || input.changes.length < 1 || input.changes.length > MAX_CHANGES) {
816
- throw new Error(`changes must contain from 1 through ${MAX_CHANGES} operations.`);
817
- }
818
- const bundle = this.getBundle(input.bundle);
1791
+ generatedStamp() {
819
1792
  const timestampValue = this.now();
820
- const generated = {
1793
+ return {
821
1794
  by: this.actor,
822
1795
  at: timestampValue instanceof Date
823
1796
  ? timestampValue.toISOString()
824
1797
  : new Date(timestampValue).toISOString(),
825
1798
  };
1799
+ }
1800
+
1801
+ targetReceipt(bundle, candidates, gitPreflight) {
1802
+ const bundleRoot = this.store.resolveWritableBundleRoot(bundle);
1803
+ const projectRoot = this.store.projectRoot
1804
+ ? path.resolve(this.store.projectRoot)
1805
+ : bundleRoot;
1806
+ return {
1807
+ bundle: bundle.id,
1808
+ bundleRoot,
1809
+ projectRoot,
1810
+ repositoryRoot: gitPreflight && gitPreflight.repositoryRoot
1811
+ ? gitPreflight.repositoryRoot
1812
+ : null,
1813
+ absolutePaths: candidates.map((candidate) => candidate.target.absolutePath),
1814
+ };
1815
+ }
1816
+
1817
+ candidateSummaries(candidates) {
1818
+ return candidates.map((candidate) => ({
1819
+ op: candidate.op,
1820
+ bundle: candidate.bundle,
1821
+ path: candidate.path,
1822
+ absolutePath: candidate.target.absolutePath,
1823
+ uri: candidate.uri,
1824
+ title: candidate.title,
1825
+ baseRevision: candidate.baseRevision,
1826
+ candidateRevision: candidate.publishedRevision,
1827
+ effects: effectsForCandidate(candidate),
1828
+ }));
1829
+ }
1830
+
1831
+ durabilityReceipt(git, filesChanged, stateOverride) {
1832
+ const persistence = git && git.persistence
1833
+ ? git.persistence
1834
+ : filesChanged ? "working_tree" : "none";
1835
+ return {
1836
+ state: stateOverride || (filesChanged
1837
+ ? git && ["committed", "observed_committed"].includes(git.commitState)
1838
+ ? "git_committed"
1839
+ : git && git.commitState === "unknown"
1840
+ ? "commit_state_unknown"
1841
+ : "filesystem_published_uncommitted"
1842
+ : "not_persisted"),
1843
+ filesChanged: Boolean(filesChanged),
1844
+ persistence,
1845
+ committed: git && hasOwn(git, "committed") ? git.committed : false,
1846
+ commitState: git && git.commitState ? git.commitState : "not_requested",
1847
+ affectedIndexState: git && git.affectedIndexState ? git.affectedIndexState : "not_inspected",
1848
+ indexState: git && git.indexState ? git.indexState : "not_inspected",
1849
+ crashDurable: false,
1850
+ };
1851
+ }
1852
+
1853
+ snapshotReceipt(plan) {
1854
+ return {
1855
+ checkedAt: plan.generated.at,
1856
+ timeOfCheck: true,
1857
+ generatedBy: plan.generated.by,
1858
+ graphValidation: "future_overlay",
1859
+ };
1860
+ }
1861
+
1862
+ preconditionsReceipt(plan) {
1863
+ return {
1864
+ allSatisfied: Boolean(plan.validation.valid && plan.gitPreflight.ready),
1865
+ revisions: plan.candidates.map((candidate) => ({
1866
+ path: candidate.path,
1867
+ absolutePath: candidate.target.absolutePath,
1868
+ baseRevision: candidate.baseRevision,
1869
+ candidateRevision: candidate.publishedRevision,
1870
+ })),
1871
+ git: {
1872
+ enabled: plan.gitPreflight.enabled,
1873
+ ready: plan.gitPreflight.ready,
1874
+ repositoryStatus: plan.gitPreflight.repositoryStatus,
1875
+ repositoryRoot: plan.gitPreflight.repositoryRoot,
1876
+ headBefore: plan.gitPreflight.headBefore,
1877
+ headRef: plan.gitPreflight.headRef,
1878
+ worktreeClean: plan.gitPreflight.worktreeClean,
1879
+ identityConfigured: plan.gitPreflight.identityConfigured,
1880
+ diagnostics: plan.gitPreflight.diagnostics,
1881
+ },
1882
+ };
1883
+ }
1884
+
1885
+ planChanges(input, context) {
1886
+ if (!isPlainObject(input)) {
1887
+ throw new AuthoringPolicyError("okf_apply_changes requires an object argument.");
1888
+ }
1889
+ if (!Array.isArray(input.changes) || input.changes.length < 1 || input.changes.length > MAX_CHANGES) {
1890
+ throw new AuthoringPolicyError(`changes must contain from 1 through ${MAX_CHANGES} operations.`);
1891
+ }
1892
+ let bundle;
1893
+ try {
1894
+ bundle = this.getBundle(input.bundle);
1895
+ } catch (error) {
1896
+ if (error && error.code) throw error;
1897
+ throw new AuthoringPolicyError(error && error.message ? error.message : String(error));
1898
+ }
1899
+ const generated = this.generatedStamp();
826
1900
  const additionalBundles = context && Array.isArray(context.additionalBundles)
827
1901
  ? context.additionalBundles
828
1902
  : [];
829
1903
  const currentIndex = this.buildIndex(additionalBundles);
830
1904
  const candidates = input.changes.map((change, index) => {
831
1905
  if (!isPlainObject(change)) {
832
- throw new Error(`changes[${index}] must be an object.`);
833
- }
834
- if (change.op === "create") {
835
- return this.createCandidate(change, bundle, generated);
1906
+ throw new AuthoringPolicyError(`changes[${index}] must be an object.`);
836
1907
  }
837
- if (change.op === "update") {
838
- return this.updateCandidate(change, bundle, currentIndex, generated);
1908
+ try {
1909
+ if (change.op === "create") {
1910
+ return this.createCandidate(change, bundle, currentIndex, generated);
1911
+ }
1912
+ if (change.op === "update") {
1913
+ return this.updateCandidate(change, bundle, currentIndex, generated);
1914
+ }
1915
+ throw new AuthoringPolicyError(`changes[${index}].op must be create or update.`);
1916
+ } catch (error) {
1917
+ if (error instanceof AuthoringPolicyError || error instanceof AuthoringOperationalError) {
1918
+ throw error;
1919
+ }
1920
+ if (error && error.code) throw error;
1921
+ throw new AuthoringPolicyError(error && error.message ? error.message : String(error));
839
1922
  }
840
- throw new Error(`changes[${index}].op must be create or update.`);
841
1923
  });
842
1924
  const targetPaths = new Set();
843
1925
  candidates.forEach((candidate) => {
844
1926
  const key = path.resolve(candidate.target.absolutePath);
845
1927
  if (targetPaths.has(key)) {
846
- throw new Error(`A batch cannot target the same concept more than once: ${candidate.path}`);
1928
+ throw new AuthoringPolicyError(`A batch cannot target the same concept more than once: ${candidate.path}`);
847
1929
  }
848
1930
  targetPaths.add(key);
849
1931
  });
1932
+ const absoluteTargets = Array.from(targetPaths);
1933
+ for (let left = 0; left < absoluteTargets.length; left += 1) {
1934
+ for (let right = left + 1; right < absoluteTargets.length; right += 1) {
1935
+ if (absoluteTargets[left].startsWith(`${absoluteTargets[right]}${path.sep}`)
1936
+ || absoluteTargets[right].startsWith(`${absoluteTargets[left]}${path.sep}`)) {
1937
+ throw new AuthoringPolicyError(
1938
+ "A batch cannot place one concept path underneath another concept file path.",
1939
+ );
1940
+ }
1941
+ }
1942
+ }
1943
+ const message = this.commitMessage(input, candidates);
850
1944
  const overrides = new Map(candidates.map((candidate) => [
851
1945
  `${candidate.bundle}\u0000${candidate.path}`,
852
1946
  candidate.markdown,
853
1947
  ]));
854
- const futureIndex = this.buildIndex(additionalBundles, overrides);
855
- const validation = this.validationResult(futureIndex, candidates);
856
- if (!validation.valid) {
1948
+ const validation = this.validationResult(
1949
+ this.buildIndex(additionalBundles, overrides),
1950
+ candidates,
1951
+ );
1952
+ const gitPreflight = this.prepareGit(bundle, candidates);
1953
+ return {
1954
+ input,
1955
+ bundle,
1956
+ generated,
1957
+ additionalBundles,
1958
+ candidates,
1959
+ message,
1960
+ validation,
1961
+ gitPreflight,
1962
+ target: this.targetReceipt(bundle, candidates, gitPreflight),
1963
+ changes: this.candidateSummaries(candidates),
1964
+ };
1965
+ }
1966
+
1967
+ validationReceipt(plan) {
1968
+ const git = {
1969
+ enabled: plan.gitPreflight.enabled,
1970
+ repository: Boolean(plan.gitPreflight.repository),
1971
+ repositoryRoot: plan.gitPreflight.repositoryRoot,
1972
+ repositoryStatus: plan.gitPreflight.repositoryStatus,
1973
+ ready: plan.gitPreflight.ready,
1974
+ headBefore: plan.gitPreflight.headBefore,
1975
+ headRef: plan.gitPreflight.headRef,
1976
+ worktreeClean: plan.gitPreflight.worktreeClean,
1977
+ identityConfigured: plan.gitPreflight.identityConfigured,
1978
+ diagnostics: plan.gitPreflight.diagnostics,
1979
+ commitState: "not_attempted",
1980
+ persistence: "none",
1981
+ };
1982
+ const readyToApply = Boolean(plan.validation.valid && plan.gitPreflight.ready);
1983
+ return {
1984
+ valid: plan.validation.valid,
1985
+ readyToApply,
1986
+ applied: false,
1987
+ filesChanged: false,
1988
+ status: !plan.validation.valid ? "invalid" : readyToApply ? "ready" : "blocked",
1989
+ snapshot: this.snapshotReceipt(plan),
1990
+ preconditions: this.preconditionsReceipt(plan),
1991
+ generated: plan.generated,
1992
+ target: plan.target,
1993
+ durability: this.durabilityReceipt(git, false),
1994
+ changes: plan.changes,
1995
+ validation: plan.validation,
1996
+ git,
1997
+ };
1998
+ }
1999
+
2000
+ invalidValidationReceipt(error) {
2001
+ const validation = policyValidation(error && error.message ? error.message : String(error));
2002
+ const generated = this.generatedStamp();
2003
+ return {
2004
+ valid: false,
2005
+ readyToApply: false,
2006
+ applied: false,
2007
+ filesChanged: false,
2008
+ status: "invalid",
2009
+ snapshot: {
2010
+ checkedAt: generated.at,
2011
+ timeOfCheck: true,
2012
+ generatedBy: generated.by,
2013
+ graphValidation: "not_run",
2014
+ },
2015
+ preconditions: {
2016
+ allSatisfied: false,
2017
+ revisions: [],
2018
+ git: {
2019
+ enabled: this.gitCommit,
2020
+ ready: false,
2021
+ repositoryStatus: "not_inspected",
2022
+ repositoryRoot: null,
2023
+ diagnostics: [],
2024
+ },
2025
+ },
2026
+ generated,
2027
+ durability: this.durabilityReceipt(null, false),
2028
+ changes: [],
2029
+ validation,
2030
+ git: {
2031
+ enabled: this.gitCommit,
2032
+ repository: false,
2033
+ repositoryRoot: null,
2034
+ repositoryStatus: "not_inspected",
2035
+ commitState: "not_attempted",
2036
+ persistence: "none",
2037
+ },
2038
+ };
2039
+ }
2040
+
2041
+ async validateChanges(input, context) {
2042
+ return this.store.withWriteLock(() => {
2043
+ try {
2044
+ return this.validationReceipt(this.planChanges(input, context));
2045
+ } catch (error) {
2046
+ if (!(error instanceof AuthoringPolicyError)) {
2047
+ throw error;
2048
+ }
2049
+ return this.invalidValidationReceipt(error);
2050
+ }
2051
+ });
2052
+ }
2053
+
2054
+ async applyChanges(input, context) {
2055
+ return this.store.withWriteLock(() => this.applyChangesUnlocked(input, context));
2056
+ }
2057
+
2058
+ async applyChangesUnlocked(input, context) {
2059
+ const plan = this.planChanges(input, context);
2060
+ if (!plan.validation.valid) {
857
2061
  return {
858
2062
  applied: false,
2063
+ readyToApply: false,
2064
+ filesChanged: false,
859
2065
  status: "rejected",
860
- generated,
861
- validation,
2066
+ snapshot: this.snapshotReceipt(plan),
2067
+ preconditions: this.preconditionsReceipt(plan),
2068
+ generated: plan.generated,
2069
+ target: plan.target,
2070
+ durability: this.durabilityReceipt(null, false),
2071
+ changes: plan.changes,
2072
+ validation: plan.validation,
2073
+ git: {
2074
+ enabled: plan.gitPreflight.enabled,
2075
+ repository: Boolean(plan.gitPreflight.repository),
2076
+ repositoryRoot: plan.gitPreflight.repositoryRoot,
2077
+ repositoryStatus: plan.gitPreflight.repositoryStatus,
2078
+ commitState: "not_attempted",
2079
+ persistence: "none",
2080
+ },
862
2081
  };
863
2082
  }
864
- const gitPreflight = this.prepareGit(bundle);
865
- const transaction = this.stageCandidates(candidates);
2083
+ if (!plan.gitPreflight.ready) {
2084
+ const blocker = plan.gitPreflight.diagnostics[0];
2085
+ throw new AuthoringPolicyError(blocker
2086
+ ? blocker.message
2087
+ : "Configured Git preconditions do not currently allow automatic apply.");
2088
+ }
2089
+ const transaction = this.stageCandidates(plan.candidates);
866
2090
  const staged = transaction.staged;
867
2091
  const applied = [];
868
2092
  try {
@@ -882,57 +2106,136 @@ class LiveAuthoringService {
882
2106
  }
883
2107
  });
884
2108
  } catch (error) {
885
- this.rollback(applied, staged, transaction.createdDirectories);
2109
+ const rollback = this.rollback(applied, staged, transaction.createdDirectories);
2110
+ if (!rollback.complete) {
2111
+ return {
2112
+ applied: false,
2113
+ readyToApply: false,
2114
+ filesChanged: true,
2115
+ status: "rollback_conflict",
2116
+ snapshot: this.snapshotReceipt(plan),
2117
+ preconditions: this.preconditionsReceipt(plan),
2118
+ generated: plan.generated,
2119
+ target: plan.target,
2120
+ durability: this.durabilityReceipt(null, true, "partial_filesystem_state"),
2121
+ changes: plan.changes,
2122
+ validation: plan.validation,
2123
+ rollback,
2124
+ error: error && error.message ? error.message : String(error),
2125
+ };
2126
+ }
886
2127
  throw error;
887
2128
  }
888
2129
  let persistedValidation;
889
2130
  try {
890
2131
  persistedValidation = this.validationResult(
891
- this.buildIndex(additionalBundles),
892
- candidates,
2132
+ this.buildIndex(plan.additionalBundles),
2133
+ plan.candidates,
893
2134
  );
894
2135
  } catch (error) {
895
- this.rollback(applied, staged, transaction.createdDirectories);
2136
+ const rollback = this.rollback(applied, staged, transaction.createdDirectories);
2137
+ if (!rollback.complete) {
2138
+ return {
2139
+ applied: false,
2140
+ readyToApply: false,
2141
+ filesChanged: true,
2142
+ status: "rollback_conflict",
2143
+ snapshot: this.snapshotReceipt(plan),
2144
+ preconditions: this.preconditionsReceipt(plan),
2145
+ generated: plan.generated,
2146
+ target: plan.target,
2147
+ durability: this.durabilityReceipt(null, true, "partial_filesystem_state"),
2148
+ changes: plan.changes,
2149
+ validation: plan.validation,
2150
+ rollback,
2151
+ error: error && error.message ? error.message : String(error),
2152
+ };
2153
+ }
896
2154
  throw error;
897
2155
  }
898
2156
  if (!persistedValidation.valid) {
899
- this.rollback(applied, staged, transaction.createdDirectories);
2157
+ const rollback = this.rollback(applied, staged, transaction.createdDirectories);
900
2158
  return {
901
2159
  applied: false,
902
- status: "rolled_back",
903
- generated,
2160
+ readyToApply: false,
2161
+ filesChanged: !rollback.complete,
2162
+ status: rollback.complete ? "rolled_back" : "rollback_conflict",
2163
+ snapshot: this.snapshotReceipt(plan),
2164
+ preconditions: this.preconditionsReceipt(plan),
2165
+ generated: plan.generated,
2166
+ target: plan.target,
2167
+ durability: this.durabilityReceipt(
2168
+ null,
2169
+ !rollback.complete,
2170
+ rollback.complete ? "rolled_back" : "partial_filesystem_state",
2171
+ ),
2172
+ changes: plan.changes,
904
2173
  validation: persistedValidation,
2174
+ rollback,
905
2175
  };
906
2176
  }
907
- const message = hasOwn(input, "message") && String(input.message).trim()
908
- ? String(input.message).trim()
909
- : this.defaultMessage(candidates);
910
2177
  let git;
911
2178
  try {
912
- git = this.commitGit(gitPreflight, candidates, message);
2179
+ git = this.commitGit(plan.gitPreflight, plan.candidates, plan.message);
913
2180
  } catch (error) {
914
2181
  git = {
915
- enabled: gitPreflight.enabled,
916
- repository: Boolean(gitPreflight.repository),
917
- committed: false,
2182
+ enabled: plan.gitPreflight.enabled,
2183
+ repository: Boolean(plan.gitPreflight.repository),
2184
+ repositoryRoot: plan.gitPreflight.repositoryRoot,
2185
+ committed: null,
2186
+ commitState: "unknown",
2187
+ persistence: "unknown",
918
2188
  error: error && error.message ? error.message : String(error),
919
2189
  };
920
2190
  }
921
- const summaries = candidates.map((candidate) => ({
922
- op: candidate.op,
923
- bundle: candidate.bundle,
924
- path: candidate.path,
925
- uri: candidate.uri,
926
- title: candidate.title,
927
- }));
2191
+ if (git.targetState === "conflict") {
2192
+ let currentValidation = persistedValidation;
2193
+ try {
2194
+ currentValidation = this.validationResult(
2195
+ this.buildIndex(plan.additionalBundles),
2196
+ [],
2197
+ );
2198
+ } catch {
2199
+ // Preserve the last complete validation receipt when the conflicting state is unreadable.
2200
+ }
2201
+ if (git.committed !== true) {
2202
+ return {
2203
+ applied: false,
2204
+ readyToApply: false,
2205
+ filesChanged: true,
2206
+ status: "post_publication_conflict",
2207
+ snapshot: this.snapshotReceipt(plan),
2208
+ preconditions: this.preconditionsReceipt(plan),
2209
+ generated: plan.generated,
2210
+ target: plan.target,
2211
+ durability: this.durabilityReceipt(git, true, "partial_filesystem_state"),
2212
+ changes: plan.changes,
2213
+ validation: currentValidation,
2214
+ git,
2215
+ error: git.error || "Validated concept bytes were replaced before Git persistence completed.",
2216
+ };
2217
+ }
2218
+ persistedValidation = currentValidation;
2219
+ }
2220
+ const status = git.commitState === "unknown"
2221
+ ? "applied_commit_unknown"
2222
+ : git.committed === true && git.targetState === "conflict"
2223
+ ? "applied_worktree_diverged"
2224
+ : git.enabled && git.repository && !git.committed
2225
+ ? "applied_uncommitted"
2226
+ : "applied";
928
2227
  return {
929
2228
  applied: true,
930
- status: git.enabled && git.repository && !git.committed
931
- ? "applied_uncommitted"
932
- : "applied",
933
- generated,
934
- changes: summaries,
935
- validation,
2229
+ readyToApply: git.targetState !== "conflict",
2230
+ filesChanged: true,
2231
+ status,
2232
+ snapshot: this.snapshotReceipt(plan),
2233
+ preconditions: this.preconditionsReceipt(plan),
2234
+ generated: plan.generated,
2235
+ target: plan.target,
2236
+ durability: this.durabilityReceipt(git, true),
2237
+ changes: plan.changes,
2238
+ validation: persistedValidation,
936
2239
  git,
937
2240
  };
938
2241
  }
@@ -941,5 +2244,6 @@ class LiveAuthoringService {
941
2244
  module.exports = {
942
2245
  LiveAuthoringService,
943
2246
  MAX_CHANGES,
2247
+ MAX_COMMIT_MESSAGE_BYTES,
944
2248
  MANAGED_METADATA_KEYS,
945
2249
  };