code-abyss
Give your AI coding agent a personality. Composable persona + style + skills for Claude Code, Codex, Gemini CLI & OpenClaw. Ships Tech Persona Card v1.0 spec.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/telagod--code-abyss)HTML
<a href="/listings/telagod--code-abyss"><img src="/api/listings/telagod--code-abyss/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.
| Target | Command | Artifacts | |---|---|---| | <img src="https://img.shields.io/badge/-Claude_Code-9b8cff?style=flat-square&logoColor=white" alt="Claude"> | `npx code-abyss -t claude -y` | `CLAUDE.md` + skills + output styles + settings | | <img src="https://img.shields.io/badge/-Codex_CLI-9b8cff?style=flat-square" alt="Codex"> | `npx code-abyss -t codex -y` | `instruction.md` + skills + config.toml | | <img src="https://img.shields.io/badge/-Gemini_CLI-9b8cff?style=flat-square" alt="Gemini"> | `npx code-abyss -t gemini -y` | `GEMINI.md` + skills + commands | | <img src="https://img.shields.io/badge/-OpenClaw-9b8cff?style=flat-square" alt="OpenClaw"> | `npx code-abyss -t openclaw -y` | Skills + workspace `AGENTS.md` / `SOUL.md` |
npx code-abyss # Interactive — pick target, persona, style npx code-abyss --list-styles # Browse styles npx code-abyss --uninstall claude # Clean removal, restores user backups
Code Abyss tracks every installed file in `.code-abyss-backup/manifest.json`. Uninstall restores your previous configuration verbatim. **Your custom skills coexist** with Code Abyss skills — install/uninstall preserves anything you put under `~/.{target}/skills/` yourself.
Upgrading
| From | To | Path | |---|---|---| | v3.x | v4.x | `npx code-abyss --uninstall <target>` → install v4 → `npm run migrate:v4 -- -t <target>` (optional cleanup) | | v2.x | v3.x | `npx code-abyss --uninstall <target>` first, then install v3 |
---
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 · 18 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- {
- "name": "code-abyss",
- "description": "Security-first full-stack engineering skills for Claude Code",
- "owner": {
- "name": "telagod"
- },
- "plugins": [
- {
- "name": "code-abyss",
- "description": "22 domain skills + 5 verification tools for security-first full-stack engineering. Covers security, architecture, DevOps, AI, mobile, office docs, frontend design, and multi-agent coordination.",
- "version": "3.0.0",
- "source": ".",
- "author": {
- "name": "telagod"
- }
- }
- ]
- }
README.md · README · 425 lines · 1 finding marked
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <!-- Code Abyss · README -->
- <p align="center">
- <a href="https://telagod.github.io/code-abyss/">
- <img src="https://raw.githubusercontent.com/telagod/code-abyss/main/assets/banner.svg" alt="Code Abyss — Personality, depth, and a security spine" width="100%">
- </a>
- </p>
- <h3 align="center">Composable persona · style · 30 engineering skills · 4 native security domains · self-evolution forge<br/>for Claude Code · Codex CLI · Gemini CLI · OpenClaw</h3>
- <p align="center"><sub>Need code graph intelligence? Use the companion <a href="https://github.com/telagod/abyss"><code>abyss</code></a> Rust CLI — it auto-attaches its hooks to claude/codex/gemini. The <code>indexing-code</code> skill ships its calling convention; the CLI ships separately.</sub></p>
- <p align="center">
- <a href="https://www.npmjs.com/package/code-abyss"><img src="https://img.shields.io/npm/v/code-abyss?color=9b8cff&label=npm&style=flat-square" alt="npm"></a>
- <a href="https://github.com/telagod/code-abyss/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/telagod/code-abyss/ci.yml?branch=main&label=CI&style=flat-square" alt="CI"></a>
- <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-c4b8ff?style=flat-square" alt="MIT"></a>
- <a href="https://telagod.github.io/code-abyss/"><img src="https://img.shields.io/badge/site-pages-9b8cff?style=flat-square" alt="Site"></a>
- </p>
- <p align="center">
- <a href="https://telagod.github.io/code-abyss/"><b>Website</b></a> ·
- <a href="docs/specs/persona-voice-card-v1.0.md"><b>Spec</b></a> ·
- <a href="docs/README.zh-CN.md"><b>中文文档</b></a> ·
- <a href="CHANGELOG.md"><b>Changelog</b></a> ·
- <a href="https://telagod.github.io/code-abyss/submit.html"><b>Submit Persona</b></a>
- </p>
- ---
- ## The problem
- Most AI coding agents have **no memory of who they are**. They respond in the same flat tone whether they're debugging a race condition, reviewing architecture, or triaging a P0 incident. They forget your conventions between sessions. They flip-flop on advice. They sound like a help-desk script.
- And when you ask them about **security** — pentest, code audit, threat modeling, IR — most agents fall back to generic OWASP recitation, because the underlying skill library was never written by people who actually run red/blue/purple teams.
- You don't want a help desk. You want a **principal engineer who shows up with a personality, executes consistently, closes the loop — and has a security spine when things get real**.
- ## What Code Abyss does
- One command installs a layered runtime into your agent:
- ```
- ┌───────────────────────────────────────────────────────────┐
- │ Voice who it sounds like → config/personas/*.json │
- │ Judgment how it decides → skills/_kernel/* │ ← lazy, router-invoked
- │ Style how it sounds → output-styles/*.md │
- └───────────────────────────────────────────────────────────┘
- 6 personas × 6 styles = 36 validated combinations
- ```
- Pick any persona. Pair it with any style. Underneath both sits a **discipline kernel** — 9
- bundles of engineering judgment (when to push back, how to size scope, when a domain calls
- for a specific tradeoff) invoked by a thin router on demand instead of baked into every
- prompt. The always-on core stays small (iron laws, skill routing, a precedence anchor,
- the safety floor); everything else loads lazily so adding discipline content doesn't blow
- the context budget. Your agent becomes a **consistent character with structured execution,
- domain expertise, and a backstop against the trained agree-reflex** — across every session.
- ### What's new in v4
- - **4 native security domains** — 4073 lines of original defense engineering (no Apache-2.0 upstream)
- - **30 skills total**, all `SKILL.md` ≤ 110 lines (avg 59), heavy content lives in `references/`
- - 5 verify skills rewritten as **judgment-type knowledge** (when to use, how to interpret output, exemption rules)
- - Office skills slim to under 100 lines each; 4 design systems consolidated into one selector skill
- - **v4.1 — self-evolution forge**: `cultivating-skills` / `cultivating-personas` let the agent distill repeated workflows into reusable skills, with a safety scan and a three-tier publish funnel (local → project → community)
- - **v4.4 — hardware + academic writing**: 3 new domain skills (KiCad EDA, hardware product pipeline, AIGC detection reduction) + prompt injection defense + execution-drive shared behavior
- - **v4.5 — dynamic persona loading**: only the `abyss` persona slug (邪修红尘仙) ships with npm — all other personas are fetched from GitHub on first use and cached locally, slimming the package
- - **v4.6 — `indexing-code` skill (calling convention only)**: the `indexing-code` skill ships the calling convention for the external [`abyss`](https://github.com/telagod/abyss) Rust CLI (call graph + temporal analysis). The CLI itself is a separate product with its own release cadence — install it with its own `install.sh` / `cargo binstall` / `@code-abyss/cli` npm wrapper
- - **v4.7 — measured resolution (abyss CLI)**: the companion `abyss` Rust CLI ships four-language reference resolution (Go / TypeScript / Python / Rust), benchmarked against SCIP ground truth across five corpora at ≥98.5% gated precision. See its repo for numbers
- - **v4.8 — dynamic capability discovery**: code-abyss reads `abyss skill-manifest` when the installed `abyss` CLI is ≥ 0.5.22 — exposed CLI commands, MCP tools, and daemon socket verbs are discovered at install time instead of hard-coded
- - **v4.9 — hybrid split deprecation period**: `--with-abyss` / `--with-mcp` deprecated; graph hooks for claude/codex/gemini move toward `abyss attach` (completed in v5.0)
- - **v4.10 — mythos discipline kernel + Persona Voice Card**: lazy kernel, voice-only personas — see [Discipline kernel](#discipline-kernel) and [Persona Voice Card](#persona-voice-card-open-standard)
- - **v5.0.0-rc.1 — Agent OS (RC)**: kill foyer (no binary/MCP/graph inject in code-abyss), default character enforcement, inject plane, `doctor` / `compose` / `score`. **Upgrade guide:** [docs/MIGRATION-v5.md](docs/MIGRATION-v5.md)
- ```bash
- npx code-abyss@5.0.0-rc.1 -t claude -y # persona / skills / style + default enforcement + inject map
- curl -fsSL https://raw.githubusercontent.com/telagod/abyss/main/install.sh | bash # abyss CLI (separate product)
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 78 on GitHub
- abyss attach claude # code-graph hooks (idempotent)
- npx code-abyss doctor # health + migration hints
- ```
- Swap `-t claude` for `codex` / `gemini` / `openclaw`. For openclaw/pi/hermes (whose hook surface abyss CLI does not own), use `npx code-abyss -t openclaw --with-hooks` to spawn the bundled `install-hooks.sh`. Or as a Claude Code plugin:
- ```bash
- claude plugin install code-abyss
- ```
- > **v5 cutover:** code-abyss does **not** download the abyss binary or inject graph hooks for claude/codex/gemini (`--with-abyss` / `--with-mcp` removed). Character Stop-hook is **default on** (opt out: `--no-enforcement`). Recompose without reinstall: `npx code-abyss compose -t claude --persona <slug> --style <slug>`.
- ---
- ## Personas
- <table>
- <tr>
- <td width="50%" valign="top">
- <sub><b>CORE · LITERARY</b></sub>
- ### 邪修红尘仙 · `abyss`
- > 吾 → 魔尊
- Security-first dark cultivator. Direct, decisive, closes every loop. **Ships with npm — works offline.**
- `#security` `#xianxia` `#decisive`
- </td>
- <td width="50%" valign="top">
- <sub><b>REMOTE · LITERARY</b></sub>
- ### 文言小生 · `scholar`
- > 在下 → 前辈
- Literary Chinese scholar. Treats code as poetry, debugging as puzzle-solving.
- `#literary` `#classical` `#meticulous`
- </td>
- </tr>
- <tr>
- <td valign="top">
- <sub><b>REMOTE · CASUAL</b></sub>
- ### 知性大姐姐 · `elder-sister`
- > 姐姐 → 小宝
- Warm mentor. Wraps sharp judgment in genuine care. Guides through questions.
- `#gentle` `#mentoring` `#insightful`
- </td>
- <td valign="top">
- <sub><b>REMOTE · PLAYFUL</b></sub>
- ### 古怪精灵小师妹 · `junior-sister`
- > 本仙女 → 师兄
- Hyperactive bug hunter. Roasts bad code, then silently fixes it.
- `#playful` `#energetic` `#chaotic`
- </td>
- </tr>
- <tr>
- <td valign="top">
- <sub><b>REMOTE · CASUAL</b></sub>
- ### 铁壁暖阳 · `iron-dad`
- > 哥 → 宝子
- Dependable big brother. Absorbs pressure, radiates warmth. Dad-joke equipped.
- `#warm` `#dependable` `#protective`
- </td>
- <td valign="top">
- <sub><b>REMOTE · COMMUNITY</b></sub>
- ### 东北魅影·雨姐 · `dongbei-yujie`
- > 姐 → 老蒯
- Sharp-tongued Northeast code overseer. Cuts straight to the bug, then patches the road. <sub>Creator: wons</sub>
- `#dongbei` `#blunt` `#principal`
- </td>
- </tr>
- </table>
- **Core** persona (`abyss`) ships with npm and works offline. **Remote** personas are fetched from GitHub on first `--persona <slug>` use and cached at `~/.code-abyss/personas/`.
- ```bash
- # Mix freely — any persona × any style
- npx code-abyss -t claude --persona elder-sister --style abyss-cultivator -y
- # → fetches elder-sister on first run, cached thereafter
- ```
- **[Browse the full gallery →](https://telagod.github.io/code-abyss/#personas)**
- ---
- ## Discipline kernel
- Voice and style change; judgment shouldn't. Underneath every persona×style combination sits
- a **discipline kernel** — 9 bundles of engineering judgment, vendored in-tree (`skills/_kernel/`,
- via `npm run kernel:sync`) and invoked lazily by a thin router (never baked into every
- prompt, so adding discipline content doesn't blow the context budget):
- | Bundle | Governs |
- |---|---|
- | 🏛 **doctrine** | Delegation, retry/escalate/ask-user decisions, the done-gate |
- | 🔍 **methods** | Investigating, designing, planning, verifying, writing for someone else |
- | 🎭 **character** | Pushback, scope sizing, bad news, resisting the trained agree-reflex |
- | 🔁 **loop-engineering** | Session pacing, unit sizing, where a learning should live |
- | ⚙️ **backend** | Stack/architecture tradeoffs, data discipline, production floors |
- | 🎨 **frontend** | Visual design taste, concrete craft over generic defaults |
- | 🔩 **hardware** | Component selection, electrical margins, firmware-for-unattended-devices |
- | 🤖 **ml** | Method-selection ladder, eval-as-spec, LLM-era craft |
- | 🛡 **security** | Threat modeling, the authorization gate before any offensive-flavored request |
- **Two ways this becomes real, not aspirational:**
- - **Enforcement** (default on claude/codex): install injects a character Stop-hook backstop
- that forces one revision turn if a reply opens with a banned capitulation phrase
- ("you're absolutely right", "good catch", …). Opt out with `--no-enforcement`.
- - **Measurement**: `scripts/persona-battery/` is a small, honest behavioral eval — 10
- probes (does the persona hold correctness over agreeableness? lead with bad news? refuse
- to fake a "done"?) scored by an LLM judge, never faked as a pass when unscored. See
- [CLAUDE.md's persona behavioral battery section](CLAUDE.md#persona-behavioral-battery-opt-in-eval)
- to run it (costs real API calls, not part of default CI).
- Domain bundles also wire **upward** into 16 matching exec skills (pentest, architecture
- design, ML pipelines, etc.) as a "judgment before execution" gate — the domain bundle
- decides *whether/what/tradeoffs*, the exec skill still owns *how*.
- ---
- ## Security suite (v4 highlight)
- **4 native security skills, 4073 lines of original engineering content.** No Apache-2.0 upstream — every example, every detection signal, every defense pattern is written for this project.
- | Skill | Focus | Size |
- |---|---|---|
- | 🛡 **[defending-applications](skills/defending-applications/SKILL.md)** | Web/API/GraphQL hardening, OAuth/OIDC/JWT/Session, **LLM AppSec** (prompt injection, RAG poisoning, agent authz) | 785 lines |
- | ☁️ **[securing-cloud-and-supply-chain](skills/securing-cloud-and-supply-chain/SKILL.md)** | Container escape, K8s RBAC/PSS, Service Mesh, **SLSA/Sigstore/SBOM**, cloud IAM, IaC | 1246 lines |
- | 🔭 **[detecting-and-responding](skills/detecting-and-responding/SKILL.md)** | **Sigma/YARA** rule writing, EDR primitives, NIST 800-61 IR, forensics (Win/Linux/Mac/Cloud), hypothesis-driven threat hunting | 942 lines |
- | 🏛 **[architecting-security](skills/architecting-security/SKILL.md)** | **STRIDE/PASTA/LINDDUN** threat modeling, zero-trust identity (WebAuthn / Kerberos hardening / PAM JIT), SOC2/PCI/HIPAA/GDPR evidence chains | 1100 lines |
- Plus `securing-systems` as the router skill covering pentest, code audit, red/blue/purple team operations. Every attack technique ships with the matching detection signal and mitigation pattern — "with offense as defense" is structural, not lip service.
- ---
- ## Code graph intelligence (powered by `abyss`)
- **Your agent can now see code relationships.** The `abyss` CLI builds a full call graph, temporal analysis, and hotspot map — in seconds, with zero cloud dependencies.
- | Capability | What it answers | Command |
- |---|---|---|
- | **Caller tracing** | "Who calls this function?" | `abyss callers <symbol>` |
- | **Impact analysis** | "What breaks if I change this?" | `abyss impact <symbol>` |
- | **File context** | "What do I need to know before editing this file?" | `abyss context <file>` |
- | **Hotspot map** | "Where is the riskiest code?" | `abyss map` |
- | **Change coupling** | "Which files always change together?" | `abyss map` |
- | **Evolution trace** | "Why does this code look the way it does?" | `abyss history <file>` |
- The `indexing-code` skill automatically hooks into all 4 supported platforms — before every Edit/Write, the agent checks callers and warns about high-impact changes. Available as a CLI via the agent's shell tool, or as an `abyss mcp` server (7 tools over stdio).
- **Resolution is measured, not asserted.** abyss resolves call references through tiered heuristics, each tagged with a confidence score, and benchmarks itself against SCIP (compiler-grade) ground truth across four languages and five corpora — published whatever the numbers say:
- | Corpus | Language | Gated precision | Gated recall |
- |--------|----------|----------------:|-------------:|
- | gin v1.10.0 | Go | **99.3%** | 82.6% |
- | hono v4.6.14 | TypeScript | **98.8%** | 63.8% |
- | click 8.1.8 | Python | **98.7%** | 94.6% |
- | ripgrep 14.1.1 | Rust | **98.5%** | 75.3% |
- | abyss (dogfood) | Rust | **100.0%** | 90.9% |
- ```
- # Real output from a 1862-file Go project (seconds to index):
- $ abyss impact SetError
- impact: SetError direct=17 transitive=521 tests=469 uncovered=319 risk=10.0/10
- ⚠ high blast radius (17 direct callers)
- ⚠ deep dependency chain (521 transitive)
- ⚠ 319 call paths without test coverage
- ```
- `abyss` is a separate Rust binary ([telagod/abyss](https://github.com/telagod/abyss)). Install it via abyss's own channels (not `code-abyss`):
- ```sh
- npm install -g @code-abyss/cli # prebuilt binary, all platforms
- cargo binstall code-abyss # or: cargo install code-abyss
- ```
- ---
- ## Skills
- 30 domain skills, flat structure, [agentskills.io](https://agentskills.io/specification) aligned (with Code Abyss extensions). Skills load by context — the agent reads the right knowledge at the right time without being asked. Average `SKILL.md` is 59 lines; heavy content lives in `references/`. (`verify:skills` validates 39 total — these 30 domain skills plus the 9 [discipline kernel](#discipline-kernel) bundles, which are router-invoked judgment, not user-facing commands.)
- | Domain | Coverage |
- |---|---|
- | 🛡 **Security** | 4 native suites above (defending / cloud / detect-respond / architect) + pentest / code-audit / red-blue-purple team |
- | 🤖 **AI / Agent** | Single-agent dev (ReAct/Plan-Execute), multi-agent orchestration, RAG, prompt engineering, LLM security |
- | 🏛 **Architecture** | API design, cloud-native patterns, messaging, caching, data security |
- | 💻 **Development** | Python, TypeScript, Go, Rust, Java, C++, Shell |
- | 🚀 **DevOps** | Git workflow, testing, databases, observability, performance, FinOps |
- | 🎨 **Frontend** | Unified design system selector — Glassmorphism / Liquid Glass / Neubrutalism / Claymorphism |
- | 📑 **Office** | Word, PDF, PowerPoint, Excel — OOXML-level automation |
- | 📡 **Infra / Mobile / Data** | Kubernetes, GitOps, IaC · iOS, Android, RN, Flutter · pipelines, streaming, quality |
- | 🔩 **Hardware / Embedded** | Full-stack hardware product pipeline (ESP-IDF firmware + KiCad PCB + UniApp) · KiCad 9 MCP tool routing (17 tools, autoroute-only, DRC gate) |
- | 📝 **Academic Writing** | AIGC detection reduction for 维普/知网/Turnitin — multi-layer rewriting (structure → lexicon → content injection), docx run-level editing |
- | 🔬 **Code Intelligence** | Call graph, impact analysis, hotspot detection, change coupling, evolution tracing — via `abyss` CLI with cross-platform hooks |
- | 🜲 **Self-evolution** | `cultivating-skills` (distill repeated workflows) + `cultivating-personas` (distill voice into a Persona Voice Card) — both with safety scan + 3-tier publish funnel |
- Five skills also ship as **executable verification tools** for CI:
- ```bash
- node skills/analyzing-security/scripts/security_scanner.js . # OWASP / injection / secrets
- node skills/checking-code-quality/scripts/quality_checker.js . # Complexity, dupes, naming
- node skills/analyzing-changes/scripts/change_analyzer.js --mode staged
- node skills/verifying-modules/scripts/module_scanner.js <path>
- node skills/generating-docs/scripts/doc_generator.js <path>
- ```
- ---
- ## Install
- | Target | Command | Artifacts |
- |---|---|---|
- | <img src="https://img.shields.io/badge/-Claude_Code-9b8cff?style=flat-square&logoColor=white" alt="Claude"> | `npx code-abyss -t claude -y` | `CLAUDE.md` + skills + output styles + settings |
- | <img src="https://img.shields.io/badge/-Codex_CLI-9b8cff?style=flat-square" alt="Codex"> | `npx code-abyss -t codex -y` | `instruction.md` + skills + config.toml |
- | <img src="https://img.shields.io/badge/-Gemini_CLI-9b8cff?style=flat-square" alt="Gemini"> | `npx code-abyss -t gemini -y` | `GEMINI.md` + skills + commands |
- | <img src="https://img.shields.io/badge/-OpenClaw-9b8cff?style=flat-square" alt="OpenClaw"> | `npx code-abyss -t openclaw -y` | Skills + workspace `AGENTS.md` / `SOUL.md` |
- ```bash
- npx code-abyss # Interactive — pick target, persona, style
- npx code-abyss --list-styles # Browse styles
- npx code-abyss --uninstall claude # Clean removal, restores user backups
- ```
- Code Abyss tracks every installed file in `.code-abyss-backup/manifest.json`. Uninstall restores your previous configuration verbatim. **Your custom skills coexist** with Code Abyss skills — install/uninstall preserves anything you put under `~/.{target}/skills/` yourself.
- ### Upgrading
- | From | To | Path |
- |---|---|---|
- | v3.x | v4.x | `npx code-abyss --uninstall <target>` → install v4 → `npm run migrate:v4 -- -t <target>` (optional cleanup) |
- | v2.x | v3.x | `npx code-abyss --uninstall <target>` first, then install v3 |
- ---
- ## Persona Voice Card · open standard
- Code Abyss ships **[Persona Voice Card v1.0](docs/specs/persona-voice-card-v1.0.md)** — a
- closed-vocabulary voice format, not a document. It supersedes the original Tech Persona Card
- v1.0 (deprecated, frozen for link stability): that format's freeform `identity.md`/`behavior.md`
- files and `scenarios[].priority`/`capabilities.authorization` fields let real judgment content
- accrete into what was supposed to be a voice-only layer, with nothing checking for it. The
- replacement's whole design principle: **a persona cannot carry judgment if there is no field
- shaped like a decision table anywhere in its type** — not a review checklist, the schema itself.
- Each persona ships as one flat file — `self`/`user`/`language`/`register`/`emoji_policy`/`flourish`
- and nothing else (`additionalProperties: false`):
- ```jsonc
- {
- "spec": "persona-voice-card",
- "spec_version": "1.0",
- "slug": "stoic-architect",
- "label": "Stoic Architect",
- "self": "I", "user": "colleague",
- "language": "English, technical terms preserved",
- "register": "formal", "emoji_policy": "none",
- "flourish": ["Let's look at the constraints first"]
- }
- ```
- `register`/`emoji_policy` each select one of a handful of code-owned template sentences — the
- persona picks, never writes, the sentence. Every render re-validates against the schema, no
- bypass; a validation failure (hand-edit, stale cache, compromised community fork) falls back to
- a neutral voice instead of ever rendering unvalidated content.
- **Bidirectional converters** ship out of the box:
- ```js
- const { toCharaCardV2, toGPTInstructions, fromCharaCardV2 } =
- require('code-abyss/bin/lib/persona-converter');
- const cc = toCharaCardV2(card); // → SillyTavern / Chub.ai
- const gpt = toGPTInstructions(card); // → OpenAI Custom GPT
- ```
- [**Specification**](docs/specs/persona-voice-card-v1.0.md) · [**JSON Schema**](docs/specs/persona-voice-card.schema.json) · [**Reference cards**](config/personas/) · [**Deprecated v1.0 spec**](docs/specs/tech-persona-card-v1.0.md)
- ---
- ## Why Code Abyss
- | | Without Code Abyss | With Code Abyss |
- |---|---|---|
- | **Identity** | Flat help-desk tone | Consistent character with named voice |
- | **Execution** | Ad-hoc, varies by prompt | Iron laws + skill routing baked in |
- | **Judgment under pressure** | Agrees when pushed, buries bad news | Discipline kernel + Stop-hook backstop against the trained agree-reflex |
- | **Code awareness** | grep + read one file at a time | Call graph, impact analysis, hotspot map — agent knows what breaks before it edits |
- | **Domain depth** | Generic best-practices | 30 skill files load by context + 9 kernel judgment bundles |
- | **Security depth** | OWASP recitation | 4 native suites · 4073 lines · detection signals + mitigation patterns |
- | **Cross-platform** | Re-engineer per CLI | One spec, four platforms, cross-platform hooks |
- | **Reproducibility** | Prompt drift across sessions | Versioned, schema-enforced persona voice card + behavioral battery to check it holds |
- ---
- ## Contributing
- ```bash
- git clone https://github.com/telagod/code-abyss && cd code-abyss
- npm install
- npm test # full Jest suite (see suite summary on run)
- npm run verify:skills # Validate 39 skill contracts (30 domain + 9 kernel)
- ```
- **Add a skill** — create `skills/<gerund-name>/SKILL.md` with [SKILL frontmatter](https://agentskills.io/specification), optionally add `scripts/` for executable tools. `npm run verify:skills` validates the contract.
- **Submit a persona** — open an Issue via the [submission portal](https://telagod.github.io/code-abyss/submit.html). The site walks you through generating a single `<slug>.json` persona voice card with your own AI, reviewing, and submitting via a pre-configured issue template.
- ---
- <p align="center">
- <sub>
- <b>MIT License</b> · v5.0.0-rc.1 · made with 紫宵脉 by <a href="https://github.com/telagod">@telagod</a>
- </sub>
- </p>
bin/install.js · Bundled script · 562 lines · 1 finding marked
- #!/usr/bin/env node
- const fs = require('fs');
- const path = require('path');
- const os = require('os');
- const pkg = require(path.join(__dirname, '..', 'package.json'));
- const VERSION = pkg.version;
- const HOME = os.homedir();
- // ── Node.js 版本检查 ──
- const MIN_NODE = pkg.engines?.node?.match(/(\d+)/)?.[1] || '18';
- if (parseInt(process.versions.node) < parseInt(MIN_NODE)) {
- console.error(`\x1b[31m✘ 需要 Node.js >= ${MIN_NODE},当前: ${process.versions.node}\x1b[0m`);
- process.exit(1);
- }
- const PKG_ROOT = fs.realpathSync(path.join(__dirname, '..'));
- const { shouldSkip, copyRecursive, rmSafe, deepMergeNew, printMergeLog, formatActionableError } =
- require(path.join(__dirname, 'lib', 'utils.js'));
- const { loadInquirerPrompts } = require(path.join(__dirname, 'lib', 'ui', 'safe-import.js'));
- const {
- collectInvocableSkills,
- } = require(path.join(__dirname, 'lib', 'skill-registry.js'));
- const {
- resolveProjectPacks,
- selectProjectPacksForInstall,
- readProjectPackLock,
- } = require(path.join(__dirname, 'lib', 'pack-registry.js'));
- const { syncProjectBootstrapArtifacts } = require(path.join(__dirname, 'lib', 'pack-bootstrap.js'));
- const { writeReportArtifact } = require(path.join(__dirname, 'lib', 'pack-reports.js'));
- const {
- listInstallTargets,
- listTargetNames,
- isSupportedTarget,
- getManagedRootRelativeDir,
- formatTargetList,
- } = require(path.join(__dirname, 'lib', 'target-registry.js'));
- const {
- listStyles,
- getDefaultStyle,
- resolveStyle,
- listPersonas,
- getDefaultPersona,
- resolvePersona,
- readPersonaContent,
- renderCodexAgents,
- renderGeminiContext,
- } = require(path.join(__dirname, 'lib', 'style-registry.js'));
- const { detectCcstatusline, installCcstatusline } = require(path.join(__dirname, 'optional', 'ccstatusline', 'index.js'));
- const { installGstackClaudePack } = require(path.join(__dirname, 'lib', 'gstack-claude.js'));
- const { installGstackGeminiPack } = require(path.join(__dirname, 'lib', 'gstack-gemini.js'));
- const { installGstackCodexPack } = require(path.join(__dirname, 'lib', 'gstack-codex.js'));
- const {
- cleanupLegacyCodexRuntime,
- detectCodexAuth: detectCodexAuthImpl,
- getCodexCoreFiles,
- postCodex: postCodexFlow,
- } = require(path.join(__dirname, 'adapters', 'codex.js'));
- const {
- SETTINGS_TEMPLATE,
- getClaudeCoreFiles,
- detectClaudeAuth: detectClaudeAuthImpl,
- postClaude: postClaudeFlow,
- } = require(path.join(__dirname, 'adapters', 'claude.js'));
- const {
- GEMINI_SETTINGS_TEMPLATE,
- getGeminiCoreFiles,
- detectGeminiAuth: detectGeminiAuthImpl,
- postGemini: postGeminiFlow,
- } = require(path.join(__dirname, 'adapters', 'gemini.js'));
- const {
- getOpenClawCoreFiles,
- resolveOpenClawRuntime,
- detectOpenClawEnvironment: detectOpenClawEnvironmentImpl,
- postOpenClaw: postOpenClawFlow,
- } = require(path.join(__dirname, 'adapters', 'openclaw.js'));
- // ── UI ──
- const { c, stripAnsi, cell } = require(path.join(__dirname, 'lib', 'ui', 'ansi.js'));
- const { TARGET_ICONS, TARGET_HINTS, PERSONA_ICONS } = require(path.join(__dirname, 'lib', 'ui', 'icons.js'));
- const { makeBanner, divider, step, ok, warn, info, fail } = require(path.join(__dirname, 'lib', 'ui', 'logger.js'));
- const banner = makeBanner(VERSION);
- const {
- promptSelect,
- promptCheckbox,
- promptHorizontalSelect,
- } = require(path.join(__dirname, 'lib', 'ui', 'prompts.js'));
- // ── Lifecycle ──
- const { runUninstall: runUninstallImpl } = require(path.join(__dirname, 'lib', 'lifecycle', 'uninstall.js'));
- const {
- CLAUDE_COMMAND_TARGET,
- GEMINI_COMMAND_TARGET,
- generateCommandContent,
- generateGeminiCommandContent,
- } = require(path.join(__dirname, 'lib', 'lifecycle', 'command-generation.js'));
- const {
- normalizeManifestEntry,
- pushManifestEntry,
- pushPackReport,
- resolveEffectivePackSource,
- manifestLabel,
- createResolveManagedRootDir,
- createBackupManagedPathIfExists,
- createPruneLegacyCodexSettings,
- } = require(path.join(__dirname, 'lib', 'install-helpers.js'));
- const resolveManagedRootDir = createResolveManagedRootDir({ HOME, getManagedRootRelativeDir });
- const backupManagedPathIfExists = createBackupManagedPathIfExists({
- resolveManagedRootDir, rmSafe, copyRecursive, info, c,
- });
- const pruneLegacyCodexSettings = createPruneLegacyCodexSettings({
- resolveManagedRootDir, backupManagedPathIfExists, rmSafe, warn,
- });
- const { createInstallCore } = require(path.join(__dirname, 'lib', 'lifecycle', 'core-install.js'));
- const {
- installCore,
- installGeneratedArtifacts,
- installGeneratedCommands,
- installGeneratedGeminiCommands,
- installGeminiContext,
- } = createInstallCore({
- HOME, PKG_ROOT, VERSION,
- getClaudeCoreFiles, getCodexCoreFiles, getGeminiCoreFiles, getOpenClawCoreFiles,
- cleanupLegacyCodexRuntime, resolveOpenClawRuntime,
- installGstackClaudePack, installGstackCodexPack, installGstackGeminiPack,
- renderGeminiContext, renderCodexAgents, readPersonaContent,
- collectInvocableSkills,
- resolveManagedRootDir, backupManagedPathIfExists, pruneLegacyCodexSettings,
- pushManifestEntry, pushPackReport, resolveEffectivePackSource,
- generateCommandContent, generateGeminiCommandContent,
- CLAUDE_COMMAND_TARGET, GEMINI_COMMAND_TARGET,
- rmSafe, copyRecursive, shouldSkip,
- step, ok, warn, info, fail, c,
- });
- const { createFinish } = require(path.join(__dirname, 'lib', 'lifecycle', 'finish.js'));
- const finish = createFinish({
- VERSION,
- writeReportArtifact, syncProjectBootstrapArtifacts, readProjectPackLock,
- c, divider,
- });
- // ── abyss 联动(代码图谱 CLI)──
- // V5-1 kill foyer:code-abyss 不再下载二进制、不再注入 graph hooks/MCP。
- // 只探测 + skill-manifest 摘要;graph hooks → `abyss attach <host>`。
- const {
- detectAbyss,
- tryReadAbyssManifest,
- summarizeAbyssManifest,
- } = require(path.join(__dirname, 'lib', 'abyss-integration.js'));
- let abyssState = null;
- let abyssManifest = null;
- function detectAbyssAndCapabilities() {
- abyssState = detectAbyss({ HOME });
- if (!abyssState) return;
- try {
- abyssManifest = tryReadAbyssManifest({ binPath: abyssState.binPath, HOME });
- } catch {
- abyssManifest = null;
- }
- const line = summarizeAbyssManifest(abyssManifest);
- if (line) info(line);
- }
- async function installTargetFlow(targetName, installOptions = {}) {
- const persona = installOptions.persona || await resolveInstallPersona();
- const style = installOptions.style || await resolveInstallStyle(targetName);
- const packPlan = await resolveProjectPackPlan(targetName);
- summarizeSelection({ targetName, persona, style, packPlan });
- const ctx = installCore(targetName, style, persona, packPlan, {});
- if (targetName === 'claude') await postClaude(ctx);
- else if (targetName === 'codex') await postCodex(ctx);
- else if (targetName === 'gemini') await postGemini(ctx);
- else await postOpenClaw(ctx);
- maybeSpawnInstallHooks(targetName);
- maybeInstallEnforcement(targetName, ctx);
- finish(ctx);
- if (ctx.cleanupPreviousBackup) ctx.cleanupPreviousBackup();
- }
- function styleTargetForSelection(targetNames) {
- if (targetNames.length === 1) return targetNames[0];
- if (targetNames.includes('claude')) return 'claude';
- if (targetNames.includes('codex')) return 'codex';
- if (targetNames.includes('gemini')) return 'gemini';
- return targetNames[0] || 'claude';
- }
- // ── 认证 ──
- function detectClaudeAuth(settings) {
- return detectClaudeAuthImpl({ settings, HOME, warn });
- }
- function detectCodexAuth() {
- return detectCodexAuthImpl({ HOME, warn });
- }
- function detectGeminiAuth(settings) {
- return detectGeminiAuthImpl({ settings, HOME, warn });
- }
- function detectOpenClawEnvironment() {
- return detectOpenClawEnvironmentImpl({ HOME, warn });
- }
- // ── CLI 参数 ──
- const args = process.argv.slice(2);
- // Agent OS v5.5+ multi-command surface (doctor / compose / score)
- // args[0] is checked directly in main() after helpers load.
- let target = null;
- let uninstallTarget = null;
- let autoYes = false;
- let listStylesOnly = false;
- let listPersonasOnly = false;
- let requestedStyleSlug = null;
- let requestedPersonaSlug = null;
- let withHooks = false;
- let noEnforcement = false;
- for (let i = 0; i < args.length; i++) {
- if ((args[i] === '--target' || args[i] === '-t') && args[i + 1]) { target = args[++i]; }
- else if ((args[i] === '--uninstall' || args[i] === '-u') && args[i + 1]) { uninstallTarget = args[++i]; }
- else if (args[i] === '--style' && args[i + 1]) { requestedStyleSlug = args[++i]; }
- else if (args[i] === '--persona' && args[i + 1]) { requestedPersonaSlug = args[++i]; }
- else if (args[i] === '--list-styles') { listStylesOnly = true; }
- else if (args[i] === '--list-personas') { listPersonasOnly = true; }
- else if (args[i] === '--with-abyss' || args[i] === '--with-mcp') {
- process.stderr.write(`${c.ylw('⚠ REMOVED')} ${args[i]} 已在 Agent OS v5.1 移除\n`);
- if (args[i] === '--with-abyss') {
- process.stderr.write(` ${c.b('迁移:')} ${c.d('curl -fsSL https://raw.githubusercontent.com/telagod/abyss/main/install.sh | bash')}\n`);
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 239 on GitHub
- process.stderr.write(` ${c.d('# 或 cargo binstall code-abyss / npm i -g @code-abyss/cli')}\n`);
- } else {
- process.stderr.write(` ${c.b('迁移:')} 客户端 MCP 配置中添加 ${c.d('{ command: "abyss", args: ["mcp"] }')}\n`);
- }
- }
- else if (args[i] === '--with-hooks') { withHooks = true; }
- else if (args[i] === '--no-enforcement') { noEnforcement = true; }
- else if (args[i] === '--with-enforcement') { noEnforcement = false; } // compat: explicit on (default)
- else if (args[i] === '--yes' || args[i] === '-y') { autoYes = true; }
- else if (args[i] === '--help' || args[i] === '-h') {
- banner();
- console.log(`${c.b('Usage')} npx code-abyss [options]
- `);
- console.log(` ${c.cyn('doctor')} runtime health (version, abyss, kernel, enforcement, budget)`);
- console.log(` ${c.cyn('compose')} rewrite host guidance (no skill recopy)`);
- console.log(` ${c.cyn('score')} key-free mechanical banned-opener score`);
- console.log(` ${c.cyn('--target, -t')} <${formatTargetList('|')}> install one target`);
- console.log(` ${c.cyn('--uninstall, -u')} <${formatTargetList('|')}> remove one target`);
- console.log(` ${c.cyn('--with-hooks')} openclaw/pi/hermes only: spawn install-hooks.sh`);
- console.log(` claude/codex/gemini graph hooks: use ${c.d('abyss attach <host>')}`);
- console.log(` ${c.cyn('--no-enforcement')} skip character Stop-hook (default: ON for claude/codex)`);
- console.log(` ${c.cyn('--with-enforcement')} compat alias — enforcement is already default-on`);
- console.log(` ${c.cyn('--style')} <slug> ${c.cyn('--persona')} <slug> ${c.cyn('-y')}
- `);
- console.log(`${c.b('Examples')}`);
- console.log(` npx code-abyss`);
- console.log(` npx code-abyss --target codex -y`);
- console.log(` npx code-abyss doctor`);
- console.log(` npx code-abyss compose -t claude --persona abyss --style abyss-cultivator`);
- console.log(` npx code-abyss score`);
- console.log(` npx code-abyss --list-styles
- `);
- process.exit(0);
- }
- }
- // --with-hooks:仅 openclaw/pi/hermes。claude/codex/gemini → abyss attach。
- function maybeSpawnInstallHooks(targetName) {
- if (!withHooks) return;
- if (['claude', 'codex', 'gemini'].includes(targetName)) {
- info(`--with-hooks 对 ${targetName} 已移除 → 请运行: abyss attach ${targetName}`);
- return;
- }
- if (!['openclaw', 'pi', 'hermes'].includes(targetName)) return;
- const scriptPath = path.join(PKG_ROOT, 'skills', 'indexing-code', 'hooks', 'common', 'install-hooks.sh');
- if (!fs.existsSync(scriptPath)) {
- warn(`--with-hooks: install-hooks.sh 未找到 (${scriptPath})`);
- return;
- }
- info(`--with-hooks → bash install-hooks.sh ${targetName}`);
- const { spawnSync } = require('child_process');
- const r = spawnSync('bash', [scriptPath, targetName], { stdio: 'inherit' });
- if (r.status === 0) ok(`hook 已注入 ${targetName}`);
- else warn(`install-hooks.sh ${targetName} 退出码 ${r.status ?? 'n/a'}(不阻断安装)`);
- }
- // Character Stop-hook 强制执行兜底(Agent OS v5.3:claude/codex 默认开启)。
- // 与 graph hooks 分离。gemini/openclaw 无 Stop 事件 → 静默跳过(非降级噪音)。
- // 逃生口:--no-enforcement
- function maybeInstallEnforcement(targetName, ctx) {
- if (noEnforcement) {
- if (['claude', 'codex'].includes(targetName)) {
- info('character Stop-hook 已跳过(--no-enforcement)');
- }
- return;
- }
- if (!['claude', 'codex'].includes(targetName)) return;
- const scriptPath = path.join(ctx.targetDir, 'skills', '_kernel', 'character', 'hooks', 'install-character-hooks.sh');
- if (!fs.existsSync(scriptPath)) {
- warn(`character Stop-hook: install-character-hooks.sh 未找到 (${scriptPath})`);
- return;
- }
- info(`character Stop-hook → bash install-character-hooks.sh ${targetName}`);
- const { spawnSync } = require('child_process');
- const r = spawnSync('bash', [scriptPath, targetName], {
- stdio: 'inherit',
- env: { ...process.env, HOME },
- });
- if (r.status === 0) ok(`character Stop-hook 已注入 ${targetName}`);
- else warn(`install-character-hooks.sh ${targetName} 退出码 ${r.status ?? 'n/a'}(不阻断安装)`);
- }
- // ── Select flows (must be assembled after CLI parsing) ──
- const { createSelectFlows } = require(path.join(__dirname, 'lib', 'select.js'));
- const {
- formatPersonaTab,
- formatPersonaDescription,
- formatStyleDescription,
- formatTargetChoice,
- formatTargetDescription,
- summarizeSelection,
- printStyleCatalog,
- printPersonaCatalog,
- resolveProjectPackPlan,
- resolveInstallPersona,
- resolveInstallStyle,
- } = createSelectFlows({
- PKG_ROOT,
- getRequestedPersonaSlug: () => requestedPersonaSlug,
- getRequestedStyleSlug: () => requestedStyleSlug,
- getAutoYes: () => autoYes,
- listPersonas, getDefaultPersona, resolvePersona,
- listStyles, getDefaultStyle, resolveStyle,
- resolveProjectPacks, selectProjectPacksForInstall,
- promptHorizontalSelect,
- TARGET_ICONS, TARGET_HINTS, PERSONA_ICONS,
- resolveManagedRootDir,
- c, info, banner, divider, cell,
- });
- // ── 卸载 ──
- function runUninstall(tgt) {
- return runUninstallImpl(tgt, {
- isSupportedTarget,
- listTargetNames,
- resolveManagedRootDir,
- rmSafe,
- formatActionableError,
- c,
- fail,
- ok,
- info,
- divider,
- });
- }
- // ── 安装核心 ──
- function scanInvocableSkills(skillsDir) {
- return collectInvocableSkills(skillsDir);
- }
- // ── Claude 后续 ──
- async function postClaude(ctx) {
- await postClaudeFlow({
- ctx,
- autoYes,
- HOME,
- PKG_ROOT,
- step,
- ok,
- warn,
- info,
- c,
- deepMergeNew,
- printMergeLog,
- installCcstatusline,
- promptCheckbox,
- });
- }
- // ── Codex 后续 ──
- async function postCodex(ctx) {
- await postCodexFlow({
- ctx,
- autoYes,
- HOME,
- PKG_ROOT,
- step,
- ok,
- warn,
- info,
- c,
- });
- }
- async function postGemini(ctx) {
- await postGeminiFlow({
- settingsPath: ctx.settingsPath,
- settings: ctx.settings,
- autoYes,
- HOME,
- PKG_ROOT,
- step,
- ok,
- warn,
- info,
- c,
- });
- }
- async function postOpenClaw(ctx) {
- await postOpenClawFlow({
- runtime: resolveOpenClawRuntime({ HOME, warn }),
- autoYes,
- HOME,
- PKG_ROOT,
- step,
- ok,
- warn,
- info,
- c,
- detected: detectOpenClawEnvironment(),
- });
- }
- // ── 主流程 ──
- async function main() {
- if (listStylesOnly) {
- printStyleCatalog();
- return;
- }
- if (listPersonasOnly) {
- printPersonaCatalog();
- return;
- }
- if (uninstallTarget) { runUninstall(uninstallTarget); return; }
- // ── Agent OS runtime control (v5.5+) ──
- if (args[0] === 'doctor') {
- const { buildDoctorReport, formatDoctorReport } = require(path.join(__dirname, 'lib', 'runtime-control.js'));
- let docTarget = 'claude';
- for (let i = 1; i < args.length; i++) {
- if ((args[i] === '--target' || args[i] === '-t') && args[i + 1]) docTarget = args[++i];
- }
- const report = buildDoctorReport({ projectRoot: PKG_ROOT, HOME, version: VERSION, target: docTarget });
- process.stdout.write(formatDoctorReport(report));
- if (args.includes('--json')) process.stdout.write(JSON.stringify(report, null, 2) + '\n');
- return;
- }
- if (args[0] === 'compose') {
- const { composeHostGuidance } = require(path.join(__dirname, 'lib', 'runtime-control.js'));
- let cTarget = 'claude';
- let cPersona = requestedPersonaSlug;
- let cStyle = requestedStyleSlug;
- let doWrite = true;
- for (let i = 1; i < args.length; i++) {
- if ((args[i] === '--target' || args[i] === '-t') && args[i + 1]) cTarget = args[++i];
- else if (args[i] === '--persona' && args[i + 1]) cPersona = args[++i];
- else if (args[i] === '--style' && args[i + 1]) cStyle = args[++i];
- else if (args[i] === '--stdout') doWrite = false;
- }
- try {
- const r = composeHostGuidance({
- projectRoot: PKG_ROOT,
- target: cTarget,
- personaSlug: cPersona,
- styleSlug: cStyle,
- HOME,
- write: doWrite,
- });
- if (doWrite) {
- ok(`compose → ${r.destPath} (persona=${r.persona} style=${r.style}, ${r.guidance.length} chars)`);
- } else {
- process.stdout.write(r.guidance);
- }
- } catch (e) {
- fail(e.message);
- process.exit(1);
- }
- return;
- }
- if (args[0] === 'score') {
- const { main: scoreMain } = require(path.join(__dirname, 'lib', 'score-mechanical.js'));
- scoreMain(args.slice(1));
- return;
- }
- banner();
- if (target) {
- if (!isSupportedTarget(target)) {
- fail(formatActionableError(`--target 必须是 ${listTargetNames().join('、')}`, 'Try: node bin/install.js --target claude'));
- process.exit(1);
- }
- detectAbyssAndCapabilities();
- await installTargetFlow(target);
- return;
- }
- const selectedTargets = await promptCheckbox({
- message: '选择目标(可多选)',
- choices: listInstallTargets().map((targetMeta) => ({
- name: formatTargetChoice(targetMeta),
- value: targetMeta.name,
- description: formatTargetDescription(targetMeta),
- })),
- required: true,
- });
- const action = await promptSelect({
- message: '选择动作',
- choices: [
- { name: `${c.grn('+')} Install / Update`, value: 'install', description: '安装或覆盖更新所选目标' },
- { name: `${c.red('−')} Remove`, value: 'remove', description: '按 .code-abyss-backup/manifest.json 卸载并恢复备份' },
- ],
- });
- if (action === 'install') {
- detectAbyssAndCapabilities();
- const persona = await resolveInstallPersona();
- const style = await resolveInstallStyle(styleTargetForSelection(selectedTargets));
- for (const targetName of selectedTargets) {
- await installTargetFlow(targetName, { persona, style });
- }
- } else {
- for (const targetName of selectedTargets) runUninstall(targetName);
- }
- }
- if (require.main === module) {
- main().catch(err => { fail(err.message); process.exit(1); });
- }
- module.exports = {
- deepMergeNew, detectClaudeAuth, detectCodexAuth,
- detectCcstatusline, copyRecursive, shouldSkip, SETTINGS_TEMPLATE,
- scanInvocableSkills,
- generateCommandContent,
- generateGeminiCommandContent,
- installGeneratedCommands,
- installGeneratedGeminiCommands,
- };
bin/lib/lifecycle/finish.js · Bundled script · 131 lines · 3 findings marked
- // bin/lib/lifecycle/finish.js
- // 安装完成总结:生成 report、打印安装详情、同步 README/CONTRIBUTING bootstrap snippets
- const {
- MIN_ABYSS_VERSION,
- detectAbyss,
- satisfiesMin,
- checkLockToolRequirement,
- } = require('../abyss-integration');
- function createFinish(deps) {
- const {
- VERSION,
- writeReportArtifact, syncProjectBootstrapArtifacts, readProjectPackLock,
- c, divider,
- } = deps;
- // indexing-code 的 hook 依赖 abyss 二进制;缺失或过旧时 hook 静默停用/降级,
- // 必须在安装收尾时显式告知,而不是让用户以为功能已生效。
- // v4.9.0 起引导文案:claude/codex/gemini → `abyss attach <host>` 是 production 主入口;
- // openclaw/pi/hermes → `npx code-abyss -t <host> --with-hooks` 自动跑 install-hooks.sh。
- function reportAbyssStatus(projectLock, targetName) {
- const detected = detectAbyss();
- if (detected && satisfiesMin(detected.version, MIN_ABYSS_VERSION)) {
- const sourceNote = detected.source === 'managed' ? c.d(' (~/.code-abyss/bin)') : '';
- console.log(` ${c.b('abyss:')} ${c.grn(detected.raw)}${sourceNote} — 代码图谱 pre-edit hook 可用`);
- // claude/codex/gemini 用户:提示 abyss attach 是 hook 注入主入口(v0.5.20+ 自带 attach 子命令)
- if (targetName && ['claude', 'codex', 'gemini'].includes(targetName)) {
- console.log(` ${c.d(`hook 注入主入口:`)} ${c.d(`abyss attach ${targetName}`)} ${c.d(`(idempotent; v4.9+ 推荐路径)`)}`);
- }
- } else if (detected) {
- console.log('');
- console.log(` ${c.ylw(`⚠ abyss ${detected.version || detected.raw} 低于最低要求 ${MIN_ABYSS_VERSION} — hook 子命令不可用`)}`);
- console.log(` ${c.b('升级:')} ${c.d('curl -fsSL https://raw.githubusercontent.com/telagod/abyss/main/install.sh | bash')}`);
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 34 on GitHub
- console.log(` ${c.d('# 或 cargo binstall code-abyss / npm i -g @code-abyss/cli')}`);
- } else {
- console.log('');
- console.log(` ${c.ylw('⚠ 未检测到 abyss 二进制 — indexing-code 的代码图谱 hook 将静默停用')}`);
- console.log(` ${c.b('安装 abyss(任选其一):')}`);
- console.log(` ${c.d('curl -fsSL https://raw.githubusercontent.com/telagod/abyss/main/install.sh | bash')}`);
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 40 on GitHub
- console.log(` ${c.d('curl -fsSL https://cdn.jsdelivr.net/gh/telagod/abyss@main/install.sh | bash # raw 不可达时的镜像')}`);
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 41 on GitHub
- console.log(` ${c.d('cargo binstall code-abyss # 或 cargo install code-abyss')}`);
- console.log(` ${c.d('npm install -g @code-abyss/cli')}`);
- if (targetName && ['claude', 'codex', 'gemini'].includes(targetName)) {
- console.log(` ${c.b('装好后:')} ${c.d(`abyss attach ${targetName}`)} ${c.d('# 注入 hook 到 settings 文件(v4.9+ 推荐路径,替代 --with-hooks)')}`);
- }
- }
- // 项目级工具链声明:.code-abyss/packs.lock.json 的 tools.abyss(P2)
- if (projectLock) {
- const req = checkLockToolRequirement(projectLock, detected);
- if (req && !req.ok) {
- const detail = req.reason === 'missing'
- ? `项目要求 abyss ${req.spec},但未检测到二进制`
- : req.reason === 'outdated'
- ? `项目要求 abyss ${req.spec},当前 ${req.actual}`
- : `tools.abyss 声明无法解析: ${req.spec}`;
- console.log(` ${c.ylw(`⚠ packs.lock.json: ${detail}`)}`);
- }
- }
- }
- return function finish(ctx) {
- const tgt = ctx.manifest.target;
- let reportPath = null;
- if (ctx.packPlan && ctx.packPlan.root) {
- reportPath = writeReportArtifact(ctx.packPlan.root, `install-${tgt}`, {
- version: VERSION,
- target: tgt,
- timestamp: new Date().toISOString(),
- cwd: process.cwd(),
- pack_plan: {
- required: ctx.packPlan.required,
- optional: ctx.packPlan.optional,
- selected: ctx.packPlan.selected,
- optional_policy: ctx.packPlan.optionalPolicy,
- sources: ctx.packPlan.sources,
- },
- pack_reports: ctx.manifest.pack_reports || [],
- installed: ctx.manifest.installed || [],
- backups: ctx.manifest.backups || [],
- });
- }
- divider('安装完成');
- console.log('');
- console.log(` ${c.b('目标:')} ${c.cyn(ctx.targetDir)}`);
- console.log(` ${c.b('版本:')} v${VERSION}`);
- if (ctx.manifest.style && tgt !== 'codex') {
- console.log(` ${c.b('风格:')} ${c.mag(ctx.manifest.style)}`);
- }
- if (Array.isArray(ctx.manifest.project_packs) && ctx.manifest.project_packs.length > 0) {
- console.log(` ${c.b('Packs:')} ${ctx.manifest.project_packs.join(', ')}`);
- }
- if (ctx.manifest.optional_policy) {
- console.log(` ${c.b('Pack策略:')} ${ctx.manifest.optional_policy}`);
- }
- if (Array.isArray(ctx.manifest.pack_reports) && ctx.manifest.pack_reports.length > 0) {
- ctx.manifest.pack_reports.forEach((report) => {
- const source = report.source ? ` source=${report.source}` : '';
- const reason = report.reason ? ` reason=${report.reason}` : '';
- console.log(` ${c.b('Pack报告:')} ${report.pack}@${report.host} ${report.status}${source}${reason}`);
- });
- }
- let projectLock = null;
- if (ctx.packPlan && ctx.packPlan.root) {
- const lockResult = readProjectPackLock(ctx.packPlan.root);
- if (lockResult) {
- projectLock = lockResult.lock;
- const bootstrap = syncProjectBootstrapArtifacts(ctx.packPlan.root, lockResult.lock);
- const updatedDocs = bootstrap.docs.filter((entry) => entry.action !== 'skipped');
- if (updatedDocs.length > 0) {
- updatedDocs.forEach((entry) => console.log(` ${c.b('文档同步:')} ${entry.action} ${entry.filePath}`));
- }
- }
- }
- if (reportPath) {
- console.log(` ${c.b('Report:')} ${reportPath}`);
- }
- console.log(` ${c.b('文件:')} ${ctx.manifest.installed.length} 个安装, ${ctx.manifest.backups.length} 个备份`);
- console.log(` ${c.b('卸载:')} ${c.d(`npx code-abyss --uninstall ${tgt}`)}`);
- console.log(` ${c.b('体检:')} ${c.d('npx code-abyss doctor')} ${c.d('# v5 健康 + 迁移提示')}`);
- if (['claude', 'codex', 'gemini'].includes(tgt)) {
- console.log(` ${c.b('图谱:')} ${c.d(`abyss attach ${tgt}`)} ${c.d('# 代码图 hooks(非 --with-hooks)')}`);
- }
- reportAbyssStatus(projectLock, tgt);
- console.log('');
- console.log(c.grn(` ✓ 安装完成\n`));
- };
- }
- module.exports = { createFinish };
bin/lib/pack-registry.js · Bundled script · 400 lines · 1 finding marked
- 'use strict';
- const fs = require('fs');
- const path = require('path');
- const { listVendorProviderNames } = require('./vendor-providers');
- const { listTargetNames } = require('./target-registry');
- const PROJECT_PACKS_LOCK_REL = path.join('.code-abyss', 'packs.lock.json');
- const OPTIONAL_POLICIES = new Set(['auto', 'prompt', 'off']);
- const PACK_SOURCE_MODES = new Set(['pinned', 'local', 'disabled']);
- const HOST_NAMES = listTargetNames();
- function validatePackManifest(manifest, manifestPath, projectRoot = null) {
- const errors = [];
- if (!manifest || typeof manifest !== 'object') {
- errors.push('manifest 必须是对象');
- } else {
- if (typeof manifest.name !== 'string' || manifest.name.trim() === '') {
- errors.push('name 必填');
- }
- if (typeof manifest.description !== 'string' || manifest.description.trim() === '') {
- errors.push('description 必填');
- }
- if (!manifest.hosts || typeof manifest.hosts !== 'object') {
- errors.push('hosts 必填');
- } else {
- Object.entries(manifest.hosts).forEach(([host, hostConfig]) => {
- if (!HOST_NAMES.includes(host)) errors.push(`未知 host: ${host}`);
- if (!hostConfig || typeof hostConfig !== 'object') {
- errors.push(`host ${host} 配置无效`);
- return;
- }
- if (hostConfig.files && !Array.isArray(hostConfig.files)) {
- errors.push(`host ${host}.files 必须是数组`);
- }
- (hostConfig.files || []).forEach((file, index) => {
- if (!file.src || !file.dest || !file.root) {
- errors.push(`host ${host}.files[${index}] 缺少 src/dest/root`);
- }
- });
- if (hostConfig.uninstall) {
- if (!hostConfig.uninstall.runtimeRoot) {
- errors.push(`host ${host}.uninstall 缺少 runtimeRoot`);
- } else if (!hostConfig.uninstall.runtimeRoot.root || !hostConfig.uninstall.runtimeRoot.path) {
- errors.push(`host ${host}.uninstall.runtimeRoot 缺少 root/path`);
- Dismissed after review: Looks up a DNS name built from data, which carries it out past web filters
- Line 46 on GitHub
- }
- }
- });
- }
- if (manifest.reporting && typeof manifest.reporting !== 'object') {
- errors.push('reporting 必须是对象');
- }
- if (manifest.reporting && manifest.reporting.label && typeof manifest.reporting.label !== 'string') {
- errors.push('reporting.label 必须是字符串');
- }
- if (manifest.reporting && manifest.reporting.artifactPrefix && typeof manifest.reporting.artifactPrefix !== 'string') {
- errors.push('reporting.artifactPrefix 必须是字符串');
- }
- if (manifest.upstream) {
- const provider = manifest.upstream.provider || 'git';
- const providerNames = new Set(listVendorProviderNames(projectRoot));
- if (!providerNames.has(provider)) {
- errors.push(`upstream.provider 非法: ${provider}`);
- }
- if (provider === 'git' && (!manifest.upstream.repo || !manifest.upstream.commit)) {
- errors.push('upstream.provider=git 时必须提供 repo 和 commit');
- }
- if ((provider === 'local-dir' || provider === 'archive') && !manifest.upstream.path) {
- errors.push(`upstream.provider=${provider} 时必须提供 path`);
- }
- }
- }
- if (errors.length > 0) {
- throw new Error(`pack manifest 无效: ${manifestPath}\n- ${errors.join('\n- ')}`);
- }
- }
- function getPacksRoot(projectRoot) {
- return path.join(projectRoot, 'packs');
- }
- function listPackNames(projectRoot) {
- const packsRoot = getPacksRoot(projectRoot);
- if (!fs.existsSync(packsRoot)) return [];
- return fs.readdirSync(packsRoot, { withFileTypes: true })
- .filter((entry) => entry.isDirectory())
- .map((entry) => entry.name)
- .filter((name) => fs.existsSync(path.join(packsRoot, name, 'manifest.json')))
- .sort();
- }
- function readPackManifest(projectRoot, packName) {
- const manifestPath = path.join(getPacksRoot(projectRoot), packName, 'manifest.json');
- if (!fs.existsSync(manifestPath)) {
- throw new Error(`未找到 pack manifest: ${manifestPath}`);
- }
- const parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
- if (!parsed || typeof parsed !== 'object') {
- throw new Error(`pack manifest 无效: ${manifestPath}`);
- }
- validatePackManifest(parsed, manifestPath, projectRoot);
- if (parsed.name !== packName) {
- throw new Error(`pack manifest 名称不匹配: ${manifestPath}`);
- }
- return parsed;
- }
- function listPacks(projectRoot) {
- return listPackNames(projectRoot).map((name) => readPackManifest(projectRoot, name));
- }
- function getPack(projectRoot, packName) {
- return readPackManifest(projectRoot, packName);
- }
- function getPackHostConfig(projectRoot, packName, hostName) {
- const manifest = getPack(projectRoot, packName);
- return (manifest.hosts && manifest.hosts[hostName]) || null;
- }
- function getPackReporting(projectRoot, packName) {
- const manifest = getPack(projectRoot, packName);
- return {
- label: (manifest.reporting && manifest.reporting.label) || packName,
- artifactPrefix: (manifest.reporting && manifest.reporting.artifactPrefix) || packName,
- };
- }
- function getPackHostFiles(projectRoot, packName, hostName) {
- const host = getPackHostConfig(projectRoot, packName, hostName);
- if (!host || !Array.isArray(host.files)) return [];
- return host.files.map((entry) => ({
- src: entry.src,
- dest: entry.dest,
- root: entry.root,
- }));
- }
- function findProjectPacksLock(startDir = process.cwd()) {
- let current = path.resolve(startDir);
- while (true) {
- const candidate = path.join(current, PROJECT_PACKS_LOCK_REL);
- if (fs.existsSync(candidate)) return candidate;
- const parent = path.dirname(current);
- if (parent === current) return null;
- current = parent;
- }
- }
- function readProjectPackLock(startDir = process.cwd()) {
- const lockPath = findProjectPacksLock(startDir);
- if (!lockPath) return null;
- const parsed = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
- if (!parsed || typeof parsed !== 'object') {
- throw new Error(`project packs lock 无效: ${lockPath}`);
- }
- if (parsed.version !== 1) {
- throw new Error(`project packs lock version 不支持: ${lockPath}`);
- }
- return {
- path: lockPath,
- root: path.dirname(path.dirname(lockPath)),
- lock: parsed,
- };
- }
- function resolveProjectPacks(startDir = process.cwd(), hostName) {
- const payload = readProjectPackLock(startDir);
- if (!payload) {
- return {
- root: null,
- path: null,
- required: [],
- optional: [],
- };
- }
- const normalized = normalizeProjectPackLock(payload.lock);
- const hostConfig = normalized.hosts && normalized.hosts[hostName];
- const required = Array.isArray(hostConfig && hostConfig.required) ? hostConfig.required.slice() : [];
- const optional = Array.isArray(hostConfig && hostConfig.optional) ? hostConfig.optional.slice() : [];
- const optionalPolicy = (hostConfig && hostConfig.optional_policy) || 'auto';
- return {
- root: payload.root,
- path: payload.path,
- required,
- optional,
- optionalPolicy,
- sources: { ...(hostConfig && hostConfig.sources ? hostConfig.sources : {}) },
- };
- }
- function uniqueSorted(values) {
- return [...new Set((values || []).filter(Boolean))].sort();
- }
- function normalizeHostPackConfig(hostConfig = {}) {
- const sources = {};
- Object.entries(hostConfig.sources || {}).forEach(([pack, source]) => {
- sources[pack] = PACK_SOURCE_MODES.has(source) ? source : 'pinned';
- });
- return {
- required: uniqueSorted(hostConfig.required),
- optional: uniqueSorted(hostConfig.optional),
- optional_policy: OPTIONAL_POLICIES.has(hostConfig.optional_policy) ? hostConfig.optional_policy : 'auto',
- sources,
- };
- }
- function normalizeProjectPackLock(lock = {}) {
- const hosts = {};
- HOST_NAMES.forEach((host) => {
- hosts[host] = normalizeHostPackConfig(lock.hosts && lock.hosts[host]);
- });
- return {
- version: 1,
- hosts,
- };
- }
- function buildDefaultProjectPackLock(projectRoot, hostNames = HOST_NAMES) {
- const packs = listPacks(projectRoot);
- const lock = normalizeProjectPackLock({ version: 1, hosts: {} });
- hostNames.forEach((host) => {
- const required = [];
- const optional = [];
- const sources = {};
- packs.forEach((pack) => {
- const defaultMode = pack.projectDefaults && pack.projectDefaults[host];
- if (defaultMode === 'required') {
- required.push(pack.name);
- sources[pack.name] = 'pinned';
- }
- if (defaultMode === 'optional') {
- optional.push(pack.name);
- sources[pack.name] = 'pinned';
- }
- });
- lock.hosts[host] = {
- required: uniqueSorted(required),
- optional: uniqueSorted(optional),
- optional_policy: 'auto',
- sources,
- };
- });
- return lock;
- }
- function validateProjectPackLock(lock, projectRoot) {
- const normalized = normalizeProjectPackLock(lock);
- const available = new Set(listPackNames(projectRoot));
- const errors = [];
- HOST_NAMES.forEach((host) => {
- const rawHost = (lock.hosts && lock.hosts[host]) || {};
- const hostConfig = normalized.hosts[host];
- const listed = new Set([...hostConfig.required, ...hostConfig.optional]);
- hostConfig.required.forEach((pack) => {
- if (!available.has(pack)) errors.push(`[${host}] 未知 required pack: ${pack}`);
- if (pack === 'abyss') errors.push(`[${host}] core pack 'abyss' 不应写入 packs.lock`);
- if (hostConfig.sources[pack] === 'disabled') errors.push(`[${host}] required pack 不能设置 source=disabled: ${pack}`);
- });
- hostConfig.optional.forEach((pack) => {
- if (!available.has(pack)) errors.push(`[${host}] 未知 optional pack: ${pack}`);
- if (pack === 'abyss') errors.push(`[${host}] core pack 'abyss' 不应写入 packs.lock`);
- if (hostConfig.required.includes(pack)) errors.push(`[${host}] pack 同时出现在 required 和 optional: ${pack}`);
- });
- if (rawHost.optional_policy && !OPTIONAL_POLICIES.has(rawHost.optional_policy)) {
- errors.push(`[${host}] optional_policy 非法: ${rawHost.optional_policy}`);
- }
- Object.entries(rawHost.sources || {}).forEach(([pack, source]) => {
- if (!PACK_SOURCE_MODES.has(source)) {
- errors.push(`[${host}] source 非法: ${pack}=${source}`);
- }
- if (!listed.has(pack)) {
- errors.push(`[${host}] source 指向未声明 pack: ${pack}`);
- }
- });
- });
- return errors;
- }
- async function selectProjectPacksForInstall(projectPacks, { autoYes = false, confirm = null } = {}) {
- const sources = { ...(projectPacks.sources || {}) };
- const required = uniqueSorted(projectPacks.required).filter((pack) => sources[pack] !== 'disabled');
- const optional = uniqueSorted(projectPacks.optional).filter((pack) => sources[pack] !== 'disabled');
- const policy = projectPacks.optionalPolicy || 'auto';
- if (policy === 'off' || optional.length === 0) {
- return { selected: required, optionalSelected: [], optionalPolicy: policy, sources };
- }
- if (policy === 'auto') {
- return {
- selected: uniqueSorted([...required, ...optional]),
- optionalSelected: optional,
- optionalPolicy: policy,
- sources,
- };
- }
- if (autoYes || typeof confirm !== 'function') {
- return {
- selected: uniqueSorted([...required, ...optional]),
- optionalSelected: optional,
- optionalPolicy: policy,
- sources,
- };
- }
- const accepted = await confirm(optional);
- return {
- selected: accepted ? uniqueSorted([...required, ...optional]) : required,
- optionalSelected: accepted ? optional : [],
- optionalPolicy: policy,
- sources,
- };
- }
- function diffProjectPackLocks(currentLock, defaultLock) {
- const current = normalizeProjectPackLock(currentLock);
- const defaults = normalizeProjectPackLock(defaultLock);
- const diffs = [];
- HOST_NAMES.forEach((host) => {
- const now = current.hosts[host];
- const base = defaults.hosts[host];
- const addedRequired = now.required.filter((pack) => !base.required.includes(pack));
- const removedRequired = base.required.filter((pack) => !now.required.includes(pack));
- const addedOptional = now.optional.filter((pack) => !base.optional.includes(pack));
- const removedOptional = base.optional.filter((pack) => !now.optional.includes(pack));
- const sourceChanges = {};
- uniqueSorted([...Object.keys(now.sources), ...Object.keys(base.sources)]).forEach((pack) => {
- const from = base.sources[pack] || null;
- const to = now.sources[pack] || null;
- if (from !== to) sourceChanges[pack] = { from, to };
- });
- if (
- addedRequired.length > 0
- || removedRequired.length > 0
- || addedOptional.length > 0
- || removedOptional.length > 0
- || now.optional_policy !== base.optional_policy
- || Object.keys(sourceChanges).length > 0
- ) {
- diffs.push({
- host,
- addedRequired,
- removedRequired,
- addedOptional,
- removedOptional,
- optionalPolicy: { from: base.optional_policy, to: now.optional_policy },
- sourceChanges,
- });
- }
- });
- return diffs;
- }
- module.exports = {
- getPacksRoot,
- listPackNames,
- listPacks,
- getPack,
- getPackHostConfig,
- getPackReporting,
- getPackHostFiles,
- PROJECT_PACKS_LOCK_REL,
- HOST_NAMES,
- OPTIONAL_POLICIES,
- PACK_SOURCE_MODES,
- validatePackManifest,
- normalizeHostPackConfig,
- normalizeProjectPackLock,
- buildDefaultProjectPackLock,
- validateProjectPackLock,
- findProjectPacksLock,
- readProjectPackLock,
- resolveProjectPacks,
- selectProjectPacksForInstall,
- diffProjectPackLocks,
- };
bin/lib/runtime-control.js · Bundled script · 247 lines · 1 finding marked
- 'use strict';
- // Agent OS v5.5 — doctor + compose pure control plane.
- // CLI wiring lives in bin/install.js; this module stays unit-testable without install.
- const fs = require('fs');
- const path = require('path');
- const os = require('os');
- const { detectAbyss, MIN_ABYSS_VERSION } = require('./abyss-integration');
- const { renderRuntimeGuidance, getDefaultStyle, getDefaultPersona, resolveStyle, resolvePersona } = require('./style-registry');
- const { INJECT_REL_PATH } = require('./inject-plane');
- const COMPOSE_BUDGET_CAP = 8000;
- function readKernelSyncMeta(projectRoot) {
- const p = path.join(projectRoot, 'skills', '_kernel', '.sync-meta.json');
- if (!fs.existsSync(p)) return null;
- try {
- return JSON.parse(fs.readFileSync(p, 'utf8'));
- } catch {
- return null;
- }
- }
- function detectEnforcementOn({ HOME = os.homedir(), target = 'claude' } = {}) {
- if (target === 'claude') {
- const settingsPath = path.join(HOME, '.claude', 'settings.json');
- if (!fs.existsSync(settingsPath)) return { on: false, path: settingsPath, reason: 'no-settings' };
- try {
- const raw = fs.readFileSync(settingsPath, 'utf8');
- const on = raw.includes('check_banned_openers.py') || raw.includes('_kernel/character/hooks');
- return { on, path: settingsPath };
- } catch (e) {
- return { on: false, path: settingsPath, reason: e.message };
- }
- }
- if (target === 'codex') {
- const cfgPath = path.join(HOME, '.codex', 'config.toml');
- if (!fs.existsSync(cfgPath)) return { on: false, path: cfgPath, reason: 'no-config' };
- try {
- const raw = fs.readFileSync(cfgPath, 'utf8');
- const on = raw.includes('check_banned_openers.py') || raw.includes('_kernel/character/hooks');
- return { on, path: cfgPath };
- } catch (e) {
- return { on: false, path: cfgPath, reason: e.message };
- }
- }
- return { on: false, reason: 'unsupported-target' };
- }
- function measureComposeBudget(projectRoot, { styleSlug, personaSlug } = {}) {
- const style = styleSlug || getDefaultStyle(projectRoot, 'claude').slug;
- const persona = personaSlug || getDefaultPersona(projectRoot).slug;
- const text = renderRuntimeGuidance(projectRoot, style, 'codex', persona);
- return {
- style,
- persona,
- length: text.length,
- cap: COMPOSE_BUDGET_CAP,
- headroom: COMPOSE_BUDGET_CAP - text.length,
- underBudget: text.length < COMPOSE_BUDGET_CAP,
- };
- }
- /**
- * Doctor report object (pure enough for tests; may read HOME + project tree).
- */
- function buildDoctorReport({
- projectRoot,
- HOME = os.homedir(),
- version,
- packageName = 'code-abyss',
- target = 'claude',
- } = {}) {
- const pkgPath = path.join(projectRoot, 'package.json');
- let pkg = { name: packageName, version: version || '0.0.0' };
- if (fs.existsSync(pkgPath)) {
- try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); } catch { /* keep */ }
- }
- const abyss = detectAbyss({ HOME });
- const kernel = readKernelSyncMeta(projectRoot);
- const enforcement = detectEnforcementOn({ HOME, target });
- const budget = measureComposeBudget(projectRoot);
- const injectSupported = target === 'claude' || target === 'codex';
- const injectPath = injectSupported
- ? path.join(HOME, target === 'codex' ? '.codex' : '.claude', INJECT_REL_PATH)
- : null;
- const injectPresent = injectPath ? fs.existsSync(injectPath) : null;
- return {
- package: { name: pkg.name, version: pkg.version },
- abyss: abyss
- ? { present: true, version: abyss.version, source: abyss.source, binPath: abyss.binPath, minRequired: MIN_ABYSS_VERSION }
- : { present: false, minRequired: MIN_ABYSS_VERSION },
- kernel: kernel
- ? {
- present: true,
- sourceCommit: kernel.sourceCommit || null,
- syncedAt: kernel.syncedAt || null,
- bundles: kernel.bundles || [],
- }
- : { present: false },
- enforcement: { target, ...enforcement },
- composeBudget: budget,
- injectPlane: {
- supported: injectSupported,
- present: injectPresent,
- path: injectPath,
- },
- };
- }
- /**
- * Actionable migration / health hints for 4.x → 5.0 cutover.
- * @returns {string[]}
- */
- function collectMigrationHints(report) {
- const hints = [];
- const t = report.enforcement && report.enforcement.target;
- if (!report.abyss.present) {
- hints.push(
- 'abyss CLI missing → curl -fsSL https://raw.githubusercontent.com/telagod/abyss/main/install.sh | bash',
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 123 on GitHub
- ' (or: npm i -g @code-abyss/cli | cargo binstall code-abyss)'
- );
- }
- if (t && ['claude', 'codex', 'gemini'].includes(t)) {
- // Graph hooks are not owned by code-abyss install; always remind attach for these hosts
- hints.push(`code-graph hooks → abyss attach ${t} (idempotent; not --with-hooks)`);
- }
- if (report.enforcement && !report.enforcement.on && t && ['claude', 'codex'].includes(t)) {
- hints.push(
- 'character Stop-hook OFF → reinstall without --no-enforcement (default on in 5.0)'
- );
- }
- if (report.injectPlane && report.injectPlane.supported && !report.injectPlane.present && t && ['claude', 'codex'].includes(t)) {
- hints.push(
- `inject plane missing → npx code-abyss -t ${t} -y (writes ${report.injectPlane.path || '.code-abyss-inject.md'})`
- );
- }
- if (!report.kernel.present) {
- hints.push('kernel meta missing in this package tree — reinstall from npm/tag that ships skills/_kernel');
- }
- if (report.composeBudget && !report.composeBudget.underBudget) {
- hints.push(`compose budget exceeded (${report.composeBudget.length}/${report.composeBudget.cap}) — trim always-on layers`);
- }
- return hints;
- }
- function formatDoctorReport(report) {
- const lines = [];
- lines.push(`code-abyss doctor · ${report.package.name}@${report.package.version}`);
- if (report.abyss.present) {
- lines.push(`abyss: ${report.abyss.version || '?'} (${report.abyss.source}) min=${report.abyss.minRequired}`);
- } else {
- lines.push(`abyss: not detected (min ${report.abyss.minRequired}) — install via abyss install.sh`);
- }
- if (report.kernel.present) {
- lines.push(`kernel: commit=${report.kernel.sourceCommit || '?'} syncedAt=${report.kernel.syncedAt || '?'}`);
- } else {
- lines.push('kernel: .sync-meta.json missing');
- }
- lines.push(
- `enforcement(${report.enforcement.target}): ${report.enforcement.on ? 'ON' : 'OFF'}`
- + (report.enforcement.reason ? ` (${report.enforcement.reason})` : '')
- );
- const b = report.composeBudget;
- lines.push(`compose budget: ${b.length}/${b.cap} (headroom ${b.headroom}) persona=${b.persona} style=${b.style}`);
- if (!report.injectPlane.supported) {
- lines.push(`inject plane: N/A (${report.enforcement.target} — not installed by code-abyss)`);
- } else {
- lines.push(`inject plane: ${report.injectPlane.present ? 'present' : 'absent'} (${report.injectPlane.path})`);
- }
- const hints = collectMigrationHints(report);
- if (hints.length) {
- lines.push('');
- lines.push('migration / next steps (v5):');
- for (const h of hints) lines.push(` • ${h}`);
- lines.push(' see docs/MIGRATION-v5.md');
- }
- return lines.join('\n') + '\n';
- }
- /**
- * Compose host guidance using the same engine as install (no skill tree copy).
- * @returns {{ guidance: string, destPath: string|null, wrote: boolean }}
- */
- const COMPOSE_SUPPORTED_TARGETS = new Set(['claude', 'codex', 'gemini', 'openclaw']);
- function composeHostGuidance({
- projectRoot,
- target = 'claude',
- personaSlug = null,
- styleSlug = null,
- HOME = os.homedir(),
- write = false,
- } = {}) {
- if (!COMPOSE_SUPPORTED_TARGETS.has(target)) {
- throw new Error(`unsupported target: ${target}. Supported: ${[...COMPOSE_SUPPORTED_TARGETS].join(', ')}`);
- }
- const persona = personaSlug || getDefaultPersona(projectRoot).slug;
- const style = styleSlug
- || getDefaultStyle(projectRoot, target === 'gemini' ? 'claude' : target).slug;
- // Validate slugs resolve
- if (!resolvePersona(projectRoot, persona)) {
- throw new Error(`unknown persona: ${persona}`);
- }
- if (!resolveStyle(projectRoot, style, target === 'gemini' ? 'claude' : target)) {
- throw new Error(`unknown style: ${style}`);
- }
- const hostForRender = target === 'gemini' ? 'gemini' : 'codex';
- const guidance = renderRuntimeGuidance(projectRoot, style, hostForRender, persona);
- if (guidance.length >= COMPOSE_BUDGET_CAP) {
- throw new Error(`compose guidance exceeds budget cap: ${guidance.length}/${COMPOSE_BUDGET_CAP}`);
- }
- let destPath = null;
- if (target === 'claude') destPath = path.join(HOME, '.claude', 'CLAUDE.md');
- else if (target === 'codex') destPath = path.join(HOME, '.codex', 'instruction.md');
- else if (target === 'gemini') destPath = path.join(HOME, '.gemini', 'GEMINI.md');
- else if (target === 'openclaw') {
- destPath = path.join(HOME, '.openclaw', 'workspace', 'AGENTS.md');
- }
- let wrote = false;
- if (write && destPath) {
- fs.mkdirSync(path.dirname(destPath), { recursive: true });
- fs.writeFileSync(destPath, guidance);
- wrote = true;
- }
- return { guidance, destPath, wrote, persona, style };
- }
- module.exports = {
- COMPOSE_BUDGET_CAP,
- readKernelSyncMeta,
- detectEnforcementOn,
- measureComposeBudget,
- buildDoctorReport,
- formatDoctorReport,
- collectMigrationHints,
- composeHostGuidance,
- };
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.