@mushi-mushi/mcp-ci 0.4.1 → 0.6.0

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/CONTRIBUTING.md CHANGED
@@ -101,17 +101,6 @@ Releases are fully automated. Maintainers don't run `npm publish` by hand.
101
101
 
102
102
  If GitHub's anti-loop protection suppresses the auto re-fire (the squash merge can be attributed to `github-actions[bot]`), trigger the workflow manually: **Actions → release → Run workflow → master**.
103
103
 
104
- ### Known CI/CD quirks and their automatic safeguards
105
-
106
- A handful of GitHub-Actions × Changesets edge cases have caused release-pipeline stalls in the past. Each is now caught automatically — keep these in mind when you see the symptom:
107
-
108
- | Symptom | Root cause | Automatic safeguard |
109
- | --- | --- | --- |
110
- | The `Build & Test` required check never registers on the `chore: version packages` PR — the PR stays "Required check missing" forever | `changeset-release/master` is pushed by `github-actions[bot]`. GitHub silently drops the downstream `pull_request` event to prevent bot loops (observed on PR #45, #102, #124). | `ci.yml` now also triggers on `push` to `changeset-release/master`, so `Build & Test` reports against the head commit directly. No empty-commit nudge needed. |
111
- | Release workflow fails with `No commits between master and changeset-release/master` after merging a PR with a new changeset. | A `.changeset/*.md` file whose YAML frontmatter only targets packages listed in `.changeset/config.json#ignore` (e.g. `@mushi-mushi/server`, `@mushi-mushi/admin`). `changeset version` produces no bumps, the version PR is empty, the next push errors (PR #102 / #121, 2026-05-19). | `pnpm check:changeset-orphans` runs in both `ci.yml` and `release.yml`. PR CI fails with an actionable message naming the orphan file *before* it can reach master. If you legitimately need to record an internal-only change, omit the changeset entirely — the diff lives in git history. |
112
- | Release workflow's `Audit signatures of installed dependencies` step fails with `npm ETARGET / No matching version found for @mushi-mushi/<pkg>@<ver>` seconds after the publish step succeeded. | npm's registry CDN can take up to ~30s to propagate a freshly-published manifest. The audit step shells out to `npm install` against the just-published version and races the CDN (observed 2026-05-20, run 26149167393). | The audit step retries with exponential backoff (1, 2, 4, 8, 16, 32s — 63s total) before failing. Sigstore signatures are written at publish time, so a one-off audit failure never indicates a corrupted package — `pnpm view <pkg> version` is the ground truth. |
113
- | Push to `master` after merging a PR doesn't fire the `Release` workflow. | Same anti-loop protection: when a squash merge is attributed to `github-actions[bot]`, GitHub may suppress the downstream `push` trigger. Sporadic — observed twice in the last 60 days. | `release.yml` keeps `workflow_dispatch` as the manual fallback. Recovery: **Actions → Release → Run workflow → master**. The `Build & Verify` job re-runs identically to the auto-fired path. |
114
-
115
104
  ### Adding a brand-new publishable package
116
105
 
117
106
  Trusted Publisher bindings are configured **per package** on `npmjs.com` and require the package to already exist on the registry. New packages therefore need a one-time bootstrap before OIDC can take over.
package/README.md CHANGED
@@ -182,3 +182,9 @@ jobs:
182
182
  ## License
183
183
 
184
184
  MIT
185
+
186
+
187
+ <!-- mushi-readme-stats-footer -->
188
+ ---
189
+
190
+ <sub>Monorepo scale (June 2026): 43 edge functions · 234 SQL migrations · 13 outbound plugins · 11 inbound adapters. 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/dist/cli.js CHANGED
@@ -2,24 +2,35 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import * as core from "@actions/core";
5
+ var API_TIMEOUT_MS = 3e4;
5
6
  async function api(endpoint, apiKey, projectId, path, init) {
6
- const res = await fetch(`${endpoint}${path}`, {
7
- ...init,
8
- headers: {
9
- "Content-Type": "application/json",
10
- "X-Mushi-Api-Key": apiKey,
11
- "X-Mushi-Project": projectId,
12
- ...init?.headers ?? {}
13
- }
14
- });
15
- const text = await res.text();
16
- let body;
7
+ const controller = new AbortController();
8
+ const timer = setTimeout(() => controller.abort(), API_TIMEOUT_MS);
17
9
  try {
18
- body = JSON.parse(text);
19
- } catch {
20
- body = { ok: false, error: { code: `HTTP_${res.status}`, message: text.slice(0, 500) } };
10
+ const res = await fetch(`${endpoint}${path}`, {
11
+ ...init,
12
+ signal: controller.signal,
13
+ headers: {
14
+ "Content-Type": "application/json",
15
+ "X-Mushi-Api-Key": apiKey,
16
+ "X-Mushi-Project": projectId,
17
+ ...init?.headers ?? {}
18
+ }
19
+ });
20
+ const text = await res.text();
21
+ let body;
22
+ try {
23
+ body = JSON.parse(text);
24
+ } catch {
25
+ body = { ok: false, error: { code: `HTTP_${res.status}`, message: text.slice(0, 500) } };
26
+ }
27
+ return body;
28
+ } catch (err) {
29
+ const message = err instanceof Error && err.name === "AbortError" ? `Request timed out after ${API_TIMEOUT_MS}ms` : err instanceof Error ? err.message : String(err);
30
+ return { ok: false, error: { code: "REQUEST_FAILED", message } };
31
+ } finally {
32
+ clearTimeout(timer);
21
33
  }
22
- return body;
23
34
  }
24
35
  async function main() {
25
36
  const apiKey = core.getInput("api-key", { required: true });
@@ -106,11 +117,47 @@ async function main() {
106
117
  handleResult(persist, failOnQuota);
107
118
  break;
108
119
  }
120
+ case "spec-drift": {
121
+ const baseSpec = core.getInput("base-spec", { required: true });
122
+ const headSpec = core.getInput("head-spec", { required: true });
123
+ const failOnBreaking = core.getInput("fail-on-breaking") !== "false";
124
+ const commitSha = core.getInput("commit-sha") || process.env.GITHUB_SHA || void 0;
125
+ const prNumber = core.getInput("pr-number") ? Number(core.getInput("pr-number")) : void 0;
126
+ const { runSpecDrift } = await import("./spec-drift-SGNI6UBK.js");
127
+ const diffFindings = await runSpecDrift({ baseSpec, headSpec });
128
+ core.info(`oasdiff found ${diffFindings.length} change(s)`);
129
+ core.setOutput("findings", JSON.stringify(diffFindings));
130
+ const breaking = diffFindings.filter((f) => f.severity === "error");
131
+ const warnings = diffFindings.filter((f) => f.severity === "warn");
132
+ const gateBody = {
133
+ gates: ["spec_drift"],
134
+ spec_diff_findings: diffFindings,
135
+ commit_sha: commitSha,
136
+ pr_number: prNumber
137
+ };
138
+ await api(
139
+ endpoint,
140
+ apiKey,
141
+ projectId,
142
+ `/v1/admin/inventory/${projectId}/gates/run`,
143
+ { method: "POST", body: JSON.stringify(gateBody) }
144
+ );
145
+ if (breaking.length > 0 && failOnBreaking) {
146
+ core.setFailed(
147
+ `Mushi Gate 6 (spec_drift): ${breaking.length} breaking change(s) detected. Review in the admin console \u2192 Inventory \u2192 Gates.`
148
+ );
149
+ } else if (warnings.length > 0) {
150
+ core.warning(`Mushi Gate 6 (spec_drift): ${warnings.length} potentially-breaking change(s).`);
151
+ } else {
152
+ core.info("Mushi Gate 6 (spec_drift): no breaking changes.");
153
+ }
154
+ break;
155
+ }
109
156
  case "gates": {
110
157
  const commitSha = core.getInput("commit-sha") || process.env.GITHUB_SHA || "";
111
158
  const prNumber = core.getInput("pr-number") || "";
112
159
  const gatesArg = core.getInput("gates") || "all";
113
- const gates = gatesArg === "all" ? ["dead_handler", "mock_leak", "api_contract", "crawl", "status_claim"] : gatesArg.split(",").map((g) => g.trim()).filter(Boolean);
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);
114
161
  const body = {
115
162
  commit_sha: commitSha || void 0,
116
163
  pr_number: prNumber ? Number(prNumber) : void 0,
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\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\nasync function api<T>(endpoint: string, apiKey: string, projectId: string, path: string, init?: RequestInit): Promise<ApiResp<T>> {\n const res = await fetch(`${endpoint}${path}`, {\n ...init,\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}\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 'gates': {\n // Mushi v2: run all five pre-release gates against the current\n // commit and post a single composite GitHub status.\n //\n // Gates 1 + 2 (lint) run inside this Action's checkout; Gates 3\n // + 4 + 5 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']\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":";;;AACA,YAAY,UAAU;AAkBtB,eAAe,IAAO,UAAkB,QAAgB,WAAmB,MAAc,MAAyC;AAChI,QAAM,MAAM,MAAM,MAAM,GAAG,QAAQ,GAAG,IAAI,IAAI;AAAA,IAC5C,GAAG;AAAA,IACH,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,MACnB,GAAI,MAAM,WAAW,CAAC;AAAA,IACxB;AAAA,EACF,CAAC;AACD,QAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,MAAI;AACJ,MAAI;AAAE,WAAO,KAAK,MAAM,IAAI;AAAA,EAAgB,QAAQ;AAAE,WAAO,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,QAAQ,IAAI,MAAM,IAAI,SAAS,KAAK,MAAM,GAAG,GAAG,EAAE,EAAE;AAAA,EAAE;AAC/I,SAAO;AACT;AAEA,eAAe,OAAsB;AACnC,QAAM,SAAc,cAAS,WAAW,EAAE,UAAU,KAAK,CAAC;AAC1D,QAAM,YAAiB,cAAS,cAAc,EAAE,UAAU,KAAK,CAAC;AAChE,QAAM,WAAgB,cAAS,cAAc,EAAE,QAAQ,OAAO,EAAE;AAChE,Q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r/bin/env node\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":";;;AACA,YAAY,UAAU;AAkBtB,IAAM,iBAAiB;AAEvB,eAAe,IAAO,UAAkB,QAAgB,WAAmB,MAAc,MAAyC;AAChI,QAAM,aAAa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,WAAK,IAAI,UAAU,OAAO,GAAG;AAC3B,QAAK,eAAU,+BAA+B,IAAI,MAAM,GAAG;AAAA,MAC7D,OAAO;AACL,QAAK,UAAK,mCAAmC;AAAA,MAC/C;AACA;AAAA,IACF;AAAA,IACA;AACE,MAAK;AAAA,QACH,oBAAoB,OAAO;AAAA,MAC7B;AAAA,EACJ;AACF;AAEA,SAAS,UAAU,QAAwB;AACzC,MAAI,WAAW,OAAQ,QAAO;AAC9B,MAAI,WAAW,OAAQ,QAAO;AAC9B,MAAI,WAAW,OAAQ,QAAO;AAC9B,MAAI,WAAW,UAAW,QAAO;AACjC,SAAO;AACT;AAEA,SAAS,aAAa,KAAuB,aAA4B;AACvE,EAAK,eAAU,UAAU,KAAK,UAAU,GAAG,CAAC;AAC5C,MAAI,CAAC,IAAI,IAAI;AACX,QAAI,IAAI,OAAO,SAAS,oBAAoB,CAAC,aAAa;AACxD,MAAK,aAAQ,6BAA6B,IAAI,OAAO,OAAO,EAAE;AAC9D;AAAA,IACF;AACA,IAAK,eAAU,GAAG,IAAI,OAAO,QAAQ,OAAO,KAAK,IAAI,OAAO,WAAW,SAAS,EAAE;AAClF;AAAA,EACF;AACA,EAAK,UAAK,aAAa,KAAK,UAAU,IAAI,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC,EAAE;AACjE;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,EAAK,eAAW,IAAc,OAAO;AACvC,CAAC;","names":[]}
@@ -0,0 +1,101 @@
1
+ // src/spec-drift.ts
2
+ import { execFileSync } from "child_process";
3
+ import { existsSync, mkdirSync, chmodSync, writeFileSync, mkdtempSync, rmSync } from "fs";
4
+ import { homedir } from "os";
5
+ import { join } from "path";
6
+ import { createHash } from "crypto";
7
+ var OASDIFF_VERSION = process.env.OASDIFF_VERSION ?? "1.10.18";
8
+ var PLATFORM_MAP = {
9
+ "linux-x64": "linux-amd64",
10
+ "linux-arm64": "linux-arm64",
11
+ "darwin-x64": "darwin-amd64",
12
+ "darwin-arm64": "darwin-arm64",
13
+ "win32-x64": "windows-amd64"
14
+ };
15
+ function getOasdiffUrl() {
16
+ const platformKey = `${process.platform}-${process.arch}`;
17
+ const platform = PLATFORM_MAP[platformKey];
18
+ if (!platform) throw new Error(`Unsupported platform for oasdiff: ${platformKey}`);
19
+ const ext = process.platform === "win32" ? ".exe" : "";
20
+ return `https://github.com/Tufin/oasdiff/releases/download/v${OASDIFF_VERSION}/oasdiff_${OASDIFF_VERSION}_${platform}${ext}.tar.gz`;
21
+ }
22
+ async function downloadOasdiff() {
23
+ const cacheDir = join(homedir(), ".mushi", "tools");
24
+ mkdirSync(cacheDir, { recursive: true });
25
+ const ext = process.platform === "win32" ? ".exe" : "";
26
+ const binPath = join(cacheDir, `oasdiff-${OASDIFF_VERSION}${ext}`);
27
+ if (existsSync(binPath)) return binPath;
28
+ const url = getOasdiffUrl();
29
+ const res = await fetch(url);
30
+ if (!res.ok) throw new Error(`Failed to download oasdiff: HTTP ${res.status} from ${url}`);
31
+ const buf = Buffer.from(await res.arrayBuffer());
32
+ const maxBytes = 64 * 1024 * 1024;
33
+ if (buf.length > maxBytes) {
34
+ throw new Error(`oasdiff download too large (${buf.length} bytes) \u2014 aborting`);
35
+ }
36
+ const tgzPath = join(cacheDir, `oasdiff-${createHash("md5").update(url).digest("hex")}.tar.gz`);
37
+ writeFileSync(tgzPath, buf);
38
+ const extractDir = mkdtempSync(join(cacheDir, "oasdiff-extract-"));
39
+ try {
40
+ execFileSync("tar", ["-xzf", tgzPath, "-C", extractDir]);
41
+ const { readdirSync, copyFileSync } = await import("fs");
42
+ const files = readdirSync(extractDir);
43
+ const binName = process.platform === "win32" ? "oasdiff.exe" : "oasdiff";
44
+ const found = files.find((f) => f === binName || f.startsWith("oasdiff"));
45
+ if (!found) throw new Error(`oasdiff binary not found in archive. Files: ${files.join(", ")}`);
46
+ copyFileSync(join(extractDir, found), binPath);
47
+ if (process.platform !== "win32") chmodSync(binPath, 493);
48
+ } finally {
49
+ rmSync(extractDir, { recursive: true, force: true });
50
+ rmSync(tgzPath, { force: true });
51
+ }
52
+ return binPath;
53
+ }
54
+ async function runSpecDrift(opts) {
55
+ let binPath;
56
+ try {
57
+ binPath = await downloadOasdiff();
58
+ } catch (err) {
59
+ throw new Error(`oasdiff download failed: ${err instanceof Error ? err.message : String(err)}`);
60
+ }
61
+ let output = "";
62
+ try {
63
+ output = execFileSync(binPath, ["breaking", opts.baseSpec, opts.headSpec, "--format", "json"], {
64
+ encoding: "utf-8",
65
+ timeout: 3e4
66
+ // oasdiff exits 1 when breaking changes are found — that's expected.
67
+ // We catch the error and still parse stdout.
68
+ });
69
+ } catch (err) {
70
+ const execErr = err;
71
+ output = execErr.stdout ?? "";
72
+ if (!output && execErr.status !== 1) {
73
+ throw new Error(
74
+ `oasdiff failed: ${execErr.stderr ?? String(err)}`
75
+ );
76
+ }
77
+ }
78
+ if (!output.trim()) return [];
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(output);
82
+ } catch {
83
+ return [{ severity: "warn", rule_id: "spec-drift-parse-error", message: output.slice(0, 500) }];
84
+ }
85
+ const items = Array.isArray(parsed) ? parsed : [];
86
+ return items.map((item) => {
87
+ const level = String(item.level ?? "error").toLowerCase();
88
+ const severity = level === "error" || level === "breaking" ? "error" : level === "warn" || level === "warning" ? "warn" : "info";
89
+ return {
90
+ severity,
91
+ rule_id: String(item.id ?? "spec-drift"),
92
+ message: String(item.text ?? item.message ?? JSON.stringify(item)),
93
+ path: item.path ? String(item.path) : void 0,
94
+ method: item.operation ? String(item.operation) : void 0
95
+ };
96
+ });
97
+ }
98
+ export {
99
+ runSpecDrift
100
+ };
101
+ //# sourceMappingURL=spec-drift-SGNI6UBK.js.map
@@ -0,0 +1 @@
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/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 mkdirSync(cacheDir, { recursive: true })\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,EAAE;AACjF,QAAM,MAAM,QAAQ,aAAa,UAAU,SAAS;AACpD,SACE,uDAAuD,eAAe,YAC3D,eAAe,IAAI,QAAQ,GAAG,GAAG;AAEhD;AAEA,eAAe,kBAAmC;AAChD,QAAM,WAAW,KAAK,QAAQ,GAAG,UAAU,OAAO;AAClD,YAAU,UAAU,EAAE,WAAW,KAAK,CAAC;AACvC,QAAM,MAAM,QAAQ,aAAa,UAAU,SAAS;AACpD,QAAM,UAAU,KAAK,UAAU,WAAW,eAAe,GAAG,GAAG,EAAE;AACjE,MAAI,WAAW,OAAO,EAAG,QAAO;AAEhC,QAAM,MAAM,cAA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ushi-mushi/mcp-ci",
3
- "version": "0.4.1",
3
+ "version": "0.6.0",
4
4
  "description": "GitHub Action entrypoint for running Mushi Mushi MCP tools in CI — trigger judge, dispatch fixes, gate merges on classification coverage.",
5
5
  "license": "MIT",
6
6
  "type": "module",