@mushi-mushi/mcp-ci 0.6.6 → 0.6.8

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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Kenji Sakuramoto
3
+ Copyright (c) 2026 Kenji Sakuramoto / Kensaurus 合同会社
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -10,8 +10,18 @@ GitHub Action that runs Mushi Mushi MCP-style tools from CI. Use it to
10
10
  deploy, dispatch fixes for a specific report, or run natural-language
11
11
  queries against your report corpus — all without leaving your workflow.
12
12
 
13
+ ```yaml
14
+ - uses: kensaurus/mushi-mushi/packages/mcp-ci@master
15
+ with:
16
+ api-key: ${{ secrets.MUSHI_API_KEY }}
17
+ project-id: ${{ secrets.MUSHI_PROJECT_ID }}
18
+ command: check-coverage # fail the step when under 80% of reports are triaged
19
+ ```
20
+
21
+ Docs: [mcp-ci reference](https://kensaur.us/mushi-mushi/docs/sdks/mcp-ci)
22
+
13
23
  > Not a full MCP server. For the full MCP experience (tools, prompts,
14
- > streaming), install [`@mushi-mushi/mcp`](../mcp) and run it against your
24
+ > streaming), install [`@mushi-mushi/mcp`](https://www.npmjs.com/package/@mushi-mushi/mcp) and run it against your
15
25
  > local Claude Code / Codex / Cursor setup. This Action is the 80% glue
16
26
  > path: short-lived CI jobs that call the same REST endpoints the MCP
17
27
  > server exposes, with no stdio transport overhead.
@@ -31,8 +41,9 @@ queries against your report corpus — all without leaving your workflow.
31
41
 
32
42
  | `command` | What it does | Required inputs |
33
43
  | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
34
- | `gates` | Runs all five pre-release gates (`dead_handler`, `mock_leak`, `api_contract`, `crawl`, `status_claim`) for the current commit and posts a single composite status. Use `gates: 'crawl,status_claim'` to run a subset. | — (uses `commit-sha` / `pr-number` / `gates`) |
44
+ | `gates` | Runs the pre-release gates for the current commit (`all` = `dead_handler`, `mock_leak`, `api_contract`, `status_claim`, `orphan_endpoint`, `unknown_call`), prints one line per gate, and fails the step when any gate fails, errors or returns no result. `dead_handler` and `mock_leak` read your ESLint JSON report (`eslint-report`); without it the step fails. The crawl runs from Inventory → Reconcile, not here. Use `gates: 'api_contract,status_claim'` to run a subset. | `eslint-report` for the lint gates (also `commit-sha` / `pr-number` / `gates`) |
35
45
  | `discover-api` | Walks the customer repo for Next.js route handlers + OpenAPI + (optionally) Supabase introspection and POSTs the resulting `discovered_apis` to `inventory-gates` so Gate 3 (`api_contract`) has something to diff against. | — (uses `repo-root` / `openapi-file` / `supabase-*`) |
46
+ | `spec-drift` | Gate 6: runs `oasdiff breaking` between two OpenAPI specs, records the findings as a `spec_drift` gate run and sets the `findings` output. Fails on a breaking change unless `fail-on-breaking: false`. | `base-spec`, `head-spec` (+ optional `fail-on-breaking`, `commit-sha`, `pr-number`) |
36
47
 
37
48
  ### Mushi v2.1 — passive discovery & proposal flow
38
49
 
@@ -40,7 +51,7 @@ queries against your report corpus — all without leaving your workflow.
40
51
  | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------- |
41
52
  | `discovery-status` | Reads `GET /v1/admin/inventory/:projectId/discovery` and surfaces `route_count`, `total_events`, `ready_to_propose` as step outputs. Useful as a CI gate before `propose`. | — |
42
53
  | `propose` | Kicks the LLM proposer (`POST /v1/admin/inventory/:projectId/propose` → `inventory-propose` Edge Function). Emits `proposal_id`; chain it into a PR-comment job. | — |
43
- | `auth-bootstrap` | Refreshes the crawler cookie via [`@mushi-mushi/inventory-auth-runner`](../inventory-auth-runner) (shells out to `npx --yes @mushi-mushi/inventory-auth-runner refresh`). Run before any `gates` step that triggers a crawl. | `TEST_USER_*` env vars consumed by your script |
54
+ | `auth-bootstrap` | Refreshes the crawler cookie via [`@mushi-mushi/inventory-auth-runner`](https://www.npmjs.com/package/@mushi-mushi/inventory-auth-runner) (shells out to `npx --yes -p @mushi-mushi/inventory-auth-runner mushi-mushi-auth refresh`). Run before any `gates` step that triggers a crawl. | `TEST_USER_*` env vars consumed by your script |
44
55
 
45
56
  ## Quick start — gate merges on triage coverage
46
57
 
@@ -100,7 +111,7 @@ jobs:
100
111
  steps:
101
112
  - uses: actions/checkout@v4
102
113
 
103
- # Refresh the crawler cookie so Gate 4 can hit auth-gated routes.
114
+ # Refresh the crawler cookie so the crawler can reach auth-gated routes.
104
115
  - uses: kensaurus/mushi-mushi/packages/mcp-ci@master
105
116
  with:
106
117
  api-key: ${{ secrets.MUSHI_API_KEY }}
@@ -117,12 +128,18 @@ jobs:
117
128
  project-id: ${{ secrets.MUSHI_PROJECT_ID }}
118
129
  command: discover-api
119
130
 
120
- # Run Gates 1–5 server-side and gate the PR on the composite status.
131
+ # Gates 1 + 2 read your ESLint report: lint with eslint-plugin-mushi-mushi
132
+ # (no-dead-handler, no-mock-leak) and save it as JSON. `|| true` keeps
133
+ # lint errors from stopping the job here; the gates step judges them.
134
+ - run: npx eslint -f json -o mushi-eslint.json src/ || true
135
+
136
+ # Run the gates; the step fails when any gate fails.
121
137
  - uses: kensaurus/mushi-mushi/packages/mcp-ci@master
122
138
  with:
123
139
  api-key: ${{ secrets.MUSHI_API_KEY }}
124
140
  project-id: ${{ secrets.MUSHI_PROJECT_ID }}
125
141
  command: gates
142
+ eslint-report: mushi-eslint.json
126
143
  commit-sha: ${{ github.event.pull_request.head.sha }}
127
144
  pr-number: ${{ github.event.pull_request.number }}
128
145
  ```
@@ -162,16 +179,21 @@ jobs:
162
179
  | `command` | yes | — | One of the commands above. |
163
180
  | `api-endpoint` | no | Hosted Supabase functions URL | Override for self-hosted deployments. |
164
181
  | `report-id` | when `dispatch-fix` | — | Report UUID to dispatch a fix for. |
182
+ | `inventory-action-node-id` | no | — | For `dispatch-fix`: pin the fix to one inventory action so its `expected_outcome` goes into the agent's prompt. |
165
183
  | `question` | when `query` | — | Natural-language query text. |
166
184
  | `min-coverage` | no | `0.8` | For `check-coverage`: minimum classified ratio. |
167
185
  | `fail-on-quota` | no | `true` | Fail the step on `QUOTA_EXCEEDED`. Set `false` to warn and continue. |
168
186
  | `commit-sha` | when `gates` | `GITHUB_SHA` | Commit the gates run against. Surfaces in the admin `/inventory ▸ Gates` view. |
169
187
  | `pr-number` | when `gates` | — | Pull-request number used to scope `gate_findings` for the admin UI. |
170
- | `gates` | when `gates` | `'all'` | Comma-separated subset (`dead_handler,mock_leak,api_contract,crawl,status_claim`). |
171
- | `repo-root` | when `discover-api` | `GITHUB_WORKSPACE` | Directory to walk for Next.js route handlers + OpenAPI files. |
188
+ | `gates` | when `gates` | `'all'` | Comma-separated subset of `dead_handler,mock_leak,api_contract,status_claim,orphan_endpoint,unknown_call`. `crawl` is refused: start it from Inventory → Reconcile. |
189
+ | `eslint-report` | when `gates` runs `dead_handler` or `mock_leak` | — | Path to an ESLint JSON report (`eslint -f json`) made with `eslint-plugin-mushi-mushi`. Without it those gates fail the step instead of passing on no evidence. |
190
+ | `repo-root` | when `discover-api` | `GITHUB_WORKSPACE` | Directory to walk for Next.js route handlers + OpenAPI files. For `gates`, the root `eslint-report` paths are made relative to. |
172
191
  | `openapi-file` | when `discover-api` | `<repo-root>/openapi.yaml` | Explicit OpenAPI file path. |
173
192
  | `supabase-url` | when `discover-api` | — | Supabase project URL to introspect via `/rest/v1/` for `db_deps`. |
174
193
  | `supabase-anon-key` | when `discover-api` | — | Supabase anon key for the introspection. |
194
+ | `base-spec` | when `spec-drift` | — | Path or URL of the base OpenAPI spec (the previous version). |
195
+ | `head-spec` | when `spec-drift` | — | Path or URL of the head OpenAPI spec (this PR). |
196
+ | `fail-on-breaking` | no | `true` | For `spec-drift`: fail the step on a breaking change. Set `false` to warn only. |
175
197
 
176
198
  ## Outputs
177
199
 
@@ -179,6 +201,7 @@ jobs:
179
201
  | ------------------- | -------------------------------------------------------------------------------------- |
180
202
  | `result` | Raw JSON envelope returned by the Mushi API. |
181
203
  | `coverage` | For `check-coverage`: observed classified ratio (0–1). |
204
+ | `findings` | For `spec-drift`: JSON array of the oasdiff findings. |
182
205
  | `ready_to_propose` | For `discovery-status`: `'true'` once the project has a defensible-sized SDK sample. |
183
206
  | `total_events` | For `discovery-status`: total `discovery_events` rows aggregated server-side. |
184
207
  | `route_count` | For `discovery-status`: distinct route templates observed in the last 30 days. |
@@ -192,4 +215,4 @@ MIT
192
215
  <!-- mushi-readme-stats-footer -->
193
216
  ---
194
217
 
195
- <sub>Monorepo scale (July 2026): 65 edge functions · 471 SQL migrations · 13 outbound plugins · 11 inbound adapters · 19 pipeline agents. Canonical counts: <a href="https://github.com/kensaurus/mushi-mushi/blob/master/docs/stats.md">docs/stats.md</a> · <code>pnpm docs-stats</code></sub>
218
+ <sub>Monorepo scale (July 2026): 76 edge functions · 509 SQL migrations · 13 outbound plugins · 11 inbound adapters · 19 pipeline agents. Canonical counts: <a href="https://github.com/kensaurus/mushi-mushi/blob/master/docs/stats.md">docs/stats.md</a> · <code>pnpm docs-stats</code></sub>
package/action.yml CHANGED
@@ -17,7 +17,7 @@ inputs:
17
17
  required: false
18
18
  default: 'https://dxptnwrhwsqckaftyymj.supabase.co/functions/v1/api'
19
19
  command:
20
- description: 'Which MCP tool to run: trigger-judge | dispatch-fix | check-coverage | query | gates | discover-api'
20
+ description: 'Which command to run: trigger-judge | dispatch-fix | check-coverage | query | gates | discover-api | spec-drift | discovery-status | propose | auth-bootstrap'
21
21
  required: true
22
22
  report-id:
23
23
  description: 'Report UUID — required for dispatch-fix.'
@@ -37,17 +37,20 @@ inputs:
37
37
  required: false
38
38
  default: 'true'
39
39
  commit-sha:
40
- description: 'For command=gates: commit SHA the gates run against. Defaults to GITHUB_SHA.'
40
+ description: 'For command=gates and spec-drift: commit SHA the gates run against. Defaults to GITHUB_SHA.'
41
41
  required: false
42
42
  pr-number:
43
- description: 'For command=gates: pull-request number, used to scope findings on the admin UI.'
43
+ description: 'For command=gates and spec-drift: pull-request number, used to scope findings on the admin UI.'
44
44
  required: false
45
45
  gates:
46
- description: 'For command=gates: comma-separated subset to run. Defaults to "all".'
46
+ description: 'For command=gates: comma-separated subset to run. "all" = dead_handler, mock_leak, api_contract, status_claim, orphan_endpoint, unknown_call (crawl runs from Inventory → Reconcile, not here).'
47
47
  required: false
48
48
  default: 'all'
49
+ eslint-report:
50
+ description: 'For command=gates: path to an ESLint JSON report (eslint -f json) made with eslint-plugin-mushi-mushi. Required when dead_handler or mock_leak is run; without it the step fails.'
51
+ required: false
49
52
  repo-root:
50
- description: 'For command=discover-api: directory to walk for Next.js route handlers + OpenAPI files. Defaults to GitHub workspace.'
53
+ description: 'For command=discover-api: directory to walk for Next.js route handlers + OpenAPI files. For command=gates: root that eslint-report file paths are made relative to. Defaults to GitHub workspace.'
51
54
  required: false
52
55
  openapi-file:
53
56
  description: 'For command=discover-api: explicit OpenAPI file path. Defaults to <repo-root>/openapi.yaml.'
@@ -58,12 +61,32 @@ inputs:
58
61
  supabase-anon-key:
59
62
  description: 'For command=discover-api: Supabase anon key for introspection.'
60
63
  required: false
64
+ base-spec:
65
+ description: 'For command=spec-drift: path or URL of the base OpenAPI spec (the previous version). Required for spec-drift.'
66
+ required: false
67
+ head-spec:
68
+ description: 'For command=spec-drift: path or URL of the head OpenAPI spec (this PR). Required for spec-drift.'
69
+ required: false
70
+ fail-on-breaking:
71
+ description: 'For command=spec-drift: fail the step when oasdiff finds a breaking change.'
72
+ required: false
73
+ default: 'true'
61
74
 
62
75
  outputs:
63
76
  result:
64
- description: 'JSON payload returned by the MCP tool.'
77
+ description: 'JSON payload returned by the Mushi API.'
65
78
  coverage:
66
79
  description: 'For check-coverage: observed classified ratio.'
80
+ findings:
81
+ description: 'For spec-drift: JSON array of the oasdiff findings.'
82
+ ready_to_propose:
83
+ description: 'For discovery-status: "true" when there is enough SDK discovery data to propose an inventory.'
84
+ total_events:
85
+ description: 'For discovery-status: number of SDK discovery events recorded.'
86
+ route_count:
87
+ description: 'For discovery-status: number of routes discovered.'
88
+ proposal_id:
89
+ description: 'For propose: id of the inventory proposal to review on /inventory → Discovery.'
67
90
 
68
91
  runs:
69
92
  using: 'node20'
@@ -126,4 +126,3 @@ export {
126
126
  parseOpenApiFile,
127
127
  walkNextAppRouter
128
128
  };
129
- //# sourceMappingURL=api-contract-RGYYDA62.js.map
package/dist/cli.js CHANGED
@@ -2,6 +2,75 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import * as core from "@actions/core";
5
+
6
+ // src/gates.ts
7
+ import { relative, sep } from "path";
8
+ var LINT_GATES = ["dead_handler", "mock_leak"];
9
+ var ALL_GATES = ["dead_handler", "mock_leak", "api_contract", "status_claim", "orphan_endpoint", "unknown_call"];
10
+ var RULE_TO_GATE = {
11
+ "mushi-mushi/no-dead-handler": "dead_handler",
12
+ "mushi-mushi/no-mock-leak": "mock_leak"
13
+ };
14
+ function parseGatesInput(arg) {
15
+ const gates = !arg || arg === "all" ? [...ALL_GATES] : arg.split(",").map((g) => g.trim()).filter(Boolean);
16
+ if (gates.includes("crawl")) {
17
+ return {
18
+ error: "The crawl gate is not run by the gates command: the server always skips it here. Start a crawl with Inventory \u2192 Reconcile in the console, then run the api_contract gate, which reads its result."
19
+ };
20
+ }
21
+ return { gates };
22
+ }
23
+ function missingLintReport(gates, reportPath) {
24
+ const lint = gates.filter((g) => LINT_GATES.includes(g));
25
+ if (lint.length === 0 || reportPath) return null;
26
+ return `The ${lint.join(" and ")} gate${lint.length > 1 ? "s need" : " needs"} lint findings, and no eslint-report was given. Run ESLint with eslint-plugin-mushi-mushi and pass its JSON report (eslint -f json -o mushi-eslint.json src/ ; eslint-report: mushi-eslint.json), or leave these gates out of the gates input.`;
27
+ }
28
+ function lintFindingsFromEslintReport(report, repoRoot) {
29
+ if (!Array.isArray(report)) throw new Error("eslint-report is not an ESLint JSON report (expected an array of file results).");
30
+ const findings = [];
31
+ for (const file of report) {
32
+ if (!file || typeof file !== "object" || !Array.isArray(file.messages)) {
33
+ throw new Error("eslint-report is not an ESLint JSON report (a file result has no messages array).");
34
+ }
35
+ const filePath = typeof file.filePath === "string" ? relative(repoRoot, file.filePath).split(sep).join("/") : void 0;
36
+ for (const m of file.messages) {
37
+ const gate = m.ruleId ? RULE_TO_GATE[m.ruleId] : void 0;
38
+ if (!gate || !m.severity) continue;
39
+ findings.push({
40
+ gate,
41
+ severity: m.severity >= 2 ? "error" : "warn",
42
+ rule_id: m.ruleId,
43
+ message: (m.message ?? m.ruleId).slice(0, 2e3),
44
+ ...filePath ? { file_path: filePath } : {},
45
+ ...typeof m.line === "number" ? { line: m.line } : {},
46
+ ...typeof m.column === "number" ? { col: m.column } : {}
47
+ });
48
+ }
49
+ }
50
+ return findings;
51
+ }
52
+ var MAX_FINDINGS = 2e3;
53
+ function capFindings(findings) {
54
+ if (findings.length <= MAX_FINDINGS) return { findings, dropped: 0 };
55
+ const sorted = [...findings].sort((a, b) => a.severity === b.severity ? 0 : a.severity === "error" ? -1 : 1);
56
+ return { findings: sorted.slice(0, MAX_FINDINGS), dropped: findings.length - MAX_FINDINGS };
57
+ }
58
+ function readGateRuns(data) {
59
+ const d = data;
60
+ const runs = Array.isArray(d?.runs) ? d.runs : Array.isArray(d?.data?.runs) ? d.data.runs : null;
61
+ return runs;
62
+ }
63
+ function judgeGateRuns(runs, requested) {
64
+ const seen = new Set(runs.map((r) => r.gate));
65
+ return {
66
+ failed: runs.filter((r) => r.status === "fail" || r.status === "error").map((r) => r.gate),
67
+ warned: runs.filter((r) => r.status === "warn").map((r) => r.gate),
68
+ skipped: runs.filter((r) => r.status === "skipped").map((r) => ({ gate: r.gate, reason: typeof r.summary?.reason === "string" ? r.summary.reason : "no reason given" })),
69
+ missing: requested.filter((g) => !seen.has(g))
70
+ };
71
+ }
72
+
73
+ // src/cli.ts
5
74
  var API_TIMEOUT_MS = 3e4;
6
75
  async function api(endpoint, apiKey, projectId, path, init) {
7
76
  const controller = new AbortController();
@@ -86,7 +155,7 @@ async function main() {
86
155
  break;
87
156
  }
88
157
  case "discover-api": {
89
- const { discoverRoutes } = await import("./api-contract-RGYYDA62.js");
158
+ const { discoverRoutes } = await import("./api-contract-3Y3AZBX6.js");
90
159
  const repoRoot = core.getInput("repo-root") || process.cwd();
91
160
  const openapiFile = core.getInput("openapi-file") || void 0;
92
161
  const supabaseUrl = core.getInput("supabase-url") || void 0;
@@ -123,7 +192,7 @@ async function main() {
123
192
  const failOnBreaking = core.getInput("fail-on-breaking") !== "false";
124
193
  const commitSha = core.getInput("commit-sha") || process.env.GITHUB_SHA || void 0;
125
194
  const prNumber = core.getInput("pr-number") ? Number(core.getInput("pr-number")) : void 0;
126
- const { runSpecDrift } = await import("./spec-drift-AHA6YMEE.js");
195
+ const { runSpecDrift } = await import("./spec-drift-AJOP675W.js");
127
196
  const diffFindings = await runSpecDrift({ baseSpec, headSpec });
128
197
  core.info(`oasdiff found ${diffFindings.length} change(s)`);
129
198
  core.setOutput("findings", JSON.stringify(diffFindings));
@@ -156,12 +225,38 @@ async function main() {
156
225
  case "gates": {
157
226
  const commitSha = core.getInput("commit-sha") || process.env.GITHUB_SHA || "";
158
227
  const prNumber = core.getInput("pr-number") || "";
159
- const gatesArg = core.getInput("gates") || "all";
160
- const gates = gatesArg === "all" ? ["dead_handler", "mock_leak", "api_contract", "crawl", "status_claim", "orphan_endpoint", "unknown_call"] : gatesArg.split(",").map((g) => g.trim()).filter(Boolean);
228
+ const parsed = parseGatesInput(core.getInput("gates") || "all");
229
+ if ("error" in parsed) {
230
+ core.setFailed(parsed.error);
231
+ break;
232
+ }
233
+ const { gates } = parsed;
234
+ const reportPath = core.getInput("eslint-report") || void 0;
235
+ const missing = missingLintReport(gates, reportPath);
236
+ if (missing) {
237
+ core.setFailed(missing);
238
+ break;
239
+ }
240
+ let findings;
241
+ if (reportPath) {
242
+ const { readFileSync } = await import("fs");
243
+ try {
244
+ const repoRoot = core.getInput("repo-root") || process.env.GITHUB_WORKSPACE || process.cwd();
245
+ findings = lintFindingsFromEslintReport(JSON.parse(readFileSync(reportPath, "utf8")), repoRoot);
246
+ } catch (err) {
247
+ core.setFailed(`could not read eslint-report ${reportPath}: ${err.message}`);
248
+ break;
249
+ }
250
+ core.info(`eslint-report: ${findings.length} dead-handler / mock-leak finding(s)`);
251
+ const capped = capFindings(findings);
252
+ if (capped.dropped > 0) core.warning(`eslint-report: sending the first ${capped.findings.length} findings (errors first); ${capped.dropped} left out.`);
253
+ findings = capped.findings;
254
+ }
161
255
  const body = {
162
256
  commit_sha: commitSha || void 0,
163
257
  pr_number: prNumber ? Number(prNumber) : void 0,
164
- gates
258
+ gates,
259
+ ...findings ? { findings } : {}
165
260
  };
166
261
  const res = await api(
167
262
  endpoint,
@@ -179,17 +274,25 @@ async function main() {
179
274
  core.setFailed(`gates run failed: ${res.error?.code ?? "unknown"} ${res.error?.message ?? ""}`);
180
275
  break;
181
276
  }
182
- const runs = res.data?.runs ?? [];
183
- const failed = runs.filter((r) => r.status === "fail");
184
- const warned = runs.filter((r) => r.status === "warn");
277
+ const runs = readGateRuns(res.data);
278
+ if (!runs) {
279
+ core.setFailed("gates run answered without gate results; nothing was checked.");
280
+ break;
281
+ }
282
+ const verdict = judgeGateRuns(runs, gates);
185
283
  const summary = runs.map((r) => `${gateGlyph(r.status)} ${r.gate} (${r.findings_count})`).join(" \xB7 ");
186
284
  core.info(`Mushi gates: ${summary}`);
187
- if (failed.length > 0) {
285
+ for (const s of verdict.skipped) core.warning(`Mushi gate ${s.gate} skipped: ${s.reason}`);
286
+ if (verdict.failed.length > 0 || verdict.missing.length > 0) {
188
287
  core.setFailed(
189
- `Mushi gate failures: ${failed.map((r) => r.gate).join(", ")}. View details on /inventory in the admin console.`
288
+ [
289
+ verdict.failed.length > 0 ? `Mushi gate failures: ${verdict.failed.join(", ")}.` : "",
290
+ verdict.missing.length > 0 ? `No result for: ${verdict.missing.join(", ")}.` : "",
291
+ "View details on /inventory in the admin console."
292
+ ].filter(Boolean).join(" ")
190
293
  );
191
- } else if (warned.length > 0) {
192
- core.warning(`Mushi gate warnings: ${warned.map((r) => r.gate).join(", ")}.`);
294
+ } else if (verdict.warned.length > 0) {
295
+ core.warning(`Mushi gate warnings: ${verdict.warned.join(", ")}.`);
193
296
  }
194
297
  break;
195
298
  }
@@ -246,7 +349,7 @@ async function main() {
246
349
  }
247
350
  default:
248
351
  core.setFailed(
249
- `unknown command: ${command}. Expected trigger-judge | dispatch-fix | check-coverage | query | gates | discover-api | discovery-status | propose | auth-bootstrap.`
352
+ `unknown command: ${command}. Expected trigger-judge | dispatch-fix | check-coverage | query | gates | discover-api | spec-drift | discovery-status | propose | auth-bootstrap.`
250
353
  );
251
354
  }
252
355
  }
@@ -272,4 +375,3 @@ function handleResult(res, failOnQuota) {
272
375
  main().catch((err) => {
273
376
  core.setFailed(err.message);
274
377
  });
275
- //# sourceMappingURL=cli.js.map
package/dist/index.js CHANGED
@@ -1 +0,0 @@
1
- //# sourceMappingURL=index.js.map
@@ -99,4 +99,3 @@ async function runSpecDrift(opts) {
99
99
  export {
100
100
  runSpecDrift
101
101
  };
102
- //# sourceMappingURL=spec-drift-AHA6YMEE.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mushi-mushi/mcp-ci",
3
- "version": "0.6.6",
4
- "description": "GitHub Action entrypoint for running Mushi Mushi MCP tools in CI — trigger judge, dispatch fixes, gate merges on classification coverage.",
3
+ "version": "0.6.8",
4
+ "description": "GitHub Action for Mushi Mushi: fail a PR while bug reports sit untriaged, have an agent open a fix PR for a report, or run pre-release checks from your workflow.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
@@ -52,7 +52,8 @@
52
52
  "typescript": "^6.0.3",
53
53
  "vitest": "^4.1.9",
54
54
  "@mushi-mushi/eslint-config": "0.0.0",
55
- "@mushi-mushi/tsconfig": "0.0.0"
55
+ "@mushi-mushi/tsconfig": "0.0.0",
56
+ "eslint-plugin-mushi-mushi": "0.3.6"
56
57
  },
57
58
  "author": "Kenji Sakuramoto <kensaurus@gmail.com> (https://github.com/kensaurus)",
58
59
  "engines": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/api-contract.ts"],"sourcesContent":["/**\n * API Contract adapter (whitepaper §5 Gate 3).\n *\n * Walks a customer repo for the THREE most common API surface\n * declarations and returns a normalised `${METHOD}:${path}` set:\n *\n * 1. Next.js App Router — `app/**\\/route.ts` exports (GET / POST / …).\n * 2. OpenAPI document — `openapi.yaml` / `openapi.json` paths.\n * 3. Supabase introspection — server URL hand-supplied; we GET\n * `/rest/v1/?apikey=` and pull the OpenAPI Postgrest exposes.\n *\n * The function is intentionally pure-Node + zero-dep so the GitHub\n * Action that wraps it stays tiny. It POSTs the discovered set into\n * the same `inventory-gates` endpoint via a `discovered_apis` payload\n * which Gate 3 already knows how to consume (it currently reads from\n * the crawl summary; this adapter widens the source).\n */\n\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\n\ntype DiscoveredRoute = string // \"METHOD:path\"\n\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const\n\n/**\n * Walk Next.js App Router route handlers — `app/**\\/route.{ts,js,tsx,jsx}`\n * exports.\n *\n * Heuristic: scan each `route.*` file for `export async function GET|POST|…`.\n * We don't full-AST parse: a string match keeps the script dependency-free\n * and false positives are low (the file name is the safety net). The path\n * is derived from the directory structure relative to `app/`.\n */\nexport async function walkNextAppRouter(rootDir: string): Promise<DiscoveredRoute[]> {\n const out = new Set<DiscoveredRoute>()\n const appDir = path.join(rootDir, 'app')\n try {\n await walk(appDir, async (filePath) => {\n const base = path.basename(filePath)\n if (!/^route\\.(ts|tsx|js|jsx)$/.test(base)) return\n const content = await fs.readFile(filePath, 'utf-8').catch(() => '')\n const relative = path.relative(appDir, path.dirname(filePath)).split(path.sep).join('/')\n // Strip Next.js App Router URL-invisible segments before deriving\n // the route. Without this filter the discovery output leaks\n // file-system organisation into the API contract:\n // - `(group)` → route groups (URL-invisible bucket)\n // - `@slot` → parallel-route slots (rendered into a slot, no URL)\n // - `_private` → private/co-located files (never routable)\n // Leaving these in produces phony entries like `GET:/(marketing)/api/foo`\n // that never exist as real URLs and create false API-contract failures\n // for repos that use these standard conventions.\n const segments = relative === '' ? [] : relative.split('/').filter((seg) => {\n if (!seg) return false\n if (seg.startsWith('(') && seg.endsWith(')')) return false\n if (seg.startsWith('@')) return false\n if (seg.startsWith('_')) return false\n return true\n })\n // Convert `[id]` and `[...slug]` → `{id}` / `{slug}` and prefix with `/`.\n const routePath = '/' + segments.join('/').replace(/\\[(\\.{3})?([^\\]]+)\\]/g, '{$2}')\n for (const method of HTTP_METHODS) {\n const re = new RegExp(`export\\\\s+(?:async\\\\s+)?function\\\\s+${method}\\\\b`)\n if (re.test(content)) out.add(`${method}:${routePath || '/'}`)\n }\n })\n } catch {\n // app/ doesn't exist or is unreadable — caller falls back to OpenAPI\n }\n return Array.from(out)\n}\n\n/**\n * Parse an OpenAPI document (`openapi.yaml` / `.json`) and emit one\n * route per (method, path) entry. We use a lightweight Yaml fallback —\n * if `yaml` isn't installed in the consumer repo we just JSON.parse.\n */\nexport async function parseOpenApiFile(filePath: string): Promise<DiscoveredRoute[]> {\n const out: DiscoveredRoute[] = []\n try {\n const content = await fs.readFile(filePath, 'utf-8')\n let doc: unknown\n if (filePath.endsWith('.json')) {\n doc = JSON.parse(content)\n } else {\n try {\n // `yaml` is an optional peer-dep here — the consumer repo may or may\n // not have it installed. Cast to `any` so TS doesn't require us to\n // declare it as a hard dep just for the dynamic-import fallback path.\n const yaml = (await import('yaml' as string)) as { parse: (s: string) => unknown }\n doc = yaml.parse(content)\n } catch {\n return []\n }\n }\n const paths = (doc as { paths?: Record<string, Record<string, unknown>> }).paths ?? {}\n for (const [p, ops] of Object.entries(paths)) {\n for (const m of Object.keys(ops)) {\n const upper = m.toUpperCase()\n if ((HTTP_METHODS as readonly string[]).includes(upper)) {\n out.push(`${upper}:${p}`)\n }\n }\n }\n } catch {\n return []\n }\n return out\n}\n\n/**\n * Fetch the Supabase Postgrest OpenAPI doc — every Supabase project\n * exposes one at `/rest/v1/?apikey=…`.\n */\nasync function fetchSupabaseOpenApi(\n supabaseUrl: string,\n apiKey: string,\n): Promise<DiscoveredRoute[]> {\n try {\n const res = await fetch(`${supabaseUrl.replace(/\\/$/, '')}/rest/v1/?apikey=${apiKey}`, {\n headers: { Accept: 'application/json' },\n })\n if (!res.ok) return []\n const doc = await res.json()\n const paths = (doc as { paths?: Record<string, Record<string, unknown>> }).paths ?? {}\n const out: DiscoveredRoute[] = []\n for (const [p, ops] of Object.entries(paths)) {\n for (const m of Object.keys(ops)) {\n const upper = m.toUpperCase()\n if ((HTTP_METHODS as readonly string[]).includes(upper)) {\n out.push(`${upper}:/rest/v1${p}`)\n }\n }\n }\n return out\n } catch {\n return []\n }\n}\n\n/**\n * Aggregate every adapter for a single repo + optional Supabase target\n * and return a deduplicated, sorted list.\n */\nexport async function discoverRoutes(opts: {\n repoRoot: string\n openapiFile?: string\n supabaseUrl?: string\n supabaseAnonKey?: string\n}): Promise<DiscoveredRoute[]> {\n const all = new Set<DiscoveredRoute>()\n\n const next = await walkNextAppRouter(opts.repoRoot)\n for (const r of next) all.add(r)\n\n if (opts.openapiFile) {\n const oas = await parseOpenApiFile(opts.openapiFile)\n for (const r of oas) all.add(r)\n } else {\n // Convention: `openapi.yaml` at repo root.\n for (const candidate of ['openapi.yaml', 'openapi.json', 'openapi.yml']) {\n const full = path.join(opts.repoRoot, candidate)\n try {\n await fs.access(full)\n const oas = await parseOpenApiFile(full)\n for (const r of oas) all.add(r)\n break\n } catch {\n // not present\n }\n }\n }\n\n if (opts.supabaseUrl && opts.supabaseAnonKey) {\n const supa = await fetchSupabaseOpenApi(opts.supabaseUrl, opts.supabaseAnonKey)\n for (const r of supa) all.add(r)\n }\n\n return Array.from(all).sort()\n}\n\nasync function walk(dir: string, onFile: (p: string) => Promise<void>): Promise<void> {\n let entries\n try {\n entries = await fs.readdir(dir, { withFileTypes: true })\n } catch {\n return\n }\n for (const entry of entries) {\n if (entry.name === 'node_modules' || entry.name === '.next' || entry.name.startsWith('.')) continue\n const full = path.join(dir, entry.name)\n if (entry.isDirectory()) {\n await walk(full, onFile)\n } else if (entry.isFile()) {\n await onFile(full)\n }\n }\n}\n"],"mappings":";AAkBA,SAAS,YAAY,UAAU;AAC/B,OAAO,UAAU;AAIjB,IAAM,eAAe,CAAC,OAAO,QAAQ,OAAO,SAAS,QAAQ;AAW7D,eAAsB,kBAAkB,SAA6C;AACnF,QAAM,MAAM,oBAAI,IAAqB;AACrC,QAAM,SAAS,KAAK,KAAK,SAAS,KAAK;AACvC,MAAI;AACF,UAAM,KAAK,QAAQ,OAAO,aAAa;AACrC,YAAM,OAAO,KAAK,SAAS,QAAQ;AACnC,UAAI,CAAC,2BAA2B,KAAK,IAAI,EAAG;AAC5C,YAAM,UAAU,MAAM,GAAG,SAAS,UAAU,OAAO,EAAE,MAAM,MAAM,EAAE;AACnE,YAAM,WAAW,KAAK,SAAS,QAAQ,KAAK,QAAQ,QAAQ,CAAC,EAAE,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG;AAUvF,YAAM,WAAW,aAAa,KAAK,CAAC,IAAI,SAAS,MAAM,GAAG,EAAE,OAAO,CAAC,QAAQ;AAC1E,YAAI,CAAC,IAAK,QAAO;AACjB,YAAI,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS,GAAG,EAAG,QAAO;AACrD,YAAI,IAAI,WAAW,GAAG,EAAG,QAAO;AAChC,YAAI,IAAI,WAAW,GAAG,EAAG,QAAO;AAChC,eAAO;AAAA,MACT,CAAC;AAED,YAAM,YAAY,MAAM,SAAS,KAAK,GAAG,EAAE,QAAQ,yBAAyB,MAAM;AAClF,iBAAW,UAAU,cAAc;AACjC,cAAM,KAAK,IAAI,OAAO,uCAAuC,MAAM,KAAK;AACxE,YAAI,GAAG,KAAK,OAAO,EAAG,KAAI,IAAI,GAAG,MAAM,IAAI,aAAa,GAAG,EAAE;AAAA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F,UAAM,OAAO,KAAK,KAAK,KAAK,MAAM,IAAI;AACtC,QAAI,MAAM,YAAY,GAAG;AACvB,YAAM,KAAK,MAAM,MAAM;AAAA,IACzB,WAAW,MAAM,OAAO,GAAG;AACzB,YAAM,OAAO,IAAI;AAAA,IACnB;AAAA,EACF;AACF;","names":[]}
package/dist/cli.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n// SPDX-License-Identifier: MIT\n// Copyright (c) 2024–2026 Kenji Sakuramoto (kensaurus) — Mushi Mushi\nimport * as core from '@actions/core'\n\n/**\n * Wave G2 — GitHub Action entrypoint.\n *\n * Intentionally NOT a full MCP client. The Action runs in a short-lived CI\n * job where spinning up an MCP server + stdio transport would add latency\n * for zero benefit. We hit the same REST endpoints the MCP tools call\n * (`/v1/admin/*`) directly, forward the result, and fail/pass the step.\n *\n * If a user wants the full MCP experience in CI, they install the\n * `@mushi-mushi/mcp` npm package and talk to it over stdio from their own\n * Claude Code / Codex CLI step. This Action is the 80% glue path: \"hey CI,\n * block merging until Mushi finishes triaging my reports\".\n */\n\ninterface ApiResp<T = unknown> { ok: boolean; data?: T; error?: { code: string; message: string } }\n\nconst API_TIMEOUT_MS = 30_000\n\nasync function api<T>(endpoint: string, apiKey: string, projectId: string, path: string, init?: RequestInit): Promise<ApiResp<T>> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), API_TIMEOUT_MS)\n try {\n const res = await fetch(`${endpoint}${path}`, {\n ...init,\n signal: controller.signal,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Mushi-Api-Key': apiKey,\n 'X-Mushi-Project': projectId,\n ...(init?.headers ?? {}),\n },\n })\n const text = await res.text()\n let body: ApiResp<T>\n try { body = JSON.parse(text) as ApiResp<T> } catch { body = { ok: false, error: { code: `HTTP_${res.status}`, message: text.slice(0, 500) } } }\n return body\n } catch (err) {\n const message = err instanceof Error && err.name === 'AbortError'\n ? `Request timed out after ${API_TIMEOUT_MS}ms`\n : (err instanceof Error ? err.message : String(err))\n return { ok: false, error: { code: 'REQUEST_FAILED', message } }\n } finally {\n clearTimeout(timer)\n }\n}\n\nasync function main(): Promise<void> {\n const apiKey = core.getInput('api-key', { required: true })\n const projectId = core.getInput('project-id', { required: true })\n const endpoint = core.getInput('api-endpoint').replace(/\\/$/, '')\n const command = core.getInput('command', { required: true })\n const failOnQuota = core.getInput('fail-on-quota') !== 'false'\n\n switch (command) {\n case 'trigger-judge': {\n const res = await api(endpoint, apiKey, projectId, '/v1/admin/judge/run', {\n method: 'POST',\n body: JSON.stringify({ limit: 50, projectId }),\n })\n handleResult(res, failOnQuota)\n break\n }\n case 'dispatch-fix': {\n const reportId = core.getInput('report-id', { required: true })\n // Optional spec-traceability anchor (whitepaper §2.10). When provided\n // the worker skips the graph walk to recover the inventory Action and\n // includes its expected_outcome contract verbatim in the LLM prompt.\n const inventoryActionNodeId = core.getInput('inventory-action-node-id') || undefined\n const body: Record<string, unknown> = { reportId }\n if (inventoryActionNodeId) body.inventoryActionNodeId = inventoryActionNodeId\n const res = await api(endpoint, apiKey, projectId, '/v1/admin/fixes/dispatch', {\n method: 'POST',\n body: JSON.stringify(body),\n })\n handleResult(res, failOnQuota)\n break\n }\n case 'check-coverage': {\n const minCoverage = Number(core.getInput('min-coverage') || '0.8')\n const res = await api<{ total: number; classified: number }>(endpoint, apiKey, projectId, '/v1/admin/stats')\n if (!res.ok || !res.data) {\n core.setFailed(`stats query failed: ${res.error?.message ?? 'unknown'}`)\n return\n }\n const ratio = res.data.total === 0 ? 1 : res.data.classified / res.data.total\n core.setOutput('coverage', ratio.toFixed(3))\n core.setOutput('result', JSON.stringify(res.data))\n if (ratio < minCoverage) {\n core.setFailed(`classification coverage ${ratio.toFixed(3)} below threshold ${minCoverage}`)\n } else {\n core.info(`classification coverage ${ratio.toFixed(3)} >= ${minCoverage} ✓`)\n }\n break\n }\n case 'query': {\n const question = core.getInput('question', { required: true })\n const res = await api(endpoint, apiKey, projectId, '/v1/admin/query', {\n method: 'POST',\n body: JSON.stringify({ question }),\n })\n handleResult(res, failOnQuota)\n break\n }\n case 'discover-api': {\n // Mushi v2 Gate 3 helper — walk the customer repo for Next.js\n // route handlers + OpenAPI + (optionally) Supabase introspection\n // and POST the resulting `discovered_apis` to the inventory-gates\n // function. The next gates run consumes this blob to compute the\n // api_contract diff.\n const { discoverRoutes } = await import('./api-contract.js')\n const repoRoot = core.getInput('repo-root') || process.cwd()\n const openapiFile = core.getInput('openapi-file') || undefined\n const supabaseUrl = core.getInput('supabase-url') || undefined\n const supabaseAnonKey = core.getInput('supabase-anon-key') || undefined\n const routes = await discoverRoutes({\n repoRoot,\n openapiFile,\n supabaseUrl,\n supabaseAnonKey,\n })\n core.info(`Discovered ${routes.length} routes`)\n core.setOutput('result', JSON.stringify({ routes }))\n // Persist as a synthetic crawl summary so Gate 3 picks it up\n // without needing a real crawl run.\n const persist = await api(\n endpoint,\n apiKey,\n projectId,\n `/v1/admin/inventory/${projectId}/gates/run`,\n {\n method: 'POST',\n body: JSON.stringify({\n gates: ['api_contract'],\n findings: [],\n commit_sha: process.env.GITHUB_SHA,\n discovered_apis: routes,\n }),\n },\n )\n handleResult(persist, failOnQuota)\n break\n }\n case 'spec-drift': {\n // Mushi v2 Gate 6 — oasdiff spec drift detection.\n //\n // Downloads the oasdiff binary (Go static binary, cross-platform), runs\n // `oasdiff breaking <base> <head>` against two OpenAPI spec versions, and\n // POSTs the findings to the inventory-gates endpoint as a `spec_drift` gate run.\n //\n // Inputs:\n // base-spec — path or URL to the base OpenAPI spec (previous version).\n // head-spec — path or URL to the head OpenAPI spec (current PR version).\n // fail-on-breaking — whether breaking changes fail the build (default: true).\n const baseSpec = core.getInput('base-spec', { required: true })\n const headSpec = core.getInput('head-spec', { required: true })\n const failOnBreaking = core.getInput('fail-on-breaking') !== 'false'\n const commitSha = core.getInput('commit-sha') || process.env.GITHUB_SHA || undefined\n const prNumber = core.getInput('pr-number') ? Number(core.getInput('pr-number')) : undefined\n\n const { runSpecDrift } = await import('./spec-drift.js')\n const diffFindings = await runSpecDrift({ baseSpec, headSpec })\n\n core.info(`oasdiff found ${diffFindings.length} change(s)`)\n core.setOutput('findings', JSON.stringify(diffFindings))\n\n const breaking = diffFindings.filter((f) => f.severity === 'error')\n const warnings = diffFindings.filter((f) => f.severity === 'warn')\n\n // Post findings to the gates API.\n const gateBody = {\n gates: ['spec_drift'],\n spec_diff_findings: diffFindings,\n commit_sha: commitSha,\n pr_number: prNumber,\n }\n await api(\n endpoint,\n apiKey,\n projectId,\n `/v1/admin/inventory/${projectId}/gates/run`,\n { method: 'POST', body: JSON.stringify(gateBody) },\n )\n\n if (breaking.length > 0 && failOnBreaking) {\n core.setFailed(\n `Mushi Gate 6 (spec_drift): ${breaking.length} breaking change(s) detected. ` +\n `Review in the admin console → Inventory → Gates.`,\n )\n } else if (warnings.length > 0) {\n core.warning(`Mushi Gate 6 (spec_drift): ${warnings.length} potentially-breaking change(s).`)\n } else {\n core.info('Mushi Gate 6 (spec_drift): no breaking changes.')\n }\n break\n }\n case 'gates': {\n // Mushi v2: run all gates against the current commit and post a single\n // composite GitHub status.\n //\n // Gates 1 + 2 (lint) run inside this Action's checkout; Gates 3–8\n // are server-side and reachable via /v1/admin/inventory.\n // The Action then reads back the consolidated gate_runs and\n // sets a single pass/fail on the calling workflow.\n const commitSha = core.getInput('commit-sha') || process.env.GITHUB_SHA || ''\n const prNumber = core.getInput('pr-number') || ''\n const gatesArg = core.getInput('gates') || 'all'\n const gates =\n gatesArg === 'all'\n ? ['dead_handler', 'mock_leak', 'api_contract', 'crawl', 'status_claim', 'orphan_endpoint', 'unknown_call']\n : gatesArg.split(',').map((g) => g.trim()).filter(Boolean)\n\n const body = {\n commit_sha: commitSha || undefined,\n pr_number: prNumber ? Number(prNumber) : undefined,\n gates,\n }\n const res = await api<{\n runs: Array<{ gate: string; status: string; findings_count: number }>\n }>(\n endpoint,\n apiKey,\n projectId,\n `/v1/admin/inventory/${projectId}/gates/run`,\n { method: 'POST', body: JSON.stringify(body) },\n )\n core.setOutput('result', JSON.stringify(res))\n if (!res.ok) {\n if (res.error?.code === 'QUOTA_EXCEEDED' && !failOnQuota) {\n core.warning(`quota exceeded, skipping: ${res.error?.message}`)\n break\n }\n core.setFailed(`gates run failed: ${res.error?.code ?? 'unknown'} ${res.error?.message ?? ''}`)\n break\n }\n const runs = res.data?.runs ?? []\n const failed = runs.filter((r) => r.status === 'fail')\n const warned = runs.filter((r) => r.status === 'warn')\n const summary = runs\n .map((r) => `${gateGlyph(r.status)} ${r.gate} (${r.findings_count})`)\n .join(' · ')\n core.info(`Mushi gates: ${summary}`)\n if (failed.length > 0) {\n core.setFailed(\n `Mushi gate failures: ${failed.map((r) => r.gate).join(', ')}. ` +\n `View details on /inventory in the admin console.`,\n )\n } else if (warned.length > 0) {\n core.warning(`Mushi gate warnings: ${warned.map((r) => r.gate).join(', ')}.`)\n }\n break\n }\n case 'discovery-status': {\n // Mushi v2.1 — read out how much SDK passive-discovery data the\n // server has. Useful in CI to gate \"should we propose yet?\".\n const res = await api<{\n routes: unknown[]\n total_events: number\n ready_to_propose: boolean\n }>(endpoint, apiKey, projectId, `/v1/admin/inventory/${projectId}/discovery`)\n core.setOutput('result', JSON.stringify(res))\n if (!res.ok) {\n core.setFailed(`discovery-status failed: ${res.error?.code ?? 'unknown'}`)\n break\n }\n const ready = res.data?.ready_to_propose ?? false\n core.setOutput('ready_to_propose', String(ready))\n core.setOutput('total_events', String(res.data?.total_events ?? 0))\n core.setOutput('route_count', String((res.data?.routes ?? []).length))\n core.info(\n `Mushi discovery: ${res.data?.total_events ?? 0} events across ${(res.data?.routes ?? []).length} routes; ${ready ? 'ready to propose' : 'not yet ready'}.`,\n )\n break\n }\n case 'propose': {\n // Mushi v2.1 — kick off the LLM proposer. Synchronous: returns\n // the proposalId so a follow-up step can comment on the PR.\n const res = await api<{ proposalId: string; storyCount: number; pageCount: number }>(\n endpoint,\n apiKey,\n projectId,\n `/v1/admin/inventory/${projectId}/propose`,\n { method: 'POST', body: '{}' },\n )\n handleResult(res, failOnQuota)\n if (res.ok && res.data) {\n core.info(\n `Mushi proposed ${res.data.storyCount} stories / ${res.data.pageCount} pages — open /inventory ▸ Discovery to review.`,\n )\n core.setOutput('proposal_id', res.data.proposalId)\n }\n break\n }\n case 'auth-bootstrap': {\n // Mushi v2.1 — refresh the crawler cookie via the scripted-auth\n // runner. We don't run Playwright inside this Action's process\n // (browsers add ~600 MB to the image); instead we invoke the\n // published @mushi-mushi/inventory-auth-runner via `npx`. The\n // runner POSTs the cookie back to the settings endpoint we\n // expose; this Action just orchestrates.\n //\n // The bin name (`mushi-mushi-auth`) intentionally differs from\n // the unscoped package name (`inventory-auth-runner`), so we use\n // `-p <package> <bin>` instead of the bare `npx <package>` form\n // — the bare form would fail with `command not found` because\n // npx tries to invoke a bin that matches the unscoped name.\n const cmd = `npx --yes -p @mushi-mushi/inventory-auth-runner mushi-mushi-auth refresh`\n core.info(`mushi auth-bootstrap → ${cmd}`)\n const env = {\n ...process.env,\n MUSHI_API_KEY: apiKey,\n MUSHI_PROJECT: projectId,\n MUSHI_API_ENDPOINT: endpoint,\n }\n const { spawnSync } = await import('node:child_process')\n const res = spawnSync(cmd, { shell: true, env, stdio: 'inherit' })\n if ((res.status ?? 0) !== 0) {\n core.setFailed(`auth-bootstrap failed (exit ${res.status})`)\n } else {\n core.info('auth-bootstrap: cookie refreshed.')\n }\n break\n }\n default:\n core.setFailed(\n `unknown command: ${command}. Expected trigger-judge | dispatch-fix | check-coverage | query | gates | discover-api | discovery-status | propose | auth-bootstrap.`,\n )\n }\n}\n\nfunction gateGlyph(status: string): string {\n if (status === 'pass') return '✅'\n if (status === 'fail') return '❌'\n if (status === 'warn') return '⚠️'\n if (status === 'skipped') return '⏭️'\n return '⏺️'\n}\n\nfunction handleResult(res: ApiResp<unknown>, failOnQuota: boolean): void {\n core.setOutput('result', JSON.stringify(res))\n if (!res.ok) {\n if (res.error?.code === 'QUOTA_EXCEEDED' && !failOnQuota) {\n core.warning(`quota exceeded, skipping: ${res.error?.message}`)\n return\n }\n core.setFailed(`${res.error?.code ?? 'ERROR'}: ${res.error?.message ?? 'unknown'}`)\n return\n }\n core.info(`Mushi ok: ${JSON.stringify(res.data).slice(0, 500)}`)\n}\n\nmain().catch((err) => {\n core.setFailed((err as Error).message)\n})\n"],"mappings":";;;AAGA,YAAY,UAAU;AAkBtB,IAAM,iBAAiB;AAEvB,eAAe,IAAO,UAAkB,QAAgB,WAAmB,MAAc,MAAyC;AAChI,QAAM,aAAa,IAAI,gBAAgB;AACvC,QAAM,QAAQ,WAAW,MAAM,WAAW,MAAM,GAAG,cAAc;AACjE,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,GAAG,QAAQ,GAAG,IAAI,IAAI;AAAA,MAC5C,GAAG;AAAA,MACH,QAAQ,WAAW;AAAA,MACnB,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,mBAAmB;AAAA,QACnB,mBAAmB;AAAA,QACnB,GAAI,MAAM,WAAW,CAAC;AAAA,MACxB;AAAA,IACF,CAAC;AACD,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,QAAI;AACJ,QAAI;AAAE,aAAO,KAAK,MAAM,IAAI;AAAA,IAAgB,QAAQ;AAAE,aAAO,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,QAAQ,IAAI,MAAM,IAAI,SAAS,KAAK,MAAM,GAAG,GAAG,EAAE,EAAE;AAAA,IAAE;AAC/I,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,UAAM,UAAU,eAAe,SAAS,IAAI,SAAS,eACjD,2BAA2B,cAAc,OACxC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACpD,WAAO,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,kBAAkB,QAAQ,EAAE;AAAA,EACjE,UAAE;AACA,iBAAa,KAAK;AAAA,EACpB;AACF;AAEA,eAAe,OAAsB;AACnC,QAAM,SAAc,cAAS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AAc,OAAO;AACvC,CAAC;","names":[]}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/spec-drift.ts"],"sourcesContent":["/**\n * spec-drift.ts — Gate 6 oasdiff-based OpenAPI spec drift detection.\n *\n * Downloads the oasdiff Go binary (static, no runtime deps) and runs\n * `oasdiff breaking <base> <head>` to find breaking API changes between\n * two OpenAPI spec versions.\n *\n * The binary is cached under ~/.mushi/tools/oasdiff-<version> after first download.\n * Version can be pinned via the OASDIFF_VERSION env var; defaults to latest.\n */\n\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, mkdirSync, chmodSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { createHash } from 'node:crypto'\n\nconst OASDIFF_VERSION = process.env.OASDIFF_VERSION ?? '1.10.18'\n\nconst PLATFORM_MAP: Record<string, string> = {\n 'linux-x64': 'linux-amd64',\n 'linux-arm64': 'linux-arm64',\n 'darwin-x64': 'darwin-amd64',\n 'darwin-arm64': 'darwin-arm64',\n 'win32-x64': 'windows-amd64',\n}\n\nfunction getOasdiffUrl(): string {\n const platformKey = `${process.platform}-${process.arch}`\n const platform = PLATFORM_MAP[platformKey]\n if (!platform) throw new Error(`Unsupported platform for oasdiff: ${platformKey}`)\n const ext = process.platform === 'win32' ? '.exe' : ''\n return (\n `https://github.com/Tufin/oasdiff/releases/download/v${OASDIFF_VERSION}/` +\n `oasdiff_${OASDIFF_VERSION}_${platform}${ext}.tar.gz`\n )\n}\n\nasync function downloadOasdiff(): Promise<string> {\n const cacheDir = join(homedir(), '.mushi', 'tools')\n // 0700: the download and extract dir stay private to this user. `mode` only\n // applies to directories mkdir creates, so tighten an existing one too.\n mkdirSync(cacheDir, { recursive: true, mode: 0o700 })\n if (process.platform !== 'win32') chmodSync(cacheDir, 0o700)\n const ext = process.platform === 'win32' ? '.exe' : ''\n const binPath = join(cacheDir, `oasdiff-${OASDIFF_VERSION}${ext}`)\n if (existsSync(binPath)) return binPath\n\n const url = getOasdiffUrl()\n const res = await fetch(url)\n if (!res.ok) throw new Error(`Failed to download oasdiff: HTTP ${res.status} from ${url}`)\n\n const buf = Buffer.from(await res.arrayBuffer())\n const maxBytes = 64 * 1024 * 1024\n if (buf.length > maxBytes) {\n throw new Error(`oasdiff download too large (${buf.length} bytes) — aborting`)\n }\n\n // Store under ~/.mushi/tools (mode 0700 dir) instead of the world-readable\n // system temp dir — avoids CodeQL insecure-temp-file + keeps cache reusable.\n const tgzPath = join(cacheDir, `oasdiff-${createHash('md5').update(url).digest('hex')}.tar.gz`)\n writeFileSync(tgzPath, buf)\n\n const extractDir = mkdtempSync(join(cacheDir, 'oasdiff-extract-'))\n try {\n execFileSync('tar', ['-xzf', tgzPath, '-C', extractDir])\n\n const { readdirSync, copyFileSync } = await import('node:fs')\n const files = readdirSync(extractDir)\n const binName = process.platform === 'win32' ? 'oasdiff.exe' : 'oasdiff'\n const found = files.find((f) => f === binName || f.startsWith('oasdiff'))\n if (!found) throw new Error(`oasdiff binary not found in archive. Files: ${files.join(', ')}`)\n copyFileSync(join(extractDir, found), binPath)\n if (process.platform !== 'win32') chmodSync(binPath, 0o755)\n } finally {\n rmSync(extractDir, { recursive: true, force: true })\n rmSync(tgzPath, { force: true })\n }\n return binPath\n}\n\nexport interface SpecDriftFinding {\n severity: 'error' | 'warn' | 'info'\n rule_id: string\n message: string\n path?: string\n method?: string\n}\n\nexport async function runSpecDrift(opts: {\n baseSpec: string\n headSpec: string\n}): Promise<SpecDriftFinding[]> {\n let binPath: string\n try {\n binPath = await downloadOasdiff()\n } catch (err) {\n throw new Error(`oasdiff download failed: ${err instanceof Error ? err.message : String(err)}`)\n }\n\n let output = ''\n try {\n output = execFileSync(binPath, ['breaking', opts.baseSpec, opts.headSpec, '--format', 'json'], {\n encoding: 'utf-8',\n timeout: 30_000,\n // oasdiff exits 1 when breaking changes are found — that's expected.\n // We catch the error and still parse stdout.\n })\n } catch (err) {\n // execFileSync throws on non-zero exit. Capture stdout from the error object.\n const execErr = err as { stdout?: string; stderr?: string; status?: number }\n output = execErr.stdout ?? ''\n // If no stdout and non-zero exit, it's a real failure (e.g. binary crash).\n if (!output && execErr.status !== 1) {\n throw new Error(\n `oasdiff failed: ${execErr.stderr ?? String(err)}`,\n )\n }\n }\n\n if (!output.trim()) return []\n\n let parsed: unknown\n try {\n parsed = JSON.parse(output)\n } catch {\n // oasdiff may output plain text in some versions — wrap as a single warning.\n return [{ severity: 'warn', rule_id: 'spec-drift-parse-error', message: output.slice(0, 500) }]\n }\n\n // oasdiff JSON output: array of { id, text, level, operation, operationId, path, source }\n const items = Array.isArray(parsed) ? parsed : []\n return items.map((item: Record<string, unknown>) => {\n const level = String(item.level ?? 'error').toLowerCase()\n const severity: SpecDriftFinding['severity'] =\n level === 'error' || level === 'breaking' ? 'error'\n : level === 'warn' || level === 'warning' ? 'warn'\n : 'info'\n return {\n severity,\n rule_id: String(item.id ?? 'spec-drift'),\n message: String(item.text ?? item.message ?? JSON.stringify(item)),\n path: item.path ? String(item.path) : undefined,\n method: item.operation ? String(item.operation) : undefined,\n }\n })\n}\n"],"mappings":";AAWA,SAAS,oBAAoB;AAC7B,SAAS,YAAY,WAAW,WAAW,eAAe,aAAa,cAAc;AACrF,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,kBAAkB;AAE3B,IAAM,kBAAkB,QAAQ,IAAI,mBAAmB;AAEvD,IAAM,eAAuC;AAAA,EAC3C,aAAa;AAAA,EACb,eAAe;AAAA,EACf,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,aAAa;AACf;AAEA,SAAS,gBAAwB;AAC/B,QAAM,cAAc,GAAG,QAAQ,QAAQ,IAAI,QAAQ,IAAI;AACvD,QAAM,WAAW,aAAa,WAAW;AACzC,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,qCAAqC,WAAW,EA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