@bridge_gpt/mcp-server 0.2.69 → 0.2.71

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 (164) hide show
  1. package/README.md +140 -292
  2. package/build/agent-launchers/claude-executor-adapter.js +27 -5
  3. package/build/agent-registry.js +5 -5
  4. package/build/agents.generated.js +15 -5
  5. package/build/artifact-diff.js +110 -0
  6. package/build/bin-entrypoint.js +36 -0
  7. package/build/bounded-wait.js +9 -1
  8. package/build/bridge-permissions.js +36 -9
  9. package/build/claude-review-workflow-drift.js +3 -3
  10. package/build/codex-bridge-profile.js +1 -1
  11. package/build/commands.generated.js +6 -6
  12. package/build/conductor/bridge-api-client.js +858 -21
  13. package/build/conductor/bring-up-facts.js +9 -9
  14. package/build/conductor/command-drift-production.js +7 -2
  15. package/build/conductor/doctor.js +472 -18
  16. package/build/conductor/epic-child-continuation.js +54 -3
  17. package/build/conductor/epic-implementer-cli.js +136 -34
  18. package/build/conductor/epic-runtime.js +2 -2
  19. package/build/conductor/epic-state.js +1 -1
  20. package/build/conductor/gate-discovery.js +524 -10
  21. package/build/conductor/gate-settings-review.js +451 -0
  22. package/build/conductor/hook-runtime-qualification.js +1 -1
  23. package/build/conductor/install-doctor.js +4 -2
  24. package/build/conductor/launch-need-probes.js +342 -0
  25. package/build/conductor/launch-plan.js +145 -0
  26. package/build/conductor/local-merge.js +241 -56
  27. package/build/conductor/merge-credential.js +172 -0
  28. package/build/conductor/merge-execution-eligibility.js +1 -1
  29. package/build/conductor/merged-child-check.js +95 -0
  30. package/build/conductor/plan-trim.js +30 -0
  31. package/build/conductor/pr-ci-producer.js +1 -1
  32. package/build/conductor/precheck-timings.js +14 -0
  33. package/build/conductor/preview-observations.js +10 -0
  34. package/build/conductor/readiness-cli.js +11 -6
  35. package/build/conductor/readiness-prerequisites.js +41 -0
  36. package/build/conductor/readiness-sections.js +348 -55
  37. package/build/conductor/readiness.js +99 -87
  38. package/build/conductor/recovery-cli.js +665 -23
  39. package/build/conductor/recovery-operations.js +350 -8
  40. package/build/conductor/repair-contract.js +47 -2
  41. package/build/conductor/repository-workflow-remedy.js +8 -6
  42. package/build/conductor/stored-merge-credential.js +76 -0
  43. package/build/conductor/stored-merge-token-probe.js +28 -0
  44. package/build/conductor/temporary-plan.js +50 -0
  45. package/build/conductor/wait-run-cli.js +759 -0
  46. package/build/conductor/worker-database-doctor-inspector.js +49 -0
  47. package/build/conductor-bin.js +2 -2
  48. package/build/conductor-claude-hook-bin.js +2 -2
  49. package/build/conductor-claude-hook-removed-stub-bin.js +2 -5
  50. package/build/conductor-removed-stub-bin.js +2 -5
  51. package/build/credential-store.js +356 -13
  52. package/build/docs.generated.js +26 -13
  53. package/build/doctor.js +94 -32
  54. package/build/drive-epic-help.js +212 -0
  55. package/build/drive-epic.js +1989 -379
  56. package/build/epic-ci-workflow-drift.js +125 -0
  57. package/build/epic-ci-workflow-install.js +240 -0
  58. package/build/epic-ci-workflow-v1.js +132 -0
  59. package/build/epic-ci-workflow.js +318 -0
  60. package/build/epic-contract-context.js +326 -0
  61. package/build/epic-implementer-bin.js +58 -42
  62. package/build/epic-implementer-claude-hook-bin.js +2 -2
  63. package/build/escalation-reachability.js +134 -0
  64. package/build/executor/ci-rerun-job.js +220 -14
  65. package/build/executor/cleanup-report.js +99 -0
  66. package/build/executor/cli.js +12 -1
  67. package/build/executor/completion-contract.js +66 -11
  68. package/build/executor/completion-supervision.js +99 -0
  69. package/build/executor/delivery-outcome.js +179 -0
  70. package/build/executor/deps.js +3 -0
  71. package/build/executor/env.js +276 -1
  72. package/build/executor/failure-reason-codes.js +126 -0
  73. package/build/executor/gate-qualification-job.js +20 -5
  74. package/build/executor/heartbeat.js +38 -0
  75. package/build/executor/http-client.js +72 -0
  76. package/build/executor/integration-job.js +298 -5
  77. package/build/executor/job-errors.js +36 -6
  78. package/build/executor/job-runner.js +830 -45
  79. package/build/executor/likely-tests.js +42 -3
  80. package/build/executor/merge-job.js +145 -2
  81. package/build/executor/observation.js +73 -4
  82. package/build/executor/permissions.js +193 -97
  83. package/build/executor/preflight.js +19 -3
  84. package/build/executor/process-containment.js +46 -2
  85. package/build/executor/prompt-spec.js +113 -9
  86. package/build/executor/rebase-finalization.js +38 -3
  87. package/build/executor/reconcile-overlap-job.js +41 -8
  88. package/build/executor/required-work-ledger.js +236 -81
  89. package/build/executor/resume-pre-spawn.js +38 -1
  90. package/build/executor/runner.js +91 -3
  91. package/build/executor/test-clock.js +8 -0
  92. package/build/executor/types.js +37 -2
  93. package/build/executor/worker-cli-launcher.js +259 -0
  94. package/build/executor/worker-command.js +177 -5
  95. package/build/executor/worker-database-target.js +91 -0
  96. package/build/executor/worker-database.js +927 -0
  97. package/build/executor/worker-finalization.js +106 -0
  98. package/build/executor/worker-guard-hook.js +203 -0
  99. package/build/executor/worker-resources.js +58 -0
  100. package/build/executor/worker-verification-guidance.js +44 -2
  101. package/build/executor/worktree.js +303 -15
  102. package/build/executor-launch.js +11 -1
  103. package/build/generated-assets-doctor.js +9 -1
  104. package/build/generated-assets-health.js +13 -4
  105. package/build/generated-assets-legacy.js +39 -0
  106. package/build/generated-assets-paths.js +12 -1
  107. package/build/generated-assets-repair.js +4 -1
  108. package/build/generated-assets-test-support.js +12 -0
  109. package/build/github-remote.js +33 -0
  110. package/build/github-sign-in.js +62 -0
  111. package/build/index.js +1133 -546
  112. package/build/init.js +39 -1
  113. package/build/install-bridge-conductor-gate.js +270 -11
  114. package/build/install-bridge-conductor-setup.js +427 -0
  115. package/build/install-bridge-conductor.js +1545 -268
  116. package/build/install-bridge.js +376 -60
  117. package/build/mcp-install-state.js +8 -2
  118. package/build/merge-pull-request.js +6 -0
  119. package/build/merge-workflow-install.js +782 -344
  120. package/build/phase-result-artifacts.js +75 -20
  121. package/build/pipeline-orchestrator.js +247 -4
  122. package/build/pipelines.generated.js +35 -35
  123. package/build/plan-discovery.js +15 -2
  124. package/build/plan-execution-ledger.js +321 -17
  125. package/build/plan-phase-routing.js +48 -13
  126. package/build/plane/cli.js +105 -51
  127. package/build/plane/defaults.js +3 -0
  128. package/build/plane/plane-freshness.js +298 -0
  129. package/build/plane/preflight.js +19 -0
  130. package/build/plane/schema-compatibility.js +137 -0
  131. package/build/plane/shutdown-deps.js +38 -0
  132. package/build/plane/shutdown.js +83 -8
  133. package/build/plane/terminal-run-cleanup.js +303 -0
  134. package/build/printed-remedy-commands.js +33 -4
  135. package/build/readiness-check.js +6 -2
  136. package/build/readiness-prerequisites.generated.js +532 -0
  137. package/build/readme.generated.js +1 -1
  138. package/build/repository-toolchains.js +581 -0
  139. package/build/setup-epic.js +421 -34
  140. package/build/shared-resources.generated.js +5 -0
  141. package/build/start-tickets.js +28 -15
  142. package/build/test-command-detection.js +284 -0
  143. package/build/test-command-validation.js +73 -0
  144. package/build/testing-config-client.js +150 -0
  145. package/build/ticket-delivery-artifacts.js +265 -0
  146. package/build/ticket-delivery-enrollment.js +369 -0
  147. package/build/ticket-delivery.js +205 -0
  148. package/build/ticket-review-summary.js +14 -0
  149. package/build/upgrade-cli.js +13 -0
  150. package/build/v2-readiness-requirements.js +552 -0
  151. package/build/version.generated.js +3 -3
  152. package/build/worker-guard-hook-bin.js +2 -2
  153. package/build/worktree-core.js +22 -7
  154. package/docs/BRIDGE-DIRECTORY-README.md +48 -0
  155. package/docs/EPIC-IMPLEMENTER-INSTALL.md +12 -867
  156. package/docs/EPIC-IMPLEMENTER.md +142 -63
  157. package/docs/epic-implementer/getting-started.md +187 -0
  158. package/docs/epic-implementer/self-hosting.md +133 -0
  159. package/package.json +4 -4
  160. package/pipelines/idea-to-ticket.json +1 -1
  161. package/pipelines/implement-ticket.json +8 -8
  162. package/pipelines/review-ticket.json +2 -2
  163. package/design-assets/favicon/favicon-32x32.png +0 -0
  164. package/design-assets/just-logo-rough-draft.png +0 -0
@@ -0,0 +1,318 @@
1
+ /**
2
+ * The customer Epic Implementer CI workflow renderer (BAPI-1460).
3
+ *
4
+ * Renders `.github/workflows/epic-implementer-ci.yml` from the repository's ONE
5
+ * stored test command. The workflow publishes the single required context the
6
+ * Epic Implementer `ci` gate observes, `epic-implementer-ci / gate`: green when
7
+ * the command passes on a same-repository pull request, and green immediately,
8
+ * without running anything, for a fork pull request.
9
+ *
10
+ * ## Why a TypeScript renderer
11
+ *
12
+ * Same precedent as `merge-workflow.ts`: the compiled renderer is the file's
13
+ * only byte source, so "did Bridge render this?" has one answer.
14
+ *
15
+ * ## The command is data, never code in this process
16
+ *
17
+ * The command is written as ONE double-quoted YAML scalar produced by
18
+ * `JSON.stringify` (a JSON string is a valid YAML double-quoted scalar), on one
19
+ * fixed `run:` line. It is never placed in this process's own shell or git
20
+ * arguments. The renderer re-checks the stored-command rules and throws on a bad
21
+ * command; `${{` in particular is refused because Actions would evaluate an
22
+ * expression inside a `run:` value before the shell sees it.
23
+ *
24
+ * ## Safe by default
25
+ *
26
+ * `on: pull_request` only, `permissions: contents: read`, no secrets, no
27
+ * path filters, `ubuntu-latest`. The execution job runs only when the pull
28
+ * request head is this repository; a fork pull request never checks out or runs
29
+ * repository code. The checkout does not persist its token.
30
+ *
31
+ * ## Toolchain provisioning (renderer version 2, BAPI-1536)
32
+ *
33
+ * Version 1 provisioned nothing, so a command that needed installed dependencies
34
+ * had to install them itself. Version 2 adds fixed setup steps between the
35
+ * checkout and the stored command, chosen from the repository's own lockfiles by
36
+ * the shared resolver (`repository-toolchains.ts`) at the moment the workflow is
37
+ * generated. The resolver reads the local working tree only. Server indexing
38
+ * metadata is deliberately NOT an input: it can be stale, absent, or describe a
39
+ * different checkout, and the workflow must be reproducible from the files it is
40
+ * committed next to.
41
+ *
42
+ * - JavaScript, Python, and Go are provisioned, in that order, when found.
43
+ * Manager priority, version-file precedence, and fixed fallbacks are defined in
44
+ * `repository-toolchains.ts`; the user-facing summary is the packaged
45
+ * `getting-started` guide.
46
+ * - Every action is pinned to a fixed major and every manager bootstrap version
47
+ * is a documented constant. Installation shell lines are fixed text. No value
48
+ * taken from the repository is rendered into a step: Node and Python versions
49
+ * are a fixed file name, and a declared pnpm or Yarn version is read by the
50
+ * action or Corepack at CI runtime. A validated pnpm version appears only in
51
+ * the header marker.
52
+ * - uv and Poetry environments are placed on `PATH`, so the stored command runs
53
+ * unchanged inside the project environment.
54
+ * - Rust uses the runner's own toolchain. Python projects with no supported
55
+ * dependency file, projects with no lockfile at all, and Make-only projects
56
+ * receive no provisioning: their command must be self-contained.
57
+ * - The complete resolved set is written into the header (a single canonical
58
+ * line) so a later run can re-render the file byte for byte and tell a
59
+ * legitimate toolchain change from a hand edit.
60
+ *
61
+ * The command still never receives a prefix or an install: it stays on its one
62
+ * protected scalar line.
63
+ */
64
+ import { BUN_VERSION_RANGE, NODE_FALLBACK_MAJOR, PNPM_FALLBACK_MAJOR, POETRY_VERSION, PYTHON_FALLBACK_MINOR, YARN_BERRY_FALLBACK_MAJOR, serializeRepositoryToolchains, validateRepositoryToolchains, } from "./repository-toolchains.js";
65
+ import { validateTestCommand } from "./test-command-validation.js";
66
+ /** Repository-relative path of the managed workflow. */
67
+ export const EPIC_CI_WORKFLOW_PATH = ".github/workflows/epic-implementer-ci.yml";
68
+ /** The renderer version written into the managed header. */
69
+ export const EPIC_CI_WORKFLOW_RENDERER_VERSION = 2;
70
+ /** The header marker key; the line is `# <key>: <version>`. */
71
+ export const EPIC_CI_WORKFLOW_VERSION_MARKER_KEY = "x-bridge-ci-renderer-version";
72
+ /** The header marker key for the canonical toolchain set; the line is `# <key>: <json>`. */
73
+ export const EPIC_CI_WORKFLOW_TOOLCHAINS_MARKER_KEY = "x-bridge-ci-toolchains";
74
+ /** The `name:` of the one step that runs the stored command. */
75
+ export const EPIC_CI_COMMAND_STEP_NAME = "Run the stored test command";
76
+ /** Pinned action majors. Changing any of these is a renderer-version change. */
77
+ export const EPIC_CI_ACTION_CHECKOUT = "actions/checkout@v7";
78
+ export const EPIC_CI_ACTION_SETUP_NODE = "actions/setup-node@v7";
79
+ export const EPIC_CI_ACTION_SETUP_PYTHON = "actions/setup-python@v7";
80
+ export const EPIC_CI_ACTION_SETUP_GO = "actions/setup-go@v6";
81
+ export const EPIC_CI_ACTION_SETUP_PNPM = "pnpm/action-setup@v4";
82
+ export const EPIC_CI_ACTION_SETUP_BUN = "oven-sh/setup-bun@v2";
83
+ export const EPIC_CI_ACTION_SETUP_UV = "astral-sh/setup-uv@v6";
84
+ /** The workflow `name:`. */
85
+ export const EPIC_CI_WORKFLOW_NAME = "epic-implementer-ci";
86
+ /**
87
+ * The required check context, and the aggregator job's display `name:`.
88
+ *
89
+ * Must equal `EPIC_IMPLEMENTER_GATE_CHECK_NAME` in
90
+ * `api/library/github/workflow_inspection.py` and `CURRENT_GATE_NAME` in
91
+ * `mcp_server/src/conductor/readiness.ts`; a test asserts all three agree.
92
+ */
93
+ export const EPIC_IMPLEMENTER_CI_CHECK_NAME = "epic-implementer-ci / gate";
94
+ /** Bound on the execution job, in minutes. */
95
+ export const EPIC_CI_TEST_JOB_TIMEOUT_MINUTES = 30;
96
+ /** Bound on the aggregator job, in minutes. */
97
+ export const EPIC_CI_GATE_JOB_TIMEOUT_MINUTES = 5;
98
+ /** The fixed indentation and key that precede the command scalar. */
99
+ export const EPIC_CI_COMMAND_LINE_PREFIX = " run: ";
100
+ /**
101
+ * Characters `JSON.stringify` leaves raw that a YAML parser may read as a line
102
+ * break or a byte-order mark (YAML 1.1 treats U+0085, U+2028 and U+2029 as
103
+ * breaks), plus DEL and the C1 controls. They are escaped as `\uXXXX`, which is
104
+ * still valid JSON and a valid YAML double-quoted escape.
105
+ */
106
+ const YAML_UNSAFE_RAW = /[\u007f-\u009f\u2028\u2029\ufeff]/g;
107
+ /** Encode the command as one JSON string that is also a safe YAML scalar. */
108
+ export function encodeCommandScalar(testCommand) {
109
+ return JSON.stringify(testCommand).replace(YAML_UNSAFE_RAW, (ch) => "\\u" + ch.charCodeAt(0).toString(16).padStart(4, "0"));
110
+ }
111
+ function nodeSetupLines(node) {
112
+ return [
113
+ " - name: Set up Node.js",
114
+ " uses: " + EPIC_CI_ACTION_SETUP_NODE,
115
+ " with:",
116
+ node === "fixed"
117
+ ? ' node-version: "' + NODE_FALLBACK_MAJOR + '"'
118
+ : " node-version-file: " + node,
119
+ ];
120
+ }
121
+ function pythonSetupLines(python) {
122
+ return [
123
+ " - name: Set up Python",
124
+ " uses: " + EPIC_CI_ACTION_SETUP_PYTHON,
125
+ " with:",
126
+ python === "fixed"
127
+ ? ' python-version: "' + PYTHON_FALLBACK_MINOR + '"'
128
+ : " python-version-file: " + python,
129
+ ];
130
+ }
131
+ function javaScriptSetupLines(js) {
132
+ switch (js.manager) {
133
+ case "npm":
134
+ return [...nodeSetupLines(js.node), " - name: Install dependencies", " run: npm ci"];
135
+ case "pnpm":
136
+ return [
137
+ " - name: Set up pnpm",
138
+ " uses: " + EPIC_CI_ACTION_SETUP_PNPM,
139
+ // A declared `packageManager` is read by the action itself at CI runtime.
140
+ // Passing `version:` as well makes it fail with "Multiple versions of pnpm
141
+ // specified" whenever the two strings differ (a Corepack `+sha` suffix is
142
+ // enough), so the input is given only for the fixed fallback.
143
+ ...(js.pnpm.source === "default" ? [" with:", ' version: "' + PNPM_FALLBACK_MAJOR + '"'] : []),
144
+ ...nodeSetupLines(js.node),
145
+ " - name: Install dependencies",
146
+ " run: pnpm install --frozen-lockfile",
147
+ ];
148
+ case "yarn":
149
+ if (js.generation === "classic") {
150
+ return [...nodeSetupLines(js.node), " - name: Install dependencies", " run: yarn install --frozen-lockfile"];
151
+ }
152
+ // Corepack reads a declared Yarn version from package.json at CI runtime;
153
+ // the activation below is only the fallback major when none is declared.
154
+ return [
155
+ ...nodeSetupLines(js.node),
156
+ " - name: Enable Corepack",
157
+ " run: corepack enable",
158
+ " - name: Activate Yarn",
159
+ " run: corepack prepare yarn@" + YARN_BERRY_FALLBACK_MAJOR + " --activate",
160
+ " - name: Install dependencies",
161
+ " run: yarn install --immutable",
162
+ ];
163
+ case "bun":
164
+ return [
165
+ " - name: Set up Bun",
166
+ " uses: " + EPIC_CI_ACTION_SETUP_BUN,
167
+ " with:",
168
+ ' bun-version: "' + BUN_VERSION_RANGE + '"',
169
+ " - name: Install dependencies",
170
+ " run: bun install --frozen-lockfile",
171
+ ];
172
+ }
173
+ }
174
+ const PROJECT_ENVIRONMENT_PATH_LINES = [
175
+ " - name: Add the project environment to PATH",
176
+ ' run: echo "$GITHUB_WORKSPACE/.venv/bin" >> "$GITHUB_PATH"',
177
+ ];
178
+ function pythonSetupLinesFor(py) {
179
+ const setup = pythonSetupLines(py.python);
180
+ switch (py.manager) {
181
+ case "uv":
182
+ return [
183
+ ...setup,
184
+ " - name: Set up uv",
185
+ " uses: " + EPIC_CI_ACTION_SETUP_UV,
186
+ " - name: Install dependencies",
187
+ " run: uv sync --frozen",
188
+ ...PROJECT_ENVIRONMENT_PATH_LINES,
189
+ ];
190
+ case "poetry":
191
+ return [
192
+ ...setup,
193
+ " - name: Install Poetry",
194
+ " run: python -m pip install poetry==" + POETRY_VERSION,
195
+ " - name: Configure Poetry",
196
+ " run: poetry config virtualenvs.in-project true",
197
+ " - name: Install dependencies",
198
+ " run: poetry install",
199
+ ...PROJECT_ENVIRONMENT_PATH_LINES,
200
+ ];
201
+ case "pip":
202
+ return [...setup, " - name: Install dependencies", " run: pip install -r requirements.txt"];
203
+ }
204
+ }
205
+ /** The setup steps for a validated set, in the fixed JavaScript, Python, Go order. */
206
+ function toolchainSetupLines(toolchains) {
207
+ const lines = [];
208
+ if (toolchains.javascript !== null)
209
+ lines.push(...javaScriptSetupLines(toolchains.javascript));
210
+ if (toolchains.python !== null)
211
+ lines.push(...pythonSetupLinesFor(toolchains.python));
212
+ if (toolchains.go !== null) {
213
+ lines.push(" - name: Set up Go", " uses: " + EPIC_CI_ACTION_SETUP_GO, " with:", " go-version-file: " + toolchains.go.dependencyFile);
214
+ }
215
+ return lines;
216
+ }
217
+ /**
218
+ * Render the workflow for `testCommand` and the resolved `toolchains`.
219
+ * Deterministic: the same inputs always give the same bytes. Throws
220
+ * `TestCommandValidationError` for a bad command and `RepositoryToolchainError`
221
+ * for a toolchain set outside the closed vocabulary.
222
+ */
223
+ export function renderEpicImplementerCiWorkflow(testCommand, toolchains) {
224
+ const command = validateTestCommand(testCommand);
225
+ const validated = validateRepositoryToolchains(toolchains);
226
+ const lines = [
227
+ "# ===========================================================================",
228
+ "# Epic Implementer CI gate — MANAGED FILE",
229
+ "#",
230
+ "# Generated by Bridge (`" + EPIC_CI_WORKFLOW_PATH + "`). Do not hand-edit: the",
231
+ "# installer compares this file byte for byte against what it renders and",
232
+ "# refuses to overwrite a modified or unrecognized copy.",
233
+ "#",
234
+ "# " + EPIC_CI_WORKFLOW_VERSION_MARKER_KEY + ": " + String(EPIC_CI_WORKFLOW_RENDERER_VERSION),
235
+ "# " + EPIC_CI_WORKFLOW_TOOLCHAINS_MARKER_KEY + ": " + serializeRepositoryToolchains(validated),
236
+ "#",
237
+ "# WHAT THIS WORKFLOW IS",
238
+ "#",
239
+ "# It publishes one required check, `" + EPIC_IMPLEMENTER_CI_CHECK_NAME + "`, that the",
240
+ "# Bridge Epic Implementer reads before it merges a child pull request. The",
241
+ "# check is green only when the repository's stored test command passes.",
242
+ "#",
243
+ "# SCOPE: SAME-REPOSITORY PULL REQUESTS ONLY",
244
+ "#",
245
+ "# The `tests` job runs only when the pull request head is this repository.",
246
+ "# A fork pull request never checks out or runs repository code; the gate",
247
+ "# passes for it immediately and says so. Nothing here uses a secret, and the",
248
+ "# token is read-only.",
249
+ "#",
250
+ "# DEPENDENCIES",
251
+ "#",
252
+ "# The setup steps before the test command were chosen from the lockfiles in",
253
+ "# the repository root when this file was generated; the toolchains line above",
254
+ "# records the choice. They install dependencies and nothing else. When no",
255
+ "# supported dependency file was found, nothing is installed for that",
256
+ "# ecosystem and the command must install what it needs itself.",
257
+ "#",
258
+ "# THE TEST COMMAND",
259
+ "#",
260
+ "# The command below is the repository's stored test command, run with bash",
261
+ "# from the repository root after the setup steps. To change it, save a new",
262
+ "# command through Bridge setup and re-run the installer; do not edit it here.",
263
+ "# ===========================================================================",
264
+ "name: " + EPIC_CI_WORKFLOW_NAME,
265
+ "",
266
+ "on:",
267
+ " pull_request:",
268
+ "",
269
+ "permissions:",
270
+ " contents: read",
271
+ "",
272
+ "jobs:",
273
+ " tests:",
274
+ " name: tests",
275
+ " if: ${{ github.event.pull_request.head.repo.full_name == github.repository }}",
276
+ " runs-on: ubuntu-latest",
277
+ " timeout-minutes: " + String(EPIC_CI_TEST_JOB_TIMEOUT_MINUTES),
278
+ " steps:",
279
+ " - name: Check out the pull request",
280
+ " uses: " + EPIC_CI_ACTION_CHECKOUT,
281
+ " with:",
282
+ " persist-credentials: false",
283
+ ...toolchainSetupLines(validated),
284
+ " - name: " + EPIC_CI_COMMAND_STEP_NAME,
285
+ " shell: bash",
286
+ EPIC_CI_COMMAND_LINE_PREFIX + encodeCommandScalar(command),
287
+ "",
288
+ " gate:",
289
+ " name: " + EPIC_IMPLEMENTER_CI_CHECK_NAME,
290
+ " needs: [tests]",
291
+ " if: ${{ always() }}",
292
+ " runs-on: ubuntu-latest",
293
+ " timeout-minutes: " + String(EPIC_CI_GATE_JOB_TIMEOUT_MINUTES),
294
+ " steps:",
295
+ " - name: Aggregate the Epic Implementer CI result",
296
+ " env:",
297
+ " HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}",
298
+ " THIS_REPOSITORY: ${{ github.repository }}",
299
+ " TESTS_RESULT: ${{ needs.tests.result }}",
300
+ " run: |",
301
+ " if [ -z \"$HEAD_REPOSITORY\" ] || [ -z \"$THIS_REPOSITORY\" ]; then",
302
+ " echo \"The pull request head repository could not be identified; the gate fails.\"",
303
+ " exit 1",
304
+ " fi",
305
+ " if [ \"$HEAD_REPOSITORY\" != \"$THIS_REPOSITORY\" ]; then",
306
+ " echo \"Fork pull request: repository code is never run for a fork, so the gate passes without running tests.\"",
307
+ " exit 0",
308
+ " fi",
309
+ " echo \"Tests: $TESTS_RESULT\"",
310
+ " if [ \"$TESTS_RESULT\" = \"success\" ]; then",
311
+ " exit 0",
312
+ " fi",
313
+ " echo \"The stored test command did not conclude 'success'; the gate fails.\"",
314
+ " exit 1",
315
+ "",
316
+ ];
317
+ return lines.join("\n");
318
+ }
@@ -0,0 +1,326 @@
1
+ /**
2
+ * epic-contract-context — the MCP side of epic-aware review resolution (BAPI-1428).
3
+ *
4
+ * Three jobs live here, kept out of `index.ts` so they can be unit-tested:
5
+ *
6
+ * 1. **The switch.** `EPIC_CONTRACT_CONTEXT_ENABLED` is the same default-ON
7
+ * variable the Python service reads
8
+ * (`api/library/tickets/epic_contract_context_config_lib.py`). It is
9
+ * independent of delivery readiness and of tool-surface gating.
10
+ * 2. **Transport.** Building the context request, and turning a complete
11
+ * transport failure into a disclosed, degraded result instead of an error,
12
+ * so an unreachable context service never stops a review.
13
+ * 3. **The structured resolution result.** Parsing and validating the fenced
14
+ * `bapi-epic-contract-resolution` block that `evaluate-and-recommend.md`
15
+ * writes into `<KEY>-review-and-resolution.md`, and deciding whether terminal
16
+ * decision capture may proceed. Capture is refused only while a finding is
17
+ * recorded as an unresolved mandatory incompatibility.
18
+ *
19
+ * The resolution duty is not duplicated here: it is the canonical
20
+ * `api/library/tickets/epic_contract_resolution_duty.md`, bundled verbatim into
21
+ * `SHARED_RESOURCES` (`shared-resources.generated.ts`) by
22
+ * `scripts/bundle-pipelines.js`.
23
+ */
24
+ import { parseDefaultOnEnvFlag } from "./env-flags.js";
25
+ import { isValidTicketKey } from "./ticket-key-utils.js";
26
+ /** The single switch, shared with the Python service. */
27
+ export const EPIC_CONTRACT_CONTEXT_ENV_VAR = "EPIC_CONTRACT_CONTEXT_ENABLED";
28
+ /** The fenced-block info string the structured result is written under. */
29
+ export const EPIC_RESOLUTION_FENCE = "bapi-epic-contract-resolution";
30
+ /** Version of the structured result this module reads and validates. */
31
+ export const EPIC_RESOLUTION_SCHEMA_VERSION = 1;
32
+ /** Bundled resource name of the canonical resolution duty. */
33
+ export const EPIC_CONTRACT_DUTY_RESOURCE = "epic-contract-resolution-duty.md";
34
+ /**
35
+ * Whether epic-contract resolution is on for new reviews in this process.
36
+ *
37
+ * `env` defaults to `process.env`; tests inject an explicit object.
38
+ */
39
+ export function epicContractContextEnabled(env = process.env) {
40
+ return parseDefaultOnEnvFlag(env[EPIC_CONTRACT_CONTEXT_ENV_VAR]);
41
+ }
42
+ /**
43
+ * Build the context route's request body. Optional selectors are omitted when
44
+ * absent rather than sent as null or empty values.
45
+ */
46
+ export function buildEpicContractContextBody(args, repoName) {
47
+ const body = {
48
+ repo_name: repoName,
49
+ ticket_key: args.ticket_key.trim().toUpperCase(),
50
+ };
51
+ if (args.policy_token)
52
+ body.policy_token = args.policy_token;
53
+ if (args.sibling_keys && args.sibling_keys.length > 0)
54
+ body.sibling_keys = args.sibling_keys;
55
+ if (args.children_cursor)
56
+ body.children_cursor = args.children_cursor;
57
+ if (args.page_limit !== undefined)
58
+ body.page_limit = args.page_limit;
59
+ if (args.include_parent !== undefined)
60
+ body.include_parent = args.include_parent;
61
+ if (args.excerpts && args.excerpts.length > 0)
62
+ body.excerpts = args.excerpts;
63
+ if (args.revalidate && args.revalidate.length > 0)
64
+ body.revalidate = args.revalidate;
65
+ return body;
66
+ }
67
+ /** The result returned when the switch is off and no starting-policy token was supplied. */
68
+ export function disabledContextResult(ticketKey) {
69
+ return {
70
+ status: "disabled",
71
+ subject_key: ticketKey.trim().toUpperCase(),
72
+ policy_enabled: false,
73
+ coverage: { complete: false, gaps: [] },
74
+ note: "Epic-contract resolution is switched off for new reviews. Continue the ordinary review; " +
75
+ "recorded decisions are unaffected.",
76
+ };
77
+ }
78
+ /**
79
+ * The degraded result for a complete transport failure.
80
+ *
81
+ * The review continues with the evidence it already has. Fallback telemetry is
82
+ * reported as `unavailable`: this process has no authenticated, non-admin
83
+ * diagnostic channel it could use instead, and it never claims a report was
84
+ * delivered when it was not.
85
+ */
86
+ export function transportFailureResult(ticketKey, duty) {
87
+ return {
88
+ status: "degraded",
89
+ subject_key: ticketKey.trim().toUpperCase(),
90
+ parent: null,
91
+ inventory: null,
92
+ siblings: [],
93
+ revalidations: [],
94
+ coverage: {
95
+ fetched: [],
96
+ partial: [],
97
+ missing_or_failed: [],
98
+ unhydrated: [],
99
+ complete: false,
100
+ gaps: [
101
+ {
102
+ reason: "read_failed",
103
+ ticket_key: null,
104
+ detail: "The epic-contract context service could not be reached.",
105
+ },
106
+ ],
107
+ },
108
+ telemetry: { status: "unavailable", reported_gap_count: 0 },
109
+ duty: duty ?? null,
110
+ note: "No epic contract was retrieved. Disclose this gap, resolve with the ticket and code " +
111
+ "evidence you have, and do not claim any parent or sibling contract was checked.",
112
+ };
113
+ }
114
+ const FENCE_PATTERN = new RegExp("^```" + EPIC_RESOLUTION_FENCE + "[ \\t]*\\r?\\n([\\s\\S]*?)\\r?\\n```[ \\t]*$", "gm");
115
+ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
116
+ const STATUSES = new Set([
117
+ "settled",
118
+ "mandatory_incompatibility",
119
+ "not_applicable",
120
+ "disabled",
121
+ ]);
122
+ const RESOLUTIONS = new Set([
123
+ "accepted",
124
+ "adapted",
125
+ "rejected",
126
+ "alternative",
127
+ "unresolved",
128
+ ]);
129
+ function isStringArray(value) {
130
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
131
+ }
132
+ function validateFinding(raw, index, errors) {
133
+ const where = `findings[${index}]`;
134
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
135
+ errors.push(`${where} must be an object`);
136
+ return null;
137
+ }
138
+ const f = raw;
139
+ if (typeof f.id !== "string" || !f.id.trim())
140
+ errors.push(`${where}.id must be a non-empty string`);
141
+ if (!isStringArray(f.source_ids))
142
+ errors.push(`${where}.source_ids must be a string array`);
143
+ if (typeof f.resolution !== "string" || !RESOLUTIONS.has(f.resolution)) {
144
+ errors.push(`${where}.resolution is not a recognized value`);
145
+ }
146
+ if (f.status !== "settled" && f.status !== "mandatory_incompatibility") {
147
+ errors.push(`${where}.status must be settled or mandatory_incompatibility`);
148
+ }
149
+ const cited = Array.isArray(f.cited_sources) ? f.cited_sources : null;
150
+ if (!cited) {
151
+ errors.push(`${where}.cited_sources must be an array`);
152
+ }
153
+ else {
154
+ cited.forEach((c, i) => {
155
+ const s = c;
156
+ if (!s ||
157
+ typeof s.ticket_key !== "string" ||
158
+ !isValidTicketKey(s.ticket_key) ||
159
+ typeof s.content_sha256 !== "string" ||
160
+ !SHA256_PATTERN.test(s.content_sha256)) {
161
+ errors.push(`${where}.cited_sources[${i}] needs a ticket_key and a 64-hex content_sha256`);
162
+ }
163
+ });
164
+ }
165
+ if (f.status === "mandatory_incompatibility") {
166
+ if (f.resolution !== "unresolved") {
167
+ errors.push(`${where} is a mandatory incompatibility, so its resolution must be unresolved`);
168
+ }
169
+ if (!isStringArray(f.conflicting_obligations) || f.conflicting_obligations.length < 2) {
170
+ errors.push(`${where}.conflicting_obligations must cite at least two obligations`);
171
+ }
172
+ if (!isStringArray(f.attempted_alternatives) || f.attempted_alternatives.length < 1) {
173
+ errors.push(`${where}.attempted_alternatives must list what was tried`);
174
+ }
175
+ if (typeof f.recommended_resolution !== "string" || !f.recommended_resolution.trim()) {
176
+ errors.push(`${where}.recommended_resolution must name the recommended decision`);
177
+ }
178
+ if (cited && cited.length < 1) {
179
+ errors.push(`${where}.cited_sources must cite the conflicting contracts`);
180
+ }
181
+ }
182
+ else if (f.resolution === "unresolved") {
183
+ errors.push(`${where} is settled, so its resolution cannot be unresolved`);
184
+ }
185
+ return errors.length > 0 ? null : f;
186
+ }
187
+ /**
188
+ * Validate a decoded structured result. Returns the typed result or the list of
189
+ * problems found; never throws.
190
+ */
191
+ export function validateEpicResolution(raw) {
192
+ const errors = [];
193
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
194
+ return { found: true, ok: false, errors: ["the block must be a JSON object"] };
195
+ }
196
+ const r = raw;
197
+ if (r.version !== EPIC_RESOLUTION_SCHEMA_VERSION) {
198
+ errors.push(`version must be ${EPIC_RESOLUTION_SCHEMA_VERSION}`);
199
+ }
200
+ if (typeof r.subject_key !== "string" || !isValidTicketKey(r.subject_key)) {
201
+ errors.push("subject_key must be a ticket key");
202
+ }
203
+ if (r.generation !== null && !(Number.isInteger(r.generation) && r.generation > 0)) {
204
+ errors.push("generation must be a positive integer or null");
205
+ }
206
+ if (r.source_bundle_sha256 !== null &&
207
+ !(typeof r.source_bundle_sha256 === "string" && SHA256_PATTERN.test(r.source_bundle_sha256))) {
208
+ errors.push("source_bundle_sha256 must be 64 lowercase hex or null");
209
+ }
210
+ const policy = r.policy;
211
+ if (!policy || typeof policy.enabled !== "boolean" || !Number.isInteger(policy.policy_version)) {
212
+ errors.push("policy must carry enabled and policy_version");
213
+ }
214
+ if (typeof r.status !== "string" || !STATUSES.has(r.status)) {
215
+ errors.push("status is not a recognized value");
216
+ }
217
+ const coverage = r.coverage;
218
+ if (!coverage || typeof coverage.complete !== "boolean" || !isStringArray(coverage.gaps)) {
219
+ errors.push("coverage must carry complete and a gaps string array");
220
+ }
221
+ const findings = [];
222
+ if (!Array.isArray(r.findings)) {
223
+ errors.push("findings must be an array");
224
+ }
225
+ else {
226
+ r.findings.forEach((raw, i) => {
227
+ const findingErrors = [];
228
+ const finding = validateFinding(raw, i, findingErrors);
229
+ errors.push(...findingErrors);
230
+ if (finding)
231
+ findings.push(finding);
232
+ });
233
+ const ids = new Set();
234
+ for (const f of findings) {
235
+ if (ids.has(f.id))
236
+ errors.push(`finding id ${f.id} is duplicated`);
237
+ ids.add(f.id);
238
+ }
239
+ }
240
+ if (errors.length === 0) {
241
+ const anyConflict = findings.some((f) => f.status === "mandatory_incompatibility");
242
+ if (anyConflict && r.status !== "mandatory_incompatibility") {
243
+ errors.push("a finding is a mandatory incompatibility, so status must be mandatory_incompatibility");
244
+ }
245
+ if (!anyConflict && r.status === "mandatory_incompatibility") {
246
+ errors.push("status is mandatory_incompatibility but no finding records one");
247
+ }
248
+ }
249
+ if (errors.length > 0)
250
+ return { found: true, ok: false, errors };
251
+ return { found: true, ok: true, result: r };
252
+ }
253
+ /**
254
+ * Find and validate the structured result in a review-and-resolution document.
255
+ *
256
+ * `{found: false}` when the document has no block — every standalone review,
257
+ * and every review from before this feature. More than one block is refused:
258
+ * a capture must never have to choose between two records.
259
+ */
260
+ export function parseEpicResolutionBlock(markdown) {
261
+ const matches = [...markdown.matchAll(FENCE_PATTERN)];
262
+ if (matches.length === 0)
263
+ return { found: false };
264
+ if (matches.length > 1) {
265
+ return { found: true, ok: false, errors: ["the document has more than one resolution block"] };
266
+ }
267
+ let decoded;
268
+ try {
269
+ decoded = JSON.parse(matches[0][1]);
270
+ }
271
+ catch {
272
+ return { found: true, ok: false, errors: ["the resolution block is not valid JSON"] };
273
+ }
274
+ return validateEpicResolution(decoded);
275
+ }
276
+ /**
277
+ * Decide whether terminal decision capture may proceed for this document.
278
+ *
279
+ * Capture proceeds when the document has no block (unrelated callers are
280
+ * unaffected), or when its block is valid, belongs to this ticket and
281
+ * generation, and records no unresolved mandatory incompatibility.
282
+ */
283
+ export function evaluateEpicCaptureGate(markdown, ticketNumber, generation) {
284
+ if (markdown === null)
285
+ return { allowed: true };
286
+ const parsed = parseEpicResolutionBlock(markdown);
287
+ if (!parsed.found)
288
+ return { allowed: true };
289
+ if (!parsed.ok) {
290
+ return {
291
+ allowed: false,
292
+ reason: "epic_resolution_malformed",
293
+ message: "The epic-contract resolution block in the review-and-resolution document is not valid. " +
294
+ "Fix the block, then capture again.",
295
+ errors: parsed.errors,
296
+ };
297
+ }
298
+ const result = parsed.result;
299
+ if (result.subject_key.toUpperCase() !== ticketNumber.trim().toUpperCase()) {
300
+ return {
301
+ allowed: false,
302
+ reason: "epic_resolution_malformed",
303
+ message: "The epic-contract resolution block names a different ticket.",
304
+ };
305
+ }
306
+ if (result.generation !== null && result.generation !== generation) {
307
+ return {
308
+ allowed: false,
309
+ reason: "epic_resolution_generation_mismatch",
310
+ message: "The epic-contract resolution was recorded against a different review generation. " +
311
+ "Wait for the review again and re-adjudicate against the current documents.",
312
+ };
313
+ }
314
+ const blocked = result.findings.filter((f) => f.status === "mandatory_incompatibility");
315
+ if (blocked.length > 0) {
316
+ return {
317
+ allowed: false,
318
+ reason: "epic_contract_incompatibility_unresolved",
319
+ message: "A finding is recorded as an unresolved mandatory incompatibility between epic contracts. " +
320
+ "Present the conflicting obligations and the recommended resolution; capture after an " +
321
+ "explicit resolving decision is recorded in the block.",
322
+ finding_ids: blocked.map((f) => f.id),
323
+ };
324
+ }
325
+ return { allowed: true };
326
+ }