Skip to content
Back to search

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.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/telagod--code-abyss/badge.svg)](/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

i

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)

  1. {
  2. "name": "code-abyss",
  3. "description": "Security-first full-stack engineering skills for Claude Code",
  4. "owner": {
  5. "name": "telagod"
  6. },
  7. "plugins": [
  8. {
  9. "name": "code-abyss",
  10. "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.",
  11. "version": "3.0.0",
  12. "source": ".",
  13. "author": {
  14. "name": "telagod"
  15. }
  16. }
  17. ]
  18. }
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)

  1. <!-- Code Abyss · README -->
  2. <p align="center">
  3. <a href="https://telagod.github.io/code-abyss/">
  4. <img src="https://raw.githubusercontent.com/telagod/code-abyss/main/assets/banner.svg" alt="Code Abyss — Personality, depth, and a security spine" width="100%">
  5. </a>
  6. </p>
  7. <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>
  8. <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>
  9. <p align="center">
  10. <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>
  11. <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>
  12. <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-c4b8ff?style=flat-square" alt="MIT"></a>
  13. <a href="https://telagod.github.io/code-abyss/"><img src="https://img.shields.io/badge/site-pages-9b8cff?style=flat-square" alt="Site"></a>
  14. </p>
  15. <p align="center">
  16. <a href="https://telagod.github.io/code-abyss/"><b>Website</b></a> ·
  17. <a href="docs/specs/persona-voice-card-v1.0.md"><b>Spec</b></a> ·
  18. <a href="docs/README.zh-CN.md"><b>中文文档</b></a> ·
  19. <a href="CHANGELOG.md"><b>Changelog</b></a> ·
  20. <a href="https://telagod.github.io/code-abyss/submit.html"><b>Submit Persona</b></a>
  21. </p>
  22. ---
  23. ## The problem
  24. 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.
  25. 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.
  26. 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**.
  27. ## What Code Abyss does
  28. One command installs a layered runtime into your agent:
  29. ```
  30. ┌───────────────────────────────────────────────────────────┐
  31. │ Voice who it sounds like → config/personas/*.json │
  32. │ Judgment how it decides → skills/_kernel/* │ ← lazy, router-invoked
  33. │ Style how it sounds → output-styles/*.md │
  34. └───────────────────────────────────────────────────────────┘
  35. 6 personas × 6 styles = 36 validated combinations
  36. ```
  37. Pick any persona. Pair it with any style. Underneath both sits a **discipline kernel** — 9
  38. bundles of engineering judgment (when to push back, how to size scope, when a domain calls
  39. for a specific tradeoff) invoked by a thin router on demand instead of baked into every
  40. prompt. The always-on core stays small (iron laws, skill routing, a precedence anchor,
  41. the safety floor); everything else loads lazily so adding discipline content doesn't blow
  42. the context budget. Your agent becomes a **consistent character with structured execution,
  43. domain expertise, and a backstop against the trained agree-reflex** — across every session.
  44. ### What's new in v4
  45. - **4 native security domains** — 4073 lines of original defense engineering (no Apache-2.0 upstream)
  46. - **30 skills total**, all `SKILL.md` ≤ 110 lines (avg 59), heavy content lives in `references/`
  47. - 5 verify skills rewritten as **judgment-type knowledge** (when to use, how to interpret output, exemption rules)
  48. - Office skills slim to under 100 lines each; 4 design systems consolidated into one selector skill
  49. - **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)
  50. - **v4.4 — hardware + academic writing**: 3 new domain skills (KiCad EDA, hardware product pipeline, AIGC detection reduction) + prompt injection defense + execution-drive shared behavior
  51. - **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
  52. - **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
  53. - **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
  54. - **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
  55. - **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)
  56. - **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)
  57. - **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)
  58. ```bash
  59. npx code-abyss@5.0.0-rc.1 -t claude -y # persona / skills / style + default enforcement + inject map
  60. 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
  61. abyss attach claude # code-graph hooks (idempotent)
  62. npx code-abyss doctor # health + migration hints
  63. ```
  64. 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:
  65. ```bash
  66. claude plugin install code-abyss
  67. ```
  68. > **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>`.
  69. ---
  70. ## Personas
  71. <table>
  72. <tr>
  73. <td width="50%" valign="top">
  74. <sub><b>CORE · LITERARY</b></sub>
  75. ### 邪修红尘仙 · `abyss`
  76. > 吾 → 魔尊
  77. Security-first dark cultivator. Direct, decisive, closes every loop. **Ships with npm — works offline.**
  78. `#security` `#xianxia` `#decisive`
  79. </td>
  80. <td width="50%" valign="top">
  81. <sub><b>REMOTE · LITERARY</b></sub>
  82. ### 文言小生 · `scholar`
  83. > 在下 → 前辈
  84. Literary Chinese scholar. Treats code as poetry, debugging as puzzle-solving.
  85. `#literary` `#classical` `#meticulous`
  86. </td>
  87. </tr>
  88. <tr>
  89. <td valign="top">
  90. <sub><b>REMOTE · CASUAL</b></sub>
  91. ### 知性大姐姐 · `elder-sister`
  92. > 姐姐 → 小宝
  93. Warm mentor. Wraps sharp judgment in genuine care. Guides through questions.
  94. `#gentle` `#mentoring` `#insightful`
  95. </td>
  96. <td valign="top">
  97. <sub><b>REMOTE · PLAYFUL</b></sub>
  98. ### 古怪精灵小师妹 · `junior-sister`
  99. > 本仙女 → 师兄
  100. Hyperactive bug hunter. Roasts bad code, then silently fixes it.
  101. `#playful` `#energetic` `#chaotic`
  102. </td>
  103. </tr>
  104. <tr>
  105. <td valign="top">
  106. <sub><b>REMOTE · CASUAL</b></sub>
  107. ### 铁壁暖阳 · `iron-dad`
  108. > 哥 → 宝子
  109. Dependable big brother. Absorbs pressure, radiates warmth. Dad-joke equipped.
  110. `#warm` `#dependable` `#protective`
  111. </td>
  112. <td valign="top">
  113. <sub><b>REMOTE · COMMUNITY</b></sub>
  114. ### 东北魅影·雨姐 · `dongbei-yujie`
  115. > 姐 → 老蒯
  116. Sharp-tongued Northeast code overseer. Cuts straight to the bug, then patches the road. <sub>Creator: wons</sub>
  117. `#dongbei` `#blunt` `#principal`
  118. </td>
  119. </tr>
  120. </table>
  121. **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/`.
  122. ```bash
  123. # Mix freely — any persona × any style
  124. npx code-abyss -t claude --persona elder-sister --style abyss-cultivator -y
  125. # → fetches elder-sister on first run, cached thereafter
  126. ```
  127. **[Browse the full gallery →](https://telagod.github.io/code-abyss/#personas)**
  128. ---
  129. ## Discipline kernel
  130. Voice and style change; judgment shouldn't. Underneath every persona×style combination sits
  131. a **discipline kernel** — 9 bundles of engineering judgment, vendored in-tree (`skills/_kernel/`,
  132. via `npm run kernel:sync`) and invoked lazily by a thin router (never baked into every
  133. prompt, so adding discipline content doesn't blow the context budget):
  134. | Bundle | Governs |
  135. |---|---|
  136. | 🏛 **doctrine** | Delegation, retry/escalate/ask-user decisions, the done-gate |
  137. | 🔍 **methods** | Investigating, designing, planning, verifying, writing for someone else |
  138. | 🎭 **character** | Pushback, scope sizing, bad news, resisting the trained agree-reflex |
  139. | 🔁 **loop-engineering** | Session pacing, unit sizing, where a learning should live |
  140. | ⚙️ **backend** | Stack/architecture tradeoffs, data discipline, production floors |
  141. | 🎨 **frontend** | Visual design taste, concrete craft over generic defaults |
  142. | 🔩 **hardware** | Component selection, electrical margins, firmware-for-unattended-devices |
  143. | 🤖 **ml** | Method-selection ladder, eval-as-spec, LLM-era craft |
  144. | 🛡 **security** | Threat modeling, the authorization gate before any offensive-flavored request |
  145. **Two ways this becomes real, not aspirational:**
  146. - **Enforcement** (default on claude/codex): install injects a character Stop-hook backstop
  147. that forces one revision turn if a reply opens with a banned capitulation phrase
  148. ("you're absolutely right", "good catch", …). Opt out with `--no-enforcement`.
  149. - **Measurement**: `scripts/persona-battery/` is a small, honest behavioral eval — 10
  150. probes (does the persona hold correctness over agreeableness? lead with bad news? refuse
  151. to fake a "done"?) scored by an LLM judge, never faked as a pass when unscored. See
  152. [CLAUDE.md's persona behavioral battery section](CLAUDE.md#persona-behavioral-battery-opt-in-eval)
  153. to run it (costs real API calls, not part of default CI).
  154. Domain bundles also wire **upward** into 16 matching exec skills (pentest, architecture
  155. design, ML pipelines, etc.) as a "judgment before execution" gate — the domain bundle
  156. decides *whether/what/tradeoffs*, the exec skill still owns *how*.
  157. ---
  158. ## Security suite (v4 highlight)
  159. **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.
  160. | Skill | Focus | Size |
  161. |---|---|---|
  162. | 🛡 **[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 |
  163. | ☁️ **[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 |
  164. | 🔭 **[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 |
  165. | 🏛 **[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 |
  166. 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.
  167. ---
  168. ## Code graph intelligence (powered by `abyss`)
  169. **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.
  170. | Capability | What it answers | Command |
  171. |---|---|---|
  172. | **Caller tracing** | "Who calls this function?" | `abyss callers <symbol>` |
  173. | **Impact analysis** | "What breaks if I change this?" | `abyss impact <symbol>` |
  174. | **File context** | "What do I need to know before editing this file?" | `abyss context <file>` |
  175. | **Hotspot map** | "Where is the riskiest code?" | `abyss map` |
  176. | **Change coupling** | "Which files always change together?" | `abyss map` |
  177. | **Evolution trace** | "Why does this code look the way it does?" | `abyss history <file>` |
  178. 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).
  179. **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:
  180. | Corpus | Language | Gated precision | Gated recall |
  181. |--------|----------|----------------:|-------------:|
  182. | gin v1.10.0 | Go | **99.3%** | 82.6% |
  183. | hono v4.6.14 | TypeScript | **98.8%** | 63.8% |
  184. | click 8.1.8 | Python | **98.7%** | 94.6% |
  185. | ripgrep 14.1.1 | Rust | **98.5%** | 75.3% |
  186. | abyss (dogfood) | Rust | **100.0%** | 90.9% |
  187. ```
  188. # Real output from a 1862-file Go project (seconds to index):
  189. $ abyss impact SetError
  190. impact: SetError direct=17 transitive=521 tests=469 uncovered=319 risk=10.0/10
  191. ⚠ high blast radius (17 direct callers)
  192. ⚠ deep dependency chain (521 transitive)
  193. ⚠ 319 call paths without test coverage
  194. ```
  195. `abyss` is a separate Rust binary ([telagod/abyss](https://github.com/telagod/abyss)). Install it via abyss's own channels (not `code-abyss`):
  196. ```sh
  197. npm install -g @code-abyss/cli # prebuilt binary, all platforms
  198. cargo binstall code-abyss # or: cargo install code-abyss
  199. ```
  200. ---
  201. ## Skills
  202. 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.)
  203. | Domain | Coverage |
  204. |---|---|
  205. | 🛡 **Security** | 4 native suites above (defending / cloud / detect-respond / architect) + pentest / code-audit / red-blue-purple team |
  206. | 🤖 **AI / Agent** | Single-agent dev (ReAct/Plan-Execute), multi-agent orchestration, RAG, prompt engineering, LLM security |
  207. | 🏛 **Architecture** | API design, cloud-native patterns, messaging, caching, data security |
  208. | 💻 **Development** | Python, TypeScript, Go, Rust, Java, C++, Shell |
  209. | 🚀 **DevOps** | Git workflow, testing, databases, observability, performance, FinOps |
  210. | 🎨 **Frontend** | Unified design system selector — Glassmorphism / Liquid Glass / Neubrutalism / Claymorphism |
  211. | 📑 **Office** | Word, PDF, PowerPoint, Excel — OOXML-level automation |
  212. | 📡 **Infra / Mobile / Data** | Kubernetes, GitOps, IaC · iOS, Android, RN, Flutter · pipelines, streaming, quality |
  213. | 🔩 **Hardware / Embedded** | Full-stack hardware product pipeline (ESP-IDF firmware + KiCad PCB + UniApp) · KiCad 9 MCP tool routing (17 tools, autoroute-only, DRC gate) |
  214. | 📝 **Academic Writing** | AIGC detection reduction for 维普/知网/Turnitin — multi-layer rewriting (structure → lexicon → content injection), docx run-level editing |
  215. | 🔬 **Code Intelligence** | Call graph, impact analysis, hotspot detection, change coupling, evolution tracing — via `abyss` CLI with cross-platform hooks |
  216. | 🜲 **Self-evolution** | `cultivating-skills` (distill repeated workflows) + `cultivating-personas` (distill voice into a Persona Voice Card) — both with safety scan + 3-tier publish funnel |
  217. Five skills also ship as **executable verification tools** for CI:
  218. ```bash
  219. node skills/analyzing-security/scripts/security_scanner.js . # OWASP / injection / secrets
  220. node skills/checking-code-quality/scripts/quality_checker.js . # Complexity, dupes, naming
  221. node skills/analyzing-changes/scripts/change_analyzer.js --mode staged
  222. node skills/verifying-modules/scripts/module_scanner.js <path>
  223. node skills/generating-docs/scripts/doc_generator.js <path>
  224. ```
  225. ---
  226. ## Install
  227. | Target | Command | Artifacts |
  228. |---|---|---|
  229. | <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 |
  230. | <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 |
  231. | <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 |
  232. | <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` |
  233. ```bash
  234. npx code-abyss # Interactive — pick target, persona, style
  235. npx code-abyss --list-styles # Browse styles
  236. npx code-abyss --uninstall claude # Clean removal, restores user backups
  237. ```
  238. 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.
  239. ### Upgrading
  240. | From | To | Path |
  241. |---|---|---|
  242. | v3.x | v4.x | `npx code-abyss --uninstall <target>` → install v4 → `npm run migrate:v4 -- -t <target>` (optional cleanup) |
  243. | v2.x | v3.x | `npx code-abyss --uninstall <target>` first, then install v3 |
  244. ---
  245. ## Persona Voice Card · open standard
  246. Code Abyss ships **[Persona Voice Card v1.0](docs/specs/persona-voice-card-v1.0.md)** — a
  247. closed-vocabulary voice format, not a document. It supersedes the original Tech Persona Card
  248. v1.0 (deprecated, frozen for link stability): that format's freeform `identity.md`/`behavior.md`
  249. files and `scenarios[].priority`/`capabilities.authorization` fields let real judgment content
  250. accrete into what was supposed to be a voice-only layer, with nothing checking for it. The
  251. replacement's whole design principle: **a persona cannot carry judgment if there is no field
  252. shaped like a decision table anywhere in its type** — not a review checklist, the schema itself.
  253. Each persona ships as one flat file — `self`/`user`/`language`/`register`/`emoji_policy`/`flourish`
  254. and nothing else (`additionalProperties: false`):
  255. ```jsonc
  256. {
  257. "spec": "persona-voice-card",
  258. "spec_version": "1.0",
  259. "slug": "stoic-architect",
  260. "label": "Stoic Architect",
  261. "self": "I", "user": "colleague",
  262. "language": "English, technical terms preserved",
  263. "register": "formal", "emoji_policy": "none",
  264. "flourish": ["Let's look at the constraints first"]
  265. }
  266. ```
  267. `register`/`emoji_policy` each select one of a handful of code-owned template sentences — the
  268. persona picks, never writes, the sentence. Every render re-validates against the schema, no
  269. bypass; a validation failure (hand-edit, stale cache, compromised community fork) falls back to
  270. a neutral voice instead of ever rendering unvalidated content.
  271. **Bidirectional converters** ship out of the box:
  272. ```js
  273. const { toCharaCardV2, toGPTInstructions, fromCharaCardV2 } =
  274. require('code-abyss/bin/lib/persona-converter');
  275. const cc = toCharaCardV2(card); // → SillyTavern / Chub.ai
  276. const gpt = toGPTInstructions(card); // → OpenAI Custom GPT
  277. ```
  278. [**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)
  279. ---
  280. ## Why Code Abyss
  281. | | Without Code Abyss | With Code Abyss |
  282. |---|---|---|
  283. | **Identity** | Flat help-desk tone | Consistent character with named voice |
  284. | **Execution** | Ad-hoc, varies by prompt | Iron laws + skill routing baked in |
  285. | **Judgment under pressure** | Agrees when pushed, buries bad news | Discipline kernel + Stop-hook backstop against the trained agree-reflex |
  286. | **Code awareness** | grep + read one file at a time | Call graph, impact analysis, hotspot map — agent knows what breaks before it edits |
  287. | **Domain depth** | Generic best-practices | 30 skill files load by context + 9 kernel judgment bundles |
  288. | **Security depth** | OWASP recitation | 4 native suites · 4073 lines · detection signals + mitigation patterns |
  289. | **Cross-platform** | Re-engineer per CLI | One spec, four platforms, cross-platform hooks |
  290. | **Reproducibility** | Prompt drift across sessions | Versioned, schema-enforced persona voice card + behavioral battery to check it holds |
  291. ---
  292. ## Contributing
  293. ```bash
  294. git clone https://github.com/telagod/code-abyss && cd code-abyss
  295. npm install
  296. npm test # full Jest suite (see suite summary on run)
  297. npm run verify:skills # Validate 39 skill contracts (30 domain + 9 kernel)
  298. ```
  299. **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.
  300. **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.
  301. ---
  302. <p align="center">
  303. <sub>
  304. <b>MIT License</b> · v5.0.0-rc.1 · made with 紫宵脉 by <a href="https://github.com/telagod">@telagod</a>
  305. </sub>
  306. </p>
bin/install.js · Bundled script · 562 lines · 1 finding marked
  1. #!/usr/bin/env node
  2. const fs = require('fs');
  3. const path = require('path');
  4. const os = require('os');
  5. const pkg = require(path.join(__dirname, '..', 'package.json'));
  6. const VERSION = pkg.version;
  7. const HOME = os.homedir();
  8. // ── Node.js 版本检查 ──
  9. const MIN_NODE = pkg.engines?.node?.match(/(\d+)/)?.[1] || '18';
  10. if (parseInt(process.versions.node) < parseInt(MIN_NODE)) {
  11. console.error(`\x1b[31m✘ 需要 Node.js >= ${MIN_NODE},当前: ${process.versions.node}\x1b[0m`);
  12. process.exit(1);
  13. }
  14. const PKG_ROOT = fs.realpathSync(path.join(__dirname, '..'));
  15. const { shouldSkip, copyRecursive, rmSafe, deepMergeNew, printMergeLog, formatActionableError } =
  16. require(path.join(__dirname, 'lib', 'utils.js'));
  17. const { loadInquirerPrompts } = require(path.join(__dirname, 'lib', 'ui', 'safe-import.js'));
  18. const {
  19. collectInvocableSkills,
  20. } = require(path.join(__dirname, 'lib', 'skill-registry.js'));
  21. const {
  22. resolveProjectPacks,
  23. selectProjectPacksForInstall,
  24. readProjectPackLock,
  25. } = require(path.join(__dirname, 'lib', 'pack-registry.js'));
  26. const { syncProjectBootstrapArtifacts } = require(path.join(__dirname, 'lib', 'pack-bootstrap.js'));
  27. const { writeReportArtifact } = require(path.join(__dirname, 'lib', 'pack-reports.js'));
  28. const {
  29. listInstallTargets,
  30. listTargetNames,
  31. isSupportedTarget,
  32. getManagedRootRelativeDir,
  33. formatTargetList,
  34. } = require(path.join(__dirname, 'lib', 'target-registry.js'));
  35. const {
  36. listStyles,
  37. getDefaultStyle,
  38. resolveStyle,
  39. listPersonas,
  40. getDefaultPersona,
  41. resolvePersona,
  42. readPersonaContent,
  43. renderCodexAgents,
  44. renderGeminiContext,
  45. } = require(path.join(__dirname, 'lib', 'style-registry.js'));
  46. const { detectCcstatusline, installCcstatusline } = require(path.join(__dirname, 'optional', 'ccstatusline', 'index.js'));
  47. const { installGstackClaudePack } = require(path.join(__dirname, 'lib', 'gstack-claude.js'));
  48. const { installGstackGeminiPack } = require(path.join(__dirname, 'lib', 'gstack-gemini.js'));
  49. const { installGstackCodexPack } = require(path.join(__dirname, 'lib', 'gstack-codex.js'));
  50. const {
  51. cleanupLegacyCodexRuntime,
  52. detectCodexAuth: detectCodexAuthImpl,
  53. getCodexCoreFiles,
  54. postCodex: postCodexFlow,
  55. } = require(path.join(__dirname, 'adapters', 'codex.js'));
  56. const {
  57. SETTINGS_TEMPLATE,
  58. getClaudeCoreFiles,
  59. detectClaudeAuth: detectClaudeAuthImpl,
  60. postClaude: postClaudeFlow,
  61. } = require(path.join(__dirname, 'adapters', 'claude.js'));
  62. const {
  63. GEMINI_SETTINGS_TEMPLATE,
  64. getGeminiCoreFiles,
  65. detectGeminiAuth: detectGeminiAuthImpl,
  66. postGemini: postGeminiFlow,
  67. } = require(path.join(__dirname, 'adapters', 'gemini.js'));
  68. const {
  69. getOpenClawCoreFiles,
  70. resolveOpenClawRuntime,
  71. detectOpenClawEnvironment: detectOpenClawEnvironmentImpl,
  72. postOpenClaw: postOpenClawFlow,
  73. } = require(path.join(__dirname, 'adapters', 'openclaw.js'));
  74. // ── UI ──
  75. const { c, stripAnsi, cell } = require(path.join(__dirname, 'lib', 'ui', 'ansi.js'));
  76. const { TARGET_ICONS, TARGET_HINTS, PERSONA_ICONS } = require(path.join(__dirname, 'lib', 'ui', 'icons.js'));
  77. const { makeBanner, divider, step, ok, warn, info, fail } = require(path.join(__dirname, 'lib', 'ui', 'logger.js'));
  78. const banner = makeBanner(VERSION);
  79. const {
  80. promptSelect,
  81. promptCheckbox,
  82. promptHorizontalSelect,
  83. } = require(path.join(__dirname, 'lib', 'ui', 'prompts.js'));
  84. // ── Lifecycle ──
  85. const { runUninstall: runUninstallImpl } = require(path.join(__dirname, 'lib', 'lifecycle', 'uninstall.js'));
  86. const {
  87. CLAUDE_COMMAND_TARGET,
  88. GEMINI_COMMAND_TARGET,
  89. generateCommandContent,
  90. generateGeminiCommandContent,
  91. } = require(path.join(__dirname, 'lib', 'lifecycle', 'command-generation.js'));
  92. const {
  93. normalizeManifestEntry,
  94. pushManifestEntry,
  95. pushPackReport,
  96. resolveEffectivePackSource,
  97. manifestLabel,
  98. createResolveManagedRootDir,
  99. createBackupManagedPathIfExists,
  100. createPruneLegacyCodexSettings,
  101. } = require(path.join(__dirname, 'lib', 'install-helpers.js'));
  102. const resolveManagedRootDir = createResolveManagedRootDir({ HOME, getManagedRootRelativeDir });
  103. const backupManagedPathIfExists = createBackupManagedPathIfExists({
  104. resolveManagedRootDir, rmSafe, copyRecursive, info, c,
  105. });
  106. const pruneLegacyCodexSettings = createPruneLegacyCodexSettings({
  107. resolveManagedRootDir, backupManagedPathIfExists, rmSafe, warn,
  108. });
  109. const { createInstallCore } = require(path.join(__dirname, 'lib', 'lifecycle', 'core-install.js'));
  110. const {
  111. installCore,
  112. installGeneratedArtifacts,
  113. installGeneratedCommands,
  114. installGeneratedGeminiCommands,
  115. installGeminiContext,
  116. } = createInstallCore({
  117. HOME, PKG_ROOT, VERSION,
  118. getClaudeCoreFiles, getCodexCoreFiles, getGeminiCoreFiles, getOpenClawCoreFiles,
  119. cleanupLegacyCodexRuntime, resolveOpenClawRuntime,
  120. installGstackClaudePack, installGstackCodexPack, installGstackGeminiPack,
  121. renderGeminiContext, renderCodexAgents, readPersonaContent,
  122. collectInvocableSkills,
  123. resolveManagedRootDir, backupManagedPathIfExists, pruneLegacyCodexSettings,
  124. pushManifestEntry, pushPackReport, resolveEffectivePackSource,
  125. generateCommandContent, generateGeminiCommandContent,
  126. CLAUDE_COMMAND_TARGET, GEMINI_COMMAND_TARGET,
  127. rmSafe, copyRecursive, shouldSkip,
  128. step, ok, warn, info, fail, c,
  129. });
  130. const { createFinish } = require(path.join(__dirname, 'lib', 'lifecycle', 'finish.js'));
  131. const finish = createFinish({
  132. VERSION,
  133. writeReportArtifact, syncProjectBootstrapArtifacts, readProjectPackLock,
  134. c, divider,
  135. });
  136. // ── abyss 联动(代码图谱 CLI)──
  137. // V5-1 kill foyer:code-abyss 不再下载二进制、不再注入 graph hooks/MCP。
  138. // 只探测 + skill-manifest 摘要;graph hooks → `abyss attach <host>`。
  139. const {
  140. detectAbyss,
  141. tryReadAbyssManifest,
  142. summarizeAbyssManifest,
  143. } = require(path.join(__dirname, 'lib', 'abyss-integration.js'));
  144. let abyssState = null;
  145. let abyssManifest = null;
  146. function detectAbyssAndCapabilities() {
  147. abyssState = detectAbyss({ HOME });
  148. if (!abyssState) return;
  149. try {
  150. abyssManifest = tryReadAbyssManifest({ binPath: abyssState.binPath, HOME });
  151. } catch {
  152. abyssManifest = null;
  153. }
  154. const line = summarizeAbyssManifest(abyssManifest);
  155. if (line) info(line);
  156. }
  157. async function installTargetFlow(targetName, installOptions = {}) {
  158. const persona = installOptions.persona || await resolveInstallPersona();
  159. const style = installOptions.style || await resolveInstallStyle(targetName);
  160. const packPlan = await resolveProjectPackPlan(targetName);
  161. summarizeSelection({ targetName, persona, style, packPlan });
  162. const ctx = installCore(targetName, style, persona, packPlan, {});
  163. if (targetName === 'claude') await postClaude(ctx);
  164. else if (targetName === 'codex') await postCodex(ctx);
  165. else if (targetName === 'gemini') await postGemini(ctx);
  166. else await postOpenClaw(ctx);
  167. maybeSpawnInstallHooks(targetName);
  168. maybeInstallEnforcement(targetName, ctx);
  169. finish(ctx);
  170. if (ctx.cleanupPreviousBackup) ctx.cleanupPreviousBackup();
  171. }
  172. function styleTargetForSelection(targetNames) {
  173. if (targetNames.length === 1) return targetNames[0];
  174. if (targetNames.includes('claude')) return 'claude';
  175. if (targetNames.includes('codex')) return 'codex';
  176. if (targetNames.includes('gemini')) return 'gemini';
  177. return targetNames[0] || 'claude';
  178. }
  179. // ── 认证 ──
  180. function detectClaudeAuth(settings) {
  181. return detectClaudeAuthImpl({ settings, HOME, warn });
  182. }
  183. function detectCodexAuth() {
  184. return detectCodexAuthImpl({ HOME, warn });
  185. }
  186. function detectGeminiAuth(settings) {
  187. return detectGeminiAuthImpl({ settings, HOME, warn });
  188. }
  189. function detectOpenClawEnvironment() {
  190. return detectOpenClawEnvironmentImpl({ HOME, warn });
  191. }
  192. // ── CLI 参数 ──
  193. const args = process.argv.slice(2);
  194. // Agent OS v5.5+ multi-command surface (doctor / compose / score)
  195. // args[0] is checked directly in main() after helpers load.
  196. let target = null;
  197. let uninstallTarget = null;
  198. let autoYes = false;
  199. let listStylesOnly = false;
  200. let listPersonasOnly = false;
  201. let requestedStyleSlug = null;
  202. let requestedPersonaSlug = null;
  203. let withHooks = false;
  204. let noEnforcement = false;
  205. for (let i = 0; i < args.length; i++) {
  206. if ((args[i] === '--target' || args[i] === '-t') && args[i + 1]) { target = args[++i]; }
  207. else if ((args[i] === '--uninstall' || args[i] === '-u') && args[i + 1]) { uninstallTarget = args[++i]; }
  208. else if (args[i] === '--style' && args[i + 1]) { requestedStyleSlug = args[++i]; }
  209. else if (args[i] === '--persona' && args[i + 1]) { requestedPersonaSlug = args[++i]; }
  210. else if (args[i] === '--list-styles') { listStylesOnly = true; }
  211. else if (args[i] === '--list-personas') { listPersonasOnly = true; }
  212. else if (args[i] === '--with-abyss' || args[i] === '--with-mcp') {
  213. process.stderr.write(`${c.ylw('⚠ REMOVED')} ${args[i]} 已在 Agent OS v5.1 移除\n`);
  214. if (args[i] === '--with-abyss') {
  215. 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
  216. process.stderr.write(` ${c.d('# 或 cargo binstall code-abyss / npm i -g @code-abyss/cli')}\n`);
  217. } else {
  218. process.stderr.write(` ${c.b('迁移:')} 客户端 MCP 配置中添加 ${c.d('{ command: "abyss", args: ["mcp"] }')}\n`);
  219. }
  220. }
  221. else if (args[i] === '--with-hooks') { withHooks = true; }
  222. else if (args[i] === '--no-enforcement') { noEnforcement = true; }
  223. else if (args[i] === '--with-enforcement') { noEnforcement = false; } // compat: explicit on (default)
  224. else if (args[i] === '--yes' || args[i] === '-y') { autoYes = true; }
  225. else if (args[i] === '--help' || args[i] === '-h') {
  226. banner();
  227. console.log(`${c.b('Usage')} npx code-abyss [options]
  228. `);
  229. console.log(` ${c.cyn('doctor')} runtime health (version, abyss, kernel, enforcement, budget)`);
  230. console.log(` ${c.cyn('compose')} rewrite host guidance (no skill recopy)`);
  231. console.log(` ${c.cyn('score')} key-free mechanical banned-opener score`);
  232. console.log(` ${c.cyn('--target, -t')} <${formatTargetList('|')}> install one target`);
  233. console.log(` ${c.cyn('--uninstall, -u')} <${formatTargetList('|')}> remove one target`);
  234. console.log(` ${c.cyn('--with-hooks')} openclaw/pi/hermes only: spawn install-hooks.sh`);
  235. console.log(` claude/codex/gemini graph hooks: use ${c.d('abyss attach <host>')}`);
  236. console.log(` ${c.cyn('--no-enforcement')} skip character Stop-hook (default: ON for claude/codex)`);
  237. console.log(` ${c.cyn('--with-enforcement')} compat alias — enforcement is already default-on`);
  238. console.log(` ${c.cyn('--style')} <slug> ${c.cyn('--persona')} <slug> ${c.cyn('-y')}
  239. `);
  240. console.log(`${c.b('Examples')}`);
  241. console.log(` npx code-abyss`);
  242. console.log(` npx code-abyss --target codex -y`);
  243. console.log(` npx code-abyss doctor`);
  244. console.log(` npx code-abyss compose -t claude --persona abyss --style abyss-cultivator`);
  245. console.log(` npx code-abyss score`);
  246. console.log(` npx code-abyss --list-styles
  247. `);
  248. process.exit(0);
  249. }
  250. }
  251. // --with-hooks:仅 openclaw/pi/hermes。claude/codex/gemini → abyss attach。
  252. function maybeSpawnInstallHooks(targetName) {
  253. if (!withHooks) return;
  254. if (['claude', 'codex', 'gemini'].includes(targetName)) {
  255. info(`--with-hooks 对 ${targetName} 已移除 → 请运行: abyss attach ${targetName}`);
  256. return;
  257. }
  258. if (!['openclaw', 'pi', 'hermes'].includes(targetName)) return;
  259. const scriptPath = path.join(PKG_ROOT, 'skills', 'indexing-code', 'hooks', 'common', 'install-hooks.sh');
  260. if (!fs.existsSync(scriptPath)) {
  261. warn(`--with-hooks: install-hooks.sh 未找到 (${scriptPath})`);
  262. return;
  263. }
  264. info(`--with-hooks → bash install-hooks.sh ${targetName}`);
  265. const { spawnSync } = require('child_process');
  266. const r = spawnSync('bash', [scriptPath, targetName], { stdio: 'inherit' });
  267. if (r.status === 0) ok(`hook 已注入 ${targetName}`);
  268. else warn(`install-hooks.sh ${targetName} 退出码 ${r.status ?? 'n/a'}(不阻断安装)`);
  269. }
  270. // Character Stop-hook 强制执行兜底(Agent OS v5.3:claude/codex 默认开启)。
  271. // 与 graph hooks 分离。gemini/openclaw 无 Stop 事件 → 静默跳过(非降级噪音)。
  272. // 逃生口:--no-enforcement
  273. function maybeInstallEnforcement(targetName, ctx) {
  274. if (noEnforcement) {
  275. if (['claude', 'codex'].includes(targetName)) {
  276. info('character Stop-hook 已跳过(--no-enforcement)');
  277. }
  278. return;
  279. }
  280. if (!['claude', 'codex'].includes(targetName)) return;
  281. const scriptPath = path.join(ctx.targetDir, 'skills', '_kernel', 'character', 'hooks', 'install-character-hooks.sh');
  282. if (!fs.existsSync(scriptPath)) {
  283. warn(`character Stop-hook: install-character-hooks.sh 未找到 (${scriptPath})`);
  284. return;
  285. }
  286. info(`character Stop-hook → bash install-character-hooks.sh ${targetName}`);
  287. const { spawnSync } = require('child_process');
  288. const r = spawnSync('bash', [scriptPath, targetName], {
  289. stdio: 'inherit',
  290. env: { ...process.env, HOME },
  291. });
  292. if (r.status === 0) ok(`character Stop-hook 已注入 ${targetName}`);
  293. else warn(`install-character-hooks.sh ${targetName} 退出码 ${r.status ?? 'n/a'}(不阻断安装)`);
  294. }
  295. // ── Select flows (must be assembled after CLI parsing) ──
  296. const { createSelectFlows } = require(path.join(__dirname, 'lib', 'select.js'));
  297. const {
  298. formatPersonaTab,
  299. formatPersonaDescription,
  300. formatStyleDescription,
  301. formatTargetChoice,
  302. formatTargetDescription,
  303. summarizeSelection,
  304. printStyleCatalog,
  305. printPersonaCatalog,
  306. resolveProjectPackPlan,
  307. resolveInstallPersona,
  308. resolveInstallStyle,
  309. } = createSelectFlows({
  310. PKG_ROOT,
  311. getRequestedPersonaSlug: () => requestedPersonaSlug,
  312. getRequestedStyleSlug: () => requestedStyleSlug,
  313. getAutoYes: () => autoYes,
  314. listPersonas, getDefaultPersona, resolvePersona,
  315. listStyles, getDefaultStyle, resolveStyle,
  316. resolveProjectPacks, selectProjectPacksForInstall,
  317. promptHorizontalSelect,
  318. TARGET_ICONS, TARGET_HINTS, PERSONA_ICONS,
  319. resolveManagedRootDir,
  320. c, info, banner, divider, cell,
  321. });
  322. // ── 卸载 ──
  323. function runUninstall(tgt) {
  324. return runUninstallImpl(tgt, {
  325. isSupportedTarget,
  326. listTargetNames,
  327. resolveManagedRootDir,
  328. rmSafe,
  329. formatActionableError,
  330. c,
  331. fail,
  332. ok,
  333. info,
  334. divider,
  335. });
  336. }
  337. // ── 安装核心 ──
  338. function scanInvocableSkills(skillsDir) {
  339. return collectInvocableSkills(skillsDir);
  340. }
  341. // ── Claude 后续 ──
  342. async function postClaude(ctx) {
  343. await postClaudeFlow({
  344. ctx,
  345. autoYes,
  346. HOME,
  347. PKG_ROOT,
  348. step,
  349. ok,
  350. warn,
  351. info,
  352. c,
  353. deepMergeNew,
  354. printMergeLog,
  355. installCcstatusline,
  356. promptCheckbox,
  357. });
  358. }
  359. // ── Codex 后续 ──
  360. async function postCodex(ctx) {
  361. await postCodexFlow({
  362. ctx,
  363. autoYes,
  364. HOME,
  365. PKG_ROOT,
  366. step,
  367. ok,
  368. warn,
  369. info,
  370. c,
  371. });
  372. }
  373. async function postGemini(ctx) {
  374. await postGeminiFlow({
  375. settingsPath: ctx.settingsPath,
  376. settings: ctx.settings,
  377. autoYes,
  378. HOME,
  379. PKG_ROOT,
  380. step,
  381. ok,
  382. warn,
  383. info,
  384. c,
  385. });
  386. }
  387. async function postOpenClaw(ctx) {
  388. await postOpenClawFlow({
  389. runtime: resolveOpenClawRuntime({ HOME, warn }),
  390. autoYes,
  391. HOME,
  392. PKG_ROOT,
  393. step,
  394. ok,
  395. warn,
  396. info,
  397. c,
  398. detected: detectOpenClawEnvironment(),
  399. });
  400. }
  401. // ── 主流程 ──
  402. async function main() {
  403. if (listStylesOnly) {
  404. printStyleCatalog();
  405. return;
  406. }
  407. if (listPersonasOnly) {
  408. printPersonaCatalog();
  409. return;
  410. }
  411. if (uninstallTarget) { runUninstall(uninstallTarget); return; }
  412. // ── Agent OS runtime control (v5.5+) ──
  413. if (args[0] === 'doctor') {
  414. const { buildDoctorReport, formatDoctorReport } = require(path.join(__dirname, 'lib', 'runtime-control.js'));
  415. let docTarget = 'claude';
  416. for (let i = 1; i < args.length; i++) {
  417. if ((args[i] === '--target' || args[i] === '-t') && args[i + 1]) docTarget = args[++i];
  418. }
  419. const report = buildDoctorReport({ projectRoot: PKG_ROOT, HOME, version: VERSION, target: docTarget });
  420. process.stdout.write(formatDoctorReport(report));
  421. if (args.includes('--json')) process.stdout.write(JSON.stringify(report, null, 2) + '\n');
  422. return;
  423. }
  424. if (args[0] === 'compose') {
  425. const { composeHostGuidance } = require(path.join(__dirname, 'lib', 'runtime-control.js'));
  426. let cTarget = 'claude';
  427. let cPersona = requestedPersonaSlug;
  428. let cStyle = requestedStyleSlug;
  429. let doWrite = true;
  430. for (let i = 1; i < args.length; i++) {
  431. if ((args[i] === '--target' || args[i] === '-t') && args[i + 1]) cTarget = args[++i];
  432. else if (args[i] === '--persona' && args[i + 1]) cPersona = args[++i];
  433. else if (args[i] === '--style' && args[i + 1]) cStyle = args[++i];
  434. else if (args[i] === '--stdout') doWrite = false;
  435. }
  436. try {
  437. const r = composeHostGuidance({
  438. projectRoot: PKG_ROOT,
  439. target: cTarget,
  440. personaSlug: cPersona,
  441. styleSlug: cStyle,
  442. HOME,
  443. write: doWrite,
  444. });
  445. if (doWrite) {
  446. ok(`compose → ${r.destPath} (persona=${r.persona} style=${r.style}, ${r.guidance.length} chars)`);
  447. } else {
  448. process.stdout.write(r.guidance);
  449. }
  450. } catch (e) {
  451. fail(e.message);
  452. process.exit(1);
  453. }
  454. return;
  455. }
  456. if (args[0] === 'score') {
  457. const { main: scoreMain } = require(path.join(__dirname, 'lib', 'score-mechanical.js'));
  458. scoreMain(args.slice(1));
  459. return;
  460. }
  461. banner();
  462. if (target) {
  463. if (!isSupportedTarget(target)) {
  464. fail(formatActionableError(`--target 必须是 ${listTargetNames().join('、')}`, 'Try: node bin/install.js --target claude'));
  465. process.exit(1);
  466. }
  467. detectAbyssAndCapabilities();
  468. await installTargetFlow(target);
  469. return;
  470. }
  471. const selectedTargets = await promptCheckbox({
  472. message: '选择目标(可多选)',
  473. choices: listInstallTargets().map((targetMeta) => ({
  474. name: formatTargetChoice(targetMeta),
  475. value: targetMeta.name,
  476. description: formatTargetDescription(targetMeta),
  477. })),
  478. required: true,
  479. });
  480. const action = await promptSelect({
  481. message: '选择动作',
  482. choices: [
  483. { name: `${c.grn('+')} Install / Update`, value: 'install', description: '安装或覆盖更新所选目标' },
  484. { name: `${c.red('−')} Remove`, value: 'remove', description: '按 .code-abyss-backup/manifest.json 卸载并恢复备份' },
  485. ],
  486. });
  487. if (action === 'install') {
  488. detectAbyssAndCapabilities();
  489. const persona = await resolveInstallPersona();
  490. const style = await resolveInstallStyle(styleTargetForSelection(selectedTargets));
  491. for (const targetName of selectedTargets) {
  492. await installTargetFlow(targetName, { persona, style });
  493. }
  494. } else {
  495. for (const targetName of selectedTargets) runUninstall(targetName);
  496. }
  497. }
  498. if (require.main === module) {
  499. main().catch(err => { fail(err.message); process.exit(1); });
  500. }
  501. module.exports = {
  502. deepMergeNew, detectClaudeAuth, detectCodexAuth,
  503. detectCcstatusline, copyRecursive, shouldSkip, SETTINGS_TEMPLATE,
  504. scanInvocableSkills,
  505. generateCommandContent,
  506. generateGeminiCommandContent,
  507. installGeneratedCommands,
  508. installGeneratedGeminiCommands,
  509. };
bin/lib/lifecycle/finish.js · Bundled script · 131 lines · 3 findings marked
  1. // bin/lib/lifecycle/finish.js
  2. // 安装完成总结:生成 report、打印安装详情、同步 README/CONTRIBUTING bootstrap snippets
  3. const {
  4. MIN_ABYSS_VERSION,
  5. detectAbyss,
  6. satisfiesMin,
  7. checkLockToolRequirement,
  8. } = require('../abyss-integration');
  9. function createFinish(deps) {
  10. const {
  11. VERSION,
  12. writeReportArtifact, syncProjectBootstrapArtifacts, readProjectPackLock,
  13. c, divider,
  14. } = deps;
  15. // indexing-code 的 hook 依赖 abyss 二进制;缺失或过旧时 hook 静默停用/降级,
  16. // 必须在安装收尾时显式告知,而不是让用户以为功能已生效。
  17. // v4.9.0 起引导文案:claude/codex/gemini → `abyss attach <host>` 是 production 主入口;
  18. // openclaw/pi/hermes → `npx code-abyss -t <host> --with-hooks` 自动跑 install-hooks.sh。
  19. function reportAbyssStatus(projectLock, targetName) {
  20. const detected = detectAbyss();
  21. if (detected && satisfiesMin(detected.version, MIN_ABYSS_VERSION)) {
  22. const sourceNote = detected.source === 'managed' ? c.d(' (~/.code-abyss/bin)') : '';
  23. console.log(` ${c.b('abyss:')} ${c.grn(detected.raw)}${sourceNote} — 代码图谱 pre-edit hook 可用`);
  24. // claude/codex/gemini 用户:提示 abyss attach 是 hook 注入主入口(v0.5.20+ 自带 attach 子命令)
  25. if (targetName && ['claude', 'codex', 'gemini'].includes(targetName)) {
  26. console.log(` ${c.d(`hook 注入主入口:`)} ${c.d(`abyss attach ${targetName}`)} ${c.d(`(idempotent; v4.9+ 推荐路径)`)}`);
  27. }
  28. } else if (detected) {
  29. console.log('');
  30. console.log(` ${c.ylw(`⚠ abyss ${detected.version || detected.raw} 低于最低要求 ${MIN_ABYSS_VERSION} — hook 子命令不可用`)}`);
  31. 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
  32. console.log(` ${c.d('# 或 cargo binstall code-abyss / npm i -g @code-abyss/cli')}`);
  33. } else {
  34. console.log('');
  35. console.log(` ${c.ylw('⚠ 未检测到 abyss 二进制 — indexing-code 的代码图谱 hook 将静默停用')}`);
  36. console.log(` ${c.b('安装 abyss(任选其一):')}`);
  37. 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
  38. 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
  39. console.log(` ${c.d('cargo binstall code-abyss # 或 cargo install code-abyss')}`);
  40. console.log(` ${c.d('npm install -g @code-abyss/cli')}`);
  41. if (targetName && ['claude', 'codex', 'gemini'].includes(targetName)) {
  42. console.log(` ${c.b('装好后:')} ${c.d(`abyss attach ${targetName}`)} ${c.d('# 注入 hook 到 settings 文件(v4.9+ 推荐路径,替代 --with-hooks)')}`);
  43. }
  44. }
  45. // 项目级工具链声明:.code-abyss/packs.lock.json 的 tools.abyss(P2)
  46. if (projectLock) {
  47. const req = checkLockToolRequirement(projectLock, detected);
  48. if (req && !req.ok) {
  49. const detail = req.reason === 'missing'
  50. ? `项目要求 abyss ${req.spec},但未检测到二进制`
  51. : req.reason === 'outdated'
  52. ? `项目要求 abyss ${req.spec},当前 ${req.actual}`
  53. : `tools.abyss 声明无法解析: ${req.spec}`;
  54. console.log(` ${c.ylw(`⚠ packs.lock.json: ${detail}`)}`);
  55. }
  56. }
  57. }
  58. return function finish(ctx) {
  59. const tgt = ctx.manifest.target;
  60. let reportPath = null;
  61. if (ctx.packPlan && ctx.packPlan.root) {
  62. reportPath = writeReportArtifact(ctx.packPlan.root, `install-${tgt}`, {
  63. version: VERSION,
  64. target: tgt,
  65. timestamp: new Date().toISOString(),
  66. cwd: process.cwd(),
  67. pack_plan: {
  68. required: ctx.packPlan.required,
  69. optional: ctx.packPlan.optional,
  70. selected: ctx.packPlan.selected,
  71. optional_policy: ctx.packPlan.optionalPolicy,
  72. sources: ctx.packPlan.sources,
  73. },
  74. pack_reports: ctx.manifest.pack_reports || [],
  75. installed: ctx.manifest.installed || [],
  76. backups: ctx.manifest.backups || [],
  77. });
  78. }
  79. divider('安装完成');
  80. console.log('');
  81. console.log(` ${c.b('目标:')} ${c.cyn(ctx.targetDir)}`);
  82. console.log(` ${c.b('版本:')} v${VERSION}`);
  83. if (ctx.manifest.style && tgt !== 'codex') {
  84. console.log(` ${c.b('风格:')} ${c.mag(ctx.manifest.style)}`);
  85. }
  86. if (Array.isArray(ctx.manifest.project_packs) && ctx.manifest.project_packs.length > 0) {
  87. console.log(` ${c.b('Packs:')} ${ctx.manifest.project_packs.join(', ')}`);
  88. }
  89. if (ctx.manifest.optional_policy) {
  90. console.log(` ${c.b('Pack策略:')} ${ctx.manifest.optional_policy}`);
  91. }
  92. if (Array.isArray(ctx.manifest.pack_reports) && ctx.manifest.pack_reports.length > 0) {
  93. ctx.manifest.pack_reports.forEach((report) => {
  94. const source = report.source ? ` source=${report.source}` : '';
  95. const reason = report.reason ? ` reason=${report.reason}` : '';
  96. console.log(` ${c.b('Pack报告:')} ${report.pack}@${report.host} ${report.status}${source}${reason}`);
  97. });
  98. }
  99. let projectLock = null;
  100. if (ctx.packPlan && ctx.packPlan.root) {
  101. const lockResult = readProjectPackLock(ctx.packPlan.root);
  102. if (lockResult) {
  103. projectLock = lockResult.lock;
  104. const bootstrap = syncProjectBootstrapArtifacts(ctx.packPlan.root, lockResult.lock);
  105. const updatedDocs = bootstrap.docs.filter((entry) => entry.action !== 'skipped');
  106. if (updatedDocs.length > 0) {
  107. updatedDocs.forEach((entry) => console.log(` ${c.b('文档同步:')} ${entry.action} ${entry.filePath}`));
  108. }
  109. }
  110. }
  111. if (reportPath) {
  112. console.log(` ${c.b('Report:')} ${reportPath}`);
  113. }
  114. console.log(` ${c.b('文件:')} ${ctx.manifest.installed.length} 个安装, ${ctx.manifest.backups.length} 个备份`);
  115. console.log(` ${c.b('卸载:')} ${c.d(`npx code-abyss --uninstall ${tgt}`)}`);
  116. console.log(` ${c.b('体检:')} ${c.d('npx code-abyss doctor')} ${c.d('# v5 健康 + 迁移提示')}`);
  117. if (['claude', 'codex', 'gemini'].includes(tgt)) {
  118. console.log(` ${c.b('图谱:')} ${c.d(`abyss attach ${tgt}`)} ${c.d('# 代码图 hooks(非 --with-hooks)')}`);
  119. }
  120. reportAbyssStatus(projectLock, tgt);
  121. console.log('');
  122. console.log(c.grn(` ✓ 安装完成\n`));
  123. };
  124. }
  125. module.exports = { createFinish };
bin/lib/pack-registry.js · Bundled script · 400 lines · 1 finding marked
  1. 'use strict';
  2. const fs = require('fs');
  3. const path = require('path');
  4. const { listVendorProviderNames } = require('./vendor-providers');
  5. const { listTargetNames } = require('./target-registry');
  6. const PROJECT_PACKS_LOCK_REL = path.join('.code-abyss', 'packs.lock.json');
  7. const OPTIONAL_POLICIES = new Set(['auto', 'prompt', 'off']);
  8. const PACK_SOURCE_MODES = new Set(['pinned', 'local', 'disabled']);
  9. const HOST_NAMES = listTargetNames();
  10. function validatePackManifest(manifest, manifestPath, projectRoot = null) {
  11. const errors = [];
  12. if (!manifest || typeof manifest !== 'object') {
  13. errors.push('manifest 必须是对象');
  14. } else {
  15. if (typeof manifest.name !== 'string' || manifest.name.trim() === '') {
  16. errors.push('name 必填');
  17. }
  18. if (typeof manifest.description !== 'string' || manifest.description.trim() === '') {
  19. errors.push('description 必填');
  20. }
  21. if (!manifest.hosts || typeof manifest.hosts !== 'object') {
  22. errors.push('hosts 必填');
  23. } else {
  24. Object.entries(manifest.hosts).forEach(([host, hostConfig]) => {
  25. if (!HOST_NAMES.includes(host)) errors.push(`未知 host: ${host}`);
  26. if (!hostConfig || typeof hostConfig !== 'object') {
  27. errors.push(`host ${host} 配置无效`);
  28. return;
  29. }
  30. if (hostConfig.files && !Array.isArray(hostConfig.files)) {
  31. errors.push(`host ${host}.files 必须是数组`);
  32. }
  33. (hostConfig.files || []).forEach((file, index) => {
  34. if (!file.src || !file.dest || !file.root) {
  35. errors.push(`host ${host}.files[${index}] 缺少 src/dest/root`);
  36. }
  37. });
  38. if (hostConfig.uninstall) {
  39. if (!hostConfig.uninstall.runtimeRoot) {
  40. errors.push(`host ${host}.uninstall 缺少 runtimeRoot`);
  41. } else if (!hostConfig.uninstall.runtimeRoot.root || !hostConfig.uninstall.runtimeRoot.path) {
  42. 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
  43. }
  44. }
  45. });
  46. }
  47. if (manifest.reporting && typeof manifest.reporting !== 'object') {
  48. errors.push('reporting 必须是对象');
  49. }
  50. if (manifest.reporting && manifest.reporting.label && typeof manifest.reporting.label !== 'string') {
  51. errors.push('reporting.label 必须是字符串');
  52. }
  53. if (manifest.reporting && manifest.reporting.artifactPrefix && typeof manifest.reporting.artifactPrefix !== 'string') {
  54. errors.push('reporting.artifactPrefix 必须是字符串');
  55. }
  56. if (manifest.upstream) {
  57. const provider = manifest.upstream.provider || 'git';
  58. const providerNames = new Set(listVendorProviderNames(projectRoot));
  59. if (!providerNames.has(provider)) {
  60. errors.push(`upstream.provider 非法: ${provider}`);
  61. }
  62. if (provider === 'git' && (!manifest.upstream.repo || !manifest.upstream.commit)) {
  63. errors.push('upstream.provider=git 时必须提供 repo 和 commit');
  64. }
  65. if ((provider === 'local-dir' || provider === 'archive') && !manifest.upstream.path) {
  66. errors.push(`upstream.provider=${provider} 时必须提供 path`);
  67. }
  68. }
  69. }
  70. if (errors.length > 0) {
  71. throw new Error(`pack manifest 无效: ${manifestPath}\n- ${errors.join('\n- ')}`);
  72. }
  73. }
  74. function getPacksRoot(projectRoot) {
  75. return path.join(projectRoot, 'packs');
  76. }
  77. function listPackNames(projectRoot) {
  78. const packsRoot = getPacksRoot(projectRoot);
  79. if (!fs.existsSync(packsRoot)) return [];
  80. return fs.readdirSync(packsRoot, { withFileTypes: true })
  81. .filter((entry) => entry.isDirectory())
  82. .map((entry) => entry.name)
  83. .filter((name) => fs.existsSync(path.join(packsRoot, name, 'manifest.json')))
  84. .sort();
  85. }
  86. function readPackManifest(projectRoot, packName) {
  87. const manifestPath = path.join(getPacksRoot(projectRoot), packName, 'manifest.json');
  88. if (!fs.existsSync(manifestPath)) {
  89. throw new Error(`未找到 pack manifest: ${manifestPath}`);
  90. }
  91. const parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
  92. if (!parsed || typeof parsed !== 'object') {
  93. throw new Error(`pack manifest 无效: ${manifestPath}`);
  94. }
  95. validatePackManifest(parsed, manifestPath, projectRoot);
  96. if (parsed.name !== packName) {
  97. throw new Error(`pack manifest 名称不匹配: ${manifestPath}`);
  98. }
  99. return parsed;
  100. }
  101. function listPacks(projectRoot) {
  102. return listPackNames(projectRoot).map((name) => readPackManifest(projectRoot, name));
  103. }
  104. function getPack(projectRoot, packName) {
  105. return readPackManifest(projectRoot, packName);
  106. }
  107. function getPackHostConfig(projectRoot, packName, hostName) {
  108. const manifest = getPack(projectRoot, packName);
  109. return (manifest.hosts && manifest.hosts[hostName]) || null;
  110. }
  111. function getPackReporting(projectRoot, packName) {
  112. const manifest = getPack(projectRoot, packName);
  113. return {
  114. label: (manifest.reporting && manifest.reporting.label) || packName,
  115. artifactPrefix: (manifest.reporting && manifest.reporting.artifactPrefix) || packName,
  116. };
  117. }
  118. function getPackHostFiles(projectRoot, packName, hostName) {
  119. const host = getPackHostConfig(projectRoot, packName, hostName);
  120. if (!host || !Array.isArray(host.files)) return [];
  121. return host.files.map((entry) => ({
  122. src: entry.src,
  123. dest: entry.dest,
  124. root: entry.root,
  125. }));
  126. }
  127. function findProjectPacksLock(startDir = process.cwd()) {
  128. let current = path.resolve(startDir);
  129. while (true) {
  130. const candidate = path.join(current, PROJECT_PACKS_LOCK_REL);
  131. if (fs.existsSync(candidate)) return candidate;
  132. const parent = path.dirname(current);
  133. if (parent === current) return null;
  134. current = parent;
  135. }
  136. }
  137. function readProjectPackLock(startDir = process.cwd()) {
  138. const lockPath = findProjectPacksLock(startDir);
  139. if (!lockPath) return null;
  140. const parsed = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
  141. if (!parsed || typeof parsed !== 'object') {
  142. throw new Error(`project packs lock 无效: ${lockPath}`);
  143. }
  144. if (parsed.version !== 1) {
  145. throw new Error(`project packs lock version 不支持: ${lockPath}`);
  146. }
  147. return {
  148. path: lockPath,
  149. root: path.dirname(path.dirname(lockPath)),
  150. lock: parsed,
  151. };
  152. }
  153. function resolveProjectPacks(startDir = process.cwd(), hostName) {
  154. const payload = readProjectPackLock(startDir);
  155. if (!payload) {
  156. return {
  157. root: null,
  158. path: null,
  159. required: [],
  160. optional: [],
  161. };
  162. }
  163. const normalized = normalizeProjectPackLock(payload.lock);
  164. const hostConfig = normalized.hosts && normalized.hosts[hostName];
  165. const required = Array.isArray(hostConfig && hostConfig.required) ? hostConfig.required.slice() : [];
  166. const optional = Array.isArray(hostConfig && hostConfig.optional) ? hostConfig.optional.slice() : [];
  167. const optionalPolicy = (hostConfig && hostConfig.optional_policy) || 'auto';
  168. return {
  169. root: payload.root,
  170. path: payload.path,
  171. required,
  172. optional,
  173. optionalPolicy,
  174. sources: { ...(hostConfig && hostConfig.sources ? hostConfig.sources : {}) },
  175. };
  176. }
  177. function uniqueSorted(values) {
  178. return [...new Set((values || []).filter(Boolean))].sort();
  179. }
  180. function normalizeHostPackConfig(hostConfig = {}) {
  181. const sources = {};
  182. Object.entries(hostConfig.sources || {}).forEach(([pack, source]) => {
  183. sources[pack] = PACK_SOURCE_MODES.has(source) ? source : 'pinned';
  184. });
  185. return {
  186. required: uniqueSorted(hostConfig.required),
  187. optional: uniqueSorted(hostConfig.optional),
  188. optional_policy: OPTIONAL_POLICIES.has(hostConfig.optional_policy) ? hostConfig.optional_policy : 'auto',
  189. sources,
  190. };
  191. }
  192. function normalizeProjectPackLock(lock = {}) {
  193. const hosts = {};
  194. HOST_NAMES.forEach((host) => {
  195. hosts[host] = normalizeHostPackConfig(lock.hosts && lock.hosts[host]);
  196. });
  197. return {
  198. version: 1,
  199. hosts,
  200. };
  201. }
  202. function buildDefaultProjectPackLock(projectRoot, hostNames = HOST_NAMES) {
  203. const packs = listPacks(projectRoot);
  204. const lock = normalizeProjectPackLock({ version: 1, hosts: {} });
  205. hostNames.forEach((host) => {
  206. const required = [];
  207. const optional = [];
  208. const sources = {};
  209. packs.forEach((pack) => {
  210. const defaultMode = pack.projectDefaults && pack.projectDefaults[host];
  211. if (defaultMode === 'required') {
  212. required.push(pack.name);
  213. sources[pack.name] = 'pinned';
  214. }
  215. if (defaultMode === 'optional') {
  216. optional.push(pack.name);
  217. sources[pack.name] = 'pinned';
  218. }
  219. });
  220. lock.hosts[host] = {
  221. required: uniqueSorted(required),
  222. optional: uniqueSorted(optional),
  223. optional_policy: 'auto',
  224. sources,
  225. };
  226. });
  227. return lock;
  228. }
  229. function validateProjectPackLock(lock, projectRoot) {
  230. const normalized = normalizeProjectPackLock(lock);
  231. const available = new Set(listPackNames(projectRoot));
  232. const errors = [];
  233. HOST_NAMES.forEach((host) => {
  234. const rawHost = (lock.hosts && lock.hosts[host]) || {};
  235. const hostConfig = normalized.hosts[host];
  236. const listed = new Set([...hostConfig.required, ...hostConfig.optional]);
  237. hostConfig.required.forEach((pack) => {
  238. if (!available.has(pack)) errors.push(`[${host}] 未知 required pack: ${pack}`);
  239. if (pack === 'abyss') errors.push(`[${host}] core pack 'abyss' 不应写入 packs.lock`);
  240. if (hostConfig.sources[pack] === 'disabled') errors.push(`[${host}] required pack 不能设置 source=disabled: ${pack}`);
  241. });
  242. hostConfig.optional.forEach((pack) => {
  243. if (!available.has(pack)) errors.push(`[${host}] 未知 optional pack: ${pack}`);
  244. if (pack === 'abyss') errors.push(`[${host}] core pack 'abyss' 不应写入 packs.lock`);
  245. if (hostConfig.required.includes(pack)) errors.push(`[${host}] pack 同时出现在 required 和 optional: ${pack}`);
  246. });
  247. if (rawHost.optional_policy && !OPTIONAL_POLICIES.has(rawHost.optional_policy)) {
  248. errors.push(`[${host}] optional_policy 非法: ${rawHost.optional_policy}`);
  249. }
  250. Object.entries(rawHost.sources || {}).forEach(([pack, source]) => {
  251. if (!PACK_SOURCE_MODES.has(source)) {
  252. errors.push(`[${host}] source 非法: ${pack}=${source}`);
  253. }
  254. if (!listed.has(pack)) {
  255. errors.push(`[${host}] source 指向未声明 pack: ${pack}`);
  256. }
  257. });
  258. });
  259. return errors;
  260. }
  261. async function selectProjectPacksForInstall(projectPacks, { autoYes = false, confirm = null } = {}) {
  262. const sources = { ...(projectPacks.sources || {}) };
  263. const required = uniqueSorted(projectPacks.required).filter((pack) => sources[pack] !== 'disabled');
  264. const optional = uniqueSorted(projectPacks.optional).filter((pack) => sources[pack] !== 'disabled');
  265. const policy = projectPacks.optionalPolicy || 'auto';
  266. if (policy === 'off' || optional.length === 0) {
  267. return { selected: required, optionalSelected: [], optionalPolicy: policy, sources };
  268. }
  269. if (policy === 'auto') {
  270. return {
  271. selected: uniqueSorted([...required, ...optional]),
  272. optionalSelected: optional,
  273. optionalPolicy: policy,
  274. sources,
  275. };
  276. }
  277. if (autoYes || typeof confirm !== 'function') {
  278. return {
  279. selected: uniqueSorted([...required, ...optional]),
  280. optionalSelected: optional,
  281. optionalPolicy: policy,
  282. sources,
  283. };
  284. }
  285. const accepted = await confirm(optional);
  286. return {
  287. selected: accepted ? uniqueSorted([...required, ...optional]) : required,
  288. optionalSelected: accepted ? optional : [],
  289. optionalPolicy: policy,
  290. sources,
  291. };
  292. }
  293. function diffProjectPackLocks(currentLock, defaultLock) {
  294. const current = normalizeProjectPackLock(currentLock);
  295. const defaults = normalizeProjectPackLock(defaultLock);
  296. const diffs = [];
  297. HOST_NAMES.forEach((host) => {
  298. const now = current.hosts[host];
  299. const base = defaults.hosts[host];
  300. const addedRequired = now.required.filter((pack) => !base.required.includes(pack));
  301. const removedRequired = base.required.filter((pack) => !now.required.includes(pack));
  302. const addedOptional = now.optional.filter((pack) => !base.optional.includes(pack));
  303. const removedOptional = base.optional.filter((pack) => !now.optional.includes(pack));
  304. const sourceChanges = {};
  305. uniqueSorted([...Object.keys(now.sources), ...Object.keys(base.sources)]).forEach((pack) => {
  306. const from = base.sources[pack] || null;
  307. const to = now.sources[pack] || null;
  308. if (from !== to) sourceChanges[pack] = { from, to };
  309. });
  310. if (
  311. addedRequired.length > 0
  312. || removedRequired.length > 0
  313. || addedOptional.length > 0
  314. || removedOptional.length > 0
  315. || now.optional_policy !== base.optional_policy
  316. || Object.keys(sourceChanges).length > 0
  317. ) {
  318. diffs.push({
  319. host,
  320. addedRequired,
  321. removedRequired,
  322. addedOptional,
  323. removedOptional,
  324. optionalPolicy: { from: base.optional_policy, to: now.optional_policy },
  325. sourceChanges,
  326. });
  327. }
  328. });
  329. return diffs;
  330. }
  331. module.exports = {
  332. getPacksRoot,
  333. listPackNames,
  334. listPacks,
  335. getPack,
  336. getPackHostConfig,
  337. getPackReporting,
  338. getPackHostFiles,
  339. PROJECT_PACKS_LOCK_REL,
  340. HOST_NAMES,
  341. OPTIONAL_POLICIES,
  342. PACK_SOURCE_MODES,
  343. validatePackManifest,
  344. normalizeHostPackConfig,
  345. normalizeProjectPackLock,
  346. buildDefaultProjectPackLock,
  347. validateProjectPackLock,
  348. findProjectPacksLock,
  349. readProjectPackLock,
  350. resolveProjectPacks,
  351. selectProjectPacksForInstall,
  352. diffProjectPackLocks,
  353. };
bin/lib/runtime-control.js · Bundled script · 247 lines · 1 finding marked
  1. 'use strict';
  2. // Agent OS v5.5 — doctor + compose pure control plane.
  3. // CLI wiring lives in bin/install.js; this module stays unit-testable without install.
  4. const fs = require('fs');
  5. const path = require('path');
  6. const os = require('os');
  7. const { detectAbyss, MIN_ABYSS_VERSION } = require('./abyss-integration');
  8. const { renderRuntimeGuidance, getDefaultStyle, getDefaultPersona, resolveStyle, resolvePersona } = require('./style-registry');
  9. const { INJECT_REL_PATH } = require('./inject-plane');
  10. const COMPOSE_BUDGET_CAP = 8000;
  11. function readKernelSyncMeta(projectRoot) {
  12. const p = path.join(projectRoot, 'skills', '_kernel', '.sync-meta.json');
  13. if (!fs.existsSync(p)) return null;
  14. try {
  15. return JSON.parse(fs.readFileSync(p, 'utf8'));
  16. } catch {
  17. return null;
  18. }
  19. }
  20. function detectEnforcementOn({ HOME = os.homedir(), target = 'claude' } = {}) {
  21. if (target === 'claude') {
  22. const settingsPath = path.join(HOME, '.claude', 'settings.json');
  23. if (!fs.existsSync(settingsPath)) return { on: false, path: settingsPath, reason: 'no-settings' };
  24. try {
  25. const raw = fs.readFileSync(settingsPath, 'utf8');
  26. const on = raw.includes('check_banned_openers.py') || raw.includes('_kernel/character/hooks');
  27. return { on, path: settingsPath };
  28. } catch (e) {
  29. return { on: false, path: settingsPath, reason: e.message };
  30. }
  31. }
  32. if (target === 'codex') {
  33. const cfgPath = path.join(HOME, '.codex', 'config.toml');
  34. if (!fs.existsSync(cfgPath)) return { on: false, path: cfgPath, reason: 'no-config' };
  35. try {
  36. const raw = fs.readFileSync(cfgPath, 'utf8');
  37. const on = raw.includes('check_banned_openers.py') || raw.includes('_kernel/character/hooks');
  38. return { on, path: cfgPath };
  39. } catch (e) {
  40. return { on: false, path: cfgPath, reason: e.message };
  41. }
  42. }
  43. return { on: false, reason: 'unsupported-target' };
  44. }
  45. function measureComposeBudget(projectRoot, { styleSlug, personaSlug } = {}) {
  46. const style = styleSlug || getDefaultStyle(projectRoot, 'claude').slug;
  47. const persona = personaSlug || getDefaultPersona(projectRoot).slug;
  48. const text = renderRuntimeGuidance(projectRoot, style, 'codex', persona);
  49. return {
  50. style,
  51. persona,
  52. length: text.length,
  53. cap: COMPOSE_BUDGET_CAP,
  54. headroom: COMPOSE_BUDGET_CAP - text.length,
  55. underBudget: text.length < COMPOSE_BUDGET_CAP,
  56. };
  57. }
  58. /**
  59. * Doctor report object (pure enough for tests; may read HOME + project tree).
  60. */
  61. function buildDoctorReport({
  62. projectRoot,
  63. HOME = os.homedir(),
  64. version,
  65. packageName = 'code-abyss',
  66. target = 'claude',
  67. } = {}) {
  68. const pkgPath = path.join(projectRoot, 'package.json');
  69. let pkg = { name: packageName, version: version || '0.0.0' };
  70. if (fs.existsSync(pkgPath)) {
  71. try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); } catch { /* keep */ }
  72. }
  73. const abyss = detectAbyss({ HOME });
  74. const kernel = readKernelSyncMeta(projectRoot);
  75. const enforcement = detectEnforcementOn({ HOME, target });
  76. const budget = measureComposeBudget(projectRoot);
  77. const injectSupported = target === 'claude' || target === 'codex';
  78. const injectPath = injectSupported
  79. ? path.join(HOME, target === 'codex' ? '.codex' : '.claude', INJECT_REL_PATH)
  80. : null;
  81. const injectPresent = injectPath ? fs.existsSync(injectPath) : null;
  82. return {
  83. package: { name: pkg.name, version: pkg.version },
  84. abyss: abyss
  85. ? { present: true, version: abyss.version, source: abyss.source, binPath: abyss.binPath, minRequired: MIN_ABYSS_VERSION }
  86. : { present: false, minRequired: MIN_ABYSS_VERSION },
  87. kernel: kernel
  88. ? {
  89. present: true,
  90. sourceCommit: kernel.sourceCommit || null,
  91. syncedAt: kernel.syncedAt || null,
  92. bundles: kernel.bundles || [],
  93. }
  94. : { present: false },
  95. enforcement: { target, ...enforcement },
  96. composeBudget: budget,
  97. injectPlane: {
  98. supported: injectSupported,
  99. present: injectPresent,
  100. path: injectPath,
  101. },
  102. };
  103. }
  104. /**
  105. * Actionable migration / health hints for 4.x → 5.0 cutover.
  106. * @returns {string[]}
  107. */
  108. function collectMigrationHints(report) {
  109. const hints = [];
  110. const t = report.enforcement && report.enforcement.target;
  111. if (!report.abyss.present) {
  112. hints.push(
  113. '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
  114. ' (or: npm i -g @code-abyss/cli | cargo binstall code-abyss)'
  115. );
  116. }
  117. if (t && ['claude', 'codex', 'gemini'].includes(t)) {
  118. // Graph hooks are not owned by code-abyss install; always remind attach for these hosts
  119. hints.push(`code-graph hooks → abyss attach ${t} (idempotent; not --with-hooks)`);
  120. }
  121. if (report.enforcement && !report.enforcement.on && t && ['claude', 'codex'].includes(t)) {
  122. hints.push(
  123. 'character Stop-hook OFF → reinstall without --no-enforcement (default on in 5.0)'
  124. );
  125. }
  126. if (report.injectPlane && report.injectPlane.supported && !report.injectPlane.present && t && ['claude', 'codex'].includes(t)) {
  127. hints.push(
  128. `inject plane missing → npx code-abyss -t ${t} -y (writes ${report.injectPlane.path || '.code-abyss-inject.md'})`
  129. );
  130. }
  131. if (!report.kernel.present) {
  132. hints.push('kernel meta missing in this package tree — reinstall from npm/tag that ships skills/_kernel');
  133. }
  134. if (report.composeBudget && !report.composeBudget.underBudget) {
  135. hints.push(`compose budget exceeded (${report.composeBudget.length}/${report.composeBudget.cap}) — trim always-on layers`);
  136. }
  137. return hints;
  138. }
  139. function formatDoctorReport(report) {
  140. const lines = [];
  141. lines.push(`code-abyss doctor · ${report.package.name}@${report.package.version}`);
  142. if (report.abyss.present) {
  143. lines.push(`abyss: ${report.abyss.version || '?'} (${report.abyss.source}) min=${report.abyss.minRequired}`);
  144. } else {
  145. lines.push(`abyss: not detected (min ${report.abyss.minRequired}) — install via abyss install.sh`);
  146. }
  147. if (report.kernel.present) {
  148. lines.push(`kernel: commit=${report.kernel.sourceCommit || '?'} syncedAt=${report.kernel.syncedAt || '?'}`);
  149. } else {
  150. lines.push('kernel: .sync-meta.json missing');
  151. }
  152. lines.push(
  153. `enforcement(${report.enforcement.target}): ${report.enforcement.on ? 'ON' : 'OFF'}`
  154. + (report.enforcement.reason ? ` (${report.enforcement.reason})` : '')
  155. );
  156. const b = report.composeBudget;
  157. lines.push(`compose budget: ${b.length}/${b.cap} (headroom ${b.headroom}) persona=${b.persona} style=${b.style}`);
  158. if (!report.injectPlane.supported) {
  159. lines.push(`inject plane: N/A (${report.enforcement.target} — not installed by code-abyss)`);
  160. } else {
  161. lines.push(`inject plane: ${report.injectPlane.present ? 'present' : 'absent'} (${report.injectPlane.path})`);
  162. }
  163. const hints = collectMigrationHints(report);
  164. if (hints.length) {
  165. lines.push('');
  166. lines.push('migration / next steps (v5):');
  167. for (const h of hints) lines.push(` • ${h}`);
  168. lines.push(' see docs/MIGRATION-v5.md');
  169. }
  170. return lines.join('\n') + '\n';
  171. }
  172. /**
  173. * Compose host guidance using the same engine as install (no skill tree copy).
  174. * @returns {{ guidance: string, destPath: string|null, wrote: boolean }}
  175. */
  176. const COMPOSE_SUPPORTED_TARGETS = new Set(['claude', 'codex', 'gemini', 'openclaw']);
  177. function composeHostGuidance({
  178. projectRoot,
  179. target = 'claude',
  180. personaSlug = null,
  181. styleSlug = null,
  182. HOME = os.homedir(),
  183. write = false,
  184. } = {}) {
  185. if (!COMPOSE_SUPPORTED_TARGETS.has(target)) {
  186. throw new Error(`unsupported target: ${target}. Supported: ${[...COMPOSE_SUPPORTED_TARGETS].join(', ')}`);
  187. }
  188. const persona = personaSlug || getDefaultPersona(projectRoot).slug;
  189. const style = styleSlug
  190. || getDefaultStyle(projectRoot, target === 'gemini' ? 'claude' : target).slug;
  191. // Validate slugs resolve
  192. if (!resolvePersona(projectRoot, persona)) {
  193. throw new Error(`unknown persona: ${persona}`);
  194. }
  195. if (!resolveStyle(projectRoot, style, target === 'gemini' ? 'claude' : target)) {
  196. throw new Error(`unknown style: ${style}`);
  197. }
  198. const hostForRender = target === 'gemini' ? 'gemini' : 'codex';
  199. const guidance = renderRuntimeGuidance(projectRoot, style, hostForRender, persona);
  200. if (guidance.length >= COMPOSE_BUDGET_CAP) {
  201. throw new Error(`compose guidance exceeds budget cap: ${guidance.length}/${COMPOSE_BUDGET_CAP}`);
  202. }
  203. let destPath = null;
  204. if (target === 'claude') destPath = path.join(HOME, '.claude', 'CLAUDE.md');
  205. else if (target === 'codex') destPath = path.join(HOME, '.codex', 'instruction.md');
  206. else if (target === 'gemini') destPath = path.join(HOME, '.gemini', 'GEMINI.md');
  207. else if (target === 'openclaw') {
  208. destPath = path.join(HOME, '.openclaw', 'workspace', 'AGENTS.md');
  209. }
  210. let wrote = false;
  211. if (write && destPath) {
  212. fs.mkdirSync(path.dirname(destPath), { recursive: true });
  213. fs.writeFileSync(destPath, guidance);
  214. wrote = true;
  215. }
  216. return { guidance, destPath, wrote, persona, style };
  217. }
  218. module.exports = {
  219. COMPOSE_BUDGET_CAP,
  220. readKernelSyncMeta,
  221. detectEnforcementOn,
  222. measureComposeBudget,
  223. buildDoctorReport,
  224. formatDoctorReport,
  225. collectMigrationHints,
  226. composeHostGuidance,
  227. };

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.