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