diff --git a/.github/workflows/mcpx.yml b/.github/workflows/mcpx.yml index 66dd0ab063..98d01eaa68 100644 --- a/.github/workflows/mcpx.yml +++ b/.github/workflows/mcpx.yml @@ -152,7 +152,7 @@ jobs: name: "basic: test" # Original coverage was push-only; the pull_request/schedule # triggers above exist for the flake-policy jobs (#1973). - if: github.event_name == 'push' + if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' needs: seed runs-on: ubuntu-latest timeout-minutes: 30 @@ -231,6 +231,7 @@ jobs: GH_TOKEN: ${{ secrets.MCPX_CONFORMANCE_VARS_TOKEN }} ON_MAIN: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }} RUN: ${{ github.run_id }}/${{ github.run_attempt }} + MCPX_FEATURE_COVERAGE_LEDGER: ${{ runner.temp }}/mcpx-feature-coverage.jsonl run: | rc=0 python3 scripts/test_gotest_report.py || rc=1 @@ -293,6 +294,14 @@ jobs: working-directory: pkgs/mcpx run: bun test plugin/opencode/mcpx/ + - name: Upload runtime feature coverage ledger + if: always() + uses: actions/upload-artifact@v7 + with: + name: mcpx-feature-coverage-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/mcpx-feature-coverage.jsonl + if-no-files-found: ignore + docs-history: name: "basic: docs-history check" # #1865: a PR that changes a compendium section's prose must carry @@ -517,6 +526,8 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} MCPX_TEST_SEED: ${{ needs.seed.outputs.seed }} + RUN_IDENTITY: ${{ github.run_id }}/${{ github.run_attempt }} + MCPX_FEATURE_COVERAGE_LEDGER: ${{ runner.temp }}/mcpx-feature-coverage.jsonl run: | # Intentional word splitting: $unit/$e2e are space-separated package # lists built in this block and must split into separate go test @@ -548,6 +559,14 @@ jobs: go test $e2e -race -shuffle=$seed -count=3 fi + - name: Upload runtime feature coverage ledger + if: always() + uses: actions/upload-artifact@v7 + with: + name: mcpx-feature-coverage-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/mcpx-feature-coverage.jsonl + if-no-files-found: ignore + stress-nightly: name: "stress: nightly full suite (race/shuffle/repeat)" # Flake policy (#1973): the whole suite, nightly, on two OSes, off diff --git a/pkgs/mcpx/internal/e2e/e2e_test.go b/pkgs/mcpx/internal/e2e/e2e_test.go index da6c5bd3cc..910bb0e214 100644 --- a/pkgs/mcpx/internal/e2e/e2e_test.go +++ b/pkgs/mcpx/internal/e2e/e2e_test.go @@ -96,6 +96,7 @@ func newEnv(t *testing.T, cfgBody string) *env { "MCPX_POLICY_WRITE=allow", ), } + recordSettingProbes(t) t.Cleanup(func() { // `stop --all` rather than `stop`: plain `stop` dials the socket // path recomputed from the environment, and a long state path moves @@ -104,7 +105,7 @@ func newEnv(t *testing.T, cfgBody string) *env { // survives. `--all` reads the daemon-.json info files instead, // which record the path the daemon actually bound. Each env has its // own MCPX_STATE_DIR, so `--all` is scoped to this test. - if out, err := e.try("stop", "--all"); err != nil { + if out, err := e.tryUnrecorded("stop", "--all"); err != nil { // Logged, not fatal: a test that has already passed should not // be failed by its own teardown, but a teardown that silently // fails is how the leak went unnoticed for so long. @@ -157,13 +158,25 @@ func (e *env) try(args ...string) (string, error) { } func (e *env) tryWith(bin string, args ...string) (string, error) { + return e.tryWithCoverage(bin, bin == e.mcpx, args...) +} + +func (e *env) tryUnrecorded(args ...string) (string, error) { + return e.tryWithCoverage(e.mcpx, false, args...) +} + +func (e *env) tryWithCoverage(bin string, record bool, args ...string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) defer cancel() cmd := exec.CommandContext(ctx, bin, args...) cmd.Dir = e.dir cmd.Env = e.envVars out, err := cmd.CombinedOutput() - return string(out), harnessTimeout(ctx, err) + err = harnessTimeout(ctx, err) + if err == nil && record { + e.recordCLI(args) + } + return string(out), err } // harnessTimeout names the harness's own deadline as the killer. Without it @@ -188,6 +201,7 @@ func (e *env) runStdin(stdin string, args ...string) string { if err != nil { e.t.Fatalf("mcpx %s failed: %v\n%s", strings.Join(args, " "), err, out) } + e.recordCLI(args) return string(out) } @@ -2630,9 +2644,12 @@ func (e *env) socketClient(t *testing.T) *http.Client { } return &http.Client{ Timeout: 3 * time.Second, - Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { - return (&net.Dialer{}).DialContext(ctx, "unix", st.Socket) - }}, + Transport: coverageRoundTripper{ + test: t.Name(), + base: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, "unix", st.Socket) + }}, + }, } } diff --git a/pkgs/mcpx/internal/e2e/feature_coverage_test.go b/pkgs/mcpx/internal/e2e/feature_coverage_test.go new file mode 100644 index 0000000000..d48f176ada --- /dev/null +++ b/pkgs/mcpx/internal/e2e/feature_coverage_test.go @@ -0,0 +1,399 @@ +package e2e_test + +import ( + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/api" + "github.com/developing-today/code/pkgs/mcpx/internal/cli" + "github.com/developing-today/code/pkgs/mcpx/internal/settings" +) + +const featureLedgerEnv = "MCPX_FEATURE_COVERAGE_LEDGER" + +type featureCoverageRow struct { + Test string `json:"test"` + Kind string `json:"kind"` + Name string `json:"name"` +} + +type coverageFeature struct { + Kind string + Name string +} + +var featureCoverage = struct { + sync.Mutex + rows map[featureCoverageRow]struct{} +}{rows: make(map[featureCoverageRow]struct{})} + +func recordFeature(t *testing.T, kind, name string) { + t.Helper() + recordFeatureForTest(t.Name(), kind, name) +} + +var featureLedgerPersistMu sync.Mutex + +func featureCoverageLedgerPath() string { + path := os.Getenv(featureLedgerEnv) + if path == "" { + path = filepath.Join(os.TempDir(), fmt.Sprintf("mcpx-feature-coverage-%d.jsonl", os.Getpid())) + } + return path +} + +// persistFeatureCoverage checkpoints the rows accumulated so far to the +// ledger on disk. TestMain's final write remains authoritative, but a +// package test timeout panics from the testing alarm goroutine and +// m.Run() never returns — without incremental checkpoints every row of +// a timed-out run is lost and the workflow's always() upload finds no +// file at all (Codex review on PR #3705). +func persistFeatureCoverage() { + featureLedgerPersistMu.Lock() + defer featureLedgerPersistMu.Unlock() + _ = writeFeatureCoverageLedger(featureCoverageLedgerPath(), featureCoverageSnapshot()) +} + +func recordFeatureForTest(test, kind, name string) { + if test == "" || kind == "" || name == "" { + return + } + row := featureCoverageRow{Test: test, Kind: kind, Name: name} + featureCoverage.Lock() + _, seen := featureCoverage.rows[row] + featureCoverage.rows[row] = struct{}{} + featureCoverage.Unlock() + if !seen { + persistFeatureCoverage() + } +} + +func featureCoverageSnapshot() []featureCoverageRow { + featureCoverage.Lock() + defer featureCoverage.Unlock() + rows := make([]featureCoverageRow, 0, len(featureCoverage.rows)) + for row := range featureCoverage.rows { + rows = append(rows, row) + } + sort.Slice(rows, func(i, j int) bool { + if rows[i].Kind != rows[j].Kind { + return rows[i].Kind < rows[j].Kind + } + if rows[i].Name != rows[j].Name { + return rows[i].Name < rows[j].Name + } + return rows[i].Test < rows[j].Test + }) + return rows +} + +func writeFeatureCoverageLedger(path string, rows []featureCoverageRow) error { + if path == "" { + path = filepath.Join(os.TempDir(), fmt.Sprintf("mcpx-feature-coverage-%d.jsonl", os.Getpid())) + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return fmt.Errorf("create feature coverage ledger directory: %w", err) + } + f, err := os.Create(path) + if err != nil { + return fmt.Errorf("create feature coverage ledger: %w", err) + } + enc := json.NewEncoder(f) + for _, row := range rows { + if err := enc.Encode(row); err != nil { + _ = f.Close() + return fmt.Errorf("write feature coverage ledger: %w", err) + } + } + if err := f.Close(); err != nil { + return fmt.Errorf("close feature coverage ledger: %w", err) + } + return nil +} + +func TestMain(m *testing.M) { + code := m.Run() + path := featureCoverageLedgerPath() + rows := featureCoverageSnapshot() + if err := writeFeatureCoverageLedger(path, rows); err != nil { + fmt.Fprintln(os.Stderr, err) + code = 1 + } else { + fmt.Printf("feature coverage ledger: %s (%d rows)\n", path, len(rows)) + } + os.Exit(code) +} + +func recordSettingProbes(t *testing.T) { + for path, test := range settings.EffectProbes { + if test == t.Name() { + recordFeature(t, "setting", path) + } + } +} + +func (e *env) recordCLI(args []string) { + name := resolveCLICommand(args, e.dir) + if name == "" { + return + } + recordFeature(e.t, "cli", name) +} + +func resolveCLICommand(args []string, dir string) string { + // A help-only dispatch (a command invoked with -h/--help anywhere in + // its arguments) exercises only the usage text: Handlers() converts + // flag.ErrHelp to nil, so the invocation "succeeds" without running + // the command. Crediting the command name would let the ledger + // conceal commands no test actually exercised (Codex review on + // PR #3705), so classify the invocation as help instead. + for _, arg := range args { + if arg == "--" { + break + } + if arg == "-h" || arg == "--help" { + return "help" + } + } + handlers := (&cli.App{}).Handlers() + for i := 0; i < len(args); i++ { + arg := args[i] + switch arg { + case "--json", "--skip-default", "--all-profiles": + continue + case "--tui": + return "tui" + case "--help", "-h": + return "help" + case "--version", "-v": + return "" + case "--profile", "--config", "--paths-config": + i++ + continue + } + if strings.HasPrefix(arg, "--profile=") || strings.HasPrefix(arg, "--config=") || strings.HasPrefix(arg, "--paths-config=") { + continue + } + if strings.HasPrefix(arg, "--") { + flagName, _, hasValue := strings.Cut(strings.TrimPrefix(arg, "--"), "=") + setting, ok := settingForFlag(flagName) + if !ok { + return "" + } + if !hasValue && setting.Kind != settings.KindBool { + i++ + } + continue + } + if strings.HasPrefix(arg, "-") { + return "" + } + if _, ok := handlers[arg]; ok { + return arg + } + if runnableCommand(arg, dir) == "run" { + return "run" + } + if runnableCommand(arg, dir) == "exec" { + return "exec" + } + return "" + } + return "" +} + +func settingForFlag(name string) (settings.Setting, bool) { + for _, setting := range settings.Registry() { + for _, candidate := range append([]string{setting.FlagName()}, setting.FlagAliases...) { + if candidate == name { + return setting, true + } + } + } + return settings.Setting{}, false +} + +func runnableCommand(arg, dir string) string { + if arg == "" || strings.HasPrefix(arg, "-") { + return "" + } + for _, ext := range []string{".ts", ".js", ".mts", ".mjs"} { + if strings.HasSuffix(arg, ext) { + return "run" + } + } + if strings.ContainsAny(arg, "(){};") || strings.Contains(arg, "await ") || + strings.Contains(arg, "console.") || strings.Contains(arg, "tools.") || strings.Contains(arg, "=>") { + return "exec" + } + path := arg + if !filepath.IsAbs(path) { + path = filepath.Join(dir, path) + } + if st, err := os.Stat(path); err == nil && !st.IsDir() { + return "run" + } + return "" +} + +func matchAPIOperation(method, path string) string { + for _, op := range api.Ops() { + if op.Method != method || !matchRoutePath(op.Path, path) { + continue + } + return op.Name + } + return "" +} + +func matchRoutePath(pattern, path string) bool { + want := strings.Split(strings.Trim(pattern, "/"), "/") + got := strings.Split(strings.Trim(path, "/"), "/") + if len(want) != len(got) { + return false + } + for i := range want { + if strings.HasPrefix(want[i], "{") && strings.HasSuffix(want[i], "}") { + continue + } + if want[i] != got[i] { + return false + } + } + return true +} + +type coverageRoundTripper struct { + base http.RoundTripper + test string +} + +func (rt coverageRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + resp, err := rt.base.RoundTrip(req) + if err == nil && resp != nil { + if op := matchAPIOperation(req.Method, req.URL.Path); op != "" { + recordFeatureForTest(rt.test, "op", op) + } + } + return resp, err +} + +func coverageViolations(required []coverageFeature, rows []featureCoverageRow, exemptions map[coverageFeature]string) []string { + covered := make(map[coverageFeature]bool, len(rows)) + for _, row := range rows { + covered[coverageFeature{Kind: row.Kind, Name: row.Name}] = true + } + var violations []string + for feature, reason := range exemptions { + if strings.TrimSpace(reason) == "" { + violations = append(violations, fmt.Sprintf("%s %s has an empty exemption reason", feature.Kind, feature.Name)) + } + } + for _, feature := range required { + if covered[feature] { + if _, exempt := exemptions[feature]; exempt { + violations = append(violations, fmt.Sprintf("%s %s is both exercised and exempt", feature.Kind, feature.Name)) + } + continue + } + if _, exempt := exemptions[feature]; !exempt { + violations = append(violations, fmt.Sprintf("%s %s has no integration-test ledger row or reasoned exemption", feature.Kind, feature.Name)) + } + } + for feature := range exemptions { + found := false + for _, candidate := range required { + if candidate == feature { + found = true + break + } + } + if !found { + violations = append(violations, fmt.Sprintf("exemption names unknown %s %s", feature.Kind, feature.Name)) + } + } + sort.Strings(violations) + return violations +} + +func TestFeatureCoverageGuardFailsForFabricatedGap(t *testing.T) { + required := []coverageFeature{{Kind: "op", Name: "fabricated_uncovered_operation"}} + if got := coverageViolations(required, nil, nil); len(got) != 1 || !strings.Contains(got[0], "fabricated_uncovered_operation") { + t.Fatalf("fabricated uncovered feature should fail the guard, got %v", got) + } +} + +func TestFeatureCoverageLedgerWritesJSONLines(t *testing.T) { + path := filepath.Join(t.TempDir(), "ledger.jsonl") + rows := []featureCoverageRow{ + {Test: "TestA", Kind: "op", Name: "status"}, + {Test: "TestB", Kind: "cli", Name: "ls"}, + } + if err := writeFeatureCoverageLedger(path, rows); err != nil { + t.Fatal(err) + } + body, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(string(body)), "\n") + if len(lines) != len(rows) { + t.Fatalf("got %d JSON lines, want %d: %s", len(lines), len(rows), body) + } + for i, line := range lines { + var got featureCoverageRow + if err := json.Unmarshal([]byte(line), &got); err != nil { + t.Fatalf("line %d is not JSON: %v", i+1, err) + } + if got != rows[i] { + t.Errorf("line %d = %+v, want %+v", i+1, got, rows[i]) + } + } +} + +func TestFeatureCoverageMatchesParameterizedAPIOperation(t *testing.T) { + if got := matchAPIOperation(http.MethodGet, "/v1/ask/example-id"); got != "ask_poll" { + t.Fatalf("matched operation %q, want ask_poll", got) + } +} + +func TestResolveCLICommandHelpOnlyIsNotCommandCoverage(t *testing.T) { + for _, args := range [][]string{ + {"events", "-h"}, + {"artifact", "--help"}, + {"--json", "ls", "-h"}, + } { + if got := resolveCLICommand(args, t.TempDir()); got != "help" { + t.Fatalf("resolved command %q for help-only %v, want help", got, args) + } + } +} + +func TestRecordFeaturePersistsLedgerIncrementally(t *testing.T) { + path := filepath.Join(t.TempDir(), "ledger.jsonl") + t.Setenv(featureLedgerEnv, path) + recordFeatureForTest("TestRecordFeaturePersistsLedgerIncrementally", "cli", "incremental-probe") + body, err := os.ReadFile(path) + if err != nil { + t.Fatalf("ledger was not persisted before TestMain: %v", err) + } + if !strings.Contains(string(body), "incremental-probe") { + t.Fatalf("persisted ledger does not contain the new row: %s", body) + } +} + +func TestResolveCLICommandAfterGlobalFlags(t *testing.T) { + if got := resolveCLICommand([]string{"--json", "--profile", "dev", "list"}, t.TempDir()); got != "list" { + t.Fatalf("resolved command %q, want alias list", got) + } + if got := resolveCLICommand([]string{"--plumbing-strict-unknown-keys", "ls"}, t.TempDir()); got != "ls" { + t.Fatalf("resolved command %q after boolean setting flag, want ls", got) + } +}