@bridge_gpt/mcp-server 0.2.71 → 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 (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Reassurance during long setup work (BAPI-1604). A notice is printed on stderr
3
+ * every few seconds while an operation runs, so a quiet terminal is not mistaken
4
+ * for a hang. It is never a timeout, a retry, or a readiness condition: the
5
+ * operation's value or exception passes through untouched, and the notice stops
6
+ * on every completion path.
7
+ */
8
+ export const SETUP_PROGRESS_INTERVAL_MS = 10_000;
9
+ /** The real timer. The interval is unreferenced so it never holds the process open. */
10
+ export function createSetupProgressTimer() {
11
+ return {
12
+ now: () => Number(process.hrtime.bigint() / 1000000n),
13
+ start: (tick, intervalMs) => {
14
+ const handle = setInterval(tick, intervalMs);
15
+ handle.unref();
16
+ return () => clearInterval(handle);
17
+ },
18
+ };
19
+ }
20
+ /** `activity` is a fixed label such as `checking readiness`; it is never user data. */
21
+ export async function withSetupProgress(activity, operation, deps) {
22
+ const timer = deps.timer ?? createSetupProgressTimer();
23
+ const startedAt = timer.now();
24
+ let cancel;
25
+ try {
26
+ cancel = timer.start(() => {
27
+ const seconds = Math.round((timer.now() - startedAt) / 1000);
28
+ deps.errorLog(`Still ${activity} (${seconds} s)…`);
29
+ }, timer.intervalMs ?? SETUP_PROGRESS_INTERVAL_MS);
30
+ }
31
+ catch {
32
+ // A timer that cannot start must not change the operation.
33
+ cancel = undefined;
34
+ }
35
+ try {
36
+ return await operation();
37
+ }
38
+ finally {
39
+ try {
40
+ cancel?.();
41
+ }
42
+ catch { /* cancellation failure never masks the outcome */ }
43
+ }
44
+ }
@@ -0,0 +1,180 @@
1
+ /** Everything except the leading question line, built structurally. */
2
+ function renderSetupQuestionBody(spec) {
3
+ return [`Current evidence:\n${spec.evidence.join("\n")}`,
4
+ `Options:\n${spec.options.map(o => `${o.id}: ${o.label}`).join("\n")}`,
5
+ `Consequences:\n${spec.consequences.join("\n")}`,
6
+ `Defer: ${spec.deferred}\nRecovery: ${spec.recovery}`].join("\n\n");
7
+ }
8
+ export function renderSetupQuestion(spec) {
9
+ return [spec.purpose, renderSetupQuestionBody(spec)].join("\n\n");
10
+ }
11
+ export function parseSetupDecision(input, options = []) {
12
+ const value = input?.trim().toLowerCase();
13
+ if (!value)
14
+ return { status: "defer" };
15
+ if (value === "y" || value === "yes")
16
+ return { status: "accept" };
17
+ if (value === "n" || value === "no")
18
+ return { status: "decline" };
19
+ const option = options.find(o => o.id.toLowerCase() === value);
20
+ return option ? { status: "selected", id: option.id } : { status: "invalid" };
21
+ }
22
+ export async function askSetupQuestion(spec, terminal) {
23
+ const question = spec.prompt ?? spec.purpose;
24
+ // The reader shows the question; print it here only when no reader will.
25
+ terminal.write?.(terminal.read ? renderSetupQuestionBody(spec) : [question, renderSetupQuestionBody(spec)].join("\n\n"));
26
+ if (!terminal.read)
27
+ return { status: "defer" };
28
+ try {
29
+ return parseSetupDecision(await terminal.read(question), spec.options);
30
+ }
31
+ catch {
32
+ return { status: "defer" };
33
+ }
34
+ }
35
+ export async function readCustomSetupCommand(terminal) {
36
+ if (!terminal.read)
37
+ return { status: "defer" };
38
+ let value;
39
+ try {
40
+ value = (await terminal.read("Enter the custom command (Enter defers): "))?.trim();
41
+ }
42
+ catch {
43
+ return { status: "defer" };
44
+ }
45
+ if (!value)
46
+ return { status: "defer" };
47
+ if (/^(y|yes|n|no)$/i.test(value))
48
+ return { status: "invalid" };
49
+ return { status: "custom", value };
50
+ }
51
+ /** Migration adapter for existing one-effect questions; secret reads stay separate. */
52
+ export function setupConsentQuestion(purpose) {
53
+ let consequence = "Only the operation named above is authorized; other setup permissions are unchanged.";
54
+ if (/token|credential/i.test(purpose))
55
+ consequence = "Credential identity affects which account may act. Secret entry uses a separate no-echo reader.";
56
+ else if (/service|executor|start|hook/i.test(purpose))
57
+ consequence = "This can install persistent automation or execute local commands with the executor's permissions.";
58
+ else if (/workflow|replace|overwrite|file/i.test(purpose))
59
+ consequence = "This can create or replace the named repository content; later CI may execute that content.";
60
+ else if (/gate|qualif|approval/i.test(purpose))
61
+ consequence = "This affects merge admission or executes the selected local gate commands. Existing required checks remain authoritative.";
62
+ else if (/url|destination|trust/i.test(purpose))
63
+ consequence = "Authenticated requests will be sent to this destination. Trust in another destination grants no permission here.";
64
+ return { purpose: purpose.replace(/\s*\[y\/n\]:?\s*$/i, "").trim(), prompt: purpose, evidence: ["Review the current state and operation details shown above. Unreadable state remains unresolved."],
65
+ options: [{ id: "yes", label: "Authorize this operation" }, { id: "no", label: "Defer this operation" }],
66
+ consequences: [consequence], deferred: "Only this operation is deferred; completed independent work is retained.",
67
+ recovery: "Rerun setup interactively after resolving the affected prerequisite." };
68
+ }
69
+ export const PLAIN_SETUP_INSTRUCTION = "Press Enter for the recommended option. Type ? for details.";
70
+ /** Invalid answers allowed after the first before the recommendation is used. */
71
+ export const PLAIN_SETUP_MAX_REASKS = 2;
72
+ /** A line ending pasted right behind an answer arrives within this window. */
73
+ export const PLAIN_SETUP_PASTE_TAIL_MS = 150;
74
+ /** Numbered options and the instruction, without the question line. */
75
+ function renderPlainSetupBody(spec) {
76
+ const lines = spec.options.map((o, i) => ` ${i + 1}. ${o.label}${o.id === spec.recommended ? " (recommended)" : ""}`);
77
+ return [...lines, ...(spec.summary ?? []), PLAIN_SETUP_INSTRUCTION].join("\n");
78
+ }
79
+ export function renderPlainSetupQuestion(spec) {
80
+ return [spec.question, renderPlainSetupBody(spec)].join("\n");
81
+ }
82
+ export function renderPlainSetupDetails(spec) {
83
+ return [`Current evidence:\n${spec.evidence.join("\n")}`,
84
+ ...(spec.consequences.length > 0 ? [`Consequences:\n${spec.consequences.join("\n")}`] : []),
85
+ `Recovery: ${spec.recovery}`].join("\n\n");
86
+ }
87
+ export function parsePlainSetupDecision(input, options) {
88
+ if (input === undefined)
89
+ return { status: "unavailable" };
90
+ const value = input.trim().toLowerCase();
91
+ if (!value)
92
+ return { status: "empty" };
93
+ if (value === "?")
94
+ return { status: "details" };
95
+ if (/^\d+$/.test(value)) {
96
+ const byNumber = options[Number(value) - 1];
97
+ return byNumber ? { status: "selected", id: byNumber.id } : { status: "invalid" };
98
+ }
99
+ const option = options.find(o => o.id.toLowerCase() === value
100
+ || (o.aliases ?? []).some(a => a.toLowerCase() === value));
101
+ return option ? { status: "selected", id: option.id } : { status: "invalid" };
102
+ }
103
+ /**
104
+ * Ask one plain question. Enter selects the recommendation; `?` shows details;
105
+ * an unavailable terminal defers (nothing is chosen) and prints the recording flag.
106
+ */
107
+ export async function askPlainSetupQuestion(spec, terminal) {
108
+ const deferUnavailable = () => {
109
+ terminal.write?.(`${spec.question}\nNo terminal is available, so nothing was chosen. To record this choice: ${spec.recordingFlag}`);
110
+ return { status: "defer" };
111
+ };
112
+ if (terminal.isTTY !== true || !terminal.read)
113
+ return deferUnavailable();
114
+ let invalid = 0;
115
+ for (;;) {
116
+ // The read prompt carries the question, so only the body is written.
117
+ terminal.write?.(renderPlainSetupBody(spec));
118
+ let parsed;
119
+ try {
120
+ parsed = parsePlainSetupDecision(await terminal.read(`${spec.question} `), spec.options);
121
+ }
122
+ catch {
123
+ return deferUnavailable();
124
+ }
125
+ if (parsed.status === "unavailable")
126
+ return deferUnavailable();
127
+ if (parsed.status === "empty")
128
+ return { status: "selected", id: spec.recommended };
129
+ if (parsed.status === "selected")
130
+ return parsed;
131
+ if (parsed.status === "details") {
132
+ terminal.write?.(renderPlainSetupDetails(spec));
133
+ continue;
134
+ }
135
+ invalid += 1;
136
+ if (invalid > PLAIN_SETUP_MAX_REASKS) {
137
+ terminal.write?.("That answer was not recognized, so the recommended option was used.");
138
+ return { status: "selected", id: spec.recommended };
139
+ }
140
+ }
141
+ }
142
+ /**
143
+ * Wrap one reader for one setup run. A pasted answer's trailing line ending can
144
+ * arrive as an immediate empty answer to the NEXT question; that one empty answer
145
+ * is dropped and the reader is asked again once. Non-empty input is never dropped,
146
+ * and only the previous answer's time and non-empty status are remembered.
147
+ */
148
+ export function createPlainInputSession(read, deps = {}) {
149
+ const now = deps.now ?? (() => Number(process.hrtime.bigint() / 1000000n));
150
+ const windowMs = deps.pasteTailMs ?? PLAIN_SETUP_PASTE_TAIL_MS;
151
+ let lastDoneAt;
152
+ let lastNonEmpty = false;
153
+ const finish = (answer) => {
154
+ lastDoneAt = now();
155
+ lastNonEmpty = (answer ?? "").trim().length > 0;
156
+ return answer;
157
+ };
158
+ return async (prompt) => {
159
+ let answer = await read(prompt);
160
+ if (answer !== undefined && answer.trim().length === 0 && lastNonEmpty
161
+ && lastDoneAt !== undefined && now() - lastDoneAt <= windowMs) {
162
+ answer = await read(prompt);
163
+ }
164
+ return finish(answer);
165
+ };
166
+ }
167
+ /** Plain consent for one operation. The safe default is `no` unless the caller says otherwise. */
168
+ export function plainConsentQuestion(purpose, recordingFlag, recommended = "no") {
169
+ const legacy = setupConsentQuestion(purpose);
170
+ return {
171
+ question: legacy.purpose,
172
+ options: [{ id: "yes", label: "Yes, do this", aliases: ["y"] }, { id: "no", label: "No, skip this", aliases: ["n"] }],
173
+ recommended, recordingFlag,
174
+ evidence: legacy.evidence, consequences: legacy.consequences, recovery: legacy.recovery,
175
+ };
176
+ }
177
+ export async function askPlainConsent(purpose, recordingFlag, terminal, recommended = "no") {
178
+ const decision = await askPlainSetupQuestion(plainConsentQuestion(purpose, recordingFlag, recommended), terminal);
179
+ return decision.status === "selected" && decision.id === "yes";
180
+ }
@@ -1262,6 +1262,10 @@ export { validateBranchName, fetchAndResolveBaseSha };
1262
1262
  * historical branch-name behavior unchanged.
1263
1263
  */
1264
1264
  export async function createWorktrees(deps, options, worktrunkBinary, baseStartPoint = options.baseBranch) {
1265
+ const { bridgeWorktreeCleanupAdvisory } = await import("./bridge-worktree-inspection.js");
1266
+ const cleanupAdvisory = await bridgeWorktreeCleanupAdvisory(deps.cwd);
1267
+ if (cleanupAdvisory)
1268
+ process.stderr.write(cleanupAdvisory + "\n");
1265
1269
  // BAPI-586: for guard-enabled Conductor fresh dispatch the caller has already
1266
1270
  // resolved `baseStartPoint` to an immutable base SHA (`nonMutatingBase`). Align
1267
1271
  // any safe pre-existing branch exactly to that SHA and verify the resulting
@@ -1,45 +1,12 @@
1
- /**
2
- * Read-only test-command detection (BAPI-1460).
3
- *
4
- * Proposes the one runnable command a repository's CI workflow should run. It
5
- * READS ONLY: the stored command, the learned `unit_testing_stack` prose, and a
6
- * handful of repository files. It never runs the command, never runs a package
7
- * manager, never imports Python, never evaluates a Make recipe, never prompts,
8
- * and never writes. Its dependency surface has no subprocess runner, no prompt
9
- * function, and no configuration writer, so it cannot.
10
- *
11
- * ## Order
12
- *
13
- * 1. A stored command (`GET /setup/testing-config`) wins, with no question.
14
- * 2. Otherwise repository files are scanned, in a fixed order: JavaScript
15
- * (`package.json` `scripts.test`, else a chain of the usable `lint`,
16
- * `typecheck`/`type-check`, and `build` scripts; the runner comes from the
17
- * shared lockfile resolver, `repository-toolchains.ts`), Make (a real
18
- * `test:` target), pytest (each listed marker), Go (`go.mod`), Rust
19
- * (`Cargo.toml`). An uninspectable repository is a `failed` result, never an
20
- * ordinary absence of scripts or lockfiles.
21
- * 3. When more than one stack is detected, the learned `unit_testing_stack`
22
- * prose picks among them through a fixed vocabulary. It is a hint and is
23
- * never interpreted as a command.
24
- * 4. No candidate means exactly one required question, with no default.
25
- *
26
- * ## Caller contract (the setup command)
27
- *
28
- * - `question: "none"` — use `selected` as is.
29
- * - `question: "accept_or_replace"` — ask once, offering `selected` as the
30
- * default and the other candidates as alternatives.
31
- * - `question: "required"` — ask once with no default. An empty answer is the
32
- * named cancellation outcome {@link TEST_COMMAND_DETECTION_CANCELLED}; nothing
33
- * is stored.
34
- * - Every chosen or typed command is validated with `validateTestCommand` and
35
- * saved through `PUT /setup/testing-config`. An invalid answer is explained
36
- * with the validation message and is never stored.
37
- *
38
- * A detected command is an UNVERIFIED proposal: passing the syntax rules does
39
- * not mean the command was run or that it works.
1
+ import { isTestScript } from "./package-script-semantics.js";
2
+ /** Read-only command evidence. Stored commands are preserved. Exactly one
3
+ * explicitly test-oriented command with an established runner and directory
4
+ * may be saved routinely. Multiple suites, conflicting runners and manifest
5
+ * hints require named selection. Unknown reads never mean no tests exist.
6
+ * Nothing here prompts, executes a command, installs dependencies or writes.
40
7
  */
41
8
  import { readOptionalRepositoryFile, RepositoryReadError, resolveRepositoryToolchains, } from "./repository-toolchains.js";
42
- import { readStoredTestCommand, readUnitTestingStack, } from "./testing-config-client.js";
9
+ import { readStoredTestCommand, } from "./testing-config-client.js";
43
10
  /** The stacks detection recognizes, in detection order. */
44
11
  export const DETECTED_STACKS = ["javascript", "make", "python", "go", "rust"];
45
12
  /** Named outcome for an empty answer to the required question. */
@@ -67,16 +34,10 @@ function selectJavaScriptRunner(resolution) {
67
34
  const js = resolution.toolchains.javascript;
68
35
  return js === null ? { manager: "npm", lockfile: null } : { manager: js.manager, lockfile: js.dependencyFile };
69
36
  }
70
- /** The scripts a fallback chain may run, in order. `typecheck` wins over `type-check`. */
71
- const FALLBACK_SCRIPT_GROUPS = [["lint"], ["typecheck", "type-check"], ["build"]];
72
- function isUsableScript(scripts, name) {
73
- const value = scripts[name];
74
- return typeof value === "string" && value.trim().length > 0;
75
- }
76
37
  async function detectJavaScript(deps, resolution) {
77
38
  const raw = await readOptional(deps, "package.json");
78
39
  if (raw === null)
79
- return null;
40
+ return [];
80
41
  let parsed;
81
42
  try {
82
43
  parsed = JSON.parse(raw);
@@ -89,31 +50,23 @@ async function detectJavaScript(deps, resolution) {
89
50
  }
90
51
  const scripts = parsed.scripts;
91
52
  if (!scripts || typeof scripts !== "object" || Array.isArray(scripts))
92
- return null;
53
+ return [];
93
54
  const table = scripts;
94
55
  const { manager, lockfile } = selectJavaScriptRunner(resolution);
95
56
  const source = lockfile === null ? "package.json" : `package.json + ${lockfile}`;
96
- if (isUsableScript(table, "test")) {
97
- // `bun test` is Bun's own runner, not the script, so Bun runs it explicitly.
98
- const command = manager === "bun" ? "bun run test" : `${manager} test`;
99
- return { stack: "javascript", command, provenance: source, verified: false };
100
- }
101
- // No test script: chain the checks the project defines. Only script NAMES
102
- // are used; script bodies are never read into a command.
103
- const chosen = [];
104
- for (const group of FALLBACK_SCRIPT_GROUPS) {
105
- const name = group.find((candidate) => isUsableScript(table, candidate));
106
- if (name !== undefined)
107
- chosen.push(name);
57
+ const lockManagers = new Set();
58
+ for (const [file, runner] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["package-lock.json", "npm"], ["npm-shrinkwrap.json", "npm"], ["bun.lock", "bun"], ["bun.lockb", "bun"]]) {
59
+ if (await readOptional(deps, file) !== null)
60
+ lockManagers.add(runner);
108
61
  }
109
- if (chosen.length === 0)
110
- return null;
111
- return {
62
+ const conflicting = lockManagers.size > 1;
63
+ return Object.entries(table).filter(([name, body]) => isTestScript(name, body)).map(([name]) => ({
112
64
  stack: "javascript",
113
- command: chosen.map((name) => `${manager} run ${name}`).join(" && "),
114
- provenance: `${lockfile === null ? "package.json" : source} scripts (${chosen.join(", ")})`,
115
- verified: false,
116
- };
65
+ command: name === "test" && manager !== "bun" ? `${manager} test` : `${manager} run ${name}`,
66
+ provenance: `${source} scripts.${name}${conflicting ? " (conflicting runner lockfiles)" : ""}`, verified: false,
67
+ runner: manager, workingDirectory: ".", scopeEvidence: `explicit test script: ${name}`,
68
+ autoSaveEligible: lockfile !== null && !conflicting,
69
+ }));
117
70
  }
118
71
  /**
119
72
  * Whether a Makefile declares a real `test` target: a rule line (not a recipe,
@@ -140,7 +93,7 @@ async function detectMake(deps) {
140
93
  continue;
141
94
  if (!makefileHasTestTarget(raw))
142
95
  return null;
143
- return { stack: "make", command: "make test", provenance: name, verified: false };
96
+ return { stack: "make", command: "make test", provenance: name, verified: false, runner: "make", workingDirectory: ".", scopeEvidence: "explicit test target", autoSaveEligible: true };
144
97
  }
145
98
  return null;
146
99
  }
@@ -164,12 +117,12 @@ async function detectPython(deps) {
164
117
  async function detectGo(deps) {
165
118
  if ((await readOptional(deps, "go.mod")) === null)
166
119
  return null;
167
- return { stack: "go", command: "go test ./...", provenance: "go.mod", verified: false };
120
+ return { stack: "go", command: "go test ./...", provenance: "go.mod (manifest hint only)", verified: false, autoSaveEligible: false };
168
121
  }
169
122
  async function detectRust(deps) {
170
123
  if ((await readOptional(deps, "Cargo.toml")) === null)
171
124
  return null;
172
- return { stack: "rust", command: "cargo test", provenance: "Cargo.toml", verified: false };
125
+ return { stack: "rust", command: "cargo test", provenance: "Cargo.toml (manifest hint only)", verified: false, autoSaveEligible: false };
173
126
  }
174
127
  /**
175
128
  * Words in the learned `unit_testing_stack` prose that name each stack. Matched
@@ -214,9 +167,8 @@ async function detectCandidates(deps) {
214
167
  const first = resolution.failures[0];
215
168
  throw new DetectionReadError(first.reason === "unreadable" ? "repository_read_failed" : "malformed_repository_file", first.file);
216
169
  }
217
- const found = [];
170
+ const found = await detectJavaScript(deps, resolution);
218
171
  const detectors = [
219
- () => detectJavaScript(deps, resolution),
220
172
  () => detectMake(deps),
221
173
  () => detectPython(deps),
222
174
  () => detectGo(deps),
@@ -225,7 +177,12 @@ async function detectCandidates(deps) {
225
177
  for (const detect of detectors) {
226
178
  const candidate = await detect();
227
179
  if (candidate)
228
- found.push(candidate);
180
+ found.push({ ...candidate,
181
+ runner: candidate.runner ?? (candidate.stack === "python" ? "pytest" : candidate.stack === "rust" ? "cargo" : candidate.stack),
182
+ workingDirectory: candidate.workingDirectory ?? ".",
183
+ scopeEvidence: candidate.scopeEvidence ?? "configuration/manifest hint; test scope unestablished",
184
+ autoSaveEligible: candidate.autoSaveEligible ?? false,
185
+ });
229
186
  }
230
187
  return found;
231
188
  }
@@ -257,7 +214,7 @@ export async function detectTestCommand(options, deps) {
257
214
  if (candidates.length === 0) {
258
215
  return { status: "none_detected", selected: null, question: "required", candidates };
259
216
  }
260
- if (candidates.length === 1) {
217
+ if (candidates.length === 1 && candidates[0].autoSaveEligible) {
261
218
  return {
262
219
  status: "detected",
263
220
  selected: candidates[0].command,
@@ -267,18 +224,5 @@ export async function detectTestCommand(options, deps) {
267
224
  candidates,
268
225
  };
269
226
  }
270
- // The learned stack is advisory: an unreadable hint falls back to the first
271
- // candidate rather than stopping detection.
272
- const stackHint = await readUnitTestingStack(deps.config);
273
- const named = stacksNamedByHint(stackHint.ok ? stackHint.value : null);
274
- const hinted = candidates.find((c) => named.has(c.stack));
275
- const chosen = hinted ?? candidates[0];
276
- return {
277
- status: "detected",
278
- selected: chosen.command,
279
- provenance: chosen.provenance,
280
- question: "accept_or_replace",
281
- selectedByStackHint: hinted !== undefined,
282
- candidates,
283
- };
227
+ return { status: "alternatives", selected: null, question: "required", candidates };
284
228
  }
@@ -0,0 +1,40 @@
1
+ /** Hermetic notes handles for orchestration fixtures; no ambient filesystem fallback. */
2
+ import { constants } from "node:fs";
3
+ import path from "node:path";
4
+ export function memoryNotesFs(cwd, files, read, write) {
5
+ const ids = new Map();
6
+ const absent = () => Object.assign(new Error("missing fixture file"), { code: "ENOENT" });
7
+ const identity = (p) => {
8
+ if (!ids.has(p))
9
+ ids.set(p, ids.size + 1);
10
+ return { dev: 1, ino: ids.get(p), isFile: () => true, isSymbolicLink: () => false };
11
+ };
12
+ return {
13
+ realpath: async (p) => { if (path.normalize(p) === path.normalize(cwd) || files.has(p))
14
+ return path.normalize(p); throw absent(); },
15
+ lstat: async (p) => { if (!files.has(p))
16
+ throw absent(); return identity(p); },
17
+ readBytes: async (p) => Buffer.from(await read(p)),
18
+ unlink: async (p) => { files.delete(p); },
19
+ open: async (p, flags) => {
20
+ if ((flags & constants.O_EXCL) && files.has(p))
21
+ throw Object.assign(new Error("exists"), { code: "EEXIST" });
22
+ if (!files.has(p)) {
23
+ if (!(flags & constants.O_CREAT))
24
+ throw absent();
25
+ files.set(p, "");
26
+ }
27
+ let content = Buffer.from(files.get(p));
28
+ return { stat: async () => identity(p), readFile: async () => Buffer.from(await read(p)),
29
+ write: async (buffer, offset, length, position) => {
30
+ const next = Buffer.alloc(Math.max(content.length, position + length));
31
+ content.copy(next);
32
+ buffer.copy(next, position, offset, offset + length);
33
+ await write(p, next.toString());
34
+ content = next;
35
+ return { bytesWritten: length };
36
+ }, truncate: async (length) => { content = content.subarray(0, length); files.set(p, content.toString()); },
37
+ sync: async () => { }, close: async () => { } };
38
+ },
39
+ };
40
+ }
@@ -51,6 +51,36 @@ export function validateThirdPartyTargetManifestEntry(entry) {
51
51
  }
52
52
  return { ok: true };
53
53
  }
54
+ /**
55
+ * BAPI-1545: validate a GRANTED entry for launch. Unlike the legacy manifest
56
+ * validator above, a bundle is OPTIONAL: an owner-approved secret-free server
57
+ * needs none. Granted entries bypass the closed registry for SUPPORT, but a
58
+ * granted name that matches a registry target still needs a bundle, because the
59
+ * registry's required keys must be resolved. Errors name only the field.
60
+ */
61
+ export function validateGrantedTargetEntry(entry) {
62
+ if (typeof entry.command !== "string" || entry.command.trim().length === 0) {
63
+ return { ok: false, error: `granted server '${entry.name}' requires a non-empty command` };
64
+ }
65
+ if (!Array.isArray(entry.args)) {
66
+ return { ok: false, error: `granted server '${entry.name}' requires an args array` };
67
+ }
68
+ const registry = getThirdPartyTargetDefinition(entry.name);
69
+ const needsBundle = (entry.secret_env_keys?.length ?? 0) > 0 || (registry?.requiredEnvKeys.length ?? 0) > 0;
70
+ if (needsBundle && (entry.secret_bundle === undefined || entry.secret_bundle.trim().length === 0)) {
71
+ return { ok: false, error: `granted server '${entry.name}' requires a secret_bundle` };
72
+ }
73
+ return { ok: true };
74
+ }
75
+ /**
76
+ * BAPI-1545: the keys a granted entry's bundle must supply — its own
77
+ * `secret_env_keys` plus, for a registry target such as `sfcc`, the registry's
78
+ * required keys. Sorted and deduplicated.
79
+ */
80
+ export function grantedEntryRequiredKeys(entry) {
81
+ const registry = getThirdPartyTargetDefinition(entry.name);
82
+ return [...new Set([...(entry.secret_env_keys ?? []), ...(registry?.requiredEnvKeys ?? [])])].sort();
83
+ }
54
84
  // ---------------------------------------------------------------------------
55
85
  // Atomic env resolution
56
86
  // ---------------------------------------------------------------------------
@@ -77,7 +77,9 @@ export async function ensureDeliveryBinding(deps, ticketKey) {
77
77
  remembered.repo_name === deps.repoName &&
78
78
  (sourceBranch === undefined || remembered.source_branch === sourceBranch)) {
79
79
  const confirmed = await confirmExecutorJob(deps, store, ticketKey, journal.registration_key, remembered);
80
- return { enrollment: "resumed", binding: confirmed, newlyRegistered: false };
80
+ return confirmed.replaced
81
+ ? { enrollment: "registered", binding: confirmed.binding, newlyRegistered: true }
82
+ : { enrollment: "resumed", binding: confirmed.binding, newlyRegistered: false };
81
83
  }
82
84
  if (!sourceBranch || sourceBranch === "HEAD") {
83
85
  return unavailable("the source branch could not be read (detached HEAD or git unavailable)");
@@ -92,7 +94,9 @@ export async function ensureDeliveryBinding(deps, ticketKey) {
92
94
  const binding = referenceFrom(recovered.body.binding);
93
95
  await store.recordBindingReference(deps.docsDir, ticketKey, binding);
94
96
  const confirmed = await confirmExecutorJob(deps, store, ticketKey, journal.registration_key, binding);
95
- return { enrollment: "recovered", binding: confirmed, newlyRegistered: false };
97
+ return confirmed.replaced
98
+ ? { enrollment: "registered", binding: confirmed.binding, newlyRegistered: true }
99
+ : { enrollment: "recovered", binding: confirmed.binding, newlyRegistered: false };
96
100
  }
97
101
  if (recovered.status !== 404) {
98
102
  return unavailable(`recovery failed (${recovered.error}): ${recovered.message}`);
@@ -162,8 +166,9 @@ function acknowledgedJobId(body, sent) {
162
166
  */
163
167
  async function confirmExecutorJob(deps, store, ticketKey, registrationKey, binding) {
164
168
  const jobId = deps.executorJobId;
165
- if (jobId === undefined || binding.confirmed_executor_job_id === jobId)
166
- return binding;
169
+ if (jobId === undefined || binding.confirmed_executor_job_id === jobId) {
170
+ return { binding, replaced: false };
171
+ }
167
172
  try {
168
173
  const response = await registerExecution(deps.client, {
169
174
  repo_name: binding.repo_name,
@@ -174,18 +179,33 @@ async function confirmExecutorJob(deps, store, ticketKey, registrationKey, bindi
174
179
  executor_job_id: jobId,
175
180
  });
176
181
  if (!response.ok)
177
- return binding;
182
+ return { binding, replaced: false };
178
183
  const confirmed = acknowledgedJobId(response.body, jobId);
184
+ // BAPI-1556 — the server may answer with a different attempt than the one this
185
+ // worker holds. Adopt it whole, built from the response and never by spreading
186
+ // the stale reference, and never carry the old attempt's job confirmation over.
187
+ if (response.body.binding.attempt_id !== binding.attempt_id) {
188
+ const replacement = referenceFrom(response.body.binding, confirmed);
189
+ await store.recordBindingReference(deps.docsDir, ticketKey, replacement);
190
+ return { binding: replacement, replaced: true };
191
+ }
179
192
  if (confirmed === undefined)
180
- return binding;
193
+ return { binding, replaced: false };
181
194
  const updated = { ...binding, confirmed_executor_job_id: confirmed };
182
195
  await store.recordBindingReference(deps.docsDir, ticketKey, updated);
183
- return updated;
196
+ return { binding: updated, replaced: false };
184
197
  }
185
198
  catch {
186
- return binding;
199
+ return { binding, replaced: false };
187
200
  }
188
201
  }
202
+ /** Non-empty string warnings from an optional server field; anything else is ignored. */
203
+ function readWarnings(value) {
204
+ if (!Array.isArray(value))
205
+ return undefined;
206
+ const warnings = value.filter((entry) => typeof entry === "string" && entry.trim() !== "");
207
+ return warnings.length > 0 ? warnings : undefined;
208
+ }
189
209
  /**
190
210
  * Send every pending batch, oldest first. Never throws.
191
211
  *
@@ -229,6 +249,7 @@ export async function syncPendingSubmissions(deps, ticketKey, binding) {
229
249
  const body = response.body;
230
250
  if (body.readiness)
231
251
  readiness = body.readiness;
252
+ const warnings = readWarnings(body.warnings);
232
253
  const report = {
233
254
  submission_id: entry.submission_id,
234
255
  phase: entry.phase,
@@ -236,6 +257,7 @@ export async function syncPendingSubmissions(deps, ticketKey, binding) {
236
257
  retryable: body.retryable === true,
237
258
  refusals: Array.isArray(body.refusals) ? body.refusals : [],
238
259
  ...(body.recovery_guidance ? { recovery_guidance: body.recovery_guidance } : {}),
260
+ ...(warnings ? { warnings } : {}),
239
261
  };
240
262
  reports.push(report);
241
263
  if (report.retryable)