@bridge_gpt/mcp-server 0.2.75 → 0.2.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +8 -6
  2. package/build/agents.generated.js +5 -5
  3. package/build/cli-dispatch.js +333 -0
  4. package/build/codex-auto-recovery.js +25 -7
  5. package/build/commands.generated.js +8 -8
  6. package/build/conductor/bridge-api-client.js +193 -13
  7. package/build/conductor/declare-blocked.js +146 -7
  8. package/build/conductor/driver-pass.js +8 -0
  9. package/build/conductor/driver-register.js +8 -2
  10. package/build/conductor/epic-implementer-cli.js +15 -10
  11. package/build/conductor/epic-server-journal.js +52 -22
  12. package/build/conductor/epic-server-recipe.js +15 -5
  13. package/build/conductor/epic-server-runtime.js +163 -45
  14. package/build/conductor/epic-server.js +13 -6
  15. package/build/conductor/install-doctor.js +30 -2
  16. package/build/conductor/launch-plan.js +28 -7
  17. package/build/conductor/local-merge.js +55 -13
  18. package/build/conductor/pr-ci-producer.js +12 -3
  19. package/build/conductor/readiness-prerequisites.js +89 -2
  20. package/build/conductor/readiness-sections.js +46 -13
  21. package/build/conductor/readiness.js +3 -40
  22. package/build/conductor/recovery-cli.js +14 -12
  23. package/build/conductor/repository-workflow-remedy.js +147 -7
  24. package/build/conductor/ui-readiness.js +224 -0
  25. package/build/conductor/wait-run-attention.js +9 -4
  26. package/build/conductor/wait-run-cli.js +9 -2
  27. package/build/docs.generated.js +67 -4
  28. package/build/doctor.js +97 -1
  29. package/build/drive-epic.js +625 -33
  30. package/build/engine-paths.js +10 -0
  31. package/build/epic-coherence-input-cli.js +105 -10
  32. package/build/epic-coherence-input.js +877 -4
  33. package/build/epic-coherence-input.test-fixtures.js +117 -0
  34. package/build/epic-implementer-bin.js +947 -120
  35. package/build/epic-implementer-env.js +2 -2
  36. package/build/epic-launch-context.js +8 -1
  37. package/build/epic-shared/cut-protocol.js +55 -3
  38. package/build/executor/completion-contract.js +14 -1
  39. package/build/executor/failure-reason-codes.js +2 -0
  40. package/build/executor/guarded-fast-forward-push.js +25 -2
  41. package/build/executor/integration-job.js +56 -2
  42. package/build/executor/job-runner.js +87 -28
  43. package/build/executor/likely-tests.js +78 -6
  44. package/build/executor/merge-job.js +45 -1
  45. package/build/executor/permissions.js +187 -2
  46. package/build/executor/provider-checks.js +101 -5
  47. package/build/executor/rebase-finalization.js +29 -27
  48. package/build/executor/reconcile-overlap-job.js +70 -17
  49. package/build/executor/rename-aside.js +265 -0
  50. package/build/executor/required-work-ledger.js +89 -6
  51. package/build/executor/resume-pre-spawn.js +32 -8
  52. package/build/executor/runner.js +26 -4
  53. package/build/executor/types.js +121 -0
  54. package/build/executor/worktree.js +39 -2
  55. package/build/index.js +2500 -495
  56. package/build/init.js +16 -0
  57. package/build/install-bridge-conductor-answers.js +4 -0
  58. package/build/install-bridge-conductor-apply.js +10 -0
  59. package/build/install-bridge-conductor-assessment.js +84 -0
  60. package/build/install-bridge-conductor-contracts.js +9 -1
  61. package/build/install-bridge-conductor-setup.js +103 -3
  62. package/build/install-bridge-conductor.js +440 -812
  63. package/build/install-bridge.js +4 -11
  64. package/build/language-catalog.generated.js +2649 -0
  65. package/build/mcp-host-config.js +54 -37
  66. package/build/phase-context-git-probe.js +16 -0
  67. package/build/pipelines.generated.js +47 -19
  68. package/build/plan-execution-ledger.js +35 -0
  69. package/build/plan-generation.js +34 -0
  70. package/build/plane/build-freshness.js +6 -0
  71. package/build/plane/cli.js +12 -5
  72. package/build/plane/plane-freshness.js +43 -26
  73. package/build/printed-remedy-commands.js +17 -0
  74. package/build/readiness-prerequisites.generated.js +28 -0
  75. package/build/readme.generated.js +1 -1
  76. package/build/run-unit-tests-launcher.js +3 -1
  77. package/build/secret-redaction.js +3 -0
  78. package/build/server.js +7946 -0
  79. package/build/setup-epic.js +41 -8
  80. package/build/start-tickets-prereqs.js +3 -6
  81. package/build/test-support/console-guard.js +30 -0
  82. package/build/test-support/create-preview-world.js +232 -0
  83. package/build/test-support/module-imports.js +155 -0
  84. package/build/test-support/server-client.js +96 -0
  85. package/build/test-support/stdio-server.js +146 -0
  86. package/build/ticket-delivery.js +65 -0
  87. package/build/v2-readiness-requirements.js +39 -5
  88. package/build/version.generated.js +3 -3
  89. package/build/worktree-core.js +51 -7
  90. package/docs/EPIC-IMPLEMENTER.md +150 -2
  91. package/docs/epic-implementer/getting-started.md +5 -1
  92. package/package.json +3 -3
  93. package/pipelines/implement-ticket.json +2 -2
  94. package/pipelines/learn-repository.json +19 -1
@@ -16,11 +16,47 @@
16
16
  * The checker is structural only. It never judges coverage — that stays the
17
17
  * reviewer's job. All I/O goes through an injectable seam so tests never touch
18
18
  * a real disk.
19
+ *
20
+ * BAPI-1766 adds two stricter, still read-only, surfaces:
21
+ * - `check --structural` checks *declarations*: every epic AC is claimed, every
22
+ * declared hand-off `thing` has its write, read, and caller owners, a
23
+ * cross-child flow names an end-to-end (`e2e`) owner, and `depends_on` forms
24
+ * no cycle. A clean result proves only that the declarations are complete
25
+ * and consistent. Whether a claimed owner really covers the requirement, or
26
+ * a declared role is really carried out, is still the independent
27
+ * reviewer's substantive judgment.
28
+ * - `check-drafts` checks that each child draft still holds its assigned
29
+ * obligations and carried findings word for word.
30
+ * Plain `check` and `build` are unchanged for documents and outlines that do
31
+ * not use the new optional fields.
19
32
  */
20
33
  import { createHash } from "node:crypto";
21
34
  import path from "node:path";
22
35
  import { TICKET_KEY_PATTERN } from "./ticket-key-utils.js";
23
36
  import { writeJsonAtomically, } from "./conductor-bundle-artifacts.js";
37
+ /** BAPI-1766: the closed vocabulary of hand-off lifecycle roles. */
38
+ export const HANDOFF_ROLES = [
39
+ "write",
40
+ "read",
41
+ "caller",
42
+ "start",
43
+ "steady_state",
44
+ "wind_down",
45
+ "consumer",
46
+ ];
47
+ /** The stable id shape of a hand-off `thing`, for example `H-1`. */
48
+ export const HANDOFF_THING_PATTERN = /^[A-Z]+-\d+$/;
49
+ /** The exact keys a `design_council.materiality` object carries. */
50
+ export const DESIGN_COUNCIL_MATERIALITY_KEYS = [
51
+ "requirements",
52
+ "interfaces_or_contracts",
53
+ "ownership",
54
+ "dependencies",
55
+ "end_to_end_proof",
56
+ "blast_radius",
57
+ ];
58
+ /** The `design_text` line prefix an epic uses to declare it has no cross-child value. */
59
+ export const NO_CROSS_CHILD_FLOW_PREFIX = "no_cross_child_flow:";
24
60
  // ===========================================================================
25
61
  // Constants
26
62
  // ===========================================================================
@@ -639,6 +675,340 @@ export function validateEpicCoherenceDocumentShape(document) {
639
675
  }
640
676
  return errors;
641
677
  }
678
+ function usableClaims(claims) {
679
+ if (!Array.isArray(claims))
680
+ return [];
681
+ const usable = [];
682
+ for (const claim of claims) {
683
+ if (!isRecord(claim))
684
+ continue;
685
+ if (!isNonEmptyString(claim.epic_ac) || !isNonEmptyString(claim.obligation))
686
+ continue;
687
+ usable.push({ epic_ac: claim.epic_ac, obligation: claim.obligation, e2e: claim.e2e });
688
+ }
689
+ return usable;
690
+ }
691
+ function usableManifestEntries(manifest) {
692
+ if (!Array.isArray(manifest))
693
+ return [];
694
+ return manifest.filter((entry) => isRecord(entry) && isNonEmptyString(entry.id));
695
+ }
696
+ function stringItems(value) {
697
+ if (!Array.isArray(value))
698
+ return [];
699
+ return value.filter((item) => typeof item === "string");
700
+ }
701
+ /**
702
+ * The problems with one supplied `design_council` value, or `[]` when it is
703
+ * well formed. Absence is not checked here: an absent council is valid and
704
+ * simply covers nothing.
705
+ */
706
+ export function designCouncilProblems(value) {
707
+ if (!isRecord(value))
708
+ return ["design_council must be an object."];
709
+ const problems = [];
710
+ if (!isNonEmptyString(value.council_id)) {
711
+ problems.push("design_council.council_id must be a non-empty string.");
712
+ }
713
+ if (!isNonEmptyString(value.design_revision)) {
714
+ problems.push("design_council.design_revision must be a non-empty string.");
715
+ }
716
+ if (typeof value.split_reviewed !== "boolean") {
717
+ problems.push("design_council.split_reviewed must be a boolean.");
718
+ }
719
+ const materiality = value.materiality;
720
+ if (!isRecord(materiality)) {
721
+ problems.push("design_council.materiality must be an object.");
722
+ }
723
+ else {
724
+ const expected = new Set(DESIGN_COUNCIL_MATERIALITY_KEYS);
725
+ for (const key of DESIGN_COUNCIL_MATERIALITY_KEYS) {
726
+ if (!(key in materiality)) {
727
+ problems.push(`design_council.materiality is missing ${key}.`);
728
+ }
729
+ else if (!isNonEmptyString(materiality[key])) {
730
+ problems.push(`design_council.materiality.${key} must be "unchanged" or a non-empty note.`);
731
+ }
732
+ }
733
+ for (const key of Object.keys(materiality)) {
734
+ if (!expected.has(key))
735
+ problems.push(`design_council.materiality has an unknown key ${key}.`);
736
+ }
737
+ }
738
+ return problems;
739
+ }
740
+ /**
741
+ * True only when `value` is well-formed design-council evidence and either
742
+ * `split_reviewed` is `true` or every materiality value is exactly
743
+ * `"unchanged"`. This is the high-risk council skip predicate the coherence
744
+ * procedure reads; absent or malformed evidence never covers high risk.
745
+ */
746
+ export function designCouncilCoversHighRisk(value) {
747
+ if (value === undefined || designCouncilProblems(value).length > 0)
748
+ return false;
749
+ const council = value;
750
+ if (council.split_reviewed === true)
751
+ return true;
752
+ return DESIGN_COUNCIL_MATERIALITY_KEYS.every((key) => council.materiality[key] === "unchanged");
753
+ }
754
+ /** True when `design_text` holds a valid `no_cross_child_flow:` reason line. */
755
+ function hasNoCrossChildFlowReason(designText) {
756
+ if (typeof designText !== "string")
757
+ return false;
758
+ return designText
759
+ .replace(/\r\n/g, "\n")
760
+ .split("\n")
761
+ .some((line) => line.startsWith(NO_CROSS_CHILD_FLOW_PREFIX) &&
762
+ line.slice(NO_CROSS_CHILD_FLOW_PREFIX.length).trim().length > 0);
763
+ }
764
+ /**
765
+ * Strongly connected components of size two or more, found with Tarjan's
766
+ * algorithm. Each component is one dependency cycle; its members are listed
767
+ * in manifest order. Self-edges are excluded by the caller.
768
+ */
769
+ function dependencyCycles(order, edges) {
770
+ let index = 0;
771
+ const indices = new Map();
772
+ const lowlink = new Map();
773
+ const onStack = new Set();
774
+ const stack = [];
775
+ const components = [];
776
+ // Iterative to stay safe on long chains.
777
+ for (const root of order) {
778
+ if (indices.has(root))
779
+ continue;
780
+ const work = [{ node: root, next: 0 }];
781
+ indices.set(root, index);
782
+ lowlink.set(root, index);
783
+ index++;
784
+ stack.push(root);
785
+ onStack.add(root);
786
+ while (work.length > 0) {
787
+ const frame = work[work.length - 1];
788
+ const targets = edges.get(frame.node) ?? [];
789
+ if (frame.next < targets.length) {
790
+ const target = targets[frame.next++];
791
+ if (!indices.has(target)) {
792
+ indices.set(target, index);
793
+ lowlink.set(target, index);
794
+ index++;
795
+ stack.push(target);
796
+ onStack.add(target);
797
+ work.push({ node: target, next: 0 });
798
+ }
799
+ else if (onStack.has(target)) {
800
+ lowlink.set(frame.node, Math.min(lowlink.get(frame.node), indices.get(target)));
801
+ }
802
+ continue;
803
+ }
804
+ work.pop();
805
+ if (work.length > 0) {
806
+ const parent = work[work.length - 1].node;
807
+ lowlink.set(parent, Math.min(lowlink.get(parent), lowlink.get(frame.node)));
808
+ }
809
+ if (lowlink.get(frame.node) === indices.get(frame.node)) {
810
+ const component = [];
811
+ for (;;) {
812
+ const member = stack.pop();
813
+ onStack.delete(member);
814
+ component.push(member);
815
+ if (member === frame.node)
816
+ break;
817
+ }
818
+ if (component.length > 1)
819
+ components.push(component);
820
+ }
821
+ }
822
+ }
823
+ const position = new Map(order.map((id, i) => [id, i]));
824
+ return components.map((component) => [...component].sort((a, b) => (position.get(a) ?? 0) - (position.get(b) ?? 0)));
825
+ }
826
+ /**
827
+ * The named structural checks alone, without the shape checks. Every check
828
+ * reads only values it has first proven well formed, so a malformed document
829
+ * yields every safely evaluable finding and never throws.
830
+ */
831
+ function structuralDeclarationErrors(document) {
832
+ const errors = [];
833
+ const entries = usableManifestEntries(document.manifest);
834
+ const childIds = entries.map((entry) => entry.id);
835
+ const childIdSet = new Set(childIds);
836
+ // ---- e2e markers ---------------------------------------------------------
837
+ const childClaims = entries.map((entry) => ({
838
+ child: entry.id,
839
+ claims: usableClaims(entry.owns_verifications),
840
+ }));
841
+ for (const entry of entries) {
842
+ const raw = entry.owns_verifications;
843
+ if (!Array.isArray(raw))
844
+ continue;
845
+ raw.forEach((claim, i) => {
846
+ if (isRecord(claim) && claim.e2e !== undefined && typeof claim.e2e !== "boolean") {
847
+ errors.push(`malformed_e2e_marker: child ${entry.id} owns_verifications[${i}].e2e must be true or false.`);
848
+ }
849
+ });
850
+ }
851
+ const nonChildClaims = [];
852
+ if (Array.isArray(document.non_child_owners)) {
853
+ for (const owner of document.non_child_owners) {
854
+ if (!isRecord(owner) || !isNonEmptyString(owner.id))
855
+ continue;
856
+ const claims = usableClaims(owner.owns_verifications);
857
+ nonChildClaims.push({ owner: owner.id, claims });
858
+ for (const claim of claims) {
859
+ if (claim.e2e === true) {
860
+ errors.push(`non_child_e2e_owner: non-child owner ${owner.id} marks its ${claim.epic_ac} claim e2e; ` +
861
+ "only a child can own the end-to-end test, so this claim never counts as the e2e owner.");
862
+ }
863
+ }
864
+ }
865
+ }
866
+ // ---- unclaimed epic ACs --------------------------------------------------
867
+ const epic = document.epic;
868
+ if (isRecord(epic) && Array.isArray(epic.acceptance_criteria)) {
869
+ const claimed = new Set();
870
+ for (const { claims } of childClaims)
871
+ for (const claim of claims)
872
+ claimed.add(claim.epic_ac);
873
+ for (const { claims } of nonChildClaims)
874
+ for (const claim of claims)
875
+ claimed.add(claim.epic_ac);
876
+ for (const ac of epic.acceptance_criteria) {
877
+ if (!isRecord(ac) || !isNonEmptyString(ac.id) || !AC_ID_PATTERN.test(ac.id))
878
+ continue;
879
+ if (!claimed.has(ac.id)) {
880
+ errors.push(`unclaimed_epic_ac: epic ${ac.id} is claimed by no child owns_verifications entry and no non_child_owners entry.`);
881
+ }
882
+ }
883
+ }
884
+ // ---- hand-off roles ------------------------------------------------------
885
+ const roleSet = new Set(HANDOFF_ROLES);
886
+ /** thing -> role -> children holding it (manifest order kept by insertion). */
887
+ const things = new Map();
888
+ for (const entry of entries) {
889
+ const child = entry.id;
890
+ const roles = entry.handoff_roles;
891
+ if (roles === undefined)
892
+ continue;
893
+ if (!Array.isArray(roles)) {
894
+ errors.push(`malformed_handoff_role: child ${child} handoff_roles must be an array of {thing, role} entries.`);
895
+ continue;
896
+ }
897
+ roles.forEach((declaration, i) => {
898
+ const where = `child ${child} handoff_roles[${i}]`;
899
+ if (!isRecord(declaration)) {
900
+ errors.push(`malformed_handoff_role: ${where} must be an object with thing and role.`);
901
+ return;
902
+ }
903
+ const { thing, role } = declaration;
904
+ let valid = true;
905
+ if (typeof thing !== "string" || !HANDOFF_THING_PATTERN.test(thing)) {
906
+ errors.push(`malformed_handoff_role: ${where}.thing ${JSON.stringify(thing)} must be a stable id such as "H-1".`);
907
+ valid = false;
908
+ }
909
+ if (typeof role !== "string" || !roleSet.has(role)) {
910
+ errors.push(`malformed_handoff_role: ${where}.role ${JSON.stringify(role)} is not one of ${HANDOFF_ROLES.join(", ")}` +
911
+ (typeof thing === "string" ? ` (thing ${thing}).` : "."));
912
+ valid = false;
913
+ }
914
+ if (!valid)
915
+ return;
916
+ const byRole = things.get(thing) ?? new Map();
917
+ const holders = byRole.get(role) ?? new Set();
918
+ holders.add(child);
919
+ byRole.set(role, holders);
920
+ things.set(thing, byRole);
921
+ });
922
+ }
923
+ const spanningThings = [];
924
+ for (const [thing, byRole] of things) {
925
+ const span = new Set();
926
+ for (const holders of byRole.values())
927
+ for (const holder of holders)
928
+ span.add(holder);
929
+ const children = childIds.filter((id) => span.has(id));
930
+ if (span.size >= 2) {
931
+ spanningThings.push(thing);
932
+ const missing = ["write", "read", "caller"].filter((role) => !byRole.has(role));
933
+ if (missing.length > 0) {
934
+ errors.push(`handoff_missing_role: ${thing} spans children ${children.join(", ")} but no child holds the ` +
935
+ `${missing.join(", ")} role.`);
936
+ }
937
+ }
938
+ if (byRole.has("read") || byRole.has("consumer")) {
939
+ const missing = ["write", "caller"].filter((role) => !byRole.has(role));
940
+ if (missing.length > 0) {
941
+ errors.push(`handoff_missing_write_or_caller: ${thing} (children ${children.join(", ")}) is read or consumed ` +
942
+ `but no child holds the ${missing.join(" or ")} role.`);
943
+ }
944
+ }
945
+ }
946
+ if (spanningThings.length > 0) {
947
+ const hasE2eOwner = childClaims.some(({ claims }) => claims.some((claim) => claim.e2e === true));
948
+ if (!hasE2eOwner) {
949
+ errors.push(`missing_e2e_owner: ${spanningThings.join(", ")} cross${spanningThings.length === 1 ? "es" : ""} ` +
950
+ "children, but no child owns_verifications entry has e2e: true with a non-empty obligation.");
951
+ }
952
+ }
953
+ // ---- the no-cross-child-flow declaration -------------------------------
954
+ const noFlowReason = hasNoCrossChildFlowReason(document.design_text);
955
+ if (childIds.length >= 2 && spanningThings.length === 0 && !noFlowReason) {
956
+ errors.push(`no_cross_child_declaration: the epic has ${childIds.length} children but declares no hand-off thing ` +
957
+ `that spans two children and no "${NO_CROSS_CHILD_FLOW_PREFIX}" reason line in design_text.`);
958
+ }
959
+ if (noFlowReason && spanningThings.length > 0) {
960
+ errors.push(`no_cross_child_flow_contradicted: design_text declares "${NO_CROSS_CHILD_FLOW_PREFIX}", ` +
961
+ `but ${spanningThings.join(", ")} spans two or more children.`);
962
+ }
963
+ // ---- dependency graphs ---------------------------------------------------
964
+ const edges = new Map();
965
+ for (const entry of entries) {
966
+ const child = entry.id;
967
+ const known = [];
968
+ for (const ref of stringItems(entry.depends_on)) {
969
+ if (ref === child) {
970
+ errors.push(`depends_on_self: child ${child} depends on itself.`);
971
+ }
972
+ else if (!childIdSet.has(ref)) {
973
+ errors.push(`depends_on_unknown_child: child ${child} depends on unknown child ${ref}.`);
974
+ }
975
+ else if (!known.includes(ref)) {
976
+ known.push(ref);
977
+ }
978
+ }
979
+ edges.set(child, [...(edges.get(child) ?? []), ...known]);
980
+ for (const ref of stringItems(entry.recommended_after)) {
981
+ if (ref === child) {
982
+ errors.push(`recommended_after_self: child ${child} is recommended after itself.`);
983
+ }
984
+ else if (!childIdSet.has(ref)) {
985
+ errors.push(`recommended_after_unknown_child: child ${child} is recommended after unknown child ${ref}.`);
986
+ }
987
+ }
988
+ }
989
+ for (const cycle of dependencyCycles([...childIdSet], edges)) {
990
+ errors.push(`depends_on_cycle: children ${cycle.join(", ")} form a depends_on cycle.`);
991
+ }
992
+ // ---- design council evidence ---------------------------------------------
993
+ if (document.design_council !== undefined) {
994
+ for (const problem of designCouncilProblems(document.design_council)) {
995
+ errors.push(`malformed_design_council: ${problem}`);
996
+ }
997
+ }
998
+ return errors;
999
+ }
1000
+ /**
1001
+ * `check --structural` in memory: every existing shape error plus every named
1002
+ * structural declaration error, each prefixed with a stable code such as
1003
+ * `unclaimed_epic_ac:`. A clean result means the declarations are complete and
1004
+ * consistent; it never judges whether they are true. Never throws.
1005
+ */
1006
+ export function validateEpicCoherenceDocumentStructure(document) {
1007
+ const errors = validateEpicCoherenceDocumentShape(document);
1008
+ if (!isRecord(document))
1009
+ return errors;
1010
+ return [...errors, ...structuralDeclarationErrors(document)];
1011
+ }
642
1012
  /**
643
1013
  * Named-file checks: every `touched_files` path stays inside the repository (a
644
1014
  * missing one may be a planned creation); every `read_files` path must exist,
@@ -660,11 +1030,57 @@ async function validateNamedFiles(document, repoRoot, deps) {
660
1030
  }
661
1031
  return errors;
662
1032
  }
1033
+ /**
1034
+ * The structural-mode variant of `validateNamedFiles`: it reads only manifest
1035
+ * entries that are objects with an id and only path lists that are string
1036
+ * arrays, and it skips any path the shape check already rejected
1037
+ * syntactically, so a malformed document is never cast or iterated unsafely.
1038
+ */
1039
+ async function validateNamedFilesGuarded(document, repoRoot, deps) {
1040
+ const errors = [];
1041
+ for (const entry of usableManifestEntries(document.manifest)) {
1042
+ const touched = isStringArray(entry.touched_files) ? entry.touched_files : [];
1043
+ for (const edit of touched) {
1044
+ if (repositoryRelativePathProblem(edit, "path"))
1045
+ continue;
1046
+ const located = await locateInsideRepository(edit, repoRoot, deps, `child ${entry.id} touched_files`);
1047
+ if (!located.ok)
1048
+ errors.push(located.error);
1049
+ }
1050
+ const reads = isStringArray(entry.read_files) ? entry.read_files : [];
1051
+ for (const read of reads) {
1052
+ if (repositoryRelativePathProblem(read, "path"))
1053
+ continue;
1054
+ const readable = await readContainedFile(read, repoRoot, deps, `child ${entry.id} read_files`);
1055
+ if (!readable.ok)
1056
+ errors.push(readable.error);
1057
+ }
1058
+ }
1059
+ return errors;
1060
+ }
663
1061
  // ===========================================================================
664
1062
  // Check mode
665
1063
  // ===========================================================================
666
1064
  /** Structurally validate an in-memory document, including its named files. */
667
- async function checkDocument(document, repoRoot, deps) {
1065
+ async function checkDocument(document, repoRoot, deps, options = {}) {
1066
+ if (options.structural) {
1067
+ // Structural mode collects every safely evaluable error instead of
1068
+ // returning after the first category.
1069
+ const errors = validateEpicCoherenceDocumentStructure(document);
1070
+ if (isRecord(document))
1071
+ errors.push(...(await validateNamedFilesGuarded(document, repoRoot, deps)));
1072
+ if (errors.length > 0)
1073
+ return { ok: false, errors, warnings: [] };
1074
+ const typed = document;
1075
+ return {
1076
+ ok: true,
1077
+ value: {
1078
+ digests: computeEpicCoherenceDigests(typed),
1079
+ design_council_covers_high_risk: designCouncilCoversHighRisk(typed.design_council),
1080
+ },
1081
+ warnings: [],
1082
+ };
1083
+ }
668
1084
  const errors = validateEpicCoherenceDocumentShape(document);
669
1085
  if (errors.length > 0)
670
1086
  return { ok: false, errors, warnings: [] };
@@ -674,8 +1090,244 @@ async function checkDocument(document, repoRoot, deps) {
674
1090
  return { ok: false, errors: fileErrors, warnings: [] };
675
1091
  return { ok: true, value: { digests: computeEpicCoherenceDigests(typed) }, warnings: [] };
676
1092
  }
677
- /** `epic-coherence-input check <path>`: validate an existing document. Writes nothing. */
678
- export async function checkEpicCoherenceInput(inputPath, deps) {
1093
+ // ===========================================================================
1094
+ // Blast-radius sidecar (BAPI-1767)
1095
+ // ===========================================================================
1096
+ /** The file name of the optional sidecar, written beside the input document. */
1097
+ export const BLAST_RADIUS_FILE_NAME = "blast-radius.json";
1098
+ /** The coverage values a version-1 blast-radius artifact may carry. */
1099
+ export const BLAST_RADIUS_COVERAGE_VALUES = ["complete", "degraded_repaired"];
1100
+ /**
1101
+ * Closed set of blanket `unaffected_reason` values. A reason must be specific
1102
+ * to its file, so a bare classification never counts. Compared after trimming,
1103
+ * lower-casing, and collapsing whitespace.
1104
+ */
1105
+ export const BLAST_RADIUS_BLANKET_REASONS = [
1106
+ "generated",
1107
+ "test-only",
1108
+ "tests only",
1109
+ "test only",
1110
+ "tests-only",
1111
+ "n/a",
1112
+ "unaffected",
1113
+ ];
1114
+ /** Normalize a repository-relative path: POSIX separators, no leading `./`. */
1115
+ function normalizeBlastRadiusPath(candidate) {
1116
+ let normalized = candidate.trim().replace(/\\/g, "/");
1117
+ normalized = path.posix.normalize(normalized);
1118
+ while (normalized.startsWith("./"))
1119
+ normalized = normalized.slice(2);
1120
+ return normalized;
1121
+ }
1122
+ /**
1123
+ * Structural check of the version-1 blast-radius envelope. Returns stable,
1124
+ * code-prefixed errors that name a field location and never echo artifact
1125
+ * contents. Unknown additive fields are ignored. Never throws.
1126
+ */
1127
+ function blastRadiusEnvelopeErrors(value) {
1128
+ if (!isRecord(value))
1129
+ return ["blast_radius_not_object: blast-radius.json must be a JSON object."];
1130
+ const errors = [];
1131
+ if (value.schema_version !== 1) {
1132
+ errors.push("blast_radius_unsupported_schema_version: schema_version must be the number 1.");
1133
+ }
1134
+ if (!isNonEmptyString(value.revision)) {
1135
+ errors.push("blast_radius_invalid_revision: revision must be a non-empty string.");
1136
+ }
1137
+ if (!Array.isArray(value.symbols) || value.symbols.length === 0) {
1138
+ errors.push("blast_radius_invalid_symbols: symbols must be a non-empty array of strings.");
1139
+ }
1140
+ else {
1141
+ value.symbols.forEach((symbol, index) => {
1142
+ if (!isNonEmptyString(symbol)) {
1143
+ errors.push(`blast_radius_invalid_symbol_entry: symbols[${index}] must be a non-empty string.`);
1144
+ }
1145
+ });
1146
+ }
1147
+ if (!Array.isArray(value.files)) {
1148
+ errors.push("blast_radius_invalid_files: files must be an array (it may be empty).");
1149
+ }
1150
+ else {
1151
+ value.files.forEach((row, index) => {
1152
+ const where = `files[${index}]`;
1153
+ if (!isRecord(row)) {
1154
+ errors.push(`blast_radius_invalid_file_row: ${where} must be an object.`);
1155
+ return;
1156
+ }
1157
+ const reasons = row.discovery_reasons;
1158
+ if (reasons === undefined) {
1159
+ errors.push(`blast_radius_missing_discovery_reasons: ${where}.discovery_reasons is required.`);
1160
+ }
1161
+ else if (!Array.isArray(reasons) || reasons.length === 0) {
1162
+ errors.push(`blast_radius_missing_discovery_reasons: ${where}.discovery_reasons must be a non-empty array.`);
1163
+ }
1164
+ else {
1165
+ reasons.forEach((reason, reasonIndex) => {
1166
+ if (!isNonEmptyString(reason)) {
1167
+ errors.push(`blast_radius_invalid_discovery_reason: ${where}.discovery_reasons[${reasonIndex}] must be a non-empty string.`);
1168
+ }
1169
+ });
1170
+ }
1171
+ });
1172
+ }
1173
+ if (typeof value.coverage !== "string" ||
1174
+ !BLAST_RADIUS_COVERAGE_VALUES.includes(value.coverage)) {
1175
+ errors.push(`blast_radius_invalid_coverage: coverage must be one of ${BLAST_RADIUS_COVERAGE_VALUES.join(", ")}.`);
1176
+ }
1177
+ const regression = value.regression_check;
1178
+ if (!isRecord(regression)) {
1179
+ errors.push("blast_radius_invalid_regression_check: regression_check must be an object.");
1180
+ }
1181
+ else {
1182
+ if (typeof regression.truncated !== "boolean") {
1183
+ errors.push("blast_radius_invalid_regression_check: regression_check.truncated must be a boolean.");
1184
+ }
1185
+ if (!isStringArray(regression.degraded_flags)) {
1186
+ errors.push("blast_radius_invalid_regression_check: regression_check.degraded_flags must be an array of strings.");
1187
+ }
1188
+ }
1189
+ if (!Array.isArray(value.targeted_searches)) {
1190
+ errors.push("blast_radius_invalid_targeted_searches: targeted_searches must be an array (it may be empty).");
1191
+ }
1192
+ else {
1193
+ value.targeted_searches.forEach((search, index) => {
1194
+ const where = `targeted_searches[${index}]`;
1195
+ if (!isRecord(search)) {
1196
+ errors.push(`blast_radius_invalid_search_entry: ${where} must be an object.`);
1197
+ return;
1198
+ }
1199
+ if (!isNonEmptyString(search.query)) {
1200
+ errors.push(`blast_radius_invalid_search_query: ${where}.query must be a non-empty string.`);
1201
+ }
1202
+ if (!isNonEmptyString(search.reason)) {
1203
+ errors.push(`blast_radius_invalid_search_reason: ${where}.reason must be a non-empty string.`);
1204
+ }
1205
+ if (!isStringArray(search.files)) {
1206
+ errors.push(`blast_radius_invalid_search_files: ${where}.files must be an array of strings.`);
1207
+ }
1208
+ else {
1209
+ search.files.forEach((file, fileIndex) => {
1210
+ const problem = repositoryRelativePathProblem(file, `${where}.files[${fileIndex}]`);
1211
+ if (problem)
1212
+ errors.push(`blast_radius_invalid_search_path: ${problem}`);
1213
+ });
1214
+ }
1215
+ });
1216
+ }
1217
+ return errors;
1218
+ }
1219
+ /**
1220
+ * Disposition checks over a version-1 envelope that already passed
1221
+ * `blastRadiusEnvelopeErrors`. Reads only guarded manifest entries, never the
1222
+ * disk, and never compares `revision` with `HEAD`.
1223
+ */
1224
+ function blastRadiusDispositionErrors(artifact, manifest) {
1225
+ const errors = [];
1226
+ const ownership = new Map();
1227
+ for (const entry of usableManifestEntries(manifest)) {
1228
+ const owned = new Set();
1229
+ for (const file of [...stringItems(entry.touched_files), ...stringItems(entry.read_files)]) {
1230
+ if (repositoryRelativePathProblem(file, "path"))
1231
+ continue;
1232
+ owned.add(normalizeBlastRadiusPath(file));
1233
+ }
1234
+ ownership.set(entry.id, owned);
1235
+ }
1236
+ const blanket = new Set(BLAST_RADIUS_BLANKET_REASONS);
1237
+ const seen = new Set();
1238
+ artifact.files.forEach((row, index) => {
1239
+ const where = `files[${index}]`;
1240
+ const pathProblem = repositoryRelativePathProblem(row.path, `${where}.path`);
1241
+ let normalized = null;
1242
+ if (pathProblem) {
1243
+ errors.push(`blast_radius_invalid_path: ${pathProblem}`);
1244
+ }
1245
+ else {
1246
+ normalized = normalizeBlastRadiusPath(row.path);
1247
+ if (seen.has(normalized)) {
1248
+ errors.push(`blast_radius_duplicate_path: ${where}.path repeats an earlier row once normalized: ${normalized}`);
1249
+ }
1250
+ seen.add(normalized);
1251
+ }
1252
+ const hasChild = "child" in row;
1253
+ const hasReason = "unaffected_reason" in row;
1254
+ if (hasChild && hasReason) {
1255
+ errors.push(`blast_radius_disposition_conflict: ${where} must carry exactly one of child and unaffected_reason.`);
1256
+ return;
1257
+ }
1258
+ if (!hasChild && !hasReason) {
1259
+ errors.push(`blast_radius_disposition_missing: ${where} must carry exactly one of child and unaffected_reason.`);
1260
+ return;
1261
+ }
1262
+ if (hasChild) {
1263
+ const child = row.child;
1264
+ if (typeof child !== "string" || !ownership.has(child)) {
1265
+ errors.push(`blast_radius_unknown_child: ${where}.child names no manifest child.`);
1266
+ }
1267
+ else if (normalized !== null && !ownership.get(child).has(normalized)) {
1268
+ errors.push(`blast_radius_child_does_not_own_path: ${where}.child ${child} lists the path in neither touched_files nor read_files.`);
1269
+ }
1270
+ return;
1271
+ }
1272
+ const reason = row.unaffected_reason;
1273
+ if (!isNonEmptyString(reason)) {
1274
+ errors.push(`blast_radius_invalid_unaffected_reason: ${where}.unaffected_reason must be a non-empty string.`);
1275
+ }
1276
+ else if (blanket.has(reason.trim().toLowerCase().replace(/\s+/g, " "))) {
1277
+ errors.push(`blast_radius_blanket_unaffected_reason: ${where}.unaffected_reason must explain this file, not give a blanket classification.`);
1278
+ }
1279
+ });
1280
+ const regression = artifact.regression_check;
1281
+ const degraded = regression.truncated || regression.degraded_flags.length > 0;
1282
+ if (degraded && artifact.coverage === "complete") {
1283
+ errors.push("blast_radius_coverage_inconsistent: coverage is complete although regression_check is truncated or degraded.");
1284
+ }
1285
+ if (degraded && artifact.targeted_searches.length === 0) {
1286
+ errors.push("blast_radius_repair_missing: truncated or degraded regression_check needs at least one recorded targeted search.");
1287
+ }
1288
+ return errors;
1289
+ }
1290
+ /**
1291
+ * Check the optional sidecar that sits beside the input document. Returns
1292
+ * `null` when the sidecar is absent, so callers keep their existing result.
1293
+ * An existing sidecar that cannot be located, read, or parsed is a named
1294
+ * failure, never an absent one.
1295
+ */
1296
+ async function blastRadiusSidecarErrors(inputPath, manifest, repoRoot, deps) {
1297
+ const sidecar = path.join(path.dirname(inputPath), BLAST_RADIUS_FILE_NAME);
1298
+ const located = await locateInsideRepository(sidecar, repoRoot, deps, "Blast-radius artifact");
1299
+ if (!located.ok)
1300
+ return [`blast_radius_unreadable: ${located.error}`];
1301
+ if (!located.value.exists)
1302
+ return null;
1303
+ let raw;
1304
+ try {
1305
+ raw = await deps.fs.readFile(located.value.canonical);
1306
+ }
1307
+ catch (err) {
1308
+ return [
1309
+ `blast_radius_unreadable: Blast-radius artifact is unreadable: ${sidecar}: ${err instanceof Error ? err.message : String(err)}`,
1310
+ ];
1311
+ }
1312
+ const parsed = parseCanonicalJson(raw, "Blast-radius artifact");
1313
+ if (!parsed.ok)
1314
+ return parsed.errors.map((error) => `blast_radius_invalid_json: ${error}`);
1315
+ const envelope = blastRadiusEnvelopeErrors(parsed.value);
1316
+ if (envelope.length > 0)
1317
+ return envelope;
1318
+ return blastRadiusDispositionErrors(parsed.value, manifest);
1319
+ }
1320
+ /**
1321
+ * `epic-coherence-input check [--structural] <path>`: validate an existing
1322
+ * document. Writes nothing. Without `structural` the result is exactly the
1323
+ * pre-BAPI-1766 plain check.
1324
+ *
1325
+ * BAPI-1767: when a `blast-radius.json` sits beside the input document, its
1326
+ * errors are added to the result in both modes. With no sidecar the result,
1327
+ * warnings, and digests are unchanged. `build` and
1328
+ * `validateEpicCoherenceDocumentShape` never read the sidecar.
1329
+ */
1330
+ export async function checkEpicCoherenceInput(inputPath, deps, options = {}) {
679
1331
  const root = await resolveRepositoryRoot(deps);
680
1332
  if (!root.ok)
681
1333
  return { ok: false, errors: [root.error], warnings: [] };
@@ -685,7 +1337,16 @@ export async function checkEpicCoherenceInput(inputPath, deps) {
685
1337
  const parsed = parseCanonicalJson(raw.value, "Input document");
686
1338
  if (!parsed.ok)
687
1339
  return parsed;
688
- return checkDocument(parsed.value, root.value, deps);
1340
+ const result = await checkDocument(parsed.value, root.value, deps, options);
1341
+ const manifest = isRecord(parsed.value) ? parsed.value.manifest : undefined;
1342
+ const sidecarErrors = await blastRadiusSidecarErrors(inputPath, manifest, root.value, deps);
1343
+ if (sidecarErrors === null || sidecarErrors.length === 0)
1344
+ return result;
1345
+ return {
1346
+ ok: false,
1347
+ errors: [...(result.ok ? [] : result.errors), ...sidecarErrors],
1348
+ warnings: result.warnings,
1349
+ };
689
1350
  }
690
1351
  // ===========================================================================
691
1352
  // Build mode
@@ -726,6 +1387,36 @@ function validateOutlineShape(outline) {
726
1387
  if (child.owns_verifications !== undefined && !Array.isArray(child.owns_verifications)) {
727
1388
  errors.push(`${label}.owns_verifications must be an array.`);
728
1389
  }
1390
+ else if (Array.isArray(child.owns_verifications)) {
1391
+ child.owns_verifications.forEach((claim, claimIndex) => {
1392
+ if (isRecord(claim) && claim.e2e !== undefined && typeof claim.e2e !== "boolean") {
1393
+ errors.push(`${label}.owns_verifications[${claimIndex}].e2e must be true or false.`);
1394
+ }
1395
+ });
1396
+ }
1397
+ // BAPI-1766: hand-off roles are optional; when supplied they must be well formed.
1398
+ // Whether every thing has its owners is `check --structural`'s job, not build's.
1399
+ if (child.handoff_roles !== undefined) {
1400
+ if (!Array.isArray(child.handoff_roles)) {
1401
+ errors.push(`${label}.handoff_roles must be an array of {thing, role} entries.`);
1402
+ }
1403
+ else {
1404
+ child.handoff_roles.forEach((declaration, roleIndex) => {
1405
+ const where = `${label}.handoff_roles[${roleIndex}]`;
1406
+ if (!isRecord(declaration)) {
1407
+ errors.push(`${where} must be an object with thing and role.`);
1408
+ return;
1409
+ }
1410
+ if (typeof declaration.thing !== "string" || !HANDOFF_THING_PATTERN.test(declaration.thing)) {
1411
+ errors.push(`${where}.thing must be a stable id such as "H-1".`);
1412
+ }
1413
+ if (typeof declaration.role !== "string" ||
1414
+ !HANDOFF_ROLES.includes(declaration.role)) {
1415
+ errors.push(`${where}.role must be one of ${HANDOFF_ROLES.join(", ")}.`);
1416
+ }
1417
+ });
1418
+ }
1419
+ }
729
1420
  });
730
1421
  }
731
1422
  if (outline.non_child_owners !== undefined && !Array.isArray(outline.non_child_owners)) {
@@ -867,6 +1558,8 @@ export async function buildEpicCoherenceInput(options, deps) {
867
1558
  touched_files: edits,
868
1559
  read_files: reads,
869
1560
  owns_verifications: claims,
1561
+ // Copied only when supplied, so an outline without roles builds byte-identical output.
1562
+ ...(child.handoff_roles !== undefined ? { handoff_roles: child.handoff_roles } : {}),
870
1563
  });
871
1564
  childEvidence.push({
872
1565
  id: child.id,
@@ -919,3 +1612,183 @@ export async function buildEpicCoherenceInput(options, deps) {
919
1612
  warnings,
920
1613
  };
921
1614
  }
1615
+ /** Only `\r\n` -> `\n`. No whitespace or case folding. */
1616
+ function normalizeLineEndings(text) {
1617
+ return text.replace(/\r\n/g, "\n");
1618
+ }
1619
+ /** The positional draft file for the child at 0-based manifest index `index`. */
1620
+ export function childDraftFileName(index) {
1621
+ return `child-${index + 1}.md`;
1622
+ }
1623
+ /**
1624
+ * Work out what each child draft must contain. Validates only the structures
1625
+ * the draft check needs; it never reruns structural clearance, council
1626
+ * resolution, or acceptance logic, so a non-clearing record is still checked.
1627
+ */
1628
+ function planDraftExpectations(document, record) {
1629
+ const errors = [];
1630
+ const expectations = [];
1631
+ if (!isRecord(document) || !Array.isArray(document.manifest) || document.manifest.length === 0) {
1632
+ errors.push("invalid_input_document: the input document has no non-empty manifest array.");
1633
+ return { errors, expectations };
1634
+ }
1635
+ const positionById = new Map();
1636
+ document.manifest.forEach((entry, index) => {
1637
+ const file = childDraftFileName(index);
1638
+ if (!isRecord(entry) || !isNonEmptyString(entry.id)) {
1639
+ errors.push(`invalid_input_document: manifest[${index}] (${file}) has no child id.`);
1640
+ return;
1641
+ }
1642
+ if (positionById.has(entry.id)) {
1643
+ errors.push(`invalid_input_document: child id ${entry.id} is not unique.`);
1644
+ return;
1645
+ }
1646
+ positionById.set(entry.id, index);
1647
+ const required = [];
1648
+ const claims = entry.owns_verifications;
1649
+ if (claims !== undefined && !Array.isArray(claims)) {
1650
+ errors.push(`invalid_input_document: child ${entry.id} owns_verifications must be an array.`);
1651
+ }
1652
+ else if (Array.isArray(claims)) {
1653
+ claims.forEach((claim, claimIndex) => {
1654
+ const where = `child ${entry.id} owns_verifications[${claimIndex}]`;
1655
+ if (!isRecord(claim) || !isNonEmptyString(claim.obligation)) {
1656
+ errors.push(`invalid_input_document: ${where} has no non-empty obligation.`);
1657
+ return;
1658
+ }
1659
+ const ac = isNonEmptyString(claim.epic_ac) ? claim.epic_ac : "an epic AC";
1660
+ required.push({
1661
+ code: "draft_missing_obligation",
1662
+ label: `the ${claim.e2e === true ? "e2e " : ""}obligation for ${ac} (owns_verifications[${claimIndex}])`,
1663
+ text: claim.obligation,
1664
+ });
1665
+ });
1666
+ }
1667
+ expectations.push({ file, child: entry.id, required });
1668
+ });
1669
+ if (!isRecord(record)) {
1670
+ errors.push("invalid_coherence_record: the coherence record must be a JSON object.");
1671
+ return { errors, expectations };
1672
+ }
1673
+ const carried = record.carried_ticket_local;
1674
+ if (carried === undefined)
1675
+ return { errors, expectations };
1676
+ if (!Array.isArray(carried)) {
1677
+ errors.push("malformed_carried_ticket_local: carried_ticket_local must be an array when present.");
1678
+ return { errors, expectations };
1679
+ }
1680
+ const byChild = new Map(expectations.map((expectation) => [expectation.child, expectation]));
1681
+ carried.forEach((carry, index) => {
1682
+ const where = `carried_ticket_local[${index}]`;
1683
+ if (!isRecord(carry)) {
1684
+ errors.push(`malformed_carry_entry: ${where} must be an object.`);
1685
+ return;
1686
+ }
1687
+ const missing = ["finding_id", "child", "evidence", "smallest_amendment"].filter((field) => !isNonEmptyString(carry[field]));
1688
+ if (missing.length > 0) {
1689
+ errors.push(`malformed_carry_entry: ${where} needs a non-empty ${missing.join(", ")}.`);
1690
+ return;
1691
+ }
1692
+ const child = carry.child;
1693
+ const target = byChild.get(child);
1694
+ if (!target) {
1695
+ errors.push(`carry_unknown_child: ${where} (finding ${String(carry.finding_id)}) names child ${child}, which is not in the manifest.`);
1696
+ return;
1697
+ }
1698
+ const finding = carry.finding_id;
1699
+ for (const field of ["finding_id", "evidence", "smallest_amendment"]) {
1700
+ target.required.push({
1701
+ code: "draft_missing_carried_finding",
1702
+ label: `the ${field} of carried finding ${finding}`,
1703
+ text: carry[field],
1704
+ });
1705
+ }
1706
+ });
1707
+ return { errors, expectations };
1708
+ }
1709
+ /**
1710
+ * The pure draft-fidelity check: every child draft holds each of its
1711
+ * `owns_verifications` obligations (`e2e` included) and, for each carried
1712
+ * ticket-local finding naming it, that finding's `finding_id`, `evidence`, and
1713
+ * `smallest_amendment`, all verbatim after only `\r\n` -> `\n`. Child N maps to
1714
+ * `child-<manifest position>.md`, never to a name built from its id. Errors
1715
+ * name the draft and the field, never the raw text.
1716
+ */
1717
+ export function checkEpicCoherenceDraftFidelity(options) {
1718
+ const { errors, expectations } = planDraftExpectations(options.document, options.record);
1719
+ for (const expectation of expectations) {
1720
+ if (!options.drafts.has(expectation.file)) {
1721
+ errors.push(`draft_missing: ${expectation.file} (child ${expectation.child}) was not supplied.`);
1722
+ continue;
1723
+ }
1724
+ const draft = options.drafts.get(expectation.file);
1725
+ if (draft === null || draft === undefined)
1726
+ continue; // Its load error is already reported.
1727
+ const body = normalizeLineEndings(draft);
1728
+ for (const required of expectation.required) {
1729
+ if (!body.includes(normalizeLineEndings(required.text))) {
1730
+ errors.push(`${required.code}: ${expectation.file} (child ${expectation.child}) does not contain ${required.label} verbatim.`);
1731
+ }
1732
+ }
1733
+ }
1734
+ return errors;
1735
+ }
1736
+ /** Read and canonically parse a contained JSON file, with snippet-free errors. */
1737
+ async function readCanonicalJsonFile(relative, repoRoot, deps, label, code) {
1738
+ const raw = await readContainedFile(relative, repoRoot, deps, label);
1739
+ if (!raw.ok)
1740
+ return { ok: false, error: `${code}_unreadable: ${raw.error}` };
1741
+ const parsed = parseCanonicalJson(raw.value, label);
1742
+ if (!parsed.ok) {
1743
+ // Never echo parser messages: they can quote the document's contents.
1744
+ return { ok: false, error: `${code}_not_canonical_json: ${label} is not valid canonical JSON: ${relative}` };
1745
+ }
1746
+ return { ok: true, value: parsed.value };
1747
+ }
1748
+ /**
1749
+ * `epic-coherence-input check-drafts --input <path> --drafts <dir> --record <path>`.
1750
+ * Read-only: it never creates a directory, writes a file, or changes a draft
1751
+ * or the record. Every path is contained in the repository by its real path,
1752
+ * so a symlinked draft directory or draft file cannot escape.
1753
+ */
1754
+ export async function checkEpicCoherenceDrafts(options, deps) {
1755
+ const root = await resolveRepositoryRoot(deps);
1756
+ if (!root.ok)
1757
+ return { ok: false, errors: [root.error], warnings: [] };
1758
+ const repoRoot = root.value;
1759
+ const errors = [];
1760
+ // Contain the original arguments before joining any path onto them.
1761
+ const draftsDir = await locateInsideRepository(options.draftsDir, repoRoot, deps, "--drafts");
1762
+ if (!draftsDir.ok)
1763
+ errors.push(`drafts_directory_unavailable: ${draftsDir.error}`);
1764
+ else if (!draftsDir.value.exists) {
1765
+ errors.push(`drafts_directory_unavailable: --drafts does not exist: ${options.draftsDir}`);
1766
+ }
1767
+ const input = await readCanonicalJsonFile(options.inputPath, repoRoot, deps, "Input document", "input");
1768
+ if (!input.ok)
1769
+ errors.push(input.error);
1770
+ const record = await readCanonicalJsonFile(options.recordPath, repoRoot, deps, "Coherence record", "record");
1771
+ if (!record.ok)
1772
+ errors.push(record.error);
1773
+ if (errors.length > 0 || !input.ok || !record.ok)
1774
+ return { ok: false, errors, warnings: [] };
1775
+ const manifest = isRecord(input.value) && Array.isArray(input.value.manifest) ? input.value.manifest : [];
1776
+ const drafts = new Map();
1777
+ const checked = [];
1778
+ for (let index = 0; index < manifest.length; index++) {
1779
+ const file = childDraftFileName(index);
1780
+ checked.push(file);
1781
+ const read = await readContainedFile(path.join(options.draftsDir, file), repoRoot, deps, `Draft ${file}`);
1782
+ if (read.ok) {
1783
+ drafts.set(file, read.value);
1784
+ }
1785
+ else {
1786
+ errors.push(`draft_unreadable: ${read.error}`);
1787
+ drafts.set(file, null);
1788
+ }
1789
+ }
1790
+ errors.push(...checkEpicCoherenceDraftFidelity({ document: input.value, record: record.value, drafts }));
1791
+ if (errors.length > 0)
1792
+ return { ok: false, errors, warnings: [] };
1793
+ return { ok: true, value: { checked_drafts: checked }, warnings: [] };
1794
+ }