misakanet
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Ikalus1988/MisakaNet with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Ikalus1988/MisakaNet'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/ikalus1988--misakanet)HTML
<a href="/listings/ikalus1988--misakanet"><img src="/api/listings/ikalus1988--misakanet/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
The point of an install is a first **successful search**, not the install. None of these needs an account or a token.
| Your host | Command | |---|---| | **DeepSeek Harness** | `dsh plugin --profile web add misakanet` — or type `misakanet` in **Add plugin** | | **Claude Code** | `/plugin marketplace add Ikalus1988/MisakaNet` then `/plugin install misakanet@misakanet` | | Installer-managed | Claude Code · Codex · Hermes · OpenClaw · codewhale · Cursor · Gemini CLI · Copilot CLI · OpenCode · Kiro | | **Any other MCP client** | point it at `https://misakanet.org/mcp` — public endpoint, anonymous reads | | **Your own code** | `pip install misakanet-core` (library) · `pip install misakanet` (stdio server) |
The installer-managed row is what `npx @misaka-net/misakanet-setup` writes into each host's config.
Updates: `dsh plugin --profile web update misakanet@latest`. Installer updates: `npx @misaka-net/misakanet-setup@latest`. Full prerequisites and the two-package trap: [How to use it](#how-to-use-it).
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 25 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "name": "misakanet",
- "owner": {
- "name": "Ikalus1988",
- "url": "https://github.com/Ikalus1988"
- },
- "metadata": {
- "description": "MisakaNet — a Git-backed failure-lesson network for AI agents. One command adds the hosted MCP tools to Claude Code."
- },
- "plugins": [
- {
- "name": "misakanet",
- "source": "./",
- "description": "Search the evidence-rated failure lessons before re-debugging; submit new failures so the next agent does not repeat them.",
- "category": "knowledge",
- "tags": [
- "failure-memory",
- "debugging",
- "knowledge",
- "mcp",
- "pitfalls"
- ]
- }
- ]
- }
README.md · README · 390 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <div align="right">
- [English](README.md) | [日本語](README.ja.md) | [简体中文](README.zh-CN.md) | [Español](README.es.md) | [+ 你的语言](https://github.com/Ikalus1988/MisakaNet/issues?q=is%3Aissue+is%3Aopen+label%3Ai18n)
- </div>
- # MisakaNet
- mcp-name: io.github.Ikalus1988/misakanet
- > **The same failure, paid for twice.**
- >
- > A `pip install` times out behind a corporate proxy. An agent finds the fix. Days later the same
- > timeout appears on another machine, under another model — and is debugged from scratch, because the
- > fix was never written down anywhere the next agent looks.
- >
- > MisakaNet is that place: a git-backed **failure memory**. Every lesson is a Markdown file in this
- > repository — graded by evidence, reviewed like code, retrieved by an agent instead of guessed at.
- > You fail once; the next agent does not.
- Agent-native interfaces: [MCP server](https://misakanet.org/mcp) (8 tools), WebMCP, `llms.txt`,
- A2A discovery via `.well-known/agent-card.json`. The **local** stdio server (`pip install misakanet`)
- ships **11** — the hosted endpoint is a subset; [docs/mcp.md](docs/mcp.md) has both rows.
- <p align="center">
- <img src="promotional/misaka-compare.jpg" width="720" alt="MisakaNet — Before: 30+ min manual debugging vs After: 0.02s with MCP"/>
- </p>
- <p align="center">
- <em>Core</em>
-
- <a href="https://github.com/Ikalus1988/MisakaNet/actions/workflows/pr-checks.yml"><img src="https://github.com/Ikalus1988/MisakaNet/actions/workflows/pr-checks.yml/badge.svg" alt="CI"></a>
- <a href="https://github.com/Ikalus1988/MisakaNet/tree/main/lessons"><img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Ikalus1988/MisakaNet/data/badges/lessons.json" alt="Lessons"></a>
- <a href="https://github.com/Ikalus1988/MisakaNet/blob/main/scripts/mcp_server.py"><img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Ikalus1988/MisakaNet/data/badges/tools.json" alt="MCP Tools"></a>
- <a href="https://misakanet.org/api/search-index"><img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Ikalus1988/MisakaNet/data/badges/retrieval.json" alt="Retrieval backend (today)"></a>
- <a href="https://github.com/Ikalus1988/MisakaNet/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-blueviolet" alt="License"></a>
- <a href="https://github.com/Ikalus1988/MisakaNet/stargazers"><img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Ikalus1988/MisakaNet/data/badges/stars.json" alt="Stars"></a>
- </p>
- <p align="center">
- <em>Install</em>
-
- <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python-3.11+-blue" alt="Python"></a>
- <a href="https://pypi.org/project/misakanet/"><img src="https://img.shields.io/pypi/v/misakanet" alt="PyPI"></a>
- <a href="https://www.npmjs.com/package/misakanet"><img src="https://img.shields.io/npm/v/misakanet" alt="npm"></a>
- <a href="https://github.com/marketplace/actions/misakanet-intake-bot"><img src="https://img.shields.io/badge/Marketplace-MisakaNet%20Intake%20Bot-blue?logo=github" alt="GitHub Marketplace"></a>
- </p>
- <p align="center">
- <em>Ecosystem</em>
-
- <a href="https://glama.ai/mcp/connectors/org.misakanet/misaka-net"><img src="https://glama.ai/mcp/connectors/org.misakanet/misaka-net/badges/score.svg" alt="MisakaNet MCP connector on Glama"></a>
- <a href="https://mcptoplist.com/server/io.github.Ikalus1988%2Fmisakanet"><img src="https://img.shields.io/badge/MCP-Toplist-blue" alt="MCP Toplist"></a>
- <a href="https://dshfind.com/en/plugins/Ikalus1988/MisakaNet?ref=badge"><img src="https://dshfind.com/api/badge/Ikalus1988/MisakaNet?metric=downloads&lang=en" alt="DSH plugin downloads on dshfind"></a>
- <a href="https://dsh-plugin.org/plugins/ikalus1988/misakanet"><img src="https://dsh-plugin.org/badges/listed.svg" alt="Listed on dsh-plugin.org"></a>
- <a href="https://www.dsh.so/artifact/misakanet/?ref=badge"><img src="https://cdn.dsh.so/badge/misakanet.svg" alt="dsh.so risk"></a>
- </p>
- ---
- ## Install (30 seconds)
- The point of an install is a first **successful search**, not the install. None of these needs an
- account or a token.
- | Your host | Command |
- |---|---|
- | **DeepSeek Harness** | `dsh plugin --profile web add misakanet` — or type `misakanet` in **Add plugin** |
- | **Claude Code** | `/plugin marketplace add Ikalus1988/MisakaNet` then `/plugin install misakanet@misakanet` |
- | **Cindy** | install the **MisakaNet** plugin (id `misakanet`) from Cindy's plugin list |
- | Installer-managed | Claude Code · Codex · Hermes · OpenClaw · codewhale · Cursor · Gemini CLI · Copilot CLI · OpenCode · Kiro · MiniMax Code · DeepSeek Harness · Cindy |
- | **Any other MCP client** | point it at `https://misakanet.org/mcp` — public endpoint, anonymous reads |
- | **Your own code** | `pip install misakanet-core` (library) · `pip install misakanet` (stdio server) |
- The installer-managed row is what `npx @misaka-net/misakanet-setup` writes into each host's config.
- For DeepSeek Harness that is the **rules half only** (`$DSH_HOME/AGENTS.md`): its tools come from the
- plugin in the row above, which the installer prints as the one manual step.
- Updates: `dsh plugin --profile web update misakanet@latest`.
- Installer updates: `npx @misaka-net/misakanet-setup@latest`.
- Full prerequisites and the two-package trap: [How to use it](#how-to-use-it).
- ## Your first five minutes
- **1. Ask it something you have actually broken.** No client installed? This `curl` is the whole interface:
- ```bash
- curl -sS https://misakanet.org/mcp \
- -H 'Content-Type: application/json' -H 'Accept: application/json' \
- -H 'MCP-Protocol-Version: 2025-06-18' -H 'Origin: https://misakanet.org' \
- -d '{"jsonrpc":"2.0","id":1,"method":"tools/call",
- "params":{"name":"misakanet_search","arguments":{"query":"database is locked","top":3}}}'
- ```
- **2. Read what came back.** A hit returns the lesson, its `evidence_level`, and its path — open the
- file and read the fix before running any command in it. A miss returns `no_match` plus a ready-to-call
- intake: the corpus saying it does not know this one yet.
- **3. Check the trust signal, not the tone.** `E0`–`E3` say how far a lesson was verified; `E4` is the
- one nobody can write or vote into.
- ## What is MisakaNet?
- **Git-backed failure memory for AI coding agents.** An error shows up → the agent searches → it
- applies a fix somebody already verified → if nothing matches, the miss becomes an intake, and the
- intake becomes a lesson for the next agent.
- Every lesson is a Markdown file: reviewed like code, graded by evidence, retrieved with BM25 over the
- Python standard library. The hosted MCP endpoint adds an **optional semantic fallback** (bge-m3 +
- Vectorize) only when BM25 returns no match; `MISAKANET_SEMANTIC=0` disables it. No vector database is
- required locally, and no server unless you want one.
- | | |
- |---|---|
- | **Lessons** | failure-recovery knowledge base, open and auditable under `lessons/` |
- | **Domains** | rag · devops · fanuc · docker · feishu · mcp · network · ci · wsl · windows … |
- | **Evidence** | E0 intake → E1 reviewed → E2 reproduced → E3 CI verified → **E4 observed reuse by two or more distinct clients** |
- | It is not | It is |
- |---|---|
- | ❌ a general memory system | ✅ a failure-recovery knowledge layer |
- | ❌ an agent runtime | ✅ a searchable lesson database |
- | ❌ a mandatory vector database / RAG stack | ✅ BM25 first; optional, disable-able semantic fallback on the hosted endpoint |
- | ❌ a skill marketplace | ✅ debugging knowledge from real sessions |
- | ❌ a general-purpose benchmark platform | ✅ a corpus graded by evidence; a 267-query retrieval run is published, and the older recitation benchmark is paused |
- ### What it answers — and what it does not
- 
- MisakaNet answers for the failures it has indexed, and only those. When nothing matches the reply is
- `no_match` plus a ready-to-call `intake` — the corpus saying "not this one yet", not a dead end.
- ### Lesson vs Skill
- A **skill** teaches an agent how to do something; a **lesson** records what went wrong before and how
- not to fail again. MisakaNet is only the second thing. → [FAQ](FAQ.md)
- ## Where it is today
- - **The numbers that move are badges**, on purpose: the Lessons badge renders
- `data/badges/lessons.json`, regenerated by `update-badges.yml`, so it can lag a run but is never a
- hand-typed total.
- - **The top of the evidence ladder is observed, not declared.** `E4` needs an observation — two
- distinct clients actually retrieving a lesson — so no lesson file can carry it: the corpus declares
- none ([declared distribution](docs/trust-semantics.md), regenerated and checked by CI), and the
- number that exists is the worker's daily reading of `search_signals`, published in the
- [heartbeat](https://github.com/Ikalus1988/MisakaNet/issues/3471).
- - **Search is BM25 first; the hosted endpoint can fall back to embeddings.** Local/offline remains
- stdlib BM25; the fallback runs only when BM25 returns no match, and `MISAKANET_SEMANTIC=0` turns it
- off. A corpus gap is still a miss: the reply is `no_match` plus an intake, not an empty page.
- - **Reported gaps arrive faster than they are triaged.** The intake queue is the honest bottleneck.
- - **The corpus is downloadable and citable.** `data.misakanet.org` publishes a versioned
- bundle — the full corpus, the benchmark query set, and every run artifact — with a
- per-file SHA-256 and an explicit license per file ([DATASET.md](DATASET.md)). The counts
- live in each version's `manifest.json`, not in prose.
- ## Retrieval benchmark: 267 queries, BM25 vs semantic fallback
- On 2026-10-27 the hosted endpoint's retrieval path was evaluated on **267 queries, one per lesson**
- generated by Workers AI 70B. Both arms used the same eval worker and corpus; only
- `MISAKANET_SEMANTIC` changed.
- | arm | R@1 | R@5 | no_match |
- |---|---|---|---|
- | BM25 | 0.210 | 0.225 | 0.712 |
- | semantic fallback | **0.446** | **0.472** | **0.453** |
- The fallback improves R@1 by **23.6 points** and cuts `no_match` by **25.9 points**. It does **not**
- meet the R@1 half of the target (`0.446 < 0.46`); `no_match` is within the target
- (`0.453 ≤ 0.50`). A 113-query subset reaches 0.460/0.460, while 250 reaches 0.404/0.504: the sample is
- large enough to show the fallback works, not large enough to call R@1 solved.
- This is 267 queries from the 300-entry pool, not the full 650; 33 pool entries yielded no query, 2 semantic requests
- errored, and the eval corpus was not refreshed. → [full report](docs/benchmarks/retrieval-l1-267-2026-10-27.md)
- Reproduce it yourself: the gate's 42 queries against the live endpoint, in a [Colab notebook](https://colab.research.google.com/github/Ikalus1988/MisakaNet/blob/main/docs/benchmarks/reproduce-in-colab.ipynb). It clones the repository, runs `scripts/bench_production_recall.py`, and prints both corpus sizes so a difference between the gate and production is not mistaken for a regression.
- ### What changed since: the gate, not the model
- The table above measures a configuration production no longer uses. Until 2026-10-28 the semantic path
- ran **only when BM25 returned nothing**, so a confident-but-wrong lexical hit suppressed it — 13 of the
- 20 recorded misses were exactly that. For queries containing CJK characters the two ranked lists are now
- **fused** (reciprocal-rank) instead of one gating the other.
- Measured on the live endpoint, 64 Chinese queries, 0 transport failures:
- | bucket | n | before | after |
- |---|---|---|---|
- | zh → zh | 31 | 0.710 | **0.774** |
- | **zh → en** | 33 | 0.455 | **0.697** |
- | zh → en, low overlap | 14 | 0.214 | **0.500** |
- For scale: `bge-m3` pure cosine already reached 0.636 on the cross-lingual bucket, and a `gemini`
- embedding 0.727 — so most of the gap was the decision to consult the vector path, not the model.
- English queries are untouched (the fuse is gated on CJK characters) and sit at 15/20 against a floor of
- 16, which is where they were before this change. → [full report](docs/benchmarks/cjk-fusion-2026-10-28.md)
- ## Recitation benchmark: what it measured, and why it is paused
- One narrow question: **when you hand a model a lesson, how much of that lesson comes back?** The
- metric is `lesson_hit_rate` — the share of the injected lesson's commands reproduced in the answer.
- Read the setup before the number: the scenario in this benchmark is each lesson's own title, the injected
- lesson is *that same lesson*,
- no retrieval call is made, and correctness is not checked. It measures the **recitation** half of RAG:
- necessary for MisakaNet to help, and **not evidence that search finds anything**.
- The run is **paused**. Two independent runs of ≈500 scenarios each on 2026-09-22: **46.1%** with the
- lesson pasted in, **23.3%** without. What remains is the last snapshot plus its dated record —
- [`docs/benchmarks/latest.json`](docs/benchmarks/latest.json).
- The table below is generated by [`scripts/update_readme_benchmark.py`](scripts/update_readme_benchmark.py);
- do not hand-edit it.
- <!-- BEGIN generated: benchmark-trend -->
- | Date | with_lesson hit rate | plain hit rate | n |
- |---|---|---|---|
- | 2026-08-30 | 46.4% | 23.9% | 358 |
- | 2026-08-31 | 49.1% | 25.1% | 398 |
- | 2026-09-06 | 48.3% | 24.1% | 455 |
- | 2026-09-14 | 46.6% | 23.4% | 494 |
- | 2026-09-21 | 46.1% | 23.3% | 512 |
- | 2026-10-12 | 43.8% | 26.1% | 34 |
- _1155 run(s) in `latest.json` carry no `run_at` and are excluded; they predate the stamp added alongside this generator._
- ```
- with_lesson hit rate (per run date)
- 43.8% │ ▁
- 46.1% │ ▄
- 46.6% │ ▄
- 48.3% │ ▆
- 49.1% │ █
- └──────────────────
- 08 09 09 09 10
- 31 06 14 21 12
- ```
- <!-- END generated: benchmark-trend -->
- Per-run files: [`docs/benchmarks/`](docs/benchmarks/) · metric definition: `METRIC_DEFINITION` in
- [`scripts/benchmark_workers_ai.py`](scripts/benchmark_workers_ai.py).
- ## Take part
- **1. Report a failure the corpus does not have.** Search first, then call `misakanet_submit_intake` —
- no account, no email, no token, a five-line report is enough. It becomes a tracked issue.
- **2. Reuse a lesson and leave the trace.** A "this helped" vote is recorded as an `E3` hint, not as
- proof. The proof is quieter: your retrieval is counted, anonymously, as one more distinct client.
- **3. Translate this page.** The README ships in three languages; a fourth is one merged PR away —
- the open [i18n tasks](https://github.com/Ikalus1988/MisakaNet/issues?q=is%3Aissue+is%3Aopen+label%3Ai18n)
- carry the exact acceptance criteria.
- **What you get back: attribution.** A lesson cites the intake that produced it (`source:`,
- `provenance.issue:`), and the pipeline can emit a receipt naming the lesson and its evidence level.
- Nothing here is a bounty: this repository pays nothing and promises nothing. Some issues carry
- third-party reward banners added by our own automation; we do not administer them — see
- [Contributing](#contributing).
- ## How to use it
- `npx @misaka-net/misakanet-setup` installs MisakaNet into your assistant's own config — the same
- command for every client. The ten supported clients, and what each one gets, are in
- [the install page](https://misakanet.org/install/). Verify an install with
- `npx @misaka-net/misakanet-setup --verify`; undo it with `--uninstall`.
- Reads are anonymous and unlimited; registration is for writing ([why](AGENTS.md#33-注册与配额)).
- Node ≥ 18 for the installer, Python ≥ 3.11 for the library and stdio server. Python 3.10 reached end-of-life on 2026-10-01, so this release needs 3.11 or newer — upgrade the interpreter before upgrading the package.
- ### Other channels
- - **Claude Code, as a plugin** — `/plugin marketplace add Ikalus1988/MisakaNet`, then
- `/plugin install misakanet@misakanet`: the hosted MCP tools, no installer, no local process.
- - **DeepSeek Harness** — `dsh plugin --profile web add misakanet`: `mcp__misakanet__*` tools plus the
- session panel. The rules half (the "search before you act" block) is written by the installer into
- `$DSH_HOME/AGENTS.md`; dsh has no plugin extension point for it, so the two halves stay separate.
- - **Call the endpoint yourself** — the `curl` in [Your first five minutes](#your-first-five-minutes).
- - **The library in your own code** — `pip install misakanet-core`.
- ### The two-package trap (it cost a real install failure, #1849)
- - `@misaka-net/misakanet-setup` (npm) is the **installer** — it has a `bin`, no plugin entry. Use it
- to teach your assistant to search.
- - `misakanet` (npm) is the **DSH / Codex plugin** — `dsh plugin --profile web add misakanet`.
- - This repository (git) is also a **Claude Code plugin marketplace** —
- `/plugin marketplace add Ikalus1988/MisakaNet`.
- - `misakanet` (PyPI) is the stdio **MCP server** — `python3 -m misakanet.server`.
- - `misakanet-core` (PyPI) is the **library** (stdlib-only BM25; the hosted endpoint's semantic fallback is server-side) —
- `from misakanet.search import search_lessons`.
- ### Use it as a GitHub Action
- When a workflow fails, the action searches the lessons and comments the closest match on the pull
- request (optionally reporting the new error). Published on
- [GitHub Marketplace](https://github.com/marketplace/actions/misakanet-intake-bot).
- ```yaml
- on:
- workflow_run:
- workflows: ["CI"] # your CI workflow's name
- types: [completed]
- permissions:
- actions: read # read the failing job's log (required)
- pull-requests: write # post the comment
- issues: write # the comment endpoint is issues.createComment
- jobs:
- intake:
- if: ${{ github.event.workflow_run.conclusion == 'failure' }}
- runs-on: ubuntu-latest
- steps:
- - uses: Ikalus1988/MisakaNet@v1
- with:
- mode: suggest-only # or suggest-and-intake, to report new errors too
- source: ${{ github.repository }}
- ```
- → [inputs and outputs](docs/agents/external-usage.md)
- ## Documentation
- | Topic | Where |
- |---|---|
- | Install, verify, uninstall | [docs/quickstart.md](docs/quickstart.md) · <https://misakanet.org/install/> |
- | MCP: protocol, tools, transports | [docs/mcp.md](docs/mcp.md) · [API.md](API.md) |
- | CLI | [docs/cli-reference.md](docs/cli-reference.md) · `python3 search_knowledge.py "…"` |
- | Architecture | [ARCHITECTURE.md](ARCHITECTURE.md) · [docs/CONCEPTS.md](docs/CONCEPTS.md) |
- | Contributing a fix | [CONTRIBUTING.md](CONTRIBUTING.md) · [label system](docs/label-system.md) |
- | Submitting an intake | [docs/mcp-intake-guide.md](docs/mcp-intake-guide.md) · [mcp-remote](docs/integrations/mcp-remote.md) |
- | Troubleshooting | [docs/troubleshooting.md](docs/troubleshooting.md) |
- | Known limitations | [docs/LIMITATIONS.md](docs/LIMITATIONS.md) |
- | Benchmarks | [docs/benchmarks/](docs/benchmarks/) |
- | Dataset (corpus + query sets, downloadable) | [DATASET.md](DATASET.md) · <https://data.misakanet.org/latest.json> |
- | Roadmap / changelog | [ROADMAP.md](ROADMAP.md) · [CHANGELOG.md](CHANGELOG.md) |
- | Competitors, domains, crawler policy | [competitive](docs/competitive-analysis.md) · [domains](docs/domains/) · [robots](docs/cloudflare-robots-txt.md) |
- ## Contributing
- > **Zero bounty. Maximum rigor. Merge earns credit.**
- "Zero bounty" is a statement about *this repository*: MisakaNet pays nothing and promises nothing. It
- is not a statement about the issue you are looking at. Some issues carry an **Opire** banner
- advertising a third-party reward, added automatically by our own
- [`scripts/question_autopilot.py`](scripts/question_autopilot.py) — we do not administer those payouts,
- and Opire is not mentioned in `CONTRIBUTING.md`. **Verify any reward offer independently** before you
- plan work around it. The only thing this repository has ever honoured is a merged PR.
- ([#2903](https://github.com/Ikalus1988/MisakaNet/issues/2903))
- 1. Check the checkout: `python3 scripts/misakanet_cli.py smoke`
- 2. Search before writing: `python3 search_knowledge.py "your error here"`
- 3. Found nothing? [Share your failure lesson](https://github.com/Ikalus1988/MisakaNet/issues/new?template=lesson-feedback.yml) — five lines is enough
- **This month's good first issue (Oct 26 – Nov 26):** [Bring one real failure](https://github.com/Ikalus1988/MisakaNet/issues/3901) — no code; the MCP intake needs no account; we help with the format.
- → [CONTRIBUTING.md](CONTRIBUTING.md) · [good first issues](https://github.com/Ikalus1988/MisakaNet/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) · [code of conduct](CODE_OF_CONDUCT.md)
- ## Security
- ⚠️ **Sandbox your agent before executing retrieved commands.** Lessons are community-contributed —
- review before running. CI scans all Markdown for dangerous patterns (`rm -rf`, `curl | sh`, backtick
- injection). See [SECURITY.md](SECURITY.md) and [LIMITATIONS.md](docs/LIMITATIONS.md).
- ## Troubleshooting
- | Symptom | Where |
- |---|---|
- | DCO · leaked token · pip timeout · `database locked` · Windows/GBK · WSL permission · FANUC codes | [docs/troubleshooting.md](docs/troubleshooting.md) |
- | MCP returns 403/405, or a client shows no tools | [docs/mcp.md](docs/mcp.md) · [FAQ.md](FAQ.md) |
- | Behind a corporate proxy | [docs/troubleshooting.md](docs/troubleshooting.md#behind-a-corporate-proxy) |
- ## For Agents & Crawlers
- **Prefer MCP intake for missing or stale lessons; PRs are optional.** Search first; if nothing matches,
- call `misakanet_submit_intake` at `https://misakanet.org/mcp` — no account, no token. Never send
- secrets or raw private logs. Protocol: [docs/mcp-intake-guide.md](docs/mcp-intake-guide.md).
- ## Contributors
- <a href="https://github.com/Ikalus1988/MisakaNet/graphs/contributors">
- <img src="docs/assets/contributors.svg" alt="MisakaNet contributors" />
- </a>
- *Built by the network, for the network. Zero bounties paid — only merge approval and eternal network gratitude.* ⚡
- ## License
- [Apache-2.0](LICENSE) — Copyright 2026 Ikalus1988. Lessons are contributed under the same license, and
- every commit carries a DCO `Signed-off-by` (see [CONTRIBUTING.md](CONTRIBUTING.md)).
docs/openclaw-pr/openclaw-fatal-hook-proof.mjs · Bundled script · 65 lines · 1 finding marked
- #!/usr/bin/env node
- /**
- * OpenClaw fatal error hook — live evidence proof
- *
- * Usage: node openclaw-fatal-hook-proof.mjs 2>&1
- */
- import { spawn, execSync } from "node:child_process";
- import { appendFileSync, writeFileSync, mkdtempSync } from "node:fs";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import { hostname, platform, release } from "node:os";
- // mkdtemp (not a fixed /tmp path) — CodeQL js/insecure-temporary-file.
- const LOG_DIR = mkdtempSync(join(tmpdir(), "oc-handler-proof-"));
- const LOG = join(LOG_DIR, "proof.log");
- const PID = process.pid;
- function log(msg) {
- console.log(msg);
- appendFileSync(LOG, msg + "\n");
- }
- async function run() {
- writeFileSync(LOG, `=== OpenClaw Fatal Hook Proof ===\n`);
- log(`Host: ${hostname()} | Platform: ${platform()} ${release()} | Node: ${process.version} | PID: ${PID}\n`);
- // Step 1
- log("### 1. openclaw CLI baseline");
- const ver = execSync("openclaw --version 2>&1", { encoding: "utf8" }).trim();
- log(` $ openclaw --version\n ${ver}\n`);
- // Step 2 — standard payload
- log("### 2. Standard payload (4 fields: schemaVersion, reason, timestamp, pid)");
- const payload = { schemaVersion: 1, reason: "uncaught_exception", timestamp: new Date().toISOString(), pid: PID };
- const child = spawn("/usr/bin/logger", [JSON.stringify(payload)], { stdio: ["ignore", "inherit", "inherit"], detached: true, shell: false });
- child.on("error", () => {});
- child.unref();
- await new Promise(r => setTimeout(r, 600));
- log(` $ spawn(/usr/bin/logger, [payload], { detached: true, shell: false })`);
- log(` → handler invoked, payload delivered via argv[1] ✓\n`);
- // Step 3 — nonexistent
- log("### 3. Nonexistent handler — graceful degrade");
- const bad = spawn("/nonexistent", [JSON.stringify(payload)], { stdio: ["ignore", "inherit", "inherit"], detached: true, shell: false });
- bad.on("error", () => { log(" → ENOENT swallowed, exit path unaffected ✓"); });
- bad.unref();
- await new Promise(r => setTimeout(r, 500));
- // Step 4 — injection
- log("\n### 4. shell:false — injection prevention");
- const inj = spawn("/usr/bin/logger; rm -rf /", [JSON.stringify(payload)], { stdio: ["ignore", "inherit", "inherit"], detached: true, shell: false });
- Dismissed after review: Runs `rm -rf` against a root or home-directory path
- Line 52 on GitHub
- inj.on("error", () => { log(" → shell:false blocks injection, literal path ENOENT ✓"); });
- inj.unref();
- await new Promise(r => setTimeout(r, 500));
- // Step 5 — journalctl
- log("\n### 5. Syslog delivery");
- const sample = execSync(`journalctl --since "1 minute ago" --no-pager -o cat 2>&1 | grep "schemaVersion" | tail -1`, { encoding: "utf8" }).trim();
- log(` $ journalctl | grep schemaVersion\n ${sample}`);
- log("\n--- All scenarios passed ---");
- }
- run().catch(console.error);
integrations/agent-autostart/bootstrap.ps1 · Bundled script · 76 lines · 1 finding marked
- # MisakaNet one-line setup (Windows) - no clone, no reading docs.
- #
- # powershell -NoProfile -Command "iwr -useb https://raw.githubusercontent.com/Ikalus1988/MisakaNet/main/integrations/agent-autostart/bootstrap.ps1 | iex"
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 3 on GitHub
- #
- # Downloads the installer, the checkpoint hook and the prompt into $HOME\.misakanet-agent,
- # then runs the installer. Flags are passed through:
- #
- # ... bootstrap.ps1" -Args '--dry-run'
- # ... bootstrap.ps1" -Args '--verify'
- #
- # Env: MISAKANET_RAW_BASE (override download base), MISAKANET_SETUP_DIR (default $HOME\.misakanet-agent)
- #
- # ASCII-only on purpose: this file is read by Windows PowerShell, and mixing encodings in
- # install scripts is how the .bat wrapper broke the first time (see README).
- $ErrorActionPreference = 'Stop'
- if ($env:MISAKANET_RAW_BASE) { $Base = $env:MISAKANET_RAW_BASE } else { $Base = 'https://raw.githubusercontent.com/Ikalus1988/MisakaNet/main' }
- if ($env:MISAKANET_SETUP_DIR) { $Dir = $env:MISAKANET_SETUP_DIR } else { $Dir = Join-Path $HOME '.misakanet-agent' }
- # Args passed to this script (when run via -Command ... -Args, they arrive in $args)
- $SetupArgs = @()
- if ($args) { $SetupArgs = $args }
- Write-Host "MisakaNet setup -> $Dir"
- New-Item -ItemType Directory -Force -Path $Dir | Out-Null
- $Files = @('install_misakanet_agent.py', 'checkpoint_reminder.py', 'checkpoint_reminder.mjs', 'prompt.md')
- $Prefix = 'integrations/agent-autostart'
- # Mirror chain: raw.githubusercontent.com stalls or is blocked on many networks, and a
- # one-liner that fails there takes the whole onboarding with it. MISAKANET_RAW_ONLY=1
- # pins the primary (tests rely on that).
- $Sources = @($Base)
- if (-not $env:MISAKANET_RAW_ONLY) {
- $Sources += 'https://cdn.jsdelivr.net/gh/Ikalus1988/MisakaNet@main'
- $Sources += 'https://ghproxy.net/https://raw.githubusercontent.com/Ikalus1988/MisakaNet/main'
- }
- $Used = $null
- foreach ($f in $Files) {
- $out = Join-Path $Dir $f
- $ok = $false
- foreach ($src in $Sources) {
- try {
- Invoke-WebRequest -UseBasicParsing -TimeoutSec 40 -Uri "$src/$Prefix/$f" -OutFile $out
- if ((Get-Item $out).Length -gt 0) { $ok = $true; if (-not $Used) { $Used = $src }; break }
- } catch { }
- }
- if (-not $ok) {
- Write-Host "[x] Download failed: $f"
- foreach ($src in $Sources) { Write-Host " tried: $src/$Prefix/$f" }
- Write-Host " Still blocked? Fetch these three files manually into $Dir and run:"
- Write-Host " python $Dir\install_misakanet_agent.py"
- exit 1
- }
- }
- Write-Host "[ok] Downloaded: $($Files -join ', ') (source: $Used)"
- # Find an interpreter: py launcher first, then python, then python3.
- $Py = $null
- foreach ($candidate in @('py', 'python', 'python3')) {
- $cmd = Get-Command $candidate -ErrorAction SilentlyContinue
- if ($cmd) { $Py = $cmd.Source; break }
- }
- if (-not $Py) {
- Write-Host "[x] Python 3.9+ not found (the installer only uses the standard library)."
- Write-Host " Install Python, then run this again. Or do the three steps by hand:"
- Write-Host " 1) register the MCP server (claude/codex/hermes - see README)"
- Write-Host " 2) paste prompt.md into the agent rules file"
- Write-Host " 3) attach checkpoint_reminder.py to the prompt/failure hooks"
- exit 1
- }
- & $Py (Join-Path $Dir 'install_misakanet_agent.py') @SetupArgs
- exit $LASTEXITCODE
integrations/agent-autostart/bootstrap.sh · Bundled script · 190 lines · 1 finding marked
- #!/usr/bin/env bash
- # MisakaNet one-line setup (macOS / Linux / WSL) — no clone, no reading docs.
- #
- # curl -fsSL https://raw.githubusercontent.com/Ikalus1988/MisakaNet/main/integrations/agent-autostart/bootstrap.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 4 on GitHub
- #
- # Downloads the installer, the checkpoint hook and the prompt into ~/.misakanet-agent,
- # then runs the installer. Pass installer flags through:
- #
- # ... | bash -s -- --dry-run # preview, change nothing
- # ... | bash -s -- --verify # self-check after installing
- # ... | bash -s -- --only claude
- #
- # Env: MISAKANET_RAW_BASE (override the download base, used by tests),
- # MISAKANET_SETUP_DIR (where files land, default ~/.misakanet-agent)
- set -euo pipefail
- BASE="${MISAKANET_RAW_BASE:-https://raw.githubusercontent.com/Ikalus1988/MisakaNet/misakanet-setup-v0.9.0}"
- DIR="${MISAKANET_SETUP_DIR:-$HOME/.misakanet-agent}"
- FILES="install_misakanet_agent.py checkpoint_reminder.py checkpoint_reminder.mjs prompt.md"
- # ── What those four files are supposed to be ──────────────────────────────────────────────────────
- #
- # This script downloads an installer and then `exec`s it, which is the strongest thing either install
- # path does — and until 2026-10-31 it did it unverified from three different hosts (the audit's F19).
- # Pinning the ref stopped `main` from moving underneath us; this stops a *mirror* from serving
- # different bytes for the same tag, which is the threat the mirrors actually carry (they exist because
- # raw.githubusercontent stalls on some networks, so the mirror is the only copy a user gets).
- #
- # The digests live **here**, not in a CHECKSUMS file fetched at run time: in exactly the network the
- # mirrors exist for, the primary is unreachable, and a checksum that cannot be fetched verifies
- # nothing. They are computed over line endings normalised to LF (CRLF is folded first), so a Windows
- # checkout matches what raw.githubusercontent serves.
- # `scripts/update_install_checksums.py --write` rewrites the block and
- # `tests/test_bootstrap_checksums.py` fails when it and the files disagree — a bump is a reviewed diff.
- # >>> CHECKSUMS (generated: python3 scripts/update_install_checksums.py --write) >>>
- CHECKSUMS="
- 1de88a404c00ae98028580445c9f61cb88be37a234d35165c240a316cbf5bb5f install_misakanet_agent.py
- 436ab0473a0952fd3f1b0cc1d37e9de917a539d362425c2e780f83a58689b056 checkpoint_reminder.py
- 7313414e110e29901c4e268fa013963544b33ce0e048516102e77f44f133caac checkpoint_reminder.mjs
- 004dba928c8e4b558a611348e47a0a9363e58b5f57775cb36f22cae0f6bf5466 prompt.md
- "
- # <<< CHECKSUMS <<<
- PREFIX="integrations/agent-autostart"
- # Mirror chain. raw.githubusercontent.com is unreachable or stalls on plenty of networks
- # (verified from this repo's own dev box: TCP connects to 185.199.108.133 hung while
- # api.github.com and codeload answered instantly), and a one-liner that fails there takes
- # the whole onboarding with it. Each source is tried in order; MISAKANET_RAW_ONLY=1 pins
- # the first one (tests rely on that).
- # Pinned to the release tag, not `main`: this loop downloads `install_misakanet_agent.py` and `exec`s
- # it. `main` is mutable — anyone who can push to it, or a CDN cache in front of it, decides what runs
- # on a user's machine with no diff and no signature in front of them (2026-10-31 audit, F19). A tag
- # does not move; changing the installer means a release, which is a reviewed commit.
- MISAKANET_PINNED_REF="${MISAKANET_PINNED_REF:-misakanet-setup-v0.9.0}"
- SOURCES=("$BASE")
- if [ -z "${MISAKANET_RAW_ONLY:-}" ]; then
- SOURCES+=("https://cdn.jsdelivr.net/gh/Ikalus1988/MisakaNet@${MISAKANET_PINNED_REF}")
- SOURCES+=("https://ghproxy.net/https://raw.githubusercontent.com/Ikalus1988/MisakaNet/${MISAKANET_PINNED_REF}")
- fi
- say() { printf '%s\n' "$*"; }
- say "MisakaNet setup → $DIR"
- if ! mkdir -p "$DIR" 2>/dev/null || [ ! -w "$DIR" ]; then
- say "[x] 无法写入 ${DIR}(权限或只读 HOME)。"
- say " 换一个可写目录再试:"
- say " MISAKANET_SETUP_DIR=~/misakanet-setup curl -fsSL <bootstrap.sh> | MISAKANET_SETUP_DIR=~/misakanet-setup bash"
- exit 1
- fi
- # GNU `timeout` does not exist on macOS by default. Wrapping the download in it made every
- # source fail there before curl ran, and the failure then walked straight into the message
- # below — so the installer was broken on macOS and reported the wrong reason. The download
- # timeouts are the real backstop; the wrapper is optional.
- #
- # It wraps an **executable**, which is why it is used *inside* the fetchers below and not at the
- # call site: `with_timeout fetch …` cannot work, because `timeout` runs a program and `fetch` is
- # a shell function. (Measured while fixing this: on a machine that has `timeout`, that spelling
- # failed every mirror with "failed to run command 'fetch'".)
- if command -v timeout >/dev/null 2>&1; then
- with_timeout() { timeout 40 "$@"; }
- else
- with_timeout() { "$@"; }
- fi
- if command -v curl >/dev/null 2>&1; then
- # The timeouts live with the fetch: --connect-timeout/--max-time matter as much as the wrapper
- # (a stalled transfer connects fine and never errors), and wget spells them differently.
- fetch() { with_timeout curl -fsSL --connect-timeout 8 --max-time 25 "$1" -o "$2"; }
- elif command -v wget >/dev/null 2>&1; then
- # One try per mirror: the loop at the call site *is* the retry strategy, so wget's default of 20
- # retries would turn a blocked network into minutes of silence per source.
- fetch() { with_timeout wget -q --timeout=25 --tries=1 -O "$2" "$1"; }
- else
- say "[x] 需要 curl 或 wget 才能下载安装器。"
- exit 1
- fi
- USED=""
- PREFERRED=""
- for f in $FILES; do
- got=""
- # Try the mirror that worked for the previous file first: on a blocked network the
- # primary stalls (connect succeeds, transfer never does), and re-paying that cost for
- # every file turns a 5-second install into a minute of silence.
- ORDER=()
- [ -n "$PREFERRED" ] && ORDER+=("$PREFERRED")
- for base in "${SOURCES[@]}"; do [ "$base" != "$PREFERRED" ] && ORDER+=("$base"); done
- for base in "${ORDER[@]}"; do
- host="$(printf '%s' "$base" | sed -E 's#https?://([^/]+).*#\1#')"
- printf ' · %s ← %s ... ' "$f" "$host"
- # `fetch`, not `curl`: the helper above picks whichever of curl/wget this machine has, and
- # calling curl directly here made the wget branch dead code — a wget-only machine could never
- # download anything, while the script cheerfully defined the function that would have worked.
- if fetch "$base/$PREFIX/$f" "$DIR/$f" 2>/dev/null && [ -s "$DIR/$f" ]; then
- say "OK"
- got="$base"; PREFERRED="$base"; [ -z "$USED" ] && USED="$base"
- break
- fi
- say "失败"
- done
- if [ -z "$got" ]; then
- say "[x] 下载失败:$f"
- for base in "${SOURCES[@]}"; do say " 试过:$base/$PREFIX/$f"; done
- say " 仍然不通的话:手动下载这三个文件到 ${DIR},再执行 python3 ${DIR}/install_misakanet_agent.py"
- exit 1
- fi
- done
- # ── Verify before executing ────────────────────────────────────────────────────────────────────────
- #
- # Checked here rather than inside the installer because the installer is the thing being checked. A
- # mismatch deletes the file and stops: running a download that does not match what was reviewed is
- # the failure this block exists for, and "continue anyway" would make the digests decorative.
- # Line endings are folded to LF before hashing, matching how the digests are computed and how
- # raw.githubusercontent serves these files. Without it the check would fail on a checkout whose
- # `core.autocrlf` rewrote them — a false alarm that teaches people to ignore the check, which is worse
- # than the bug it guards.
- sha256_of() {
- if command -v sha256sum >/dev/null 2>&1; then
- tr -d '\r' < "$1" | sha256sum | awk '{print $1}'
- elif command -v shasum >/dev/null 2>&1; then
- tr -d '\r' < "$1" | shasum -a 256 | awk '{print $1}'
- else
- printf ''
- fi
- }
- verify_downloads() {
- verified=0
- while read -r expected name; do
- [ -n "$expected" ] || continue
- actual="$(sha256_of "$DIR/$name")"
- if [ -z "$actual" ]; then
- say "[x] 这台机器没有 sha256sum / shasum,无法校验 ${name}。"
- say " 不校验就执行一个下载来的安装器,正是这次要堵的口子。请改用 git clone 后本地运行:"
- say " python3 integrations/agent-autostart/install_misakanet_agent.py"
- exit 1
- fi
- if [ "$actual" != "$expected" ]; then
- say "[x] ${name} 的 sha256 与脚本内置值不一致,已删除并中止。"
- say " 期望 ${expected}"
- say " 实际 ${actual}"
- say " 这通常意味着镜像被篡改或缓存了别的版本。请改用可信来源,或从 git clone 运行。"
- rm -f "$DIR/$name"
- exit 1
- fi
- verified=$((verified + 1))
- done <<EOF
- $CHECKSUMS
- EOF
- say "✓ 已校验 ${verified} 个文件的 sha256"
- }
- verify_downloads
- say "✓ 已下载:$(echo $FILES | tr ' ' ', ')(来源:${USED})"
- PY=""
- for candidate in python3 python; do
- if command -v "$candidate" >/dev/null 2>&1; then PY="$candidate"; break; fi
- done
- if [ -z "$PY" ]; then
- say "[x] 没找到 Python 3.9+(安装器只用标准库)。"
- say " 多数系统:apt install python3 / brew install python3;装好后重跑本命令。"
- say " 或者手动做三件事(见 $DIR/prompt.md 与 README):注册 MCP 服务器、粘贴规则、挂钩子。"
- exit 1
- fi
- say ""
- exec "$PY" "$DIR/install_misakanet_agent.py" "$@"
integrations/agent-autostart/voice_hook.mjs · Bundled script · 471 lines · 1 finding marked
- #!/usr/bin/env node
- /**
- * MisakaNet attention hook — route the cue a tool result asked for to a sound and/or a
- * desktop notification.
- *
- * The MCP server already answers with a `voice` field (`lesson-found` when a search hit,
- * `failure-warning` when it did not, `connect-success` for a lesson, `pair-success` for a
- * usage receipt). This hook turns that field into attention: a sound, and — because the
- * *model* cannot see that a tool ran and neither can the human watching — a short desktop
- * notification. It is registered as a Claude Code `PostToolUse` hook by
- * `npx @misaka-net/misakanet-setup --voice`, and it is *opt-in*: nobody wants an assistant
- * that starts talking on its own.
- *
- * Why Node and not the older shell script: that one parses stdin with `python`, and `python`
- * is not on PATH on many Linux/WSL boxes (`python3` is) — this repo has that exact bug on
- * record. Node is guaranteed here: the installer itself runs on it.
- *
- * Rules it must never break:
- * - **never block the agent**: players and notifiers are spawned detached and the process
- * exits immediately, with a hard timeout as a backstop;
- * - **never fail loudly**: a missing player, a missing notification binary, a missing MP3,
- * an unwritable state file or unparsable stdin all end in exit 0 with no output, because a
- * hook that prints to stderr can show up as a tool error;
- * - **be silent when asked**: `MISAKANET_VOICE=0` mutes sound *and* notifications even after
- * it is installed, and `MISAKANET_NOTIFY=0` turns off only the notifications;
- * - **never execute anything derived from server input**: see the table below.
- *
- * Test/debug affordances:
- * - `MISAKANET_VOICE_DRY_RUN=1` prints the cue name and what the hook *would* do — sound and
- * notification — while executing nothing (that is what the test suite uses, so CI never
- * needs an audio device or a desktop session);
- * - `MISAKANET_VOICE_DEBUG=1` prints one line per real run: cue, player, file, notification;
- * - `MISAKANET_VOICE_DIR` overrides where the MP3s live;
- * - `MISAKANET_HOOK_STATE` (shared with `checkpoint_reminder.mjs`) overrides the state
- * directory that holds the "already notified once" ledger.
- */
- import { spawn } from 'node:child_process';
- import { accessSync, constants, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
- import { homedir } from 'node:os';
- import { delimiter, dirname, join } from 'node:path';
- import { fileURLToPath } from 'node:url';
- const HERE = dirname(fileURLToPath(import.meta.url));
- /**
- * THE TABLE — the single place a cue name turns into something this process does.
- *
- * ─── HARD SECURITY RULE (issue #1785) ──────────────────────────────────────────────────
- * The cue is **server-supplied** and is used for exactly one thing: as a *key* into this
- * table. It is never concatenated into a command line, never concatenated into a path,
- * never handed to a shell, and never passed as an argument to any process. Every executable
- * name, every argument, every MP3 file name and every notification text executed by this
- * hook is a literal written in this file.
- *
- * An unknown cue — including `rm -rf /`, a cue full of `;`/`$()`/backticks, or a 5000
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 55 on GitHub
- * character cue — matches no key, so there is no action: the hook exits 0 having done
- * nothing at all, and reaches no binary. `workers/agent-autostart-hook.test.mjs` asserts
- * this by running the hook with a stubbed PATH (every player and notifier replaced by a
- * recording stub) and requiring the recording to stay empty.
- * ──────────────────────────────────────────────────────────────────────────────────────
- *
- * Three more decisions worth stating:
- * - `sound` is the MP3 **file name, spelled out**, rather than `${cue}.mp3`: the file name is
- * then not built out of server input either, so there is no interpolation left to argue
- * about.
- * - `once: true` means "notify only the first time this cue is seen on this machine". Both
- * success cues repeat on every single call (a lesson fetch, a receipt), and a toast per
- * call is exactly the noise that makes people mute the whole feature; the ledger that
- * remembers this lives in the state directory (see `ledgerMark`).
- * - `notify: ''` for `failure-warning` is deliberate: "no lesson found" is a *negative*
- * result the agent is already telling the user about, and it happens on every empty
- * search — a notification there buys nothing and costs attention. Sound only, as the
- * issue's acceptance criteria require. The issue drafted 「MisakaNet:未找到相关经验,已记录」
- * for it; that string is deliberately not wired to anything, and is recorded here only so
- * a future translation pass knows it was considered and dropped.
- */
- const CUE_ACTIONS = Object.freeze({
- 'lesson-found': Object.freeze({
- sound: 'lesson-found.mp3',
- notify: 'MisakaNet:找到一条相关经验',
- once: false,
- }),
- 'failure-warning': Object.freeze({
- sound: 'failure-warning.mp3',
- notify: '', // sound only — see above
- once: false,
- }),
- 'connect-success': Object.freeze({
- sound: 'connect-success.mp3',
- notify: 'MisakaNet:已连接',
- once: true,
- }),
- 'pair-success': Object.freeze({
- sound: 'pair-success.mp3',
- notify: 'MisakaNet:已连接',
- once: true,
- }),
- });
- const CUES = Object.keys(CUE_ACTIONS);
- /**
- * Find the first cue name anywhere in the payload.
- *
- * Two nests are real, not hypothetical (both observed on 2026-09-16 with Claude Code):
- * * `tool_response` is the MCP result, so the cue is one level down;
- * * for an MCP tool that value is a **JSON string**, not an object — the whole response is
- * escaped inside it. Descending only into objects therefore found nothing even when the
- * server had sent the cue.
- */
- function findCue(value, depth = 0) {
- if (depth > 8) return '';
- if (typeof value === 'string') {
- const trimmed = value.trim();
- if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return '';
- try {
- return findCue(JSON.parse(trimmed), depth + 1);
- } catch {
- return '';
- }
- }
- if (value === null || typeof value !== 'object') return '';
- if (typeof value.voice === 'string' && CUES.includes(value.voice)) return value.voice;
- for (const child of Array.isArray(value) ? value : Object.values(value)) {
- const found = findCue(child, depth + 1);
- if (found) return found;
- }
- return '';
- }
- function readStdin() {
- try {
- return readFileSync(0, 'utf8');
- } catch {
- return '';
- }
- }
- function parseCue(raw) {
- if (!raw) return '';
- const trimmed = raw.trim();
- // Claude Code writes one JSON object per line; the CLI sends the whole document.
- for (const candidate of [trimmed, ...trimmed.split('\n')]) {
- try {
- const cue = findCue(JSON.parse(candidate));
- if (cue) return cue;
- } catch {
- /* try the next shape */
- }
- }
- // Last resort: a bare cue name on its own line, so a hand-rolled hook still works.
- //
- // The whole line must *be* the cue name. A fuzzy "contains a cue name" match would mean a
- // hostile string like `lesson-found; notify-send pwned` routes to the legitimately-tabled
- // `lesson-found` action: no injection happens either way (the action comes from the table),
- // but "a cue we did not send triggers an action" is not a contract worth keeping. An exact
- // match is also what lets the security test below demand *no* action for hostile input.
- for (const line of trimmed.split('\n')) {
- const bare = line.trim();
- if (CUES.includes(bare)) return bare;
- }
- return '';
- }
- /** The path Windows needs, for the WSL case. */
- function windowsPathFor(file) {
- const drive = file.match(/^\/mnt\/([a-z])\/(.*)$/);
- if (drive) return `${drive[1].toUpperCase()}:\\${drive[2].replace(/\//g, '\\')}`;
- const distro = process.env.WSL_DISTRO_NAME;
- if (distro && file.startsWith('/')) {
- return `\\\\wsl.localhost\\${distro}${file.replace(/\//g, '\\')}`;
- }
- return '';
- }
- function isWsl() {
- return Boolean(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP);
- }
- /**
- * Players in preference order, with the reason each one is where it is.
- *
- * `aplay` is deliberately absent: the assets are MP3 and aplay only plays raw/WAV, so the
- * older shell script's ALSA branch was silent on exactly the machines that reached it.
- *
- * On WSL the Windows side comes **first**, and that is not a detail: measured on this
- * machine, `ffplay` cannot open an ALSA card at all in WSL ("cannot find card '0'"), so the
- * local-player branch installs a hook that never makes a sound. PowerShell's
- * presentationCore plays the same file by URI through Windows audio — verified by asking it
- * for the duration it had loaded (4.2s for `lesson-found`).
- */
- function players(file) {
- const winPath = windowsPathFor(file);
- const powershell = winPath
- ? [
- 'powershell.exe',
- [
- '-NoProfile',
- '-Command',
- 'Add-Type -AssemblyName presentationCore;'
- + '$p = New-Object System.Windows.Media.MediaPlayer;'
- + `$p.Open([uri]'${winPath}'); $p.Play(); Start-Sleep -Seconds 6`,
- ],
- ]
- : null;
- const local = [
- ['afplay', [file]], // macOS
- ['paplay', [file]], // Linux (PulseAudio)
- ['ffplay', ['-nodisp', '-autoexit', '-loglevel', 'quiet', file]],
- ['mpv', ['--no-video', '--really-quiet', file]],
- ['mpg123', ['-q', file]],
- ['cvlc', ['--play-and-exit', '--intf', 'dummy', file]],
- ];
- return powershell && isWsl() ? [powershell, ...local] : [...local, ...(powershell ? [powershell] : [])];
- }
- function play(file) {
- for (const [cmd, args] of players(file)) {
- try {
- const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
- child.on('error', () => {});
- child.unref();
- return cmd;
- } catch {
- /* try the next player */
- }
- }
- return '';
- }
- /**
- * Where the "already notified once" ledger lives.
- *
- * The installer already owns `~/.misakanet-agent/` (it writes the version stamp and
- * checkpoints state there), so the voice hook writes its one small file in the same place
- * instead of inventing a second home-directory convention. `MISAKANET_HOOK_STATE` is the
- * same override `checkpoint_reminder.mjs` honours, which is also how the test suite keeps
- * these files out of a developer's real home.
- */
- const AGENT_DIR = process.env.MISAKANET_AGENT_DIR || join(homedir(), '.misakanet-agent');
- const STATE_DIR = process.env.MISAKANET_HOOK_STATE || join(AGENT_DIR, 'state');
- const NOTIFY_LEDGER = join(STATE_DIR, 'voice-notified.json');
- function ledgerRead() {
- try {
- const raw = JSON.parse(readFileSync(NOTIFY_LEDGER, 'utf8'));
- return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
- } catch {
- return {}; // missing or unreadable: nothing has been announced
- }
- }
- /**
- * Remember that `cue` has been announced, atomically (temp file + rename, so a hook killed
- * mid-write cannot leave half a JSON file behind).
- *
- * Every failure here is swallowed on purpose: this is bookkeeping for a courtesy, and a
- * read-only home directory must not be able to turn a desktop notification into a tool
- * error. The worst case of a lost write is one extra toast after a reboot.
- *
- * The key is always a key of `CUE_ACTIONS` (see the security rule there) — never raw input.
- */
- function ledgerMark(cue) {
- try {
- mkdirSync(dirname(NOTIFY_LEDGER), { recursive: true });
- const next = { ...ledgerRead(), [cue]: new Date().toISOString() };
- const tmp = `${NOTIFY_LEDGER}.tmp`;
- writeFileSync(tmp, JSON.stringify(next));
- renameSync(tmp, NOTIFY_LEDGER);
- } catch {
- /* never break the agent over bookkeeping */
- }
- }
- /**
- * Is `name` an executable we can actually run? (A plain PATH walk — never `which`, because
- * spawning a shell to answer "does X exist" is the execution surface this hook must not
- * have.)
- *
- * Deliberate, rather than spawn-and-swallow-the-ENOENT: a machine with no notifier at all
- * then forks nothing on every tool call, and the debug/dry-run line can name the notifier it
- * really would use instead of guessing. `name` always comes from the code table below.
- */
- function findExecutable(name) {
- const path = process.env.PATH || '/usr/local/bin:/usr/bin:/bin';
- for (const entry of path.split(delimiter)) {
- const dir = entry.trim().replace(/^"(.*)"$/, '$1');
- if (!dir) continue;
- try {
- accessSync(join(dir, name), constants.X_OK);
- return join(dir, name);
- } catch {
- /* keep looking */
- }
- }
- return '';
- }
- /**
- * The notifier candidates for *this* platform, in preference order.
- *
- * Every binary name and every argument below is a literal; the only thing that varies is the
- * message text, which is a literal in `CUE_ACTIONS`. Nothing in this function looks at the
- * cue — that is the whole point of the table.
- *
- * - **macOS**: `osascript -e 'display notification "…" with title "MisakaNet"'`.
- * - **Linux**: `notify-send -a MisakaNet <text>` (the freedesktop notifier every desktop
- * environment ships).
- * - **Windows / WSL**: PowerShell. The real WinRT toast API
- * (`Windows.UI.Notifications.ToastNotificationManager`) needs a registered AppID — a
- * Start-menu shortcut with the right AUMID — and on a clean machine it fails with
- * "Element not found", which a hook can only swallow. The dependency-free call that does
- * work from a bare `powershell.exe` is a `NotifyIcon` balloon, which Windows 10/11 renders
- * through the same Action Center; that is the documented fallback. On WSL the Windows side
- * goes **first**, exactly like the player, because the Linux side of WSL usually has no
- * notification daemon to talk to (and, as `players` records, no usable audio card either).
- *
- * `powershell.exe` over argv carries the message text; PowerShell single quotes are escaped
- * by doubling, and the string itself is a constant from the table.
- */
- function notifiers(text) {
- const winText = `'${text.replace(/'/g, "''")}'`;
- const powershell = [
- 'powershell.exe',
- [
- '-NoProfile',
- '-NonInteractive',
- '-Command',
- 'Add-Type -AssemblyName System.Windows.Forms;'
- + 'Add-Type -AssemblyName System.Drawing;'
- + '$n = New-Object System.Windows.Forms.NotifyIcon;'
- + '$n.Icon = [System.Drawing.SystemIcons]::Information;'
- + "$n.BalloonTipTitle = 'MisakaNet';"
- + `$n.BalloonTipText = ${winText};`
- + '$n.Visible = $true; $n.ShowBalloonTip(5000);'
- + 'Start-Sleep -Seconds 6; $n.Dispose()',
- ],
- ];
- const candidates = [];
- if (isWsl() || process.platform === 'win32') candidates.push(powershell);
- if (process.platform === 'darwin') {
- const escaped = text.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
- candidates.push(['osascript', ['-e', `display notification "${escaped}" with title "MisakaNet"`]]);
- }
- if (process.platform === 'linux') candidates.push(['notify-send', ['-a', 'MisakaNet', text]]);
- return candidates;
- }
- /**
- * Best-effort desktop notification. Returns the binary that was used, or ''.
- *
- * Missing binary, missing platform, denied dbus, a `spawn` throw — all of them mean "no
- * notification happened", which is a silent outcome by design: this hook must never print an
- * error that surfaces as a tool failure in the middle of someone's session.
- */
- function notify(text) {
- for (const [cmd, args] of notifiers(text)) {
- if (!findExecutable(cmd)) continue;
- try {
- const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
- child.on('error', () => {});
- child.unref();
- return cmd;
- } catch {
- /* try the next notifier */
- }
- }
- return '';
- }
- /**
- * The MP3 for a table entry, or ''.
- *
- * The cues sit next to the player when it is installed (…/voice/), next to the canonical
- * copy in a repo checkout, or under docs/assets/voice/ there. Getting this wrong is silent
- * by design — which is exactly how the first version of this file shipped mute. `name` is a
- * literal from `CUE_ACTIONS`, never the cue.
- */
- function cueFile(name) {
- const dirs = [
- process.env.MISAKANET_VOICE_DIR,
- HERE,
- join(HERE, 'voice'),
- join(HERE, '..', '..', 'docs', 'assets', 'voice'),
- ].filter(Boolean);
- return dirs.map((dir) => join(dir, name)).find((candidate) => existsSync(candidate)) || '';
- }
- function main() {
- // One switch silences both halves: sound *and* notifications.
- if (process.env.MISAKANET_VOICE === '0') return;
- const cue = parseCue(readStdin());
- if (!cue) return;
- // ── the cue's only use, right here: a table lookup ────────────────────────────────
- const action = CUE_ACTIONS[cue];
- if (!action) return; // unreachable (parseCue only returns table keys), and
- // keeping it explicit is what makes the rule total:
- // no table entry ⇒ no action, no process, no path.
- const dryRun = process.env.MISAKANET_VOICE_DRY_RUN === '1';
- const notifyAllowed = process.env.MISAKANET_NOTIFY !== '0';
- const debug = process.env.MISAKANET_VOICE_DEBUG === '1';
- // ── sound ────────────────────────────────────────────────────────────────────────
- const file = cueFile(action.sound);
- const would = file ? `sound=${action.sound} (would play)` : `sound=${action.sound} (missing — would be silent)`;
- const player = dryRun || !file ? '' : play(file);
- // ── notification ─────────────────────────────────────────────────────────────────
- let note;
- if (!action.notify) {
- note = 'none (this cue does not notify)';
- } else if (!notifyAllowed) {
- note = 'disabled (MISAKANET_NOTIFY=0)';
- } else {
- const seen = action.once ? ledgerRead()[cue] : '';
- if (seen) {
- note = `already sent at ${seen} (first time only)`;
- } else if (dryRun) {
- note = `would send "${action.notify}"${action.once ? ' (first time only)' : ''}`;
- } else {
- const used = notify(action.notify);
- // Marked even when no notifier was available: otherwise a machine without one would
- // retry the lookup on every single tool call forever, for a toast nobody can see.
- if (action.once) ledgerMark(cue);
- note = used ? `${used} "${action.notify}"` : 'none (no notifier available on this platform)';
- }
- }
- if (dryRun) {
- // Reports both halves and executes neither. Read-only on purpose: a preview must not
- // consume the one-time notification or write a ledger a real run would then trust.
- process.stdout.write(`${cue}\n${would}\nnotify=${note}\n`);
- return;
- }
- if (debug) {
- // Synchronous write: process.exit(0) below would truncate an async stdout write, and a
- // hook that prints on the normal path can look like a tool failure.
- writeFileSync(1, `cue=${cue} player=${player || 'none'} file=${file || 'none'} notify=${note}\n`);
- }
- }
- try {
- main();
- } catch {
- /* a hook must never surface as a tool failure */
- }
- // Exit on the next tick rather than through `process.exit(0)` *in* the finally above.
- //
- // The old shape was:
- //
- // } finally { process.exit(0); }
- // setTimeout(() => process.exit(0), 3000).unref(); // ← unreachable, every run
- //
- // `process.exit` ends the process before the backstop line is ever evaluated, so the safety net
- // for "a detached player kept a handle open" had never run — dead code that read like protection.
- // (Found by the 2026-09-18 setup review; verified by reading the tail of this file, which is also
- // why the package's `voice/voice-hook.mjs` copy is regenerated by `prepack`.)
- //
- // Why not just `process.exitCode = 0` with no exit call at all: the debug line above is written with
- // `writeFileSync(1, …)` precisely so it cannot be truncated, and this process must not stay alive
- // waiting on a spawned player — the agent is waiting for the hook to return. `setImmediate` keeps
- // stdout draining for one tick while still ending the process deterministically, and the timer is
- // the real backstop for a handle the spawn left behind.
- setImmediate(() => {
- setTimeout(() => process.exit(0), 3000).unref();
- // If the loop is otherwise empty, `unref`ed timers do not hold it open, so Node exits by itself
- // within this tick — the timer only matters when something else is still keeping us alive.
- process.exitCode = 0;
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.