@bridge_gpt/mcp-server 0.2.70 → 0.2.72

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 (134) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +29 -4
  3. package/build/agent-notes.js +171 -95
  4. package/build/agent-registry.js +5 -5
  5. package/build/agents.generated.js +12 -2
  6. package/build/bounded-wait.js +9 -1
  7. package/build/bridge-permissions.js +17 -5
  8. package/build/bridge-worktree-inspection.js +237 -0
  9. package/build/check-evidence.js +6 -0
  10. package/build/claude-review-workflow.js +1 -1
  11. package/build/cli-help.js +6 -0
  12. package/build/codex-auto-recovery.js +126 -0
  13. package/build/codex-skill-adapter.js +2 -0
  14. package/build/commands.generated.js +5 -5
  15. package/build/conductor/bridge-api-client.js +776 -23
  16. package/build/conductor/command-drift-production.js +7 -2
  17. package/build/conductor/doctor.js +93 -13
  18. package/build/conductor/epic-implementer-cli.js +55 -2
  19. package/build/conductor/gate-discovery.js +659 -19
  20. package/build/conductor/gate-settings-review.js +751 -0
  21. package/build/conductor/git-hooks-uninstall.js +112 -0
  22. package/build/conductor/git-hooks.js +81 -15
  23. package/build/conductor/guided-repair.js +10 -1
  24. package/build/conductor/install-doctor.js +2 -4
  25. package/build/conductor/launch-need-probes.js +16 -11
  26. package/build/conductor/launch-plan.js +185 -0
  27. package/build/conductor/local-merge.js +12 -1
  28. package/build/conductor/merge-execution-contract.js +1 -1
  29. package/build/conductor/merged-child-check.js +2 -1
  30. package/build/conductor/precheck-timings.js +14 -0
  31. package/build/conductor/prerequisite-inputs.js +379 -0
  32. package/build/conductor/preview-observations.js +10 -0
  33. package/build/conductor/readiness-assessment.js +78 -0
  34. package/build/conductor/readiness-cli.js +10 -0
  35. package/build/conductor/readiness-prerequisites.js +53 -0
  36. package/build/conductor/readiness-sections.js +25 -9
  37. package/build/conductor/readiness.js +20 -2
  38. package/build/conductor/recovery-cli.js +281 -14
  39. package/build/conductor/recovery-operations.js +78 -5
  40. package/build/conductor/repair-contract.js +33 -0
  41. package/build/conductor/tools.js +34 -3
  42. package/build/conductor/wait-run-attention.js +115 -0
  43. package/build/conductor/wait-run-cli.js +96 -3
  44. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  45. package/build/credential-store.js +25 -20
  46. package/build/dependency-install-declarations.js +157 -0
  47. package/build/docs.generated.js +4 -4
  48. package/build/doctor.js +37 -5
  49. package/build/drive-epic-help.js +2 -2
  50. package/build/drive-epic.js +240 -56
  51. package/build/epic-ci-workflow-drift.js +71 -23
  52. package/build/epic-ci-workflow-install.js +83 -26
  53. package/build/epic-ci-workflow-v1.js +132 -0
  54. package/build/epic-ci-workflow.js +174 -13
  55. package/build/epic-implementer-bin.js +119 -44
  56. package/build/epic-launch-profile.js +1 -1
  57. package/build/executor/ci-rerun-job.js +220 -14
  58. package/build/executor/cli.js +2 -0
  59. package/build/executor/completion-contract.js +16 -0
  60. package/build/executor/credentials.js +1 -1
  61. package/build/executor/delivery-observations.js +113 -0
  62. package/build/executor/delivery-outcome.js +30 -0
  63. package/build/executor/dependency-refresh-runner.js +132 -0
  64. package/build/executor/dependency-refresh.js +530 -0
  65. package/build/executor/deps.js +4 -0
  66. package/build/executor/env.js +274 -5
  67. package/build/executor/gate-qualification-job.js +20 -5
  68. package/build/executor/harness-coverage.js +19 -0
  69. package/build/executor/http-client.js +35 -1
  70. package/build/executor/index.js +2 -1
  71. package/build/executor/install-preflight.js +1 -1
  72. package/build/executor/job-runner.js +355 -36
  73. package/build/executor/likely-tests.js +100 -98
  74. package/build/executor/preflight.js +5 -0
  75. package/build/executor/process-containment.js +18 -0
  76. package/build/executor/prompt-spec.js +84 -15
  77. package/build/executor/reconcile-overlap-job.js +6 -1
  78. package/build/executor/required-verification.js +28 -0
  79. package/build/executor/required-work-diagnostics.js +30 -0
  80. package/build/executor/required-work-ledger.js +19 -1
  81. package/build/executor/results.js +42 -0
  82. package/build/executor/service-discovery.js +42 -0
  83. package/build/executor/service-lifecycle.js +109 -2
  84. package/build/executor/service-uninstall.js +205 -0
  85. package/build/executor/service-unit.js +5 -3
  86. package/build/executor/test-clock.js +3 -0
  87. package/build/executor/verification-hints.js +179 -0
  88. package/build/executor/worker-command.js +188 -1
  89. package/build/executor/worker-database.js +299 -40
  90. package/build/executor/worker-finalization.js +65 -10
  91. package/build/executor/worker-guard-hook.js +10 -2
  92. package/build/executor/worker-resources.js +12 -1
  93. package/build/executor/worker-verification-guidance.js +64 -0
  94. package/build/executor/worktree-inspection.js +42 -0
  95. package/build/github-sign-in.js +1 -1
  96. package/build/index.js +767 -310
  97. package/build/init.js +3 -3
  98. package/build/install-bridge-conductor-gate.js +416 -41
  99. package/build/install-bridge-conductor-setup.js +135 -32
  100. package/build/install-bridge-conductor.js +769 -353
  101. package/build/install-bridge.js +419 -124
  102. package/build/install-maintenance.js +104 -0
  103. package/build/install-reexec.js +1 -1
  104. package/build/local-cleanup.js +59 -0
  105. package/build/mcp-install-state.js +68 -2
  106. package/build/merge-workflow-install.js +22 -2
  107. package/build/package-script-semantics.js +10 -0
  108. package/build/pipeline-utils.js +1 -1
  109. package/build/pipelines.generated.js +6 -6
  110. package/build/plan-execution-ledger.js +171 -10
  111. package/build/plane/plane-freshness.js +12 -9
  112. package/build/plane/preflight.js +19 -0
  113. package/build/plane/terminal-run-cleanup.js +5 -1
  114. package/build/plane/terminal-run-status.js +4 -0
  115. package/build/printed-remedy-commands.js +31 -4
  116. package/build/readiness-check.js +1 -78
  117. package/build/readiness-prerequisites.generated.js +199 -0
  118. package/build/readme.generated.js +1 -1
  119. package/build/repository-toolchains.js +623 -0
  120. package/build/setup-change-policy.js +32 -0
  121. package/build/setup-epic.js +26 -9
  122. package/build/setup-question.js +62 -0
  123. package/build/start-tickets.js +4 -0
  124. package/build/test-command-detection.js +61 -80
  125. package/build/test-support/notes-fs.js +40 -0
  126. package/build/ticket-delivery-artifacts.js +7 -0
  127. package/build/ticket-delivery-enrollment.js +80 -4
  128. package/build/ticket-delivery-run-scope.js +128 -0
  129. package/build/version.generated.js +3 -3
  130. package/build/worker-guard-hook-bin.js +2 -2
  131. package/build/worktrees.js +105 -0
  132. package/docs/EPIC-IMPLEMENTER.md +43 -0
  133. package/docs/epic-implementer/getting-started.md +95 -14
  134. package/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import { describeCheckEvidence } from "../check-evidence.js";
1
2
  /**
2
3
  * Deterministic, read-only CI gate discovery (BAPI-1391).
3
4
  *
@@ -43,9 +44,20 @@
43
44
  * Bridge API repository's own layout.
44
45
  * - Deterministic order everywhere: file names sorted by code unit, jobs in file
45
46
  * order, local candidates in a fixed order.
47
+ *
48
+ * ## Worker variables and reproduction hints (BAPI-1520)
49
+ *
50
+ * Discovery also proposes two optional, owner-confirmed settings. Both are
51
+ * conservative to the point of omission: a literal is proposed only when this
52
+ * scanner is certain of it, and anything it cannot read with certainty is left
53
+ * out (by NAME only, never by value). The proposal's values live in memory for
54
+ * the interactive confirmation and nowhere else: they are not copied into
55
+ * {@link GateEvidence}, summaries, reports, or MCP output.
46
56
  */
47
57
  import fs from "node:fs/promises";
48
58
  import path from "node:path";
59
+ import { LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV } from "../epic-implementer-env.js";
60
+ import { TOOLCHAIN_CONTENT_FILES, installArgvForJavaScript, installArgvForPython, resolveRepositoryToolchains, } from "../repository-toolchains.js";
49
61
  // ---------------------------------------------------------------------------
50
62
  // Bounds and fixed vocabularies
51
63
  // ---------------------------------------------------------------------------
@@ -65,7 +77,72 @@ export const JENKINS_LOOKUP_NAMES = [
65
77
  "continuous-integration/jenkins/pr-merge",
66
78
  ];
67
79
  /** The script body `npm init` writes; it is a placeholder, not a test command. */
68
- export const NPM_PLACEHOLDER_TEST_SCRIPT = 'echo "Error: no test specified" && exit 1';
80
+ export { NPM_PLACEHOLDER_TEST_SCRIPT } from "../package-script-semantics.js";
81
+ import { isUsablePackageScript } from "../package-script-semantics.js";
82
+ export { isUsablePackageScript };
83
+ /** BAPI-1520 — at most this many worker-variable names are proposed. */
84
+ export const MAX_WORKER_ENV_CANDIDATES = 32;
85
+ /** BAPI-1520 — the longest value, in UTF-8 bytes, that may be proposed. */
86
+ export const MAX_WORKER_ENV_VALUE_BYTES = 1024;
87
+ /** BAPI-1520 — the name syntax the server enforces. */
88
+ export const WORKER_ENV_NAME_PATTERN = /^[A-Z_][A-Z0-9_]{0,63}$/;
89
+ /**
90
+ * BAPI-1520 — names a confirmed worker variable may never use. This is a COPY:
91
+ * `api/library/epic_implementer/gate_profile.py` (`WORKER_ENV_RESERVED_NAMES`)
92
+ * is the authority, and a drift test compares the two sorted lists.
93
+ */
94
+ export const WORKER_ENV_RESERVED_NAMES = [
95
+ "BASH_ENV",
96
+ "BRIDGE_SKIP_PREPUSH",
97
+ "CI",
98
+ LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV,
99
+ "DATABASE_URL",
100
+ "EPIC_IMPLEMENTER_NODE_PATH",
101
+ "GITHUB_MERGE_TOKEN",
102
+ "GITHUB_TOKEN",
103
+ "GH_TOKEN",
104
+ "HOME",
105
+ "LANG",
106
+ "LC_ALL",
107
+ "LD_PRELOAD",
108
+ "LOGNAME",
109
+ "MAX_MCP_OUTPUT_TOKENS",
110
+ "NODE_OPTIONS",
111
+ "NO_COLOR",
112
+ "OPENAI_API_KEY",
113
+ "PATH",
114
+ "PGDATABASE",
115
+ "PGHOST",
116
+ "PGPASSFILE",
117
+ "PGPASSWORD",
118
+ "PGPORT",
119
+ "PGSERVICE",
120
+ "PGUSER",
121
+ "POSTGRES_DATABASE",
122
+ "POSTGRES_DB",
123
+ "POSTGRES_HOST",
124
+ "POSTGRES_PASSWORD",
125
+ "POSTGRES_PORT",
126
+ "POSTGRES_USER",
127
+ "SHELL",
128
+ "TEMP",
129
+ "TERM",
130
+ "TMP",
131
+ "TMPDIR",
132
+ "USER",
133
+ "XDG_CONFIG_HOME",
134
+ ];
135
+ /** BAPI-1520 — reserved name prefixes; a copy of `WORKER_ENV_RESERVED_PREFIXES`. */
136
+ export const WORKER_ENV_RESERVED_PREFIXES = [
137
+ "ANTHROPIC_",
138
+ "BAPI_",
139
+ "BRIDGE_",
140
+ "CLAUDE_",
141
+ "DYLD_",
142
+ "GIT_CONFIG_",
143
+ ];
144
+ /** BAPI-1520 — case-insensitive fragments that make a name secret-looking. */
145
+ export const WORKER_ENV_SECRET_FRAGMENTS = ["TOKEN", "SECRET", "PASSWORD", "API_KEY"];
69
146
  const WORKFLOWS_DIR = ".github/workflows";
70
147
  const CIRCLECI_CONFIG = ".circleci/config.yml";
71
148
  /**
@@ -312,7 +389,7 @@ export function parseInlineScalar(rest) {
312
389
  * also recognised anywhere beneath `strategy:`). Anything the scanner cannot
313
390
  * read confidently marks the job `unclear` rather than guessing a name.
314
391
  */
315
- export function scanJobsBlock(text) {
392
+ export function scanJobsBlock(text, options = {}) {
316
393
  const lines = significantLines(text);
317
394
  const start = lines.findIndex((l) => {
318
395
  if (l.indent !== 0)
@@ -333,6 +410,10 @@ export function scanJobsBlock(text) {
333
410
  let childIndent = null;
334
411
  let inStrategy = false;
335
412
  let afterName = false;
413
+ // Step tracking (BAPI-1520); only consulted when `options.structure` is set.
414
+ let inSteps = false;
415
+ let stepIndent = null;
416
+ let stepKeyIndent = null;
336
417
  for (let i = start + 1; i < lines.length; i++) {
337
418
  const line = lines[i];
338
419
  if (line.indent === 0)
@@ -355,12 +436,23 @@ export function scanJobsBlock(text) {
355
436
  childIndent = null;
356
437
  inStrategy = false;
357
438
  afterName = false;
439
+ inSteps = false;
440
+ stepIndent = null;
441
+ stepKeyIndent = null;
358
442
  if (kv === null) {
359
443
  unclear = true;
360
444
  current = null;
361
445
  continue;
362
446
  }
363
- current = { key: kv.key, name: null, matrix: false, expression: false, reusable: false, unclear: kv.rest !== "" };
447
+ current = {
448
+ key: kv.key,
449
+ name: null,
450
+ matrix: false,
451
+ expression: false,
452
+ reusable: false,
453
+ unclear: kv.rest !== "",
454
+ structure: { runSteps: 0, runCommand: null, blocked: false, opaque: false },
455
+ };
364
456
  jobs.push(current);
365
457
  continue;
366
458
  }
@@ -374,9 +466,13 @@ export function scanJobsBlock(text) {
374
466
  if (line.indent === childIndent) {
375
467
  inStrategy = false;
376
468
  afterName = false;
469
+ inSteps = false;
470
+ stepIndent = null;
471
+ stepKeyIndent = null;
377
472
  const kv = splitKeyLine(line.text);
378
473
  if (kv === null) {
379
474
  current.unclear = true;
475
+ current.structure.opaque = true;
380
476
  continue;
381
477
  }
382
478
  if (kv.key === "name") {
@@ -404,6 +500,12 @@ export function scanJobsBlock(text) {
404
500
  else if (kv.key === "uses") {
405
501
  current.reusable = true;
406
502
  }
503
+ else if (kv.key === "steps" && kv.rest === "") {
504
+ inSteps = true;
505
+ }
506
+ else if (kv.key === "container" || kv.key === "defaults") {
507
+ current.structure.blocked = true;
508
+ }
407
509
  continue;
408
510
  }
409
511
  // Deeper than the job's direct children.
@@ -414,6 +516,18 @@ export function scanJobsBlock(text) {
414
516
  }
415
517
  if (inStrategy && splitKeyLine(line.text)?.key === "matrix")
416
518
  current.matrix = true;
519
+ if (options.structure === true && inSteps) {
520
+ const isItem = line.text.startsWith("-") && (stepIndent === null || line.indent === stepIndent);
521
+ if (isItem) {
522
+ stepIndent = line.indent;
523
+ const after = line.text.slice(1);
524
+ stepKeyIndent = line.indent + 1 + (after.length - after.trimStart().length);
525
+ noteStepKey(current.structure, splitKeyLine(after.trim()));
526
+ }
527
+ else if (stepKeyIndent !== null && line.indent === stepKeyIndent) {
528
+ noteStepKey(current.structure, splitKeyLine(line.text));
529
+ }
530
+ }
417
531
  }
418
532
  return {
419
533
  found: true,
@@ -430,15 +544,33 @@ export function scanJobsBlock(text) {
430
544
  : j.reusable
431
545
  ? "reusable_workflow"
432
546
  : null,
547
+ ...(options.structure === true ? { structure: j.structure } : {}),
433
548
  })),
434
549
  };
435
550
  }
551
+ /** Record one step-level key into a job's {@link JobStructure}. */
552
+ function noteStepKey(structure, kv) {
553
+ if (kv === null) {
554
+ structure.opaque = true;
555
+ return;
556
+ }
557
+ if (kv.key === "run") {
558
+ structure.runSteps += 1;
559
+ if (structure.runSteps === 1) {
560
+ const parsed = kv.rest === "" ? { kind: "unclear" } : parseInlineScalar(kv.rest);
561
+ structure.runCommand = parsed.kind === "value" && parsed.value !== "" ? parsed.value : null;
562
+ }
563
+ }
564
+ else if (kv.key === "working-directory" || kv.key === "shell") {
565
+ structure.blocked = true;
566
+ }
567
+ }
436
568
  /**
437
569
  * A GitHub Actions workflow's jobs. The check-run name a job reports is its
438
570
  * `name:` when present, else its key — exact only when `variance` is null.
439
571
  */
440
- export function scanWorkflowJobs(text) {
441
- const scan = scanJobsBlock(text);
572
+ export function scanWorkflowJobs(text, options = {}) {
573
+ const scan = scanJobsBlock(text, options);
442
574
  return {
443
575
  ...scan,
444
576
  jobs: scan.jobs.map((j) => j.variance === null && (j.name ?? j.key).trim() === "" ? { ...j, variance: "unclear" } : j),
@@ -460,6 +592,310 @@ export function workflowJobReportedName(job) {
460
592
  export function circleCiStatusName(jobKey) {
461
593
  return `ci/circleci: ${jobKey.trim()}`;
462
594
  }
595
+ /** Plain scalars YAML would read as something other than a string. */
596
+ const NON_STRING_PLAIN = /^(?:~|null|true|false|yes|no|on|off|y|n)$/i;
597
+ /**
598
+ * Read one single-line env value as a string literal, or null when it is
599
+ * anything else. Deliberately stricter than {@link parseInlineScalar}: quoted
600
+ * values keep their exact characters (no trimming), and escapes, comments,
601
+ * expressions, anchors, aliases, tags, block scalars, flow collections, and
602
+ * plain scalars YAML could type as a number, boolean, null, or date are all
603
+ * refused rather than partly interpreted.
604
+ */
605
+ export function parseEnvScalar(rest) {
606
+ const text = rest.trim();
607
+ if (text === "")
608
+ return null;
609
+ let value;
610
+ if (text[0] === '"') {
611
+ const close = text.indexOf('"', 1);
612
+ if (close < 0 || text.slice(close + 1).trim() !== "")
613
+ return null;
614
+ value = text.slice(1, close);
615
+ if (value.includes("\\"))
616
+ return null;
617
+ }
618
+ else if (text[0] === "'") {
619
+ let out = "";
620
+ let closed = -1;
621
+ for (let i = 1; i < text.length; i++) {
622
+ if (text[i] === "'") {
623
+ if (text[i + 1] === "'") {
624
+ out += "'";
625
+ i++;
626
+ continue;
627
+ }
628
+ closed = i;
629
+ break;
630
+ }
631
+ out += text[i];
632
+ }
633
+ if (closed < 0 || text.slice(closed + 1).trim() !== "")
634
+ return null;
635
+ value = out;
636
+ }
637
+ else {
638
+ if (UNSUPPORTED_SCALAR_STARTS.has(text[0] ?? "") || /^[-?:](\s|$)/.test(text))
639
+ return null;
640
+ if (/\s#/.test(text) || text.includes("\t"))
641
+ return null;
642
+ if (/:(\s|$)/.test(text))
643
+ return null;
644
+ if (NON_STRING_PLAIN.test(text))
645
+ return null;
646
+ // Numbers, signed numbers, dates and `.inf`/`.nan` all start with a digit, sign, or dot.
647
+ if (/^[-+.\d]/.test(text))
648
+ return null;
649
+ value = text;
650
+ }
651
+ if (value.includes("${{") || value.includes("$(") || value.includes("${"))
652
+ return null;
653
+ return value;
654
+ }
655
+ /** Display-safe name for a skipped declaration; anything stranger is not named. */
656
+ const SKIPPED_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
657
+ /**
658
+ * Read the block map whose key line is `lines[at]`, appending each entry to
659
+ * `out`. Entries are read at the first nested indentation; a deeper line (a
660
+ * nested structure or continuation) or an unreadable line marks the entry — or,
661
+ * when no entry can be named, the whole block — unsupported. Returns whether
662
+ * the block was fully readable.
663
+ */
664
+ function readEnvMap(lines, at, parentIndent, out) {
665
+ let readable = true;
666
+ let entryIndent = null;
667
+ let last = null;
668
+ for (let i = at + 1; i < lines.length && lines[i].indent > parentIndent; i++) {
669
+ const line = lines[i];
670
+ if (line.tabIndent) {
671
+ readable = false;
672
+ last = null;
673
+ continue;
674
+ }
675
+ entryIndent ??= line.indent;
676
+ if (line.indent > entryIndent) {
677
+ // Nested structure or a continued scalar: the entry above is not a plain literal.
678
+ if (last)
679
+ last.value = null;
680
+ else
681
+ readable = false;
682
+ continue;
683
+ }
684
+ if (line.indent < entryIndent) {
685
+ readable = false;
686
+ last = null;
687
+ continue;
688
+ }
689
+ const kv = splitKeyLine(line.text);
690
+ if (kv === null || !SKIPPED_NAME_PATTERN.test(kv.key)) {
691
+ readable = false;
692
+ last = null;
693
+ continue;
694
+ }
695
+ last = { name: kv.key, value: parseEnvScalar(kv.rest) };
696
+ out.push(last);
697
+ }
698
+ return readable;
699
+ }
700
+ /**
701
+ * Scan block-style env maps: workflow-, job-, and step-level `env:` for GitHub
702
+ * Actions, job-level `environment:` for CircleCI. Flow-style, aliased, or
703
+ * otherwise unreadable maps are not read and set `unclear`.
704
+ */
705
+ export function scanEnvMaps(text, mode) {
706
+ const lines = significantLines(text);
707
+ const declarations = [];
708
+ let unclear = false;
709
+ const envKey = mode === "github" ? "env" : "environment";
710
+ const readBlock = (at, parentIndent, rest) => {
711
+ if (rest !== "") {
712
+ unclear = true;
713
+ return;
714
+ }
715
+ if (!readEnvMap(lines, at, parentIndent, declarations))
716
+ unclear = true;
717
+ };
718
+ if (mode === "github") {
719
+ lines.forEach((line, i) => {
720
+ if (line.indent !== 0)
721
+ return;
722
+ const kv = splitKeyLine(line.text);
723
+ if (kv?.key === envKey)
724
+ readBlock(i, 0, kv.rest);
725
+ });
726
+ }
727
+ const start = lines.findIndex((l) => l.indent === 0 && splitKeyLine(l.text)?.key === "jobs");
728
+ if (start < 0)
729
+ return { declarations, unclear };
730
+ let jobIndent = null;
731
+ let childIndent = null;
732
+ let inSteps = false;
733
+ let stepIndent = null;
734
+ let stepKeyIndent = null;
735
+ const stepKey = (kv, at, keyIndent) => {
736
+ if (kv?.key === envKey)
737
+ readBlock(at, keyIndent, kv.rest);
738
+ };
739
+ for (let i = start + 1; i < lines.length; i++) {
740
+ const line = lines[i];
741
+ if (line.indent === 0)
742
+ break;
743
+ if (line.tabIndent) {
744
+ unclear = true;
745
+ continue;
746
+ }
747
+ jobIndent ??= line.indent;
748
+ if (line.indent < jobIndent)
749
+ continue;
750
+ if (line.indent === jobIndent) {
751
+ childIndent = null;
752
+ inSteps = false;
753
+ stepIndent = null;
754
+ stepKeyIndent = null;
755
+ continue;
756
+ }
757
+ childIndent ??= line.indent;
758
+ if (line.indent < childIndent)
759
+ continue;
760
+ if (line.indent === childIndent && !line.text.startsWith("-")) {
761
+ inSteps = false;
762
+ stepIndent = null;
763
+ stepKeyIndent = null;
764
+ const kv = splitKeyLine(line.text);
765
+ if (kv?.key === envKey)
766
+ readBlock(i, childIndent, kv.rest);
767
+ else if (mode === "github" && kv?.key === "steps" && kv.rest === "")
768
+ inSteps = true;
769
+ continue;
770
+ }
771
+ if (mode !== "github" || !inSteps)
772
+ continue;
773
+ const isItem = line.text.startsWith("-") && (stepIndent === null || line.indent === stepIndent);
774
+ if (isItem) {
775
+ stepIndent = line.indent;
776
+ const after = line.text.slice(1);
777
+ stepKeyIndent = line.indent + 1 + (after.length - after.trimStart().length);
778
+ stepKey(splitKeyLine(after.trim()), i, stepKeyIndent);
779
+ }
780
+ else if (stepKeyIndent !== null && line.indent === stepKeyIndent) {
781
+ stepKey(splitKeyLine(line.text), i, stepKeyIndent);
782
+ }
783
+ }
784
+ return { declarations, unclear };
785
+ }
786
+ /** True when `name` is reserved (exactly, or by prefix) and may never be a worker variable. */
787
+ export function isReservedWorkerEnvName(name) {
788
+ return (WORKER_ENV_RESERVED_NAMES.includes(name) || WORKER_ENV_RESERVED_PREFIXES.some((prefix) => name.startsWith(prefix)));
789
+ }
790
+ /** True when `name` looks secret, so its literal needs the owner's individual confirmation. */
791
+ export function isSecretLookingName(name) {
792
+ const upper = name.toUpperCase();
793
+ return WORKER_ENV_SECRET_FRAGMENTS.some((fragment) => upper.includes(fragment));
794
+ }
795
+ /** True when `value` satisfies the server's value bounds (no NUL/CR/LF, at most 1,024 UTF-8 bytes). */
796
+ export function isAcceptableWorkerEnvValue(value) {
797
+ return !/[\u0000\r\n]/.test(value) && Buffer.byteLength(value, "utf8") <= MAX_WORKER_ENV_VALUE_BYTES;
798
+ }
799
+ /**
800
+ * Turn every observed declaration into proposals, conflicts, and name-only
801
+ * notices. A name is proposed only when ALL of its observed declarations are
802
+ * supported literals with one identical value; otherwise it is left out.
803
+ */
804
+ export function resolveWorkerEnv(observations) {
805
+ const byName = new Map();
806
+ for (const { source, declaration } of observations) {
807
+ const entry = byName.get(declaration.name) ?? { values: new Set(), sources: new Set(), unsupported: false };
808
+ if (declaration.value === null)
809
+ entry.unsupported = true;
810
+ else
811
+ entry.values.add(declaration.value);
812
+ entry.sources.add(source);
813
+ byName.set(declaration.name, entry);
814
+ }
815
+ const skipped = new Set();
816
+ const conflicts = new Set();
817
+ const eligible = [];
818
+ for (const [name, entry] of byName) {
819
+ if (!WORKER_ENV_NAME_PATTERN.test(name) || isReservedWorkerEnvName(name) || entry.unsupported) {
820
+ skipped.add(name);
821
+ continue;
822
+ }
823
+ if (entry.values.size > 1) {
824
+ conflicts.add(name);
825
+ continue;
826
+ }
827
+ const [value] = [...entry.values];
828
+ if (value === undefined || !isAcceptableWorkerEnvValue(value)) {
829
+ skipped.add(name);
830
+ continue;
831
+ }
832
+ eligible.push({
833
+ name,
834
+ value,
835
+ committedLiteral: isSecretLookingName(name),
836
+ sources: [...entry.sources].sort(byCodeUnit),
837
+ });
838
+ }
839
+ eligible.sort((a, b) => byCodeUnit(a.name, b.name));
840
+ return {
841
+ candidates: eligible.slice(0, MAX_WORKER_ENV_CANDIDATES),
842
+ conflicts: [...conflicts].sort(byCodeUnit),
843
+ skipped: [...skipped].sort(byCodeUnit),
844
+ overflow: Math.max(0, eligible.length - MAX_WORKER_ENV_CANDIDATES),
845
+ };
846
+ }
847
+ // ---------------------------------------------------------------------------
848
+ // Reproduction hints (BAPI-1520)
849
+ // ---------------------------------------------------------------------------
850
+ /** A token a recognised command may contain: no shell metacharacter at all. */
851
+ const SAFE_COMMAND_TOKEN = /^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/;
852
+ /** Split a one-line command into tokens, or null when it is not plainly one command. */
853
+ function plainCommandTokens(command) {
854
+ const trimmed = command.trim();
855
+ if (trimmed === "" || /[\r\n]/.test(trimmed))
856
+ return null;
857
+ const tokens = trimmed.split(/\s+/).map((token) => {
858
+ // Matching quotes around a whole token are harmless; nothing else is.
859
+ const quoted = /^(["'])(.*)\1$/.exec(token);
860
+ return quoted ? (quoted[2] ?? "") : token;
861
+ });
862
+ return tokens.every((token) => SAFE_COMMAND_TOKEN.test(token)) ? tokens : null;
863
+ }
864
+ /**
865
+ * The structured argv a single-line CI command is exactly equal to, or null.
866
+ * Only `make <test|check|lint>` for a Makefile target that exists, and
867
+ * `npm`/`pnpm`/`yarn` invocations of a `package.json` script that exists, are
868
+ * recognised. Pipes, chaining, substitution, wrappers, and anything with an
869
+ * extra argument are not.
870
+ */
871
+ export function recognizeReproductionCommand(command, context) {
872
+ const tokens = plainCommandTokens(command);
873
+ if (tokens === null)
874
+ return null;
875
+ const [program, ...args] = tokens;
876
+ if (program === "make") {
877
+ const target = args[0];
878
+ if (args.length !== 1 || !MAKE_GATE_TARGETS.includes(target))
879
+ return null;
880
+ return context.makeTargets.includes(target) ? ["make", target] : null;
881
+ }
882
+ if (program !== "npm" && program !== "pnpm" && program !== "yarn")
883
+ return null;
884
+ let script;
885
+ if (args.length === 1 && args[0] !== "run" && args[0] !== "run-script") {
886
+ // `npm test`, `pnpm test`, `yarn lint`: the bare form names a script directly,
887
+ // except that npm only has such a shortcut for `test`.
888
+ if (program === "npm" && args[0] !== "test")
889
+ return null;
890
+ script = args[0];
891
+ }
892
+ else if (args.length === 2 && args[0] === "run") {
893
+ script = args[1];
894
+ }
895
+ if (script === undefined || !context.packageScripts.includes(script))
896
+ return null;
897
+ return packageScriptArgv(program, script);
898
+ }
463
899
  const MAKE_GATE_TARGETS = ["test", "check", "lint"];
464
900
  /**
465
901
  * Makefile targets named exactly `test`, `check`, or `lint`, in that fixed
@@ -488,12 +924,6 @@ export function packageScriptArgv(pm, script) {
488
924
  return [pm, "run", script];
489
925
  }
490
926
  /** True when a package.json script value is a usable command (not empty, not the npm placeholder). */
491
- export function isUsablePackageScript(value) {
492
- if (typeof value !== "string")
493
- return false;
494
- const trimmed = value.trim();
495
- return trimmed !== "" && trimmed !== NPM_PLACEHOLDER_TEST_SCRIPT;
496
- }
497
927
  /** True when `name` is a valid local command name. */
498
928
  export function isGateCommandName(name) {
499
929
  return GATE_COMMAND_NAME_PATTERN.test(name);
@@ -597,7 +1027,97 @@ function jobDetail(job) {
597
1027
  detail += ` (name may vary: ${VARIANCE_TEXT[job.variance]})`;
598
1028
  return detail;
599
1029
  }
600
- async function collectWorkflows(fsSeam, evidence, lookups) {
1030
+ /** Environment names whose literal value shows that CI provides a database. */
1031
+ const CI_DATABASE_ENV_NAME = /^(?:DATABASE_URL|POSTGRES_[A-Z0-9_]+|PG[A-Z0-9_]+)$/;
1032
+ /** BAPI-1551 — classify one readable workflow file's database evidence. */
1033
+ function workflowDatabaseEvidence(text, jobsReadable) {
1034
+ const lines = significantLines(text);
1035
+ const hasServices = lines.some((l) => l.indent > 0 && splitKeyLine(l.text)?.key === "services");
1036
+ const env = scanEnvMaps(text, "github");
1037
+ const databaseNames = env.declarations.filter((d) => CI_DATABASE_ENV_NAME.test(d.name));
1038
+ if (hasServices || databaseNames.some((d) => d.value !== null))
1039
+ return "present";
1040
+ // A database name with a non-literal value (an expression, a number) cannot
1041
+ // prove absence, and neither can an env map or a jobs block that was unclear.
1042
+ if (!jobsReadable || env.unclear || databaseNames.length > 0)
1043
+ return "unclear";
1044
+ return "absent";
1045
+ }
1046
+ /**
1047
+ * BAPI-1551 — the `ci_database` proposal from the workflow files that hold a job
1048
+ * reporting one of `providerChecks`. `provided` wins when any such file has
1049
+ * definite evidence; `none` needs every reported check mapped to a workflow file
1050
+ * and every such file clearly without a database; anything else is `unknown`.
1051
+ */
1052
+ export function proposeCiDatabase(providerChecks, workflowFiles) {
1053
+ if (providerChecks.length === 0)
1054
+ return { value: "unknown", sources: [] };
1055
+ const relevant = workflowFiles.filter((f) => f.reportedNames.some((n) => providerChecks.includes(n)));
1056
+ const sources = relevant.map((f) => f.source);
1057
+ if (relevant.some((f) => f.database === "present")) {
1058
+ return { value: "provided", sources: relevant.filter((f) => f.database === "present").map((f) => f.source) };
1059
+ }
1060
+ const allMapped = providerChecks.every((check) => relevant.some((f) => f.reportedNames.includes(check)));
1061
+ // A workflow file whose jobs could not be named might report a check too.
1062
+ const unnamedFiles = workflowFiles.some((f) => !f.jobsReadable);
1063
+ if (relevant.length === 0 || !allMapped || unnamedFiles || relevant.some((f) => f.database !== "absent")) {
1064
+ return { value: "unknown", sources };
1065
+ }
1066
+ return { value: "none", sources };
1067
+ }
1068
+ /**
1069
+ * BAPI-1551 — read the toolchain resolver's files through the bounded discovery
1070
+ * seam. The seam answers `null` for an absent, unreadable, or over-size file, so
1071
+ * `exists` tells them apart: a file that exists but cannot be read throws a
1072
+ * non-missing error (the resolver then reports `unknown`), except a file the
1073
+ * resolver checks only for existence, which reads as present.
1074
+ */
1075
+ function toolchainReader(fsSeam) {
1076
+ return async (relPath) => {
1077
+ const text = await readBounded(fsSeam, relPath);
1078
+ if (text !== null)
1079
+ return text;
1080
+ if (!(await fsSeam.exists(relPath))) {
1081
+ throw Object.assign(new Error("absent"), { code: "ENOENT" });
1082
+ }
1083
+ if (!TOOLCHAIN_CONTENT_FILES.includes(relPath))
1084
+ return "";
1085
+ throw Object.assign(new Error("unreadable"), { code: "EIO" });
1086
+ };
1087
+ }
1088
+ /** BAPI-1551 — the root dependency-refresh proposals and the notes on what was left out. */
1089
+ export async function proposeDependencyInstall(fsSeam) {
1090
+ let resolution;
1091
+ try {
1092
+ resolution = await resolveRepositoryToolchains(toolchainReader(fsSeam));
1093
+ }
1094
+ catch {
1095
+ return { candidates: [], notes: ["dependency_install_toolchain_unresolved"] };
1096
+ }
1097
+ if (resolution.status !== "resolved") {
1098
+ return { candidates: [], notes: ["dependency_install_toolchain_unresolved"] };
1099
+ }
1100
+ const candidates = [];
1101
+ const notes = [];
1102
+ const js = resolution.toolchains.javascript;
1103
+ if (js !== null) {
1104
+ candidates.push({
1105
+ cwd: ".",
1106
+ argv: installArgvForJavaScript(js),
1107
+ lockfiles: [js.dependencyFile],
1108
+ label: js.manager === "yarn" ? `yarn (${js.generation})` : js.manager,
1109
+ });
1110
+ }
1111
+ const py = resolution.toolchains.python;
1112
+ if (py !== null) {
1113
+ if (py.manager === "pip")
1114
+ notes.push("dependency_install_pip_not_proposed");
1115
+ else
1116
+ candidates.push({ cwd: ".", argv: installArgvForPython(py), lockfiles: [py.dependencyFile], label: py.manager });
1117
+ }
1118
+ return { candidates, notes };
1119
+ }
1120
+ async function collectWorkflows(fsSeam, evidence, lookups, extras) {
601
1121
  const entries = await fsSeam.listDir(WORKFLOWS_DIR);
602
1122
  if (entries === null)
603
1123
  return;
@@ -608,9 +1128,23 @@ async function collectWorkflows(fsSeam, evidence, lookups) {
608
1128
  for (const file of files) {
609
1129
  const source = `${WORKFLOWS_DIR}/${file}`;
610
1130
  const text = await readBounded(fsSeam, source);
611
- if (text === null)
1131
+ if (text === null) {
1132
+ // BAPI-1551: an unreadable workflow file can neither prove nor rule out a database.
1133
+ extras.workflowFiles.push({ source, reportedNames: [], jobsReadable: false, database: "unclear" });
612
1134
  continue;
613
- const scan = scanWorkflowJobs(text);
1135
+ }
1136
+ const scan = scanWorkflowJobs(text, { structure: true });
1137
+ const facts = {
1138
+ source,
1139
+ reportedNames: [],
1140
+ jobsReadable: scan.jobs.length > 0,
1141
+ database: workflowDatabaseEvidence(text, scan.jobs.length > 0),
1142
+ };
1143
+ extras.workflowFiles.push(facts);
1144
+ for (const declaration of scanEnvMaps(text, "github").declarations) {
1145
+ extras.envObservations.push({ source, declaration });
1146
+ }
1147
+ const workflowBlocked = significantLines(text).some((l) => l.indent === 0 && splitKeyLine(l.text)?.key === "defaults");
614
1148
  if (scan.jobs.length === 0) {
615
1149
  // A workflow file whose jobs could not be read is still evidence of provider CI.
616
1150
  evidence.push({
@@ -630,15 +1164,25 @@ async function collectWorkflows(fsSeam, evidence, lookups) {
630
1164
  nameMayVary: reported === null,
631
1165
  };
632
1166
  evidence.push(e);
633
- if (reported !== null)
1167
+ if (reported !== null) {
1168
+ facts.reportedNames.push(reported);
634
1169
  lookups.add(reported, e);
1170
+ if (job.structure) {
1171
+ const jobs = extras.hintJobs.get(reported) ?? [];
1172
+ jobs.push({ source, structure: job.structure, workflowBlocked });
1173
+ extras.hintJobs.set(reported, jobs);
1174
+ }
1175
+ }
635
1176
  }
636
1177
  }
637
1178
  }
638
- async function collectCircleCi(fsSeam, evidence, lookups) {
1179
+ async function collectCircleCi(fsSeam, evidence, lookups, extras) {
639
1180
  const text = await readBounded(fsSeam, CIRCLECI_CONFIG);
640
1181
  if (text === null)
641
1182
  return;
1183
+ for (const declaration of scanEnvMaps(text, "circleci").declarations) {
1184
+ extras.envObservations.push({ source: CIRCLECI_CONFIG, declaration });
1185
+ }
642
1186
  const scan = scanCircleCiJobs(text);
643
1187
  if (scan.jobs.length === 0) {
644
1188
  evidence.push({
@@ -843,8 +1387,9 @@ export async function discoverGate(input) {
843
1387
  const evidence = [];
844
1388
  const localCandidates = [];
845
1389
  const lookups = new LookupNames();
846
- await collectWorkflows(fsSeam, evidence, lookups);
847
- await collectCircleCi(fsSeam, evidence, lookups);
1390
+ const extras = { envObservations: [], hintJobs: new Map(), workflowFiles: [] };
1391
+ await collectWorkflows(fsSeam, evidence, lookups, extras);
1392
+ await collectCircleCi(fsSeam, evidence, lookups, extras);
848
1393
  await collectOtherProviders(fsSeam, evidence, lookups);
849
1394
  await collectHooks(fsSeam, evidence);
850
1395
  await collectPackageJson(fsSeam, evidence, localCandidates);
@@ -860,7 +1405,8 @@ export async function discoverGate(input) {
860
1405
  // When history is not `available`, no outcome is trusted, even one the response carried.
861
1406
  const outcome = history.status === "available" ? outcomeFor(outcomes, entry.name) : null;
862
1407
  if (outcome === "reported") {
863
- providerCandidates.push({ name: entry.name, outcome, confidence: "high", evidence: entry.evidence });
1408
+ providerCandidates.push({ name: entry.name, outcome, confidence: "high", evidence: entry.evidence,
1409
+ checkEvidence: describeCheckEvidence(entry.name, "reported", "provider history") });
864
1410
  }
865
1411
  else {
866
1412
  unreportedProviderNames.push({
@@ -878,6 +1424,9 @@ export async function discoverGate(input) {
878
1424
  const validLocal = localCandidates.filter((c) => isGateCommandName(c.name));
879
1425
  const providerChecks = providerCandidates.map((c) => c.name);
880
1426
  const localCommandIds = providerChecks.length > 0 ? [] : validLocal.filter((c) => c.confidence === "high").map((c) => c.id);
1427
+ const workerEnv = resolveWorkerEnv(extras.envObservations);
1428
+ const hints = await proposeReproductionHints(fsSeam, providerChecks, extras.hintJobs);
1429
+ const dependencyInstall = await proposeDependencyInstall(fsSeam);
881
1430
  return {
882
1431
  providerCandidates,
883
1432
  unreportedProviderNames,
@@ -886,5 +1435,96 @@ export async function discoverGate(input) {
886
1435
  history,
887
1436
  proposed: { kind: deriveProposalKind(providerChecks, localCommandIds), providerChecks, localCommandIds },
888
1437
  noCandidates: providerCandidates.length === 0 && validLocal.length === 0,
1438
+ workerEnvCandidates: workerEnv.candidates,
1439
+ workerEnvConflicts: workerEnv.conflicts,
1440
+ workerEnvSkipped: workerEnv.skipped,
1441
+ workerEnvOverflow: workerEnv.overflow,
1442
+ reproductionHints: hints.proposed,
1443
+ reproductionHintsSkipped: hints.skipped,
1444
+ ...declarationFields(dependencyInstall, proposeCiDatabase(providerChecks, extras.workflowFiles)),
1445
+ };
1446
+ }
1447
+ /**
1448
+ * BAPI-1551 — only the declaration proposals, for a repository whose gate is
1449
+ * already confirmed: the root dependency refreshes, and the CI-database value
1450
+ * read from the workflow files that report one of the CONFIRMED provider checks.
1451
+ * Makes no provider-history call.
1452
+ */
1453
+ export async function discoverDeclarations(input) {
1454
+ const extras = { envObservations: [], hintJobs: new Map(), workflowFiles: [] };
1455
+ await collectWorkflows(input.fs, [], new LookupNames(), extras);
1456
+ const dependencyInstall = await proposeDependencyInstall(input.fs);
1457
+ return declarationFields(dependencyInstall, proposeCiDatabase(input.providerChecks, extras.workflowFiles));
1458
+ }
1459
+ /**
1460
+ * BAPI-1551 — the declaration fields of a proposal. Each is present only when it
1461
+ * says something (a candidate, a note, or a value other than `unknown`), so a
1462
+ * repository with nothing to propose yields exactly the pre-BAPI-1551 proposal.
1463
+ */
1464
+ function declarationFields(dependencyInstall, ciDatabase) {
1465
+ return {
1466
+ ...(dependencyInstall.candidates.length > 0 ? { dependencyInstallCandidates: dependencyInstall.candidates } : {}),
1467
+ ...(dependencyInstall.notes.length > 0 ? { dependencyInstallNotes: dependencyInstall.notes } : {}),
1468
+ ...(ciDatabase.value !== "unknown" ? { ciDatabaseProposal: ciDatabase } : {}),
889
1469
  };
890
1470
  }
1471
+ /**
1472
+ * The Makefile targets and package scripts a CI command may name (BAPI-1520).
1473
+ * Read through the same bounded seam as every other file.
1474
+ */
1475
+ async function loadHintContext(fsSeam) {
1476
+ const makefile = await readBounded(fsSeam, "Makefile");
1477
+ const makeTargets = makefile === null ? [] : scanMakefileTargets(makefile);
1478
+ let packageScripts = [];
1479
+ const text = await readBounded(fsSeam, "package.json");
1480
+ if (text !== null) {
1481
+ try {
1482
+ const parsed = JSON.parse(text);
1483
+ const raw = typeof parsed === "object" && parsed !== null ? parsed.scripts : undefined;
1484
+ if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
1485
+ const scripts = raw;
1486
+ packageScripts = PACKAGE_GATE_SCRIPTS.filter((s) => Object.prototype.hasOwnProperty.call(scripts, s) && isUsablePackageScript(scripts[s]));
1487
+ }
1488
+ }
1489
+ catch {
1490
+ // Unparseable package.json: no script is recognised.
1491
+ }
1492
+ }
1493
+ return { makeTargets, packageScripts };
1494
+ }
1495
+ /**
1496
+ * A hint exists only for a REPORTED provider check that maps to exactly one
1497
+ * workflow job, whose only `run:` step is one plain line equal to a recognised
1498
+ * Makefile target or package script, with nothing around it that an argv at the
1499
+ * worktree root could not reproduce. Every other mapped check is named, never
1500
+ * guessed at. A check with no workflow job (CircleCI, Jenkins) is not mentioned.
1501
+ */
1502
+ async function proposeReproductionHints(fsSeam, reportedChecks, hintJobs) {
1503
+ const proposed = [];
1504
+ const skipped = [];
1505
+ const mapped = reportedChecks.filter((check) => hintJobs.has(check));
1506
+ if (mapped.length === 0)
1507
+ return { proposed, skipped };
1508
+ const context = await loadHintContext(fsSeam);
1509
+ for (const check of mapped) {
1510
+ const jobs = hintJobs.get(check) ?? [];
1511
+ const job = jobs.length === 1 ? jobs[0] : undefined;
1512
+ const structure = job?.structure;
1513
+ const argv = job !== undefined &&
1514
+ structure !== undefined &&
1515
+ !job.workflowBlocked &&
1516
+ !structure.blocked &&
1517
+ !structure.opaque &&
1518
+ structure.runSteps === 1 &&
1519
+ structure.runCommand !== null
1520
+ ? recognizeReproductionCommand(structure.runCommand, context)
1521
+ : null;
1522
+ if (job !== undefined && argv !== null) {
1523
+ proposed.push({ check, argv, timeoutSeconds: LOCAL_COMMAND_TIMEOUT_SECONDS, source: job.source });
1524
+ }
1525
+ else {
1526
+ skipped.push(check);
1527
+ }
1528
+ }
1529
+ return { proposed, skipped };
1530
+ }