@mushi-mushi/mcp-ci 0.2.2 → 0.4.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.
@@ -40,7 +40,7 @@ Examples of unacceptable behavior:
40
40
  ## Enforcement
41
41
 
42
42
  Instances of abusive, harassing, or otherwise unacceptable behavior may be
43
- reported to the project team at **security@mushimushi.dev**.
43
+ reported to the project team at **kensaurus@gmail.com**.
44
44
 
45
45
  All complaints will be reviewed and investigated promptly and fairly.
46
46
 
package/CONTRIBUTING.md CHANGED
@@ -33,6 +33,10 @@ pnpm lint # ESLint
33
33
  pnpm format # Prettier
34
34
  ```
35
35
 
36
+ Ad-hoc screenshots captured during UI reviews can live temporarily at the repo
37
+ root, but root-level `*.png` files are intentionally ignored. Canonical
38
+ screenshots that should be versioned belong under `docs/screenshots/`.
39
+
36
40
  ### Working on a single package
37
41
 
38
42
  ```bash
package/README.md CHANGED
@@ -13,13 +13,30 @@ queries against your report corpus — all without leaving your workflow.
13
13
 
14
14
  ## Commands
15
15
 
16
+ ### Triage & fix loop
17
+
16
18
  | `command` | What it does | Required inputs |
17
19
  | ------------------ | ---------------------------------------------------------------------------- | ------------------------------------- |
18
20
  | `check-coverage` | Fails if `classified / total` is below `min-coverage`. Default threshold `0.8`. | — |
19
21
  | `trigger-judge` | Runs the classification pipeline on up to 50 unclassified reports. | — |
20
- | `dispatch-fix` | Queues an agentic fix attempt for a specific report. | `report-id` |
22
+ | `dispatch-fix` | Queues an agentic fix attempt for a specific report. Optionally accepts `inventory-action-node-id` to pin the fix to a specific inventory `Action` so the worker threads its `expected_outcome` contract into the LLM prompt and runs a targeted post-PR synthetic probe (whitepaper §2.10). | `report-id` (+ optional `inventory-action-node-id`) |
21
23
  | `query` | Runs a natural-language query and prints the result. | `question` |
22
24
 
25
+ ### Mushi v2 — bidirectional inventory & gates
26
+
27
+ | `command` | What it does | Required inputs |
28
+ | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
29
+ | `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`) |
30
+ | `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-*`) |
31
+
32
+ ### Mushi v2.1 — passive discovery & proposal flow
33
+
34
+ | `command` | What it does | Required inputs |
35
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------- |
36
+ | `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`. | — |
37
+ | `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. | — |
38
+ | `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 |
39
+
23
40
  ## Quick start — gate merges on triage coverage
24
41
 
25
42
  ```yaml
@@ -65,25 +82,102 @@ jobs:
65
82
  report-id: ${{ github.event.issue.body }}
66
83
  ```
67
84
 
85
+ ## Quick start — Mushi v2 gates on every PR
86
+
87
+ ```yaml
88
+ # .github/workflows/mushi-gates.yml
89
+ name: Mushi v2 Gates
90
+ on: [pull_request]
91
+
92
+ jobs:
93
+ gates:
94
+ runs-on: ubuntu-latest
95
+ steps:
96
+ - uses: actions/checkout@v4
97
+
98
+ # Refresh the crawler cookie so Gate 4 can hit auth-gated routes.
99
+ - uses: mushi-mushi/mushi-mushi/packages/mcp-ci@v1
100
+ with:
101
+ api-key: ${{ secrets.MUSHI_API_KEY }}
102
+ project-id: ${{ secrets.MUSHI_PROJECT_ID }}
103
+ command: auth-bootstrap
104
+ env:
105
+ TEST_USER_EMAIL: ${{ secrets.MUSHI_TEST_USER_EMAIL }}
106
+ TEST_USER_PASSWORD: ${{ secrets.MUSHI_TEST_USER_PASSWORD }}
107
+
108
+ # Feed Gate 3 (api_contract) the current commit's API surface.
109
+ - uses: mushi-mushi/mushi-mushi/packages/mcp-ci@v1
110
+ with:
111
+ api-key: ${{ secrets.MUSHI_API_KEY }}
112
+ project-id: ${{ secrets.MUSHI_PROJECT_ID }}
113
+ command: discover-api
114
+
115
+ # Run Gates 1–5 server-side and gate the PR on the composite status.
116
+ - uses: mushi-mushi/mushi-mushi/packages/mcp-ci@v1
117
+ with:
118
+ api-key: ${{ secrets.MUSHI_API_KEY }}
119
+ project-id: ${{ secrets.MUSHI_PROJECT_ID }}
120
+ command: gates
121
+ commit-sha: ${{ github.event.pull_request.head.sha }}
122
+ pr-number: ${{ github.event.pull_request.number }}
123
+ ```
124
+
125
+ ## Quick start — Mushi v2.1 weekly proposal job
126
+
127
+ ```yaml
128
+ on:
129
+ schedule:
130
+ - cron: '0 9 * * 1' # every Monday 09:00 UTC
131
+
132
+ jobs:
133
+ propose:
134
+ runs-on: ubuntu-latest
135
+ steps:
136
+ - id: status
137
+ uses: mushi-mushi/mushi-mushi/packages/mcp-ci@v1
138
+ with:
139
+ api-key: ${{ secrets.MUSHI_API_KEY }}
140
+ project-id: ${{ secrets.MUSHI_PROJECT_ID }}
141
+ command: discovery-status
142
+
143
+ - if: steps.status.outputs.ready_to_propose == 'true'
144
+ uses: mushi-mushi/mushi-mushi/packages/mcp-ci@v1
145
+ with:
146
+ api-key: ${{ secrets.MUSHI_API_KEY }}
147
+ project-id: ${{ secrets.MUSHI_PROJECT_ID }}
148
+ command: propose
149
+ ```
150
+
68
151
  ## Inputs
69
152
 
70
- | Input | Required | Default | Description |
71
- | --------------- | --------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------- |
72
- | `api-key` | yes | — | Mushi project API key. Store as a repo secret. |
73
- | `project-id` | yes | — | Mushi project UUID. |
74
- | `command` | yes | — | One of the commands above. |
75
- | `api-endpoint` | no | Hosted Supabase functions URL | Override for self-hosted deployments. |
76
- | `report-id` | when `dispatch-fix` | — | Report UUID to dispatch a fix for. |
77
- | `question` | when `query` | — | Natural-language query text. |
78
- | `min-coverage` | no | `0.8` | For `check-coverage`: minimum classified ratio. |
79
- | `fail-on-quota` | no | `true` | Fail the step on `QUOTA_EXCEEDED`. Set `false` to warn and continue. |
153
+ | Input | Required | Default | Description |
154
+ | ------------------- | --------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
155
+ | `api-key` | yes | — | Mushi project API key. Store as a repo secret. |
156
+ | `project-id` | yes | — | Mushi project UUID. |
157
+ | `command` | yes | — | One of the commands above. |
158
+ | `api-endpoint` | no | Hosted Supabase functions URL | Override for self-hosted deployments. |
159
+ | `report-id` | when `dispatch-fix` | — | Report UUID to dispatch a fix for. |
160
+ | `question` | when `query` | — | Natural-language query text. |
161
+ | `min-coverage` | no | `0.8` | For `check-coverage`: minimum classified ratio. |
162
+ | `fail-on-quota` | no | `true` | Fail the step on `QUOTA_EXCEEDED`. Set `false` to warn and continue. |
163
+ | `commit-sha` | when `gates` | `GITHUB_SHA` | Commit the gates run against. Surfaces in the admin `/inventory ▸ Gates` view. |
164
+ | `pr-number` | when `gates` | — | Pull-request number used to scope `gate_findings` for the admin UI. |
165
+ | `gates` | when `gates` | `'all'` | Comma-separated subset (`dead_handler,mock_leak,api_contract,crawl,status_claim`). |
166
+ | `repo-root` | when `discover-api` | `GITHUB_WORKSPACE` | Directory to walk for Next.js route handlers + OpenAPI files. |
167
+ | `openapi-file` | when `discover-api` | `<repo-root>/openapi.yaml` | Explicit OpenAPI file path. |
168
+ | `supabase-url` | when `discover-api` | — | Supabase project URL to introspect via `/rest/v1/` for `db_deps`. |
169
+ | `supabase-anon-key` | when `discover-api` | — | Supabase anon key for the introspection. |
80
170
 
81
171
  ## Outputs
82
172
 
83
- | Output | Description |
84
- | ---------- | -------------------------------------------------------- |
85
- | `result` | Raw JSON envelope returned by the Mushi API. |
86
- | `coverage` | For `check-coverage`: observed classified ratio (0–1). |
173
+ | Output | Description |
174
+ | ------------------- | -------------------------------------------------------------------------------------- |
175
+ | `result` | Raw JSON envelope returned by the Mushi API. |
176
+ | `coverage` | For `check-coverage`: observed classified ratio (0–1). |
177
+ | `ready_to_propose` | For `discovery-status`: `'true'` once the project has a defensible-sized SDK sample. |
178
+ | `total_events` | For `discovery-status`: total `discovery_events` rows aggregated server-side. |
179
+ | `route_count` | For `discovery-status`: distinct route templates observed in the last 30 days. |
180
+ | `proposal_id` | For `propose`: UUID of the new `inventory_proposals` row, ready to deep-link into the admin. |
87
181
 
88
182
  ## License
89
183
 
package/SECURITY.md CHANGED
@@ -19,15 +19,59 @@ If you discover a security vulnerability, please report it responsibly.
19
19
 
20
20
  **Do NOT open a public GitHub issue.**
21
21
 
22
- Instead, email: **security@mushimushi.dev**
22
+ Use either channel below:
23
+
24
+ 1. **GitHub Private Vulnerability Reporting** — strongly preferred.
25
+ <https://github.com/kensaurus/mushi-mushi/security/advisories/new>
26
+ Routes the report into a private advisory with built-in CVE issuance,
27
+ patch coordination, and contributor-credit workflow.
28
+ 2. **Email** — `kensaurus@gmail.com`, subject prefix `[mushi-security]`.
29
+ PGP welcome but not required.
23
30
 
24
31
  Include:
25
32
  - Description of the vulnerability
26
- - Steps to reproduce
27
- - Impact assessment
33
+ - Steps to reproduce (smallest reproducer wins)
34
+ - Impact assessment (what an attacker gains)
28
35
  - Suggested fix (if any)
36
+ - Whether you want public credit (and how to spell your name)
37
+
38
+ ### Coordinated-disclosure timeline
39
+
40
+ | Day | Action |
41
+ |-----|--------|
42
+ | 0 | Report received |
43
+ | ≤ 2 | Acknowledgment + assigned a tracking ID |
44
+ | ≤ 7 | Triage complete: severity assigned (CVSS 3.1) and target patch date communicated |
45
+ | ≤ 30 | Patch released for critical / high (CVSS ≥ 7.0); ≤ 60 days for medium; best-effort for low |
46
+ | Patch + 7 | Public advisory + CVE published; reporter credited unless they declined |
47
+ | Patch + 90 | Embargo expires regardless; if upstream is unresponsive, the reporter is free to publish |
48
+
49
+ ### Safe harbor
50
+
51
+ Good-faith security research on Mushi Mushi is welcome. If you stay
52
+ within the rules below, we will not pursue legal action, will not ask
53
+ your hosting provider to take you offline, and will publicly credit your
54
+ work:
55
+
56
+ - Test only against your own self-hosted instance, the public demo at
57
+ <https://kensaur.us/mushi-mushi/admin/>, or accounts you own.
58
+ - Do not access, exfiltrate, or modify data belonging to other users.
59
+ - Do not run automated scanning that affects availability for others
60
+ (rate-limit your tooling, exclude `/health`).
61
+ - Disclose privately first (channels above); do not publish before the
62
+ embargo above expires.
63
+ - Do not intentionally exploit a finding to escalate beyond proving it
64
+ exists.
29
65
 
30
- We will acknowledge receipt within 48 hours and aim to release a patch within 7 days for critical issues.
66
+ If a finding requires touching production data to confirm, **stop and
67
+ ask first** — describe what you'd need to do and we'll spin up a sandbox.
68
+
69
+ ### Hall of fame
70
+
71
+ Researchers who report a confirmed vulnerability are credited in the
72
+ release notes for the patched version and added to
73
+ [`docs/SECURITY_HALL_OF_FAME.md`](./docs/SECURITY_HALL_OF_FAME.md) (with
74
+ permission).
31
75
 
32
76
  ## Scope
33
77
 
@@ -48,3 +92,196 @@ We will acknowledge receipt within 48 hours and aim to release a patch within 7
48
92
  - **Rotate API keys** regularly via the admin console
49
93
  - **Enable SSO** for team projects (Enterprise tier)
50
94
  - **Review audit logs** periodically for suspicious activity
95
+ - **Verify SDK integrity** with `npm audit signatures` after install
96
+ - **Set `Content-Security-Policy`** on any page embedding the Mushi widget;
97
+ the widget itself ships with `script-src 'self'` and does not load
98
+ remote scripts.
99
+
100
+ ## Threat model
101
+
102
+ What we treat as in-scope attacker capabilities, and what we don't.
103
+
104
+ | Capability | In scope | Notes |
105
+ |-----------|----------|-------|
106
+ | Unauthenticated network attacker hitting public endpoints | ✅ | Rate-limit + HMAC + replay protection on every webhook endpoint (`packages/server/supabase/functions/_shared/webhook-middleware.ts`). |
107
+ | Authenticated user trying to read another tenant's data | ✅ | Postgres RLS on every `public.*` table; advisor lints reviewed monthly. |
108
+ | Authenticated user trying to escalate to super-admin | ✅ | Role lives in `auth.users.raw_app_meta_data.role`; cannot be self-edited via PostgREST. |
109
+ | Compromised dependency (npm supply-chain attack) | ✅ | 7-day cooldown + provenance + Harden-Runner + pinned SHAs (see "Supply-chain hardening" below). |
110
+ | Stolen API key | ✅ | Per-key scopes (`api_key_has_scope`), revocation via admin console, audit log of every use. |
111
+ | User pasting a Stripe / OpenAI / GitHub PAT into a bug report | ✅ | PII scrubber redacts ~15 vendor token formats client-side before the report leaves the device. Mirrors `packages/core/src/pii-scrubber.ts` across iOS, Android, Flutter, React Native. |
112
+ | Stolen end-user device with the SDK installed | ⚠️ partial | Offline queue is AsyncStorage / Keychain / SharedPreferences — no app-level encryption beyond the OS default. Reports waiting to flush are vulnerable to a forensic attacker. |
113
+ | Compromised Supabase service-role key | ❌ | Treated as a tier-0 incident; would require key rotation and audit-log forensics. Not defendable in software. |
114
+ | Compromise of `kensaurus@gmail.com` | ❌ | Treated as a project-fork event; downstream consumers should pin to the last known-good version and follow the new release channel. |
115
+ | Physical / OS-level attacker on an end-user device | ❌ | Out of scope. |
116
+ | Malicious fork using the Mushi name to ship malware | ❌ (technical) ✅ (legal) | The MIT/BSL grant lets the fork exist; the trademark policy (`TRADEMARK.md`) makes shipping it under the Mushi name an infringement we will pursue. |
117
+
118
+ ## Data handling and PII
119
+
120
+ ### What the SDK collects by default
121
+
122
+ | Field | Scope | PII risk |
123
+ |-------|-------|----------|
124
+ | URL / route the user was on | Always | Low — strip query strings if your routes encode user IDs. |
125
+ | Browser / OS / device | Always | None |
126
+ | Console errors (last 50) | Opt-in via `captureConsole: true` | Medium — can include user data your code logs. |
127
+ | Network failures (URL + status) | Opt-in via `captureNetwork: true` | Medium — query params logged as-is unless you redact in-app. |
128
+ | User id / email / role | Only if you call `setUser()` | High — only set what you need; we do not auto-discover. |
129
+ | Session replay frames | Off by default | High — handled by the masking layer; passwords / cards / opted-out elements never leave the page. |
130
+ | Free-text bug description | Always | Medium — passed through the PII scrubber (see below). |
131
+
132
+ ### What the PII scrubber redacts before send
133
+
134
+ Implemented identically across `@mushi-mushi/core`, the iOS, Android,
135
+ Flutter, and React Native SDKs. Defaults are below — every category can
136
+ be toggled off, but `secretTokens` is on by default and we recommend
137
+ keeping it that way.
138
+
139
+ | Category | Default | Patterns |
140
+ |----------|---------|----------|
141
+ | `ssns` | on | `123-45-6789` |
142
+ | `creditCards` | on | 12–19 digit Luhn-shaped sequences with optional separators |
143
+ | `secretTokens` | on | AWS access key (`AKIA…` / `ASIA…`), AWS secret (`aws_secret_access_key=…`), Stripe (`sk_live_…`, `sk_test_…`, `rk_…`, `pk_…`), Slack (`xox[abpor]-…`), GitHub PAT (`ghp_…`, `github_pat_…`), OpenAI (`sk-…`, `sk-proj-…`), Anthropic (`sk-ant-…`), Google API (`AIza…`), JWT (`eyJ…` 3-segment) |
144
+ | `emails` | on | RFC-5322 lite |
145
+ | `phones` | on | E.164 with optional country code |
146
+ | `ipAddresses` | off | IPv4 (off because internal IPs are usually not PII and noise hurts triage) |
147
+ | `ipv6` | off | Same |
148
+
149
+ The fields scrubbed are:
150
+
151
+ - `description` — primary free-text field of every bug report
152
+ - `summary` — short summary, in the same composer
153
+ - `breadcrumbs[].message` — auto-captured user-action trail (clicks, route changes, console messages)
154
+
155
+ Structured fields you set explicitly (`metadata.userEmail`,
156
+ `metadata.userId`, etc.) are intentionally **not** scrubbed — those are
157
+ opt-in attribution data, and silently rewriting them would break
158
+ support workflows.
159
+
160
+ ### Where data lives
161
+
162
+ - **Reports & telemetry** — Supabase Postgres in the `us-west-1` region.
163
+ - **Session replays** — Supabase Storage, same region. Lifecycle policy
164
+ trims replays older than 30 days unless explicitly retained from the
165
+ admin console.
166
+ - **Inbound webhook bodies** — only a SHA-256 hash + `delivery_id` of
167
+ the body is persisted (`webhook_audit_log`). The full body is
168
+ processed in memory and discarded.
169
+ - **Outbound integrations** (Slack, Jira, …) — Mushi is a sender only;
170
+ the receiving system's retention applies.
171
+
172
+ ### Encryption
173
+
174
+ | Surface | At rest | In transit |
175
+ |---------|---------|------------|
176
+ | Postgres (Supabase) | AES-256 (Supabase default) | TLS 1.2+ |
177
+ | Supabase Storage (replays) | AES-256 | TLS 1.2+ |
178
+ | Edge Function ↔ Postgres | — | TLS via the Supavisor pooler |
179
+ | SDK ↔ ingest endpoint | — | TLS 1.2+ enforced; HSTS preload on `kensaur.us` |
180
+ | Inbound webhooks | — | TLS terminated at CloudFront / Supabase edge |
181
+ | Audit log integrity | append-only by RLS; no in-row signing | — |
182
+
183
+ ### Cryptographic primitives
184
+
185
+ | Use | Algorithm | Implementation |
186
+ |-----|-----------|---------------|
187
+ | Webhook HMAC verification (Sentry, GitHub, Datadog, Honeycomb, Grafana, Bugsnag, Rollbar, Crashlytics) | HMAC-SHA256, constant-time compare | Web Crypto in Deno; `crypto.subtle.timingSafeEqual` analogue |
188
+ | AWS SNS subscription confirmation | RSA-SHA1 / RSA-SHA256 | Deno `crypto.subtle.verify` with the cert from `SigningCertURL` (URL allow-listed to `*.sns.*.amazonaws.com`) |
189
+ | Opsgenie JWT shared-token | HS256 with `aud` claim verification | `jose` (Deno-compatible) |
190
+ | API-key hashing (database) | SHA-256 prefix + bcrypt secret half | `pgcrypto` |
191
+ | Provenance attestations (npm) | Sigstore (Fulcio + Rekor) | `npm publish --provenance` |
192
+
193
+ We deliberately do not roll our own crypto. If you find an algorithm or
194
+ library above that has been deprecated, please file a security advisory.
195
+
196
+ ### Operator security checklist
197
+
198
+ When you provision a new self-hosted Mushi instance:
199
+
200
+ - [ ] Set `auth_leaked_password_protection = true` in Supabase Auth
201
+ (HaveIBeenPwned blocklist; flagged as `auth_leaked_password_protection`
202
+ in the security advisor).
203
+ - [ ] Enable at least two MFA factors in Supabase Auth (`auth_insufficient_mfa_options`).
204
+ - [ ] Rotate the service-role key on day 1, then quarterly.
205
+ - [ ] Restrict Postgres direct connections to your CI / migration runners
206
+ via Supabase network restrictions.
207
+ - [ ] Run `pnpm dlx supabase advisors --project-ref <ref>` after every
208
+ migration; aim for zero ERROR-level findings.
209
+ - [ ] Configure a Supabase log drain to your SIEM if you are subject to
210
+ SOC 2 / ISO 27001.
211
+ - [ ] Set CSP `frame-ancestors` on the host page if you embed the Mushi
212
+ widget (the widget is iframe-friendly but does not enforce
213
+ framing constraints itself).
214
+
215
+ ## Supply-chain hardening (how this package is protected)
216
+
217
+ Mushi Mushi is built and published with the controls below. Consumers can
218
+ verify each control independently — the goal is to make tampering both
219
+ difficult and detectable.
220
+
221
+ ### Publish-time controls
222
+
223
+ | Control | What it does | How to verify |
224
+ |---|---|---|
225
+ | **npm Trusted Publisher (OIDC)** | Every release is published from `.github/workflows/release.yml` on `master` using a short-lived OIDC token. Long-lived `NPM_TOKEN` is not used for publishing. | `npm view @mushi-mushi/<pkg> --json` shows `"trustedPublisher"` populated for recent versions. |
226
+ | **npm provenance attestations** | Every published tarball ships a [Sigstore provenance attestation](https://docs.npmjs.com/generating-provenance-statements) cryptographically linking the tarball to the exact GitHub Actions run that built it. | `npm audit signatures` (run inside any project that depends on `@mushi-mushi/*`) reports `verified registry signatures` and `verified attestations`. The npm web UI shows a "Built and signed on GitHub Actions" badge on each version. |
227
+ | **Pre-publish workspace-protocol guard** | Aborts the publish if `workspace:*` ranges leaked into the tarball (the bug class behind the v0.1.0 incident). | `scripts/check-workspace-protocol.mjs` runs before `changeset publish` in `pnpm release`. |
228
+ | **Post-publish tarball verification** | Re-downloads each just-published tarball and asserts it doesn't contain `workspace:*`. | See the "Verify published tarballs do not contain workspace:*" step in `release.yml`. |
229
+ | **Post-publish `npm audit signatures`** | Re-installs each published version and validates registry signatures + provenance against npm's transparency log. | See the "Audit signatures of installed dependencies" step in `release.yml`. |
230
+
231
+ ### Build-time controls
232
+
233
+ | Control | What it does |
234
+ |---|---|
235
+ | **All third-party GitHub Actions pinned to commit SHAs** | Every `uses:` in every workflow under `.github/workflows/` is pinned to a 40-character commit SHA with a version comment. Floating tags (`@v4`, `@main`) are mutable and were the entry point for the [tj-actions/changed-files compromise (CVE-2025-30066)](https://github.com/step-security/harden-runner#detected-attacks). |
236
+ | **Harden-Runner egress audit on every job** | [step-security/harden-runner](https://github.com/step-security/harden-runner) records every outbound network call, file write, and process spawn on every CI runner. Detects exfiltration attempts in real time — caught the tj-actions, NX, Shai-Hulud, and Axios attacks for other projects. |
237
+ | **OpenSSF Scorecard** | Weekly + on-push score of the repo's security posture (Pinned-Dependencies, Token-Permissions, Branch-Protection, Code-Review, Dangerous-Workflow, Maintained, SAST, Security-Policy, Signed-Releases, Vulnerabilities). Public results at [scorecard.dev](https://scorecard.dev/viewer/?uri=github.com/kensaurus/mushi-mushi). |
238
+ | **Server-side secret scan (Gitleaks)** | Every PR and every push to `master` runs Gitleaks across the diff / full tree. Belt-and-suspenders to the local pre-commit hook (`scripts/check-no-secrets.mjs`) which can be bypassed with `--no-verify`. |
239
+ | **Local pre-commit secret scanner** | `scripts/check-no-secrets.mjs` runs as a git hook installed by `pnpm install`, blocking commits that look like AWS / Stripe / GitHub / Anthropic / OpenAI / Slack / Supabase keys. |
240
+ | **CodeQL `security-extended`** | Semantic analysis of every TypeScript / JavaScript change finds injection sinks, taint flows, prototype pollution, etc. Runs on every PR, push, and weekly cron. |
241
+ | **Dependency review on PRs** | `actions/dependency-review-action` blocks the PR if it adds or upgrades a dep with a high-severity advisory. |
242
+ | **`pnpm audit --prod --audit-level=high`** | Weekly cron + every push to `master` fails on any high/critical advisory in production deps. |
243
+
244
+ ### Install-time controls (protect the project's own dependency graph)
245
+
246
+ | Control | What it does |
247
+ |---|---|
248
+ | **`min-release-age` (npm) / `minimumReleaseAge` (pnpm)** | Refuses to resolve any dep version published less than 7 days ago. The Axios 1.14.1 / 0.30.4 compromise (Mar 2026) was detected and removed within ~5 hours; Shai-Hulud (Sep 2025) within <12 hours — a 7-day cooldown blocks every publicly-disclosed 2025–2026 npm supply-chain attack outright. |
249
+ | **`strictDepBuilds: true`** | Fails the install if any transitive dep tries to run a `postinstall` hook the workspace hasn't pre-approved (`onlyBuiltDependencies` allow-list). |
250
+ | **`blockExoticSubdeps: true`** | Refuses to resolve transitive deps from git URLs, tarball URLs, or filesystem paths — anything that didn't go through the npm registry's signing pipeline. |
251
+ | **Dependabot with cooldown** | Routine dep upgrades wait 7 days; security advisories bypass the cooldown automatically. |
252
+ | **`pnpm audit signatures`-style verification** | The release pipeline re-runs `npm audit signatures` against each published version after the publish, with `--audit-level=high`. |
253
+
254
+ ### Verifying a Mushi Mushi tarball before installing
255
+
256
+ ```bash
257
+ # 1. Check provenance attestation matches the public GitHub Actions run
258
+ npm view @mushi-mushi/core --json | jq '.signatures, .dist'
259
+
260
+ # 2. Inside your own project after install
261
+ npm audit signatures
262
+
263
+ # Expected: every @mushi-mushi/* package reports
264
+ # "verified registry signature"
265
+ # "verified attestation"
266
+ ```
267
+
268
+ If `npm audit signatures` reports any `@mushi-mushi/*` package as unsigned
269
+ or with an invalid attestation, **stop the install and email
270
+ kensaurus@gmail.com immediately** — that's the symptom of either a
271
+ registry compromise or a tampered tarball, and we want to know within
272
+ hours, not days.
273
+
274
+ ### What this hardening does NOT cover
275
+
276
+ - **Self-hosted deployments.** Once the package is on your machine, the
277
+ security of your `node_modules`, build pipeline, and runtime is your
278
+ responsibility. The hardening above protects the path from source to
279
+ registry; it cannot protect a tarball after it has been downloaded.
280
+ - **Compromise of `kensaurus@gmail.com`.** A trusted-publisher rule still
281
+ lets the legitimate maintainer publish from any branch they push. If
282
+ you find yourself with admin access to this repo, treat
283
+ `.github/workflows/release.yml` as a tier-0 secret.
284
+ - **First-party bugs.** Provenance proves *who* built the tarball and
285
+ *when*; it does not prove the code is bug-free. CodeQL + tests cover
286
+ that surface, but no automation catches everything — please continue
287
+ to report issues to the address above.
package/action.yml CHANGED
@@ -17,11 +17,14 @@ 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'
20
+ description: 'Which MCP tool to run: trigger-judge | dispatch-fix | check-coverage | query | gates | discover-api'
21
21
  required: true
22
22
  report-id:
23
23
  description: 'Report UUID — required for dispatch-fix.'
24
24
  required: false
25
+ inventory-action-node-id:
26
+ description: 'For command=dispatch-fix: optional spec-traceability anchor (whitepaper §2.10). When provided, the worker skips the graph walk to recover the inventory Action and includes its expected_outcome contract verbatim in the LLM prompt.'
27
+ required: false
25
28
  question:
26
29
  description: 'NL query text — required for command=query.'
27
30
  required: false
@@ -33,6 +36,28 @@ inputs:
33
36
  description: 'Whether to fail the action when Mushi returns 402 QUOTA_EXCEEDED.'
34
37
  required: false
35
38
  default: 'true'
39
+ commit-sha:
40
+ description: 'For command=gates: commit SHA the gates run against. Defaults to GITHUB_SHA.'
41
+ required: false
42
+ pr-number:
43
+ description: 'For command=gates: pull-request number, used to scope findings on the admin UI.'
44
+ required: false
45
+ gates:
46
+ description: 'For command=gates: comma-separated subset to run. Defaults to "all".'
47
+ required: false
48
+ default: 'all'
49
+ repo-root:
50
+ description: 'For command=discover-api: directory to walk for Next.js route handlers + OpenAPI files. Defaults to GitHub workspace.'
51
+ required: false
52
+ openapi-file:
53
+ description: 'For command=discover-api: explicit OpenAPI file path. Defaults to <repo-root>/openapi.yaml.'
54
+ required: false
55
+ supabase-url:
56
+ description: 'For command=discover-api: Supabase project URL to introspect via /rest/v1/.'
57
+ required: false
58
+ supabase-anon-key:
59
+ description: 'For command=discover-api: Supabase anon key for introspection.'
60
+ required: false
36
61
 
37
62
  outputs:
38
63
  result:
@@ -0,0 +1,130 @@
1
+ // src/api-contract.ts
2
+ import { promises as fs } from "fs";
3
+ import path from "path";
4
+ var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
5
+ async function walkNextAppRouter(rootDir) {
6
+ const out = /* @__PURE__ */ new Set();
7
+ const appDir = path.join(rootDir, "app");
8
+ try {
9
+ await walk(appDir, async (filePath) => {
10
+ const base = path.basename(filePath);
11
+ if (!/^route\.(ts|tsx|js|jsx)$/.test(base)) return;
12
+ const content = await fs.readFile(filePath, "utf-8").catch(() => "");
13
+ const relative = path.relative(appDir, path.dirname(filePath)).split(path.sep).join("/");
14
+ const segments = relative === "" ? [] : relative.split("/").filter((seg) => {
15
+ if (!seg) return false;
16
+ if (seg.startsWith("(") && seg.endsWith(")")) return false;
17
+ if (seg.startsWith("@")) return false;
18
+ if (seg.startsWith("_")) return false;
19
+ return true;
20
+ });
21
+ const routePath = "/" + segments.join("/").replace(/\[(\.{3})?([^\]]+)\]/g, "{$2}");
22
+ for (const method of HTTP_METHODS) {
23
+ const re = new RegExp(`export\\s+(?:async\\s+)?function\\s+${method}\\b`);
24
+ if (re.test(content)) out.add(`${method}:${routePath || "/"}`);
25
+ }
26
+ });
27
+ } catch {
28
+ }
29
+ return Array.from(out);
30
+ }
31
+ async function parseOpenApiFile(filePath) {
32
+ const out = [];
33
+ try {
34
+ const content = await fs.readFile(filePath, "utf-8");
35
+ let doc;
36
+ if (filePath.endsWith(".json")) {
37
+ doc = JSON.parse(content);
38
+ } else {
39
+ try {
40
+ const yaml = await import("yaml");
41
+ doc = yaml.parse(content);
42
+ } catch {
43
+ return [];
44
+ }
45
+ }
46
+ const paths = doc.paths ?? {};
47
+ for (const [p, ops] of Object.entries(paths)) {
48
+ for (const m of Object.keys(ops)) {
49
+ const upper = m.toUpperCase();
50
+ if (HTTP_METHODS.includes(upper)) {
51
+ out.push(`${upper}:${p}`);
52
+ }
53
+ }
54
+ }
55
+ } catch {
56
+ return [];
57
+ }
58
+ return out;
59
+ }
60
+ async function fetchSupabaseOpenApi(supabaseUrl, apiKey) {
61
+ try {
62
+ const res = await fetch(`${supabaseUrl.replace(/\/$/, "")}/rest/v1/?apikey=${apiKey}`, {
63
+ headers: { Accept: "application/json" }
64
+ });
65
+ if (!res.ok) return [];
66
+ const doc = await res.json();
67
+ const paths = doc.paths ?? {};
68
+ const out = [];
69
+ for (const [p, ops] of Object.entries(paths)) {
70
+ for (const m of Object.keys(ops)) {
71
+ const upper = m.toUpperCase();
72
+ if (HTTP_METHODS.includes(upper)) {
73
+ out.push(`${upper}:/rest/v1${p}`);
74
+ }
75
+ }
76
+ }
77
+ return out;
78
+ } catch {
79
+ return [];
80
+ }
81
+ }
82
+ async function discoverRoutes(opts) {
83
+ const all = /* @__PURE__ */ new Set();
84
+ const next = await walkNextAppRouter(opts.repoRoot);
85
+ for (const r of next) all.add(r);
86
+ if (opts.openapiFile) {
87
+ const oas = await parseOpenApiFile(opts.openapiFile);
88
+ for (const r of oas) all.add(r);
89
+ } else {
90
+ for (const candidate of ["openapi.yaml", "openapi.json", "openapi.yml"]) {
91
+ const full = path.join(opts.repoRoot, candidate);
92
+ try {
93
+ await fs.access(full);
94
+ const oas = await parseOpenApiFile(full);
95
+ for (const r of oas) all.add(r);
96
+ break;
97
+ } catch {
98
+ }
99
+ }
100
+ }
101
+ if (opts.supabaseUrl && opts.supabaseAnonKey) {
102
+ const supa = await fetchSupabaseOpenApi(opts.supabaseUrl, opts.supabaseAnonKey);
103
+ for (const r of supa) all.add(r);
104
+ }
105
+ return Array.from(all).sort();
106
+ }
107
+ async function walk(dir, onFile) {
108
+ let entries;
109
+ try {
110
+ entries = await fs.readdir(dir, { withFileTypes: true });
111
+ } catch {
112
+ return;
113
+ }
114
+ for (const entry of entries) {
115
+ if (entry.name === "node_modules" || entry.name === ".next" || entry.name.startsWith(".")) continue;
116
+ const full = path.join(dir, entry.name);
117
+ if (entry.isDirectory()) {
118
+ await walk(full, onFile);
119
+ } else if (entry.isFile()) {
120
+ await onFile(full);
121
+ }
122
+ }
123
+ }
124
+ export {
125
+ discoverRoutes,
126
+ fetchSupabaseOpenApi,
127
+ parseOpenApiFile,
128
+ walkNextAppRouter
129
+ };
130
+ //# sourceMappingURL=api-contract-5PFMVTHT.js.map
@@ -0,0 +1 @@
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 */\nexport async 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;AA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AAC3F,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 CHANGED
@@ -38,9 +38,12 @@ async function main() {
38
38
  }
39
39
  case "dispatch-fix": {
40
40
  const reportId = core.getInput("report-id", { required: true });
41
+ const inventoryActionNodeId = core.getInput("inventory-action-node-id") || void 0;
42
+ const body = { reportId };
43
+ if (inventoryActionNodeId) body.inventoryActionNodeId = inventoryActionNodeId;
41
44
  const res = await api(endpoint, apiKey, projectId, "/v1/admin/fixes/dispatch", {
42
45
  method: "POST",
43
- body: JSON.stringify({ reportId })
46
+ body: JSON.stringify(body)
44
47
  });
45
48
  handleResult(res, failOnQuota);
46
49
  break;
@@ -71,10 +74,142 @@ async function main() {
71
74
  handleResult(res, failOnQuota);
72
75
  break;
73
76
  }
77
+ case "discover-api": {
78
+ const { discoverRoutes } = await import("./api-contract-5PFMVTHT.js");
79
+ const repoRoot = core.getInput("repo-root") || process.cwd();
80
+ const openapiFile = core.getInput("openapi-file") || void 0;
81
+ const supabaseUrl = core.getInput("supabase-url") || void 0;
82
+ const supabaseAnonKey = core.getInput("supabase-anon-key") || void 0;
83
+ const routes = await discoverRoutes({
84
+ repoRoot,
85
+ openapiFile,
86
+ supabaseUrl,
87
+ supabaseAnonKey
88
+ });
89
+ core.info(`Discovered ${routes.length} routes`);
90
+ core.setOutput("result", JSON.stringify({ routes }));
91
+ const persist = await api(
92
+ endpoint,
93
+ apiKey,
94
+ projectId,
95
+ `/v1/admin/inventory/${projectId}/gates/run`,
96
+ {
97
+ method: "POST",
98
+ body: JSON.stringify({
99
+ gates: ["api_contract"],
100
+ findings: [],
101
+ commit_sha: process.env.GITHUB_SHA,
102
+ discovered_apis: routes
103
+ })
104
+ }
105
+ );
106
+ handleResult(persist, failOnQuota);
107
+ break;
108
+ }
109
+ case "gates": {
110
+ const commitSha = core.getInput("commit-sha") || process.env.GITHUB_SHA || "";
111
+ const prNumber = core.getInput("pr-number") || "";
112
+ 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);
114
+ const body = {
115
+ commit_sha: commitSha || void 0,
116
+ pr_number: prNumber ? Number(prNumber) : void 0,
117
+ gates
118
+ };
119
+ const res = await api(
120
+ endpoint,
121
+ apiKey,
122
+ projectId,
123
+ `/v1/admin/inventory/${projectId}/gates/run`,
124
+ { method: "POST", body: JSON.stringify(body) }
125
+ );
126
+ core.setOutput("result", JSON.stringify(res));
127
+ if (!res.ok) {
128
+ if (res.error?.code === "QUOTA_EXCEEDED" && !failOnQuota) {
129
+ core.warning(`quota exceeded, skipping: ${res.error?.message}`);
130
+ break;
131
+ }
132
+ core.setFailed(`gates run failed: ${res.error?.code ?? "unknown"} ${res.error?.message ?? ""}`);
133
+ break;
134
+ }
135
+ const runs = res.data?.runs ?? [];
136
+ const failed = runs.filter((r) => r.status === "fail");
137
+ const warned = runs.filter((r) => r.status === "warn");
138
+ const summary = runs.map((r) => `${gateGlyph(r.status)} ${r.gate} (${r.findings_count})`).join(" \xB7 ");
139
+ core.info(`Mushi gates: ${summary}`);
140
+ if (failed.length > 0) {
141
+ core.setFailed(
142
+ `Mushi gate failures: ${failed.map((r) => r.gate).join(", ")}. View details on /inventory in the admin console.`
143
+ );
144
+ } else if (warned.length > 0) {
145
+ core.warning(`Mushi gate warnings: ${warned.map((r) => r.gate).join(", ")}.`);
146
+ }
147
+ break;
148
+ }
149
+ case "discovery-status": {
150
+ const res = await api(endpoint, apiKey, projectId, `/v1/admin/inventory/${projectId}/discovery`);
151
+ core.setOutput("result", JSON.stringify(res));
152
+ if (!res.ok) {
153
+ core.setFailed(`discovery-status failed: ${res.error?.code ?? "unknown"}`);
154
+ break;
155
+ }
156
+ const ready = res.data?.ready_to_propose ?? false;
157
+ core.setOutput("ready_to_propose", String(ready));
158
+ core.setOutput("total_events", String(res.data?.total_events ?? 0));
159
+ core.setOutput("route_count", String((res.data?.routes ?? []).length));
160
+ core.info(
161
+ `Mushi discovery: ${res.data?.total_events ?? 0} events across ${(res.data?.routes ?? []).length} routes; ${ready ? "ready to propose" : "not yet ready"}.`
162
+ );
163
+ break;
164
+ }
165
+ case "propose": {
166
+ const res = await api(
167
+ endpoint,
168
+ apiKey,
169
+ projectId,
170
+ `/v1/admin/inventory/${projectId}/propose`,
171
+ { method: "POST", body: "{}" }
172
+ );
173
+ handleResult(res, failOnQuota);
174
+ if (res.ok && res.data) {
175
+ core.info(
176
+ `Mushi proposed ${res.data.storyCount} stories / ${res.data.pageCount} pages \u2014 open /inventory \u25B8 Discovery to review.`
177
+ );
178
+ core.setOutput("proposal_id", res.data.proposalId);
179
+ }
180
+ break;
181
+ }
182
+ case "auth-bootstrap": {
183
+ const cmd = `npx --yes -p @mushi-mushi/inventory-auth-runner mushi-mushi-auth refresh`;
184
+ core.info(`mushi auth-bootstrap \u2192 ${cmd}`);
185
+ const env = {
186
+ ...process.env,
187
+ MUSHI_API_KEY: apiKey,
188
+ MUSHI_PROJECT: projectId,
189
+ MUSHI_API_ENDPOINT: endpoint
190
+ };
191
+ const { spawnSync } = await import("child_process");
192
+ const res = spawnSync(cmd, { shell: true, env, stdio: "inherit" });
193
+ if ((res.status ?? 0) !== 0) {
194
+ core.setFailed(`auth-bootstrap failed (exit ${res.status})`);
195
+ } else {
196
+ core.info("auth-bootstrap: cookie refreshed.");
197
+ }
198
+ break;
199
+ }
74
200
  default:
75
- core.setFailed(`unknown command: ${command}. Expected trigger-judge | dispatch-fix | check-coverage | query.`);
201
+ core.setFailed(
202
+ `unknown command: ${command}. Expected trigger-judge | dispatch-fix | check-coverage | query | gates | discover-api | discovery-status | propose | auth-bootstrap.`
203
+ );
76
204
  }
77
205
  }
206
+ function gateGlyph(status) {
207
+ if (status === "pass") return "\u2705";
208
+ if (status === "fail") return "\u274C";
209
+ if (status === "warn") return "\u26A0\uFE0F";
210
+ if (status === "skipped") return "\u23ED\uFE0F";
211
+ return "\u23FA\uFE0F";
212
+ }
78
213
  function handleResult(res, failOnQuota) {
79
214
  core.setOutput("result", JSON.stringify(res));
80
215
  if (!res.ok) {
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 const res = await api(endpoint, apiKey, projectId, '/v1/admin/fixes/dispatch', {\n method: 'POST',\n body: JSON.stringify({ reportId }),\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 default:\n core.setFailed(`unknown command: ${command}. Expected trigger-judge | dispatch-fix | check-coverage | query.`)\n }\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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AAS,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":[]}
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,QAAM,UAAe,cAAS,WAAW,EAAE,UAAU,KAAK,CAAC;AAC3D,QAAM,cAAmB,cAAS,eAAe,MAAM;AAEvD,UAAQ,SAAS;AAAA,IACf,KAAK,iBAAiB;AACpB,YAAM,MAAM,MAAM,IAAI,UAAU,QAAQ,WAAW,uBAAuB;AAAA,QACxE,QAAQ;AAAA,QACR,MAAM,KAAK,UAAU,EAAE,OAAO,IAAI,UAAU,CAAC;AAAA,MAC/C,CAAC;AACD,mBAAa,KAAK,WAAW;AAC7B;AAAA,IACF;AAAA,IACA,KAAK,gBAA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,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":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mushi-mushi/mcp-ci",
3
- "version": "0.2.2",
3
+ "version": "0.4.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",