@bridge_gpt/mcp-server 0.2.72 → 0.2.73

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 (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -11,7 +11,14 @@
11
11
  * A folder holding a regular DAG but no regular metadata is reported as a skipped
12
12
  * `missing-meta` entry so the operator can see it. It is only reported: the DAG
13
13
  * supplies no identity, so such a folder is never a candidate and never changes
14
- * the result.
14
+ * the result. Plan generation reads that DAG only to judge whether it could be
15
+ * this epic's half-written plan ({@link unrelatedMissingMetaPaths}).
16
+ *
17
+ * BAPI-1621: a dot-prefixed folder is never a candidate. Generation stages a plan
18
+ * in `.staging-<random>/` and publishes it by renaming the folder, so an unfinished
19
+ * (or crash-abandoned) staging folder is reported as `staging-folder` and never
20
+ * counted, even when it already holds both files. A found plan whose metadata says
21
+ * `generated_by: "drive-epic"` carries that provenance and its validated summary.
15
22
  *
16
23
  * Every filesystem read goes through the injected {@link PlanDiscoveryFs}, so a
17
24
  * unit test reaches no real disk. Nothing here throws for a filesystem failure:
@@ -20,15 +27,18 @@
20
27
  */
21
28
  import path from "node:path";
22
29
  import { EPIC_KEY_PATTERN } from "./drive-epic-key.js";
30
+ import { PLAN_GENERATED_BY, parseGeneratedPlanSummary } from "./plan-generation.js";
23
31
  /** Why a metadata file was named but not counted. Fixed vocabulary, never raw text. */
24
32
  export const PLAN_DISCOVERY_SKIP_REASONS = [
25
33
  "unreadable",
26
34
  "malformed-json",
27
35
  "not-an-object",
28
36
  "missing-or-non-string-epic-key",
37
+ "invalid-epic-key",
29
38
  "missing-dag",
30
39
  "missing-meta",
31
40
  "unlistable-directory",
41
+ "staging-folder",
32
42
  ];
33
43
  const META_FILE = "epic-plan.meta.json";
34
44
  const DAG_FILE = "epic-plan.dag.json";
@@ -57,6 +67,7 @@ export async function discoverEpicPlan(epicKey, docsDir, fs) {
57
67
  return notFound();
58
68
  const skipped = [];
59
69
  const candidates = [];
70
+ const generatedByCandidate = new Map();
60
71
  let planDirs;
61
72
  try {
62
73
  planDirs = await fs.readdir(epicPlansDir);
@@ -72,6 +83,11 @@ export async function discoverEpicPlan(epicKey, docsDir, fs) {
72
83
  if (planDir.isSymbolicLink?.() === true || !planDir.isDirectory())
73
84
  continue;
74
85
  const dirPath = path.join(epicPlansDir, planDir.name);
86
+ // BAPI-1621 — a staging folder is named, never read and never counted.
87
+ if (planDir.name.startsWith(".")) {
88
+ skipped.push({ path: dirPath, reason: "staging-folder" });
89
+ continue;
90
+ }
75
91
  let files;
76
92
  try {
77
93
  files = await fs.readdir(dirPath);
@@ -119,23 +135,39 @@ export async function discoverEpicPlan(epicKey, docsDir, fs) {
119
135
  continue;
120
136
  }
121
137
  // Exact comparison, and both sides must satisfy the shared pattern. Metadata
122
- // naming a key the CLI would reject is never a match.
123
- if (!EPIC_KEY_PATTERN.test(key) || key !== epicKey)
138
+ // naming a key the CLI would reject is never a match, and it is named so its
139
+ // presence is never read as a reliable absence (BAPI-1621).
140
+ if (!EPIC_KEY_PATTERN.test(key)) {
141
+ skipped.push({ path: metaPath, reason: "invalid-epic-key" });
142
+ continue;
143
+ }
144
+ if (key !== epicKey)
124
145
  continue;
125
146
  const dag = files.find((entry) => entry.name === DAG_FILE && isRegular(entry));
126
147
  if (dag === undefined) {
127
148
  skipped.push({ path: metaPath, reason: "missing-dag" });
128
149
  continue;
129
150
  }
130
- candidates.push(path.join(dirPath, DAG_FILE));
151
+ const dagPath = path.join(dirPath, DAG_FILE);
152
+ candidates.push(dagPath);
153
+ // Provenance comes from the metadata object already parsed above: no second read.
154
+ if (parsed.generated_by === PLAN_GENERATED_BY) {
155
+ const version = parsed.generator_version;
156
+ generatedByCandidate.set(dagPath, {
157
+ generator_version: typeof version === "number" && Number.isSafeInteger(version) ? version : null,
158
+ summary: parseGeneratedPlanSummary(parsed.summary),
159
+ });
160
+ }
131
161
  }
132
162
  candidates.sort();
133
163
  if (candidates.length === 1) {
164
+ const generated = generatedByCandidate.get(candidates[0]);
134
165
  return {
135
166
  status: "found",
136
167
  path: candidates[0],
137
168
  epic_plans_dir: epicPlansDir,
138
169
  skipped: [...skipped].sort(byPath),
170
+ ...(generated !== undefined ? { generated } : {}),
139
171
  };
140
172
  }
141
173
  if (candidates.length >= 2) {
@@ -148,3 +180,64 @@ export async function discoverEpicPlan(epicKey, docsDir, fs) {
148
180
  }
149
181
  return notFound(skipped);
150
182
  }
183
+ /**
184
+ * BAPI-1621 — whether a discovery result permits generating a plan.
185
+ *
186
+ * Only `plan_not_found` qualifies, and only when every skipped entry is a staging
187
+ * folder. Any other skipped entry (an unreadable folder, malformed or keyless
188
+ * metadata, a DAG with no metadata) might be this epic's real plan, so it blocks
189
+ * generation and keeps today's stop, which names those paths.
190
+ *
191
+ * `unrelatedMissingMeta` names `missing-meta` entries already shown to belong to
192
+ * other epics (see {@link unrelatedMissingMetaPaths}); only those are ignored.
193
+ * Without it, every `missing-meta` entry blocks.
194
+ */
195
+ export function isPlanGenerationEligible(result, unrelatedMissingMeta = new Set()) {
196
+ return (result.status === "plan_not_found" &&
197
+ result.skipped.every((entry) => entry.reason === "staging-folder" || (entry.reason === "missing-meta" && unrelatedMissingMeta.has(entry.path))));
198
+ }
199
+ /**
200
+ * The paths of `missing-meta` entries whose DAG belongs to some other epic.
201
+ *
202
+ * A DAG with no metadata may be `/plan-epic` still writing this epic's plan, so it
203
+ * must block generation. It is unrelated only when it reads and parses, every node
204
+ * carries a string `ticket_key`, and none of those keys is in `relatedKeys` (the
205
+ * epic key and every known child key). An unreadable or malformed DAG is never
206
+ * unrelated: when unsure, it blocks. Reads go through the same injected
207
+ * {@link PlanDiscoveryFs}; nothing here throws.
208
+ */
209
+ export async function unrelatedMissingMetaPaths(result, relatedKeys, fs) {
210
+ const related = new Set(relatedKeys);
211
+ const unrelated = new Set();
212
+ for (const entry of result.skipped) {
213
+ if (entry.reason !== "missing-meta")
214
+ continue;
215
+ const keys = await readDagTicketKeys(path.join(path.dirname(entry.path), DAG_FILE), fs);
216
+ if (keys !== null && !keys.some((key) => related.has(key)))
217
+ unrelated.add(entry.path);
218
+ }
219
+ return unrelated;
220
+ }
221
+ /** Every node's `ticket_key`, or null when the DAG cannot be read or is malformed. */
222
+ async function readDagTicketKeys(dagPath, fs) {
223
+ let parsed;
224
+ try {
225
+ parsed = JSON.parse(await fs.readFile(dagPath));
226
+ }
227
+ catch {
228
+ return null;
229
+ }
230
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
231
+ return null;
232
+ const nodes = parsed.nodes;
233
+ if (!Array.isArray(nodes))
234
+ return null;
235
+ const keys = [];
236
+ for (const node of nodes) {
237
+ const key = node !== null && typeof node === "object" ? node.ticket_key : undefined;
238
+ if (typeof key !== "string")
239
+ return null;
240
+ keys.push(key);
241
+ }
242
+ return keys;
243
+ }
@@ -19,7 +19,8 @@
19
19
  * ownership registry it fails on the review and rendered-UI classes — that failing
20
20
  * assertion is the regression test for Miss 20.
21
21
  * - **Every owned step gets a terminal disposition.** {@link validatePhaseResult}
22
- * rejects a phase result that leaves an owned step unsettled. There is no
22
+ * rejects a phase result that leaves an owned step unsettled (a partial
23
+ * `pre_pr_verification` envelope is forwarded and the server decides, BAPI-1584). There is no
23
24
  * "skipped": a step is executed, mechanically adapted, escalated, or declared
24
25
  * advisory in the plan itself.
25
26
  * - **The record is durable and monotonic.** {@link mergePlanStepRecords} keeps
@@ -122,7 +123,32 @@ export const HANDOFF_CAUSES = [
122
123
  "credential_unavailable",
123
124
  "mcp_unavailable",
124
125
  "preexisting_at_base",
126
+ "not_applicable",
125
127
  ];
128
+ /**
129
+ * BAPI-1609: the step has genuinely nothing to verify for this ticket (never
130
+ * unfinished implementation). Accepted on every pre-PR class, the review classes
131
+ * included, and the only cause that may carry the optional `rule_hint` and
132
+ * `target_path`. A missing, blank, or unknown hint is accepted. It is never an
133
+ * admitted hand-off: the server keeps it an unresolved escalation, carries it in
134
+ * an authorized Epic Implementer run, and labels the claim separately. Mirrors
135
+ * `HANDOFF_CAUSE_NOT_APPLICABLE` and its neighbours in
136
+ * `api/library/vcs/ticket_delivery_identity.py`, with identical wording.
137
+ */
138
+ export const HANDOFF_CAUSE_NOT_APPLICABLE = "not_applicable";
139
+ export const NOT_APPLICABLE_HANDOFF_CLASSES = [
140
+ "unit_tests",
141
+ "e2e_tests",
142
+ "rendered_ui_review",
143
+ "test_gap_review",
144
+ "final_plan_review",
145
+ "combined_review_test",
146
+ ];
147
+ export const NOT_APPLICABLE_OPTIONAL_KEYS = ["rule_hint", "target_path"];
148
+ export const NOT_APPLICABLE_RULE_HINTS = ["no_rendered_surface", "target_absent", "zero_tests"];
149
+ export const MAX_NOT_APPLICABLE_HINT_CHARS = 64;
150
+ export const MAX_NOT_APPLICABLE_TARGET_PATH_CHARS = 1000;
151
+ export const NOT_APPLICABLE_OPTIONAL_TYPE_MESSAGE = "handoff not_applicable rule_hint and target_path must be strings when present";
126
152
  /**
127
153
  * BAPI-1552: the one cause that is not a missing capability. The step ran and
128
154
  * failed, and the same tests already fail at the base commit. Only this cause
@@ -180,6 +206,22 @@ export const ESCALATION_ONLY_CATEGORIES = [
180
206
  "dependencies",
181
207
  "security",
182
208
  ];
209
+ /**
210
+ * BAPI-1608: optional category an agent may attach to an escalated record. Advisory
211
+ * metadata only: the server stores it as authored and the client never rejects,
212
+ * coerces, or enforces it, so an unknown or non-string value is not an error. A
213
+ * value outside this list is presented as `other`. Mirrors `ESCALATION_CATEGORIES`
214
+ * in `api/library/vcs/ticket_delivery_identity.py`; both sides must agree.
215
+ */
216
+ export const ESCALATION_CATEGORIES = [
217
+ "needs_human_decision",
218
+ "needs_access_or_credential",
219
+ "needs_service_or_environment",
220
+ "ticket_contradictory",
221
+ "outside_ticket_scope",
222
+ "prerequisite_not_built",
223
+ "other",
224
+ ];
183
225
  /**
184
226
  * Which phase must settle each class of step.
185
227
  *
@@ -554,6 +596,9 @@ function validateRecordShape(record, metadata, phase) {
554
596
  if (!PLAN_STEP_DISPOSITIONS.includes(record.disposition)) {
555
597
  throw new PlanLedgerError(`step ${record.stepId} has unsupported disposition '${String(record.disposition)}'; expected one of ${PLAN_STEP_DISPOSITIONS.join(", ")}`);
556
598
  }
599
+ // BAPI-1608: `escalationCategory` is deliberately not checked here. It is
600
+ // optional advisory metadata, so an unknown string or a non-string value never
601
+ // rejects an otherwise valid record.
557
602
  // BAPI-1552: mirrors the server, which refuses this cause on a non-escalated
558
603
  // record before any generic disposition check can hide the closed code.
559
604
  const handoffValue = record.handoff;
@@ -658,15 +703,27 @@ export function validateHandoff(record, metadata, phase) {
658
703
  validatePreexistingHandoff(record, metadata, phase);
659
704
  return;
660
705
  }
661
- const keys = isObject ? Object.keys(value).sort() : [];
662
- const expected = [...HANDOFF_FIELDS].sort();
663
- if (!isObject || keys.length !== expected.length || keys.some((k, i) => k !== expected[i])) {
706
+ // BAPI-1609: only not_applicable may add the optional rule_hint and target_path.
707
+ const notApplicable = isObject && value.cause === HANDOFF_CAUSE_NOT_APPLICABLE;
708
+ const keys = isObject ? Object.keys(value) : [];
709
+ const required = new Set(HANDOFF_FIELDS);
710
+ const allowed = new Set([
711
+ ...HANDOFF_FIELDS,
712
+ ...(notApplicable ? NOT_APPLICABLE_OPTIONAL_KEYS : []),
713
+ ]);
714
+ if (!isObject ||
715
+ keys.some((k) => !allowed.has(k)) ||
716
+ [...required].some((k) => !keys.includes(k))) {
664
717
  fail(`handoff must be an object with exactly ${HANDOFF_FIELDS.join(", ")}`);
665
718
  }
666
719
  const handoff = value;
667
720
  if (!HANDOFF_CAUSES.includes(handoff.cause)) {
668
721
  fail(`handoff cause must be one of ${HANDOFF_CAUSES.join(", ")}`);
669
722
  }
723
+ if (notApplicable &&
724
+ NOT_APPLICABLE_OPTIONAL_KEYS.some((k) => k in handoff && typeof handoff[k] !== "string")) {
725
+ fail(NOT_APPLICABLE_OPTIONAL_TYPE_MESSAGE);
726
+ }
670
727
  for (const field of HANDOFF_TEXT_FIELDS) {
671
728
  const text = handoff[field];
672
729
  if (typeof text !== "string" || text.trim() === "") {
@@ -686,7 +743,10 @@ export function validateHandoff(record, metadata, phase) {
686
743
  PLAN_CLASS_OWNERSHIP[owningPart.provenance_class] !== "pre_pr_verification") {
687
744
  fail("handoff is accepted only on a pre_pr_verification record");
688
745
  }
689
- if (!HANDOFF_ELIGIBLE_CLASSES.includes(owningPart.provenance_class)) {
746
+ const eligibleClasses = notApplicable
747
+ ? NOT_APPLICABLE_HANDOFF_CLASSES
748
+ : HANDOFF_ELIGIBLE_CLASSES;
749
+ if (!eligibleClasses.includes(owningPart.provenance_class)) {
690
750
  fail("handoff is accepted only for unit_tests, e2e_tests, or rendered_ui_review steps; review steps always run");
691
751
  }
692
752
  if (record.prDependency !== undefined) {
@@ -789,6 +849,22 @@ function normalizeHandoff(handoff) {
789
849
  observed_head_sha: handoff.observed_head_sha.trim().toLowerCase(),
790
850
  next_action: bound(handoff.next_action),
791
851
  };
852
+ // BAPI-1609: carry a non-blank hint and path through, stripped and bounded the
853
+ // way the server stores them; a blank one is dropped.
854
+ const optional = (text, limit) => {
855
+ if (typeof text !== "string")
856
+ return undefined;
857
+ const trimmed = text.trim().slice(0, limit).trim();
858
+ return trimmed === "" ? undefined : trimmed;
859
+ };
860
+ if (handoff.cause === HANDOFF_CAUSE_NOT_APPLICABLE) {
861
+ const hint = optional(handoff.rule_hint, MAX_NOT_APPLICABLE_HINT_CHARS);
862
+ const path = optional(handoff.target_path, MAX_NOT_APPLICABLE_TARGET_PATH_CHARS);
863
+ if (hint !== undefined)
864
+ normalized.rule_hint = hint;
865
+ if (path !== undefined)
866
+ normalized.target_path = path;
867
+ }
792
868
  // BAPI-1552: carry the proof through explicitly, or the local ledger drops it.
793
869
  const proof = handoff.base_reproduction;
794
870
  if (proof !== undefined) {
@@ -806,7 +882,12 @@ function normalizeHandoff(handoff) {
806
882
  *
807
883
  * Every owned step must be settled exactly once. An omission is the historical bug
808
884
  * (work quietly not done), a duplicate makes the record ambiguous, and an unowned
809
- * step means the phase acted outside its routing.
885
+ * step means the phase acted outside its routing. The one exception is
886
+ * `pre_pr_verification` (BAPI-1584): an omitted step is allowed locally only when the
887
+ * accepted ledger already holds a pre-PR record for it; the server decides whether
888
+ * that record is current at this head and refuses with "leaves owned steps unsettled"
889
+ * if not.
890
+ * Unowned and duplicate steps are still refused here for every phase.
810
891
  *
811
892
  * For `post_pr_gap_close`, `accepted` is the server-accepted ledger as it stood
812
893
  * BEFORE this envelope, so an envelope cannot grant itself post-PR ownership.
@@ -836,7 +917,19 @@ export function validatePhaseResult(result, metadata, phase, accepted) {
836
917
  }
837
918
  settled.add(record.stepId);
838
919
  }
839
- const missing = [...owned].filter((step) => !settled.has(step)).sort((a, b) => a - b);
920
+ // BAPI-1584: a pre-PR envelope may omit a step only when the server-accepted
921
+ // ledger already holds a pre-PR record for it. The server still decides whether
922
+ // that record is current at this head; this client never reconstructs omitted
923
+ // evidence. A first-pass omission has no accepted record and is refused here, so
924
+ // paths where no server ever checks the envelope cannot skip a step silently.
925
+ const alreadyAccepted = new Set(phase === "pre_pr_verification"
926
+ ? (accepted?.acceptedRecords ?? [])
927
+ .filter((record) => record.phase === "pre_pr_verification")
928
+ .map((record) => record.step_id)
929
+ : []);
930
+ const missing = [...owned]
931
+ .filter((step) => !settled.has(step) && !alreadyAccepted.has(step))
932
+ .sort((a, b) => a - b);
840
933
  if (missing.length > 0) {
841
934
  throw new PlanLedgerError(`phase '${phase}' left owned steps unsettled: ${missing.join(", ")}. Every owned step must end as executed, adapted, escalated, or declared-advisory — there is no silent skip.`);
842
935
  }
@@ -0,0 +1,262 @@
1
+ /**
2
+ * BAPI-1621: the input collection and publication around the pure builder in
3
+ * `plan-generation.ts`.
4
+ *
5
+ * `drive-epic` calls into this module ONLY after discovery returned
6
+ * `plan_not_found` with no `--plan-file`, and only when no non-staging entry was
7
+ * skipped. A found, supplied, or ambiguous plan never reaches it, so a launch with
8
+ * a plan present makes none of these reads.
9
+ *
10
+ * Collection reads through the GENERAL Bridge resolver — the same path
11
+ * `prerequisite-inputs` uses since BAPI-1617 — because it runs before any local
12
+ * plane is up. It reads, in order: the epic's live run (only a successful "no
13
+ * run" answer continues), the epic's complete child list, the epic and child
14
+ * descriptions, and the tracked-file inventory (`git ls-files -z`, once, as a
15
+ * list-form subprocess with no shell and no ticket-derived argument). Every
16
+ * failure maps to one fixed reason from `PLAN_GENERATION_FAILURE_REASONS`; no raw
17
+ * error text, ticket text, or credential leaves this module.
18
+ *
19
+ * Publication (real launches only — a preview never calls it) stages the DAG and
20
+ * then the metadata in a random `.staging-…` folder beside the destination,
21
+ * validates the plan with the server's read-only validate lane, and publishes by
22
+ * ONE plain `rename` of the folder to `<epic-key-lowercase>-generated/`. The rename
23
+ * refuses an existing non-empty folder, which is how two concurrent launches end
24
+ * with one plan: the loser removes only its own staging folder and runs discovery
25
+ * again. A failure before the rename removes the staging folder; nothing after the
26
+ * rename is undone.
27
+ */
28
+ import { execFile } from "node:child_process";
29
+ import { randomBytes } from "node:crypto";
30
+ import { mkdir, readFile, rename, rm, unlink, writeFile, realpath } from "node:fs/promises";
31
+ import path from "node:path";
32
+ import { writeJsonAtomically } from "./conductor-bundle-artifacts.js";
33
+ import { GENERATED_PLAN_VERSION, PLAN_GENERATED_BY, PLAN_GENERATOR_VERSION, buildGeneratedEpicPlan, compareTicketKeys, } from "./plan-generation.js";
34
+ /**
35
+ * Collect the inputs, build the plan, and validate it with the server. Writes
36
+ * nothing. Only a successful "no live run" answer reaches the child list.
37
+ */
38
+ export async function attemptPlanGeneration(epicKey, deps) {
39
+ const failed = (reason) => ({ kind: "failed", reason });
40
+ let access;
41
+ try {
42
+ const resolved = await deps.resolveAccess();
43
+ if (!resolved.ok)
44
+ return failed("access_unavailable");
45
+ access = resolved.access;
46
+ }
47
+ catch {
48
+ return failed("access_unavailable");
49
+ }
50
+ let live;
51
+ try {
52
+ live = await deps.readLiveRun(access, epicKey);
53
+ }
54
+ catch {
55
+ live = "unknown";
56
+ }
57
+ if (live === "live" || live === "conflict")
58
+ return { kind: "not_attempted", liveRun: live };
59
+ if (live !== "none")
60
+ return failed("live_run_unknown");
61
+ let enumeration;
62
+ try {
63
+ enumeration = await deps.fetchChildren(access, epicKey);
64
+ }
65
+ catch {
66
+ return failed("children_unreadable");
67
+ }
68
+ if (!enumeration.enumeration_complete)
69
+ return failed("enumeration_incomplete");
70
+ let epicDescription;
71
+ try {
72
+ epicDescription = (await deps.fetchTicket(access, epicKey)).description ?? "";
73
+ }
74
+ catch {
75
+ return failed("description_unreadable");
76
+ }
77
+ // Descriptions are read one at a time, in key order, so the read count and
78
+ // order are deterministic. A failed read is never an empty description, but a
79
+ // blank ticket is. Only children the builder may plan are read: a done child
80
+ // or a spike contributes no text, so its body can never stop generation.
81
+ const childDescriptions = new Map();
82
+ const byKey = [...enumeration.children].sort((a, b) => compareTicketKeys(a.ticket_key, b.ticket_key));
83
+ for (const child of byKey) {
84
+ if (!mayBePlanned(child))
85
+ continue;
86
+ try {
87
+ childDescriptions.set(child.ticket_key, (await deps.fetchTicket(access, child.ticket_key)).description ?? "");
88
+ }
89
+ catch {
90
+ return failed("description_unreadable");
91
+ }
92
+ }
93
+ let trackedFiles;
94
+ try {
95
+ trackedFiles = await deps.listTrackedFiles();
96
+ }
97
+ catch {
98
+ trackedFiles = null;
99
+ }
100
+ if (trackedFiles === null)
101
+ return failed("inventory_unavailable");
102
+ const built = buildGeneratedEpicPlan({
103
+ epicKey,
104
+ enumerationComplete: enumeration.enumeration_complete,
105
+ children: enumeration.children,
106
+ epicDescription,
107
+ childDescriptions,
108
+ trackedFiles,
109
+ });
110
+ if (!built.ok)
111
+ return failed(built.reason);
112
+ const verdict = await validateGeneratedPlan(access, epicKey, built.dag, deps.validatePlan);
113
+ if (verdict !== "valid")
114
+ return failed(verdict);
115
+ return { kind: "generated", dag: built.dag, summary: built.summary, access };
116
+ }
117
+ /**
118
+ * Whether the builder could make this child a `planned` node. Mirrors the
119
+ * builder's classification (done first, then spikes) so only those descriptions
120
+ * are read. Malformed metadata still counts as "may be planned": the builder
121
+ * rejects it with `invalid_child_metadata` either way.
122
+ */
123
+ function mayBePlanned(child) {
124
+ if (child.status_category === "done")
125
+ return false;
126
+ return (child.issue_type ?? "").trim().toLowerCase() !== "spike";
127
+ }
128
+ /** The server's read-only validate lane, reduced to a fixed verdict. */
129
+ export async function validateGeneratedPlan(access, epicKey, dag, validatePlan) {
130
+ try {
131
+ const result = await validatePlan(access, {
132
+ planVersion: GENERATED_PLAN_VERSION,
133
+ planBlob: dag,
134
+ epicKey,
135
+ });
136
+ return result.valid ? "valid" : "validation_rejected";
137
+ }
138
+ catch {
139
+ // Unreachable, an older server (404), or a malformed answer: never "valid".
140
+ return "validation_unavailable";
141
+ }
142
+ }
143
+ // ---------------------------------------------------------------------------
144
+ // Tracked-file inventory
145
+ // ---------------------------------------------------------------------------
146
+ const GIT_TIMEOUT_MS = 15_000;
147
+ const GIT_MAX_BUFFER = 64 * 1024 * 1024;
148
+ function runGit(args, cwd) {
149
+ return new Promise((resolve) => {
150
+ // List form, no shell: the arguments are fixed literals, never ticket text.
151
+ execFile("git", [...args], { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER, encoding: "utf8" }, (err, stdout) => {
152
+ resolve(err ? null : stdout);
153
+ });
154
+ });
155
+ }
156
+ /** `git ls-files -z` at the repository root that holds `cwd`; null on any failure. */
157
+ export async function listTrackedFilesWithGit(cwd) {
158
+ const top = await runGit(["rev-parse", "--show-toplevel"], cwd);
159
+ const root = top?.trim();
160
+ if (!root || !path.isAbsolute(root))
161
+ return null;
162
+ const listed = await runGit(["ls-files", "-z"], root);
163
+ if (listed === null)
164
+ return null;
165
+ return listed.split("\0").filter((entry) => entry !== "");
166
+ }
167
+ export function createDefaultPlanPublicationFs() {
168
+ return {
169
+ readFile: (filePath) => readFile(filePath, "utf8"),
170
+ writeFile: (filePath, data) => writeFile(filePath, data, "utf8"),
171
+ rename: (from, to) => rename(from, to),
172
+ unlink: (filePath) => unlink(filePath),
173
+ realpath: (filePath) => realpath(filePath),
174
+ mkdir: (dirPath, options) => mkdir(dirPath, options),
175
+ removeTree: (dirPath) => rm(dirPath, { recursive: true, force: true }),
176
+ };
177
+ }
178
+ /** The one folder a generated plan for `epicKey` is published to. */
179
+ export function generatedPlanFolder(docsDir, epicKey) {
180
+ return path.join(path.resolve(docsDir, "epic-plans"), `${epicKey.toLowerCase()}-generated`);
181
+ }
182
+ /** The metadata a generated plan carries beside its DAG. */
183
+ export function generatedPlanMetadata(epicKey, summary) {
184
+ return {
185
+ epic_key: epicKey,
186
+ generated_by: PLAN_GENERATED_BY,
187
+ generator_version: PLAN_GENERATOR_VERSION,
188
+ summary,
189
+ };
190
+ }
191
+ const COLLISION_CODES = new Set(["EEXIST", "ENOTEMPTY", "EPERM"]);
192
+ function errorCode(err) {
193
+ const code = err?.code;
194
+ return typeof code === "string" ? code : undefined;
195
+ }
196
+ /** Stage, validate, and publish one generated plan by a single folder rename. */
197
+ export async function publishGeneratedPlan(input) {
198
+ const { fs } = input;
199
+ const plansDir = path.resolve(input.docsDir, "epic-plans");
200
+ const finalDir = generatedPlanFolder(input.docsDir, input.epicKey);
201
+ const suffix = input.randomSuffix?.() ?? randomBytes(8).toString("hex");
202
+ const stagingDir = path.join(plansDir, `.staging-${suffix}`);
203
+ const cleanup = async () => {
204
+ try {
205
+ await fs.removeTree(stagingDir);
206
+ }
207
+ catch {
208
+ // Best effort: discovery never counts a dot-folder, so a leftover is inert.
209
+ }
210
+ };
211
+ try {
212
+ await fs.mkdir(plansDir, { recursive: true });
213
+ // Not recursive: the staging folder must be new and ours alone.
214
+ await fs.mkdir(stagingDir, { recursive: false });
215
+ }
216
+ catch {
217
+ return { kind: "failed", reason: "publish_failed" };
218
+ }
219
+ // DAG first, metadata last: a folder with no metadata is never a candidate.
220
+ const dagWrite = await writeJsonAtomically(path.join(stagingDir, "epic-plan.dag.json"), input.dag, fs);
221
+ const metaWrite = dagWrite.ok
222
+ ? await writeJsonAtomically(path.join(stagingDir, "epic-plan.meta.json"), generatedPlanMetadata(input.epicKey, input.summary), fs)
223
+ : dagWrite;
224
+ if (!metaWrite.ok) {
225
+ await cleanup();
226
+ return { kind: "failed", reason: "publish_failed" };
227
+ }
228
+ let verdict;
229
+ try {
230
+ verdict = await input.validate();
231
+ }
232
+ catch {
233
+ verdict = "validation_unavailable";
234
+ }
235
+ if (verdict !== "valid") {
236
+ await cleanup();
237
+ return { kind: "failed", reason: verdict };
238
+ }
239
+ try {
240
+ // No destination precheck: the rename itself is the exclusive claim.
241
+ await fs.rename(stagingDir, finalDir);
242
+ }
243
+ catch (err) {
244
+ await cleanup();
245
+ if (!COLLISION_CODES.has(errorCode(err) ?? ""))
246
+ return { kind: "failed", reason: "publish_failed" };
247
+ let discovery;
248
+ try {
249
+ discovery = await input.rediscover();
250
+ }
251
+ catch {
252
+ return { kind: "failed", reason: "collision_unresolved" };
253
+ }
254
+ // A winner's plan is found (use it) or ambiguous (today's stop). "Not found"
255
+ // after a collision means the destination holds something that is not a plan:
256
+ // stop rather than try a second name.
257
+ if (discovery.status === "plan_not_found")
258
+ return { kind: "failed", reason: "collision_unresolved" };
259
+ return { kind: "collision", discovery };
260
+ }
261
+ return { kind: "published", dagPath: path.join(finalDir, "epic-plan.dag.json") };
262
+ }