honeycomb
AI coding agents forget. They forget across sessions, and they forget across tools. A decision you reached in Claude Code at midnight is invisible to Cursor the next morning. Honeycomb fixes that. Learn something once; recall it everywhere,
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/legioncodeinc/honeycomb with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/legioncodeinc/honeycomb'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/legioncodeinc--honeycomb)HTML
<a href="/listings/legioncodeinc--honeycomb"><img src="/api/listings/legioncodeinc--honeycomb/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.
These steps run a script from the network that findsafeskills does not scan.
No Node? No npm? No problem. The installer detects and sets up everything, then **opens a dashboard in your browser**. The terminal is just a progress log; the product is the first thing you touch.
# macOS / Linux curl -fsSL https://get.theapiary.sh | sh
# Windows (PowerShell) irm https://get.theapiary.sh/install.ps1 | iex
That single line installs a current Node/npm if missing, installs **`@legioncodeinc/honeycomb`** globally, brings up the daemon on `127.0.0.1:3850`, opens the dashboard (Hive portal at `127.0.0.1:3853`), and sets up **[Doctor](https://github.com/legioncodeinc/doctor#readme)**, a tiny watchdog that keeps it all healthy (opt out with `--no-doctor`). Then:
1. The dashboard loads in a **pre-auth setup state**. No token ever touches your shell. 2. Click **"First time setup."** Honeycomb runs the Deeplake device-flow login *for* you, shows the code right on the page, and opens the verification tab. 3. Done. The same running daemon lights up its Deeplake-backed surfaces, and capture and recall go live.
> Already running **Hivemind**? The dashboard detects it, explains that running both is unsupported, and **"Proceed with Honeycomb"** migrates you cleanly. Prefer to inspect before you pipe? The script and a published `SHA256SUMS` are served from [get.theapiary.sh](https://get.theapiary.sh).
<details> <summary><strong>Prefer to build from source?</strong></summary>
git clone https://github.com/legioncodeinc/honeycomb.git cd honeycomb npm install npm run build # tsc + esbuild → bundle/cli.js, daemon, harness, MCP, embed bundles node bundle/cli.js setup # detect your assistants, wire hooks, start the daemon node bundle/cli.js status # check the daemon and your environment
`setup` wires every coding assistant it detects and starts the loopback daemon; any storage command auto-starts the daemon if it is down. You'll need Activeloop Deeplake credentials; the device flow above writes them to the shared `~/.deeplake/credentials.json`.
> **Self-hosting the storage backend?** You can run Honeycomb against Activeloop's open-source [`pg_deeplake`](https://quay.io/activeloopai/pg-deeplake) Postgres extension instead of hosted Deeplake, and point Honeycomb at it with `honeycomb login --endpoint postgres://...` (direct) or `--endpoint https://...` (HTTP gateway), no Activeloop account required. See the [self-hosting guide](library/knowledge/public/guides/self-hosting.md) for the setup and the backend contract.
</details>
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": "honeycomb",
- "owner": {
- "name": "Honeycomb"
- },
- "metadata": {
- "description": "Honeycomb — persistent memory daemon and thin harness clients for AI coding assistants",
- "version": "0.22.1"
- },
- "plugins": [
- {
- "name": "honeycomb",
- "description": "Honeycomb Claude Code plugin — captures session activity and provides cross-session memory through the local daemon",
- "version": "0.22.1",
- "source": "./harnesses/claude-code"
- }
- ]
- }
README.md · README · 336 lines · 2 findings marked
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <!-- ─────────────────────────────── HERO ─────────────────────────────── -->
- <p align="center">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="assets/brand/honeycomb-wordmark-on-dark.svg">
- <img src="assets/brand/honeycomb-wordmark-black.svg" alt="Honeycomb" height="84">
- </picture>
- </p>
- <h1 align="center">Honeycomb</h1>
- <p align="center">
- <strong>Shared, persistent memory for your AI coding agents.</strong><br>
- What one harness learns, every other one recalls, across sessions, tools, devices, and teammates.
- </p>
- <p align="center">
- <a href="https://www.npmjs.com/package/@legioncodeinc/honeycomb"><img src="https://img.shields.io/npm/v/@legioncodeinc/honeycomb?style=flat-square&color=F7A823&label=version" alt="npm version"></a>
- <img src="https://img.shields.io/badge/harnesses-3%20supported%20%7C%203%20in%20progress-F7A823?style=flat-square" alt="3 supported, 3 in progress">
- <img src="https://img.shields.io/badge/OS-windows%20%7C%20macos%20%7C%20linux-6E6A62?style=flat-square" alt="Windows, macOS, Linux">
- </p>
- <p align="center">
- <a href="https://linktr.ee/marioaldayuz"><img src="https://img.shields.io/badge/designed%20by-Mario%20Aldayuz-8B7CF0?style=flat-square" alt="Designed by Mario Aldayuz"></a>
- <a href="https://www.legioncodeinc.com"><img src="https://img.shields.io/badge/built%20by-Legion%20Code%20Inc.-111111?style=flat-square" alt="Built by Legion Code Inc."></a>
- <a href="https://deeplake.ai"><img src="https://img.shields.io/badge/powered%20by-Deeplake-ff5a1f?style=flat-square" alt="Powered by Deeplake"></a>
- </p>
- <p align="center">
- <a href="https://github.com/legioncodeinc/honeycomb"><img src="https://img.shields.io/github/stars/legioncodeinc/honeycomb?style=flat-square&color=F7A823" alt="GitHub stars"></a>
- <a href="https://discord.gg/GX95YTQypQ"><img src="https://img.shields.io/badge/discord-find%20us-5865F2?style=flat-square&logo=discord&logoColor=white" alt="Discord"></a>
- </p>
- <!-- ────────────────────────────── PARTNERS ────────────────────────────── -->
- <p align="center">
- <a href="https://github.com/legioncodeinc">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="assets/brand/legion-logo-dark.svg">
- <img src="assets/brand/legion-logo-light.svg" alt="Legion Code" height="34">
- </picture>
- </a>
-
- <a href="https://github.com/activeloopai">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="assets/brand/activeloop-full-mark-logo-on-dark.svg">
- <img src="assets/brand/activeloop-full-mark-logo.svg" alt="Activeloop" height="26">
- </picture>
- </a>
- </p>
- <p align="center"><em>A <a href="https://github.com/legioncodeinc">Legion Code Inc.</a> × <a href="https://github.com/activeloopai">Activeloop</a> collaboration.</em></p>
- <img src="assets/brand/divider-major.svg" width="100%" height="6">
- AI coding agents forget. They forget across sessions, and they forget across tools. A decision you reached in Claude Code at midnight is invisible to Cursor the next morning. **Honeycomb fixes that.** A local daemon captures what happens on every turn, distills it, and serves it back to any harness that asks. Learn something once; recall it everywhere, on any machine, in any tool, for anyone on your team.
- It answers the questions you keep paying for twice: *What did we decide about this? Why is it built this way? What fixed it the last time it broke? Who on the team already solved this?*
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- > **New here?** One command and you're on a dashboard. [Jump to Install](#-install-one-command). · **Want the docs?** Everything lives at **[theapiary.sh](https://theapiary.sh)**.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- <table>
- <tr>
- <td width="50%" valign="top">
- #### 🛹 For AI Augmented Devs
- Stop re-explaining your project to a fresh agent every morning. Honeycomb remembers your decisions, your conventions, and the fixes that worked, then primes your next session with them automatically. One install command, a friendly dashboard, no SQL, no config gauntlet.
- </td>
- <td width="50%" valign="top">
- #### 🏢 For Enterprise Teams
- One shared brain across every developer, device, and coding tool. A skill discovered by one engineer propagates to the whole team on their next session. Tenancy is enforced at the storage layer; credentials live behind a single loopback boundary; everything is versioned and auditable.
- </td>
- </tr>
- </table>
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## ✨ What makes Honeycomb different
- A vector database can store text and hand it back by similarity. Honeycomb does that, and then keeps going. On top of [Activeloop Deeplake](https://deeplake.ai), **[Legion Code](https://github.com/legioncodeinc)** builds the memory system that turns raw recall into a brain your agents actually trust.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- - **🧠 Three-tier memory.** Every memory exists at three resolutions at once (one-line **key** → **summary** → full **raw** session). Agents skim the keys, then zoom into detail only when they need it. *(Legion Code)*
- - **🎯 Session priming.** At session start a tiny, bounded index (~300-800 tokens) of your most relevant keys is pushed once; the agent pulls deeper on demand. No per-turn injection, no "lost in the middle." *(Legion Code)*
- - **🍯 Skillify & propagation.** The daemon mines reusable skills out of real sessions, gates them for quality, and auto-pulls the team's latest skills into every agent at session start. Author a skill once; everyone gets it. *(Legion Code)*
- - **🌼 The pollinating loop.** A periodic maintenance pass reasons over accumulated memory and the entity graph to merge duplicates, prune junk, and supersede stale facts, so memory gets *sharper* over time, not noisier. *(Legion Code)*
- - **🕸️ Knowledge graph.** An entity-centric, versioned, provenance-tracked index over your memories. Newer facts supersede stale ones; every claim traces back to the session that produced it. *(Legion Code)*
- - **🔀 Hybrid recall.** Lexical (BM25) and semantic (768-dim vectors) search fused by Reciprocal Rank Fusion, with a measured **recall@5 ≈ 0.72-0.78**. *(built on Deeplake)*
- - **🗺️ Codebase graph.** A multi-language AST graph (TypeScript, JS, Python, Go, Rust, Java, Ruby, C/C++) of files, functions, and their call/import/extends edges, queryable for impact and neighborhood. *(Legion Code)*
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## 🚀 Install (one command)
- No Node? No npm? No problem. The installer detects and sets up everything, then **opens a dashboard in your browser**. The terminal is just a progress log; the product is the first thing you touch.
- ```bash
- # macOS / Linux
- curl -fsSL https://get.theapiary.sh | sh
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 107 on GitHub
- ```
- ```powershell
- # Windows (PowerShell)
- irm https://get.theapiary.sh/install.ps1 | iex
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 112 on GitHub
- ```
- That single line installs a current Node/npm if missing, installs **`@legioncodeinc/honeycomb`** globally, brings up the daemon on `127.0.0.1:3850`, opens the dashboard (Hive portal at `127.0.0.1:3853`), and sets up **[Doctor](https://github.com/legioncodeinc/doctor#readme)**, a tiny watchdog that keeps it all healthy (opt out with `--no-doctor`). Then:
- 1. The dashboard loads in a **pre-auth setup state**. No token ever touches your shell.
- 2. Click **"First time setup."** Honeycomb runs the Deeplake device-flow login *for* you, shows the code right on the page, and opens the verification tab.
- 3. Done. The same running daemon lights up its Deeplake-backed surfaces, and capture and recall go live.
- > Already running **Hivemind**? The dashboard detects it, explains that running both is unsupported, and **"Proceed with Honeycomb"** migrates you cleanly. Prefer to inspect before you pipe? The script and a published `SHA256SUMS` are served from [get.theapiary.sh](https://get.theapiary.sh).
- <details>
- <summary><strong>Prefer to build from source?</strong></summary>
- ```bash
- git clone https://github.com/legioncodeinc/honeycomb.git
- cd honeycomb
- npm install
- npm run build # tsc + esbuild → bundle/cli.js, daemon, harness, MCP, embed bundles
- node bundle/cli.js setup # detect your assistants, wire hooks, start the daemon
- node bundle/cli.js status # check the daemon and your environment
- ```
- `setup` wires every coding assistant it detects and starts the loopback daemon; any storage command auto-starts the daemon if it is down. You'll need Activeloop Deeplake credentials; the device flow above writes them to the shared `~/.deeplake/credentials.json`.
- > **Self-hosting the storage backend?** You can run Honeycomb against Activeloop's open-source [`pg_deeplake`](https://quay.io/activeloopai/pg-deeplake) Postgres extension instead of hosted Deeplake, and point Honeycomb at it with `honeycomb login --endpoint postgres://...` (direct) or `--endpoint https://...` (HTTP gateway), no Activeloop account required. See the [self-hosting guide](library/knowledge/public/guides/self-hosting.md) for the setup and the backend contract.
- </details>
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## 🖥️ Using the dashboard
- The dashboard is **Hive portal at `http://127.0.0.1:3853`**, the one UI for the whole Apiary stack and the first thing the installer opens. Honeycomb's old in-daemon dashboard is retired; the daemon on `:3850` serves data, the portal serves the picture. Everything Honeycomb knows shows up there: KPIs up top (memories, turns, estimated savings, team skills), memory recall you can query by hand, the codebase graph, every captured turn, skill-sync status, and settings, hydrated server-side from the daemon's API. It doubles as the guided-setup surface for first-time login.
- <!-- screenshot pending: drop honeycomb dashboard capture into assets/screenshots/dashboard.png -->
- <img src="assets/screenshots/dashboard.png" alt="Honeycomb dashboard" width="100%">
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## ⌨️ Using the CLI
- One unified `honeycomb` binary drives everything. Run `honeycomb --help` for the full list; these are the core verbs:
- ```bash
- honeycomb install # one-shot install on a fresh machine
- honeycomb setup # detect your coding assistants and wire hooks
- honeycomb status # daemon + environment health at a glance
- honeycomb login # sign in via the Deeplake device flow, any time
- honeycomb start # start the installed OS service and verify health
- honeycomb stop # stop the installed OS service
- honeycomb restart # restart through the OS service and verify health
- honeycomb service-install # install/reconcile only the OS service
- honeycomb service-uninstall # remove only the OS service; preserve state/registration
- honeycomb register # idempotently upsert Honeycomb in Doctor's registry
- honeycomb logs # last 100 service-log lines, then follow
- honeycomb telemetry # read-only telemetry state and delivery summary
- honeycomb update --check # compare installed and approved release versions
- honeycomb daemon start|stop|status # legacy process-level compatibility commands
- honeycomb uninstall --yes # confirmed full removal of Honeycomb-owned state
- honeycomb remember "<fact>" # write a memory from anywhere
- honeycomb recall "<query>" # search the shared memory
- honeycomb sessions # browse captured sessions
- honeycomb skill # list, inspect, and sync mined skills
- honeycomb goal # track goals across sessions
- honeycomb sources # manage capture sources
- honeycomb graph # query the codebase and knowledge graphs
- honeycomb dashboard # open the dashboard (Hive portal, :3853)
- ```
- A few lifecycle notes:
- - **The suite-wide command contract is shared.** The normative matrix and semantics live in [`@legioncodeinc/cli-kit`](https://github.com/legioncodeinc/cli-kit/blob/main/library/notes/prd-003-command-matrix.md); this section documents Honeycomb-specific behavior and compatibility commands only.
- - **Automation is structured.** Every baseline operational verb accepts `--json`; malformed usage exits `2`, runtime failures exit `1`, and successful/idempotent requests exit `0`. Use `--no-color` or `NO_COLOR=1` for plain human output.
- - **Logs are isolated.** `honeycomb logs` can read only Honeycomb's configured service log. It supports `--lines <n>`, `--no-follow`, and `--since <duration-or-timestamp>` and redacts recognized credentials on output.
- - **Sign-in knows who owns it.** When [Hive](https://github.com/legioncodeinc/hive#readme) is installed alongside, `honeycomb install` never opens its own sign-in; Hive's onboarding is the one login surface, and the daemon sits degraded on `/health` until that login writes the shared `~/.deeplake/credentials.json`, then recovers on its own, no restart needed. Solo (no Hive), a fresh install with no credentials opens the device-flow sign-in automatically, and headless sessions get the URL and code printed instead of a browser. `honeycomb login` works the same way in both modes whenever you want it.
- - **`uninstall` is surgical.** It removes only Honeycomb's things: assistant hooks, the OS service unit (current and legacy labels), Honeycomb's entry in Doctor's registry, and `~/.apiary/honeycomb`. Shared credentials and every other product survive. Running it when nothing is installed is a friendly no-op. For a full-machine wipe, use `doctor purge` or the one-command uninstall at [get.theapiary.sh](https://get.theapiary.sh).
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## 🐝 First memory, shared across tools
- ```bash
- # Capture a decision once…
- honeycomb remember "we deploy from the prd-022 branch, never from main"
- # …recall it anywhere: same daemon, same Deeplake, any harness
- honeycomb recall "how do we deploy"
- ```
- Write it from Claude Code; recall it from Cursor tomorrow on a different laptop. That's the whole point.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## 🏗️ How it works
- Honeycomb is a long-lived local **daemon** plus thin clients. The daemon is the *only* process that talks to storage. Every harness, the CLI, the MCP server, and the SDK reach it over loopback HTTP. One shared memory behind one boundary; your Deeplake credentials in exactly one place.
- ```mermaid
- flowchart TB
- CC["Claude Code"] --> TC
- CU["Cursor"] --> TC
- CX["Codex"] --> TC
- HE["Hermes"] --> TC
- PI["pi"] --> TC
- OC["OpenClaw"] --> TC
- TC["thin clients<br/>hooks · CLI · MCP · SDK"] --> HTTP["loopback HTTP<br/>127.0.0.1:3850"]
- HTTP --> D["honeycomb daemon<br/>capture · recall · skillify · pollinate · session priming<br/>sole storage client, owns your credentials"]
- D --> DL["Activeloop Deeplake<br/>Tier 1 · Tier 2 · Tier 3<br/>BM25 + semantic vectors"]
- ```
- - **Capture on every turn.** Per-harness hooks stream each turn to the daemon, which distills and persists it: always-on, cheap, and soft-failing so a capture error never breaks your agent's turn.
- - **Recall through the daemon.** Any harness asks for relevant memories; the daemon runs the query and returns results already scoped to your org and workspace. The client never sees a storage handle or a line of SQL.
- - **Shared by construction.** Every client reaches the same daemon and the same dataset, so a memory written from one harness is recallable from all of them.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## 🧠 The three-tier memory system
- This is the heart of what **Legion Code** adds on top of Deeplake. The same memory lives at three levels of detail at once, and the agent chooses how far to zoom:
- | Tier | What it is | When it's used |
- |---|---|---|
- | **Tier 1 · Key** | One keyword-dense sentence per session or fact. The index. | Skimmed at session start during priming. |
- | **Tier 2 · Summary** | A distilled recap: goals, decisions, blockers, outcomes. Carries the semantic embedding. | Pulled when a key looks relevant. |
- | **Tier 3 · Raw** | The full session dialogue: exact turns and tool calls, never rewritten. | Resolved when the agent needs ground truth. |
- Resolution is a **deterministic SQL join, not a fuzzy search**. `key → summary → raw` is a pointer walk down three Deeplake tables. Mining ("find the thing I didn't know to name") is where the hybrid vector + lexical search kicks in. Cheap when you're skimming, precise when you're zooming.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## 💎 Why Deeplake makes the difference
- Most agent-memory tools bolt onto a vector-only store, which forces *every* access pattern through a similarity engine. Honeycomb's zoom model needs both exact joins **and** semantic search, and [**Deeplake**](https://deeplake.ai), the database for AI, gives it both natively:
- - **SQL + vector in one engine.** The cheap skim and the deterministic zoom run as SQL; semantic mining runs as vector search; a single store serves both. No second database, no sync problem.
- - **Versioned & append-only.** Writes bump a version instead of mutating in place, so memory's full history stays on disk. Supersession marks old facts stale without losing them, which is what makes the pollinating loop safe and auditable.
- - **Hybrid lexical + semantic search.** BM25 and 768-dim `nomic-embed-text-v1.5` cosine arms, fused by Reciprocal Rank Fusion. Turn embeddings off and recall silently falls back to lexical, never an error, no quality cliff.
- - **Built to scale & BYOC.** The same substrate that serves one developer's laptop serves an organization's entire history, in your own cloud bucket if you want it.
- > Honeycomb stands on two shoulders: **[Deeplake](https://deeplake.ai)** gives the memories somewhere durable and queryable to live, and **[Hivemind](https://github.com/activeloopai/hivemind)**, Activeloop's open-source agent-memory project, is the foundation Legion Code extended into Honeycomb's multi-tier system.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## 🔌 Supported harnesses
- Honeycomb supports 3 harnesses in production (Claude Code, Codex, Cursor). Hermes, pi, and OpenClaw are in progress.
- | Supported today | In progress |
- |---|---|
- | **Claude Code**, **Cursor**, **Codex** | **Hermes**, **pi**, **OpenClaw** |
- `honeycomb setup` detects the ones you have installed and wires each idempotently; `honeycomb uninstall` reverses only Honeycomb's changes. A skill mined while you were in Cursor is auto-pulled and ready in Claude Code on your next session.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## 🎛️ Other interfaces
- Beyond the CLI, three more ways to reach the same daemon and the same shared memory:
- - **Dashboard.** Hive portal at `http://127.0.0.1:3853`, covered [above](#%EF%B8%8F-using-the-dashboard). One front door for the whole stack; Honeycomb's data hydrates through it.
- - **MCP server.** A [Model Context Protocol](https://modelcontextprotocol.io) server (bundled to `mcp/bundle`) exposing Honeycomb's read/resolve and search/mine tools to any MCP-capable host.
- - **TypeScript SDK.** The `@legioncodeinc/honeycomb` client with framework subpath entries (`/react`, `/vercel`, `/openai`). The core entry is fetch-only and browser-safe; `react` and `ai` are optional peers.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- <h2 align="center"><a href="https://ideas.theapiary.sh">📍 Status & Roadmap</a></h2>
- Honeycomb is **production ready (v0.4.x)** and fully tested in live scenarios. We document what's real and flag what's opt-in.
- **Production today**
- - Capture-to-recall, proven end-to-end and live-tested against Deeplake (`npm run smoke:golden-path` with credentials).
- - One-command install → guided dashboard setup, the loopback daemon, the unified CLI, per-harness hooks, the MCP server, and the SDK.
- - Three-tier memory, session priming, skillify + propagation, the pollinating loop, the knowledge graph, and the codebase graph.
- - Self-hosted backends: point the CLI at your own Postgres-backed Deeplake endpoint with `honeycomb login --endpoint`, with idle connection hibernation for scale-to-zero.
- **Opt-in / by design**
- - **Embeddings are opt-in.** Recall runs the lexical BM25 path by default; turning on the local embedding runtime (≈600 MB, model fetched on first warmup) adds 768-dim semantic recall. The fallback is silent and intentional; recall never errors when embeddings are unavailable.
- - **The distillation pipeline is off by default** to avoid surprise model spend; enable it when you want background summarization and graph extraction.
- - The daemon binds **loopback only** (single machine). Cross-device and cross-user sharing happen through Deeplake's org/workspace scope, not a remote daemon bind.
- Full documentation and guides live at **[theapiary.sh](https://theapiary.sh)**; vote on what ships next at **[ideas.theapiary.sh](https://ideas.theapiary.sh)**.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## 🛠️ Development
- ```bash
- npm install # dependencies
- npm run build # tsc + esbuild → bundle/cli.js, the daemon, harness, MCP, and embed bundles
- npm run ci # the gate: typecheck + duplication (jscpd) + tests (vitest) + SQL-safety audit
- ```
- `npm run ci` is the quality gate every change must pass.
- <img src="assets/brand/divider-major.svg" width="100%" height="6">
- ## 🙏 Credits
- Honeycomb exists because two halves fit together:
- - **[Activeloop](https://activeloop.ai/)** brings **[Deeplake](https://deeplake.ai/)** (the versioned, multi-modal database for AI with native vector + columnar indexing and hybrid search) and **[Hivemind](https://github.com/activeloopai/hivemind)**, the open-source agent-memory project Honeycomb is built upon.
- - **[Legion Code Inc](https://github.com/legioncodeinc)** brings the multi-tier memory system (Tier 1 / 2 / 3 keys, summaries, raw), code base atlas memory architecture, auto healing service, session priming, automatic skill development & propagation, the pollinating loop, the knowledge graph, cross device cross repository cross team skill sharing, and the daemon architecture that turns Deeplake into a shared brain your coding agents read and write on every turn.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- ## License
- Honeycomb is licensed under the **GNU Affero General Public License v3.0 or later** ([AGPL-3.0-or-later](LICENSE)).
- Use it commercially or privately, free of charge. In return: keep the copyright and license notices intact, and if you modify it, your changes ship under the same AGPL license with source available. The "Affero" part is the point: run a modified version as a network service and you owe its source to the users who interact with it. No locking a fork behind a SaaS wall.
- © 2026 Legion Code Inc.
- <img src="assets/brand/divider-minor.svg" width="100%" height="3">
- <p align="center">
- <sub><strong>Built by <a href="https://github.com/legioncodeinc">Legion Code Inc</a></strong> · <strong>Powered by <a href="https://deeplake.ai/">Activeloop Deeplake</a></strong> · <a href="https://theapiary.sh/">theapiary.sh</a></sub>
- </p>
- <p align="center"><strong>I am Legion. We are Legion.</strong></p>
- <p align="center">#vibewithlegion</p>
src/cli/daemon-service.ts · Bundled script · 1,017 lines · 1 finding marked
- /**
- * The primary-daemon OS-native service helper, PRD-064h (AC-064h.1..6).
- *
- * ── Why this module exists (OD-1 / 064h) ─────────────────────────────────────
- * The shipped daemon lifecycle (`src/cli/runtime.ts`) brings the daemon up by a DETACHED
- * `spawn()`, which dies with the machine and is not restarted on crash. 064h makes the OS
- * service manager the LIVENESS FLOOR: it restarts the daemon on crash and starts it on boot,
- * while Doctor stays the intelligent healing layer above it. This module is the small,
- * pure, per-OS surface that registers / unregisters / starts / stops / restarts / reports the
- * daemon as a userland service:
- * - macOS → launchd LaunchAgent (`~/Library/LaunchAgents/<label>.plist`, `launchctl`)
- * - Linux → systemd `--user` unit (`~/.config/systemd/user/<unit>.service`, `systemctl --user`)
- * - Windows→ per-user Scheduled Task (no admin / no UAC, the resolved default), `schtasks`
- *
- * ── Design rules (binding) ───────────────────────────────────────────────────
- * 1. ADDITIVE + FALLBACK. This module never replaces the detached spawn; `runtime.ts` prefers
- * service mode when a manager is available and falls back to spawn where registration is
- * impossible (CI, locked-down corp machines, the existing tests). {@link detectServiceManager}
- * returns `null` on those hosts, which is the signal `runtime.ts` reads to fall back.
- * 2. CHEAP, SIDE-EFFECT-FREE DETECTION. {@link detectServiceManager} only reads `platform` + a
- * couple of env probes (it does NOT shell out, write files, or spawn work). An explicit
- * `HONEYCOMB_DAEMON_SERVICE=spawn` opt-out forces the spawn fallback everywhere.
- * 3. WRITABLE WORKSPACE PINNED INTO THE UNIT (AC-064h.4). The generated unit pins BOTH the
- * working directory and `HONEYCOMB_WORKSPACE` to the caller-resolved writable workspace, so a
- * service-started daemon never boots from `C:\WINDOWS\system32` (the documented "secrets 502"
- * class). The workspace is RESOLVED BY THE CALLER (`runtime.ts`, which owns the writable-probe)
- * and threaded in, this module never re-resolves it.
- * 4. ARGV BEHIND AN INJECTED RUNNER (test discipline). Every shell-out to `launchctl` /
- * `systemctl` / `schtasks` goes through an injected {@link ServiceRunner}, so a unit test
- * asserts the exact argv WITHOUT executing anything. The default runner (used only in
- * production) is the lazy `createRequire`-loaded `node:child_process` `execFileSync`, never a
- * shell string, always fixed-argv.
- *
- * ── Scope boundary ───────────────────────────────────────────────────────────
- * This is the PRIMARY daemon's service. Doctor's OWN service is 064b (a sibling, separate
- * unit). The two share the same approach and acceptably-duplicated templates; this module lives
- * in the MAIN package (`src/`) and does not import from `doctor/`.
- */
- import { createRequire } from "node:module";
- import { homedir } from "node:os";
- import { join, normalize, resolve, sep, win32 } from "node:path";
- import { PRODUCT_SLUG } from "../shared/constants.js";
- import { APIARY_HOME_ENV, honeycombStateDir } from "../shared/fleet-root.js";
- /** The three OS service managers this module can target (the resolved per-OS default). */
- export type ServiceManager = "launchd" | "systemd-user" | "schtasks";
- /**
- * The label / unit / task name the daemon's service is registered under (one per host family).
- * Decision #32 (2026-07-02, nectar `library/requirements/PRD-DECISIONS-AND-DEFAULTS.md`): the
- * fleet-wide scheme is reverse-DNS `com.legioncode.<shortname>` with the product short name
- * `honeycomb`, superseding the shipped `ai.honeycomb.daemon` / `HoneycombDaemon` names.
- */
- export const SERVICE_LABEL = "com.legioncode.honeycomb" as const;
- /** The systemd --user unit name (decision #32: `<shortname>.service`). */
- export const SERVICE_SYSTEMD_UNIT = "honeycomb.service" as const;
- /** The Windows Scheduled Task name (decision #32: the bare short name). */
- export const SERVICE_TASK_NAME = "honeycomb" as const;
- /** The pre-decision-#32 launchd label, deregistered on register (migration path). */
- export const LEGACY_SERVICE_LABEL = "ai.honeycomb.daemon" as const;
- /** The pre-decision-#32 systemd unit name (the old label + `.service`), deregistered on register. */
- export const LEGACY_SERVICE_SYSTEMD_UNIT = "ai.honeycomb.daemon.service" as const;
- /** The pre-decision-#32 Windows task name, deregistered on register. */
- export const LEGACY_SERVICE_TASK_NAME = "HoneycombDaemon" as const;
- /**
- * The opt-out env var that forces the detached-spawn fallback regardless of the host. Set
- * `HONEYCOMB_DAEMON_SERVICE=spawn` to disable OS-service mode (CI, locked-down machines, or a user
- * who simply prefers the old lifecycle). Any other value (or unset) keeps auto-detection.
- */
- export const SERVICE_MODE_ENV = "HONEYCOMB_DAEMON_SERVICE" as const;
- /** Fixed host for exact-identity cleanup after Task Scheduler ends its conhost wrapper. */
- export const WINDOWS_POWERSHELL_PATH = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" as const;
- /** Shared PowerShell 5-safe decoder and exact expected-command builder. */
- const WINDOWS_HONEYCOMB_IDENTITY_SETUP_SCRIPT =
- "$ErrorActionPreference='Stop'; " +
- "$entry=[IO.Path]::GetFullPath([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($entry64))); " +
- "$node=[IO.Path]::GetFullPath([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($node64))); " +
- "$flagsJson=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($flags64)); " +
- "$decodedFlags=ConvertFrom-Json -InputObject $flagsJson; " +
- "if($null -eq $decodedFlags){$flagItems=@()}elseif($decodedFlags -is [System.Array]){$flagItems=$decodedFlags}else{$flagItems=@($decodedFlags)}; " +
- "$flags=@(); foreach($flag in $flagItems){if($flag -isnot [string]){throw 'Honeycomb node flags must be strings.'}; $flags+=[string]$flag}; " +
- "$dq=[char]34; $tokenPattern={ param([string]$value) " +
- "$plain=[Regex]::Escape($value); $quoted=[Regex]::Escape(($dq+$value+$dq)); " +
- "if($value.Contains(' ')){ $fragmented=[Regex]::Escape(($value -replace ' ',($dq+' '+$dq))); return '(?:'+$quoted+'|'+$fragmented+')' }; " +
- "return '(?:'+$quoted+'|'+$plain+')' }; " +
- "$expectedParts=@($node); foreach($flag in $flags){$expectedParts+=$flag}; $expectedParts+=$entry; " +
- "$patterns=@(); foreach($part in $expectedParts){$patterns+=(& $tokenPattern ([string]$part))}; " +
- "$expectedPattern='^\\s*'+($patterns -join '\\s+')+'\\s*$'; $expected=$expectedParts -join ' '; ";
- /**
- * `schtasks /End` can leave the Node daemon alive beneath `conhost --headless`. Paths are supplied
- * as UTF-16/base64 argv values, never interpolated into this fixed script. The filter requires the
- * exact Node executable and exact Honeycomb daemon entry before terminating a process.
- */
- export const WINDOWS_HONEYCOMB_PROCESS_CLEANUP_SCRIPT =
- "& { param([string]$entry64,[string]$node64,[string]$flags64); " +
- WINDOWS_HONEYCOMB_IDENTITY_SETUP_SCRIPT +
- "$matching={ @((Get-CimInstance Win32_Process | Where-Object { " +
- "$_.Name -ieq 'node.exe' -and $_.CommandLine -and $_.ExecutablePath -and " +
- "[StringComparer]::OrdinalIgnoreCase.Equals([IO.Path]::GetFullPath($_.ExecutablePath),$node) -and " +
- "[Regex]::IsMatch($_.CommandLine,$expectedPattern,[Text.RegularExpressions.RegexOptions]::IgnoreCase) " +
- "})) }; " +
- "@(& $matching) | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction Stop }; " +
- "Start-Sleep -Milliseconds 100; " +
- "$remaining=@(& $matching); if($remaining.Count -ne 0){ throw 'Honeycomb daemon process remained after stop.' } }";
- /**
- * Non-destructive PowerShell 5 regression probe using the exact production decoder/comparator.
- * It never enumerates or stops processes: success means the supplied synthetic identity matches.
- */
- export const WINDOWS_HONEYCOMB_PROCESS_IDENTITY_PROBE_SCRIPT =
- "& { param([string]$entry64,[string]$node64,[string]$flags64,[string]$actualExe64,[string]$actualCommand64); " +
- WINDOWS_HONEYCOMB_IDENTITY_SETUP_SCRIPT +
- "$actualExe=[IO.Path]::GetFullPath([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($actualExe64))); " +
- "$actualCommand=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($actualCommand64)); " +
- "if(-not [StringComparer]::OrdinalIgnoreCase.Equals($actualExe,$node)){exit 4}; " +
- "if(-not [Regex]::IsMatch($actualCommand,$expectedPattern,[Text.RegularExpressions.RegexOptions]::IgnoreCase)){exit 5}; " +
- "Write-Output $expected }";
- function windowsCommandTokenPattern(value: string): string {
- const escaped = value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
- const quoted = `"${value}"`.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
- if (!value.includes(" ")) return `(?:${quoted}|${escaped})`;
- const fragmented = value.replaceAll(" ", '" "').replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
- return `(?:${quoted}|${fragmented})`;
- }
- export function matchesWindowsDaemonProcess(
- executablePath: string,
- commandLine: string,
- spec: ServiceSpec,
- ): boolean {
- if (!win32.isAbsolute(executablePath) || !win32.isAbsolute(spec.nodePath)) return false;
- const executableMatches = win32.normalize(executablePath).toLowerCase() === win32.normalize(spec.nodePath).toLowerCase();
- const expected = [spec.nodePath, ...spec.nodeFlags, spec.entry].map(windowsCommandTokenPattern).join("\\s+");
- return executableMatches && new RegExp(`^\\s*${expected}\\s*$`, "iu").test(commandLine);
- }
- /** Fixed PowerShell probe: success only while the task and its exact Honeycomb Node descendant run. */
- export const WINDOWS_TASK_RUNNING_SCRIPT =
- "& { param([string]$taskName,[string]$entry64,[string]$node64,[string]$flags64); " +
- WINDOWS_HONEYCOMB_IDENTITY_SETUP_SCRIPT +
- "$task=Get-ScheduledTask -TaskName $taskName -ErrorAction Stop; " +
- "if([string]$task.State -ne 'Running'){ exit 3 }; " +
- "$matching=@((Get-CimInstance Win32_Process | Where-Object { " +
- "$_.Name -ieq 'node.exe' -and $_.CommandLine -and $_.ExecutablePath -and " +
- "[StringComparer]::OrdinalIgnoreCase.Equals([IO.Path]::GetFullPath($_.ExecutablePath),$node) -and " +
- "[Regex]::IsMatch($_.CommandLine,$expectedPattern,[Text.RegularExpressions.RegexOptions]::IgnoreCase) " +
- "})); if($matching.Count -ne 1){ exit 4 } }";
- function encodedWindowsPath(value: string): string {
- return Buffer.from(value, "utf16le").toString("base64");
- }
- function cleanupWindowsDaemon(runner: ServiceRunner, spec: ServiceSpec): void {
- runner.run(WINDOWS_POWERSHELL_PATH, [
- "-NoLogo",
- "-NoProfile",
- "-NonInteractive",
- "-ExecutionPolicy",
- "Bypass",
- "-Command",
- WINDOWS_HONEYCOMB_PROCESS_CLEANUP_SCRIPT,
- encodedWindowsPath(spec.entry),
- encodedWindowsPath(spec.nodePath),
- encodedWindowsPath(JSON.stringify(spec.nodeFlags)),
- ]);
- }
- /**
- * Detect the OS service manager available on this host, or `null` when service registration is not
- * available / not wanted (→ the caller falls back to the detached spawn).
- *
- * CHEAP + SIDE-EFFECT-FREE (critical directive): reads `platform` + a couple of env vars only. It
- * does NOT shell out to probe for `launchctl`/`systemctl`/`schtasks`, write any file, or spawn any
- * work, so it is safe to call on every `start()` / `install`. The honest "is the binary actually
- * present" check is deferred to the runner (a `register` that shells out fails loudly and the caller
- * falls back); a cheap heuristic here is enough to PICK the manager.
- *
- * - `HONEYCOMB_DAEMON_SERVICE=spawn` → `null` (explicit opt-out; the spawn fallback).
- * - darwin → `launchd` (LaunchAgents are always available per-user on macOS).
- * - linux → `systemd-user` ONLY when a user systemd is plausibly present. We require a
- * positive signal (`XDG_RUNTIME_DIR` set, the conventional `systemctl --user` bus dir) rather
- * than assuming systemd, a container / CI box without a user bus returns `null` and falls back
- * to spawn, which keeps CI on the existing path.
- * - win32 → `schtasks` (the per-user Scheduled Task default; no admin needed).
- * - anything else → `null` (spawn fallback).
- */
- export function detectServiceManager(
- env: NodeJS.ProcessEnv = process.env,
- platform: NodeJS.Platform = process.platform,
- ): ServiceManager | null {
- // Explicit opt-out wins everywhere, this is how CI / locked-down hosts force the spawn path.
- if ((env[SERVICE_MODE_ENV] ?? "").trim().toLowerCase() === "spawn") return null;
- if (platform === "darwin") return "launchd";
- if (platform === "win32") return "schtasks";
- if (platform === "linux") {
- // Require a positive user-systemd signal. `XDG_RUNTIME_DIR` is set by a logind user session
- // (where `systemctl --user` works); its absence (a bare CI container) means no user bus, so we
- // fall back to spawn rather than registering a unit that can never start.
- const xdg = (env.XDG_RUNTIME_DIR ?? "").trim();
- if (xdg.length > 0) return "systemd-user";
- return null;
- }
- return null;
- }
- /**
- * Select the native manager for explicit service inspection/control. Unlike
- * {@link detectServiceManager}, this deliberately ignores spawn-mode preference and Linux user-bus
- * heuristics: explicit lifecycle and destructive removal must inspect the known platform identity
- * and fail loudly when that inspection is unavailable.
- */
- export function serviceManagerForPlatform(platform: NodeJS.Platform = process.platform): ServiceManager | null {
- if (platform === "darwin") return "launchd";
- if (platform === "win32") return "schtasks";
- if (platform === "linux") return "systemd-user";
- return null;
- }
- /**
- * The injected shell-out seam (test discipline). A `register`/`unregister`/`control` runs the
- * service manager through this; a unit test passes a recorder so the exact argv is asserted WITHOUT
- * executing. The default ({@link defaultServiceRunner}) shells out fixed-argv via `execFileSync`.
- *
- * `run` returns the captured stdout (trimmed) on success and THROWS on a non-zero exit / missing
- * binary, the caller (`runtime.ts`) treats a throw as "service path unavailable" and falls back.
- */
- export interface ServiceRunner {
- /** Run `cmd` with fixed `args`. Returns trimmed stdout. Throws on failure / missing binary. */
- run(cmd: string, args: readonly string[]): string;
- /**
- * Write a unit/plist/task file to `path` with `contents`. `encoding` defaults to `utf8`
- * (launchd/systemd); the Windows task XML is written as `utf16le` (schtasks `/XML` requires a
- * UTF-16 file with a BOM, else it fails with "unable to switch the encoding"). Throws on failure.
- */
- writeFile(path: string, contents: string, encoding?: BufferEncoding): void;
- /** Remove a unit/plist file at `path`. Never throws (a missing file is success). */
- removeFile(path: string): void;
- /** True iff `path` exists (used to report service status for file-based managers). */
- fileExists(path: string): boolean;
- }
- /**
- * The production {@link ServiceRunner}: fixed-argv `execFileSync` + `node:fs`, loaded lazily through
- * `createRequire` so this module stays import-light and the bundle's static-analysis (the OpenClaw
- * ClawHub scanner forbids bare `spawn`/`execFileSync`) never sees a top-level child_process import.
- * Never a shell string, every call is `(cmd, args[])`, so a metacharacter in a path can never be
- * re-parsed by a shell.
- */
- export function defaultServiceRunner(): ServiceRunner {
- const require = createRequire(import.meta.url);
- // Lazy, indirected requires (ClawHub-clean): resolved at call time, never a top-level import.
- const cp = require("node:child_process") as typeof import("node:child_process");
- const fs = require("node:fs") as typeof import("node:fs");
- return {
- run(cmd: string, args: readonly string[]): string {
- const out = cp.execFileSync(cmd, [...args], {
- encoding: "utf8",
- stdio: ["ignore", "pipe", "pipe"],
- timeout: 15_000,
- windowsHide: true,
- });
- return typeof out === "string" ? out.trim() : "";
- },
- writeFile(path: string, contents: string, encoding: BufferEncoding = "utf8"): void {
- fs.mkdirSync(join(path, ".."), { recursive: true });
- fs.writeFileSync(path, contents, { encoding });
- },
- removeFile(path: string): void {
- try {
- fs.rmSync(path, { force: true });
- } catch {
- // A missing unit on unregister is success, the goal (no unit) already holds.
- }
- },
- fileExists(path: string): boolean {
- try {
- return fs.existsSync(path);
- } catch {
- return false;
- }
- },
- };
- }
- /**
- * The inputs the unit/plist/XML templates are rendered from. RESOLVED BY THE CALLER (`runtime.ts`)
- * and threaded in, this module never resolves the workspace or the entry on its own.
- */
- export interface ServiceSpec {
- /** Absolute path to the Node binary the service launches (`process.execPath` in production). */
- readonly nodePath: string;
- /** Absolute path to the bundled `daemon/index.js` the service runs. */
- readonly entry: string;
- /** Extra Node flags prepended to the entry (e.g. `--experimental-sqlite`). */
- readonly nodeFlags: readonly string[];
- /**
- * The guaranteed-WRITABLE workspace pinned into the unit's working-dir AND `HONEYCOMB_WORKSPACE`
- * (AC-064h.4). Resolved by `runtime.ts` (which owns the create-write-unlink probe); never
- * `C:\WINDOWS\system32`. Both are pinned as defense-in-depth (the daemon resolves its `.secrets/`
- * root from `HONEYCOMB_WORKSPACE ?? cwd`, so either alone would suffice).
- */
- readonly workspace: string;
- /** The home dir the file-based unit paths resolve under. Defaults to `os.homedir()`. */
- readonly home?: string;
- /**
- * The RESOLVED fleet root (ADR-0003 / PRD-072d) pinned into the unit's environment as
- * `APIARY_HOME`, beside `HONEYCOMB_WORKSPACE`. The caller (`src/cli/runtime.ts`) resolves it once
- * at registration time (`resolveFleetRoot`), so a service-launched daemon resolves the SAME root
- * the installing CLI resolved, including the Windows LocalSystem opt-in (which resolves
- * `os.homedir()` to `System32\config\systemprofile` without the pin). Pin-always: the caller sets
- * it unconditionally for determinism; when absent the renderers simply omit the env line.
- */
- readonly fleetRoot?: string;
- /** Authoritative product-owned service log consumed by `honeycomb logs`. */
- readonly logPath?: string;
- }
- /**
- * Assert that a resolved unit/plist path stays CONTAINED within `home`, then return it
- * (PRD-064 Aikido SAST hardening). The `home` here is `spec.home ?? os.homedir()` - a
- * caller-supplied, variable-derived base - so the unit-path builders below thread it
- * through this validator before the path ever reaches a file syscall (`writeFileSync` /
- * `rmSync` / `existsSync` in {@link defaultServiceRunner}). The fixed sub-segments are
- * literals we control, so the ONLY way the result escapes `home` is a hostile `home`,
- * which we reject. Built-ins only (node:path). Mirrors doctor/src/safe-path.ts.
- */
- function containedUnitPath(home: string, segments: readonly string[]): string {
- const resolvedHome = normalize(resolve(home));
- const candidate = normalize(resolve(resolvedHome, ...segments));
- const homeWithSep = resolvedHome.endsWith(sep) ? resolvedHome : resolvedHome + sep;
- if (candidate !== resolvedHome && !candidate.startsWith(homeWithSep)) {
- // A throw is this module's documented "service path unavailable" signal; runtime.ts
- // falls back to the safe detached spawn rather than touching an out-of-home unit file.
- throw new Error("resolved service unit path escapes the home dir");
- }
- return candidate;
- }
- /** Resolve the launchd LaunchAgent plist path (`~/Library/LaunchAgents/<label>.plist`). */
- export function launchdPlistPath(home: string): string {
- return containedUnitPath(home, ["Library", "LaunchAgents", `${SERVICE_LABEL}.plist`]);
- }
- /** Resolve the systemd --user unit path (`~/.config/systemd/user/honeycomb.service`). */
- export function systemdUnitPath(home: string): string {
- return containedUnitPath(home, [".config", "systemd", "user", SERVICE_SYSTEMD_UNIT]);
- }
- /** The PRE-decision-#32 LaunchAgent plist path, removed on register (migration path). */
- export function legacyLaunchdPlistPath(home: string): string {
- return containedUnitPath(home, ["Library", "LaunchAgents", `${LEGACY_SERVICE_LABEL}.plist`]);
- }
- /** The PRE-decision-#32 systemd unit path, removed on register (migration path). */
- export function legacySystemdUnitPath(home: string): string {
- return containedUnitPath(home, [".config", "systemd", "user", LEGACY_SERVICE_SYSTEMD_UNIT]);
- }
- /**
- * XML-escape a value bound into XML text (a launchd plist `<string>`, or the Windows task XML's
- * `<Command>`/`<Arguments>`/`<UserId>`). Escapes all five predefined XML entities (`& < > " '`); the
- * apostrophe matters on Windows because a path such as `C:\Users\O'Brien\...` passes the cmd-safety
- * guard (`'` is not a cmd metacharacter) yet still has to be escaped once it becomes XML text.
- */
- function xmlEscape(value: string): string {
- return value
- .replace(/&/g, "&")
- .replace(/</g, "<")
- .replace(/>/g, ">")
- .replace(/"/g, """)
- .replace(/'/g, "'");
- }
- /**
- * Render the launchd LaunchAgent plist (AC-064h.4: pins `WorkingDirectory` + the `HONEYCOMB_WORKSPACE`
- * env to the writable workspace; `KeepAlive`+`RunAtLoad` make launchd the liveness floor ,
- * restart-on-crash + start-on-login).
- */
- export function renderLaunchdPlist(spec: ServiceSpec): string {
- const argv = [spec.nodePath, ...spec.nodeFlags, spec.entry];
- const argvXml = argv.map((a) => `\t\t<string>${xmlEscape(a)}</string>`).join("\n");
- return `<?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
- <plist version="1.0">
- <dict>
- <key>Label</key>
- <string>${SERVICE_LABEL}</string>
- <key>ProgramArguments</key>
- <array>
- ${argvXml}
- </array>
- <key>WorkingDirectory</key>
- <string>${xmlEscape(spec.workspace)}</string>
- <key>EnvironmentVariables</key>
- <dict>
- <key>HONEYCOMB_WORKSPACE</key>
- <string>${xmlEscape(spec.workspace)}</string>${
- spec.fleetRoot !== undefined
- ? `\n\t\t<key>${APIARY_HOME_ENV}</key>\n\t\t<string>${xmlEscape(spec.fleetRoot)}</string>`
- : ""
- }
- </dict>
- <key>RunAtLoad</key>
- <true/>
- <key>KeepAlive</key>
- <true/>
- <key>ProcessType</key>
- <string>Background</string>
- ${spec.logPath !== undefined ? `<key>StandardOutPath</key>\n\t<string>${xmlEscape(spec.logPath)}</string>\n\t<key>StandardErrorPath</key>\n\t<string>${xmlEscape(spec.logPath)}</string>` : ""}
- </dict>
- </plist>
- `;
- }
- /**
- * Render the systemd --user unit (AC-064h.4: `WorkingDirectory` + `Environment=HONEYCOMB_WORKSPACE`
- * pin the writable workspace; `Restart=always`+`RestartSec` + the `[Install] WantedBy` make systemd
- * the liveness floor, restart-on-crash + start-on-login when the unit is `enable`d).
- */
- export function renderSystemdUnit(spec: ServiceSpec): string {
- // systemd parses these fields itself (there is no shell), including `%` specifiers and `$VAR`
- // expansion in ExecStart. Reject those expansion carriers and quote/escape every variable token so
- // an env-derived workspace/fleet root/log path cannot inject a unit directive or alter argv.
- const systemdToken = (value: string): string => {
- if (/[\u0000-\u001f\u007f%$]/u.test(value)) throw new Error("unsafe character in systemd service value");
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
- };
- const execStart = [spec.nodePath, ...spec.nodeFlags, spec.entry].map(systemdToken).join(" ");
- const apiaryHomeLine =
- spec.fleetRoot !== undefined ? `\nEnvironment=${systemdToken(`${APIARY_HOME_ENV}=${spec.fleetRoot}`)}` : "";
- const logLines =
- spec.logPath !== undefined
- ? `\nStandardOutput=${systemdToken(`append:${spec.logPath}`)}\nStandardError=${systemdToken(`append:${spec.logPath}`)}`
- : "";
- return `[Unit]
- Description=Honeycomb primary daemon (127.0.0.1:3850)
- After=network.target
- [Service]
- Type=simple
- ExecStart=${execStart}
- WorkingDirectory=${systemdToken(spec.workspace)}
- Environment=${systemdToken(`HONEYCOMB_WORKSPACE=${spec.workspace}`)}${apiaryHomeLine}
- Restart=always
- RestartSec=5${logLines}
- [Install]
- WantedBy=default.target
- `;
- }
- /**
- * Reject a path bound into the Windows task command string if it carries a cmd.exe
- * metacharacter (PRD-064h security hardening). Even though the task is now registered from a staged
- * XML definition (not an inline `/TR`), the action's `<Arguments>` still embeds a `cmd /c "..."`
- * string that cmd.exe RE-PARSES at every logon. `spec.workspace` is derived from
- * `HONEYCOMB_WORKSPACE` / the CLI cwd (src/cli/runtime.ts resolveDaemonWorkspace), and `spec.entry`
- * can be overridden via `HONEYCOMB_DAEMON_ENTRY`, so a path containing `& | < > ^ " % !` (or a CR/LF)
- * would break out of the intended command and execute arbitrary commands under the user's login
- * session on every boot. We THROW on such a path; a throw is this module's documented "service path
- * unavailable" signal, so runtime.ts falls back to the safe detached spawn (which passes the
- * workspace as a real argv/env value, never a shell string) rather than registering a poisoned task.
- * Legitimate Windows paths never contain these characters. XML escaping ({@link xmlEscape}) is a
- * SECOND, independent layer applied after this guard because the values also become XML text.
- */
- function assertCmdSafe(value: string): void {
- // cmd.exe command separators / redirection / escape / env-expansion / quote, plus CR/LF.
- // `!` is a metacharacter ONLY under delayed expansion, but the scheduled-task action now runs
- // `cmd /v:on` (renderScheduledTaskXml, for the relaunch loop's `!errorlevel!` read), which makes
- // `!VAR!` expand at execution time on the SAME command line these paths are embedded in. An
- // unfiltered `!` in a poisoned HONEYCOMB_WORKSPACE / HONEYCOMB_DAEMON_ENTRY / APIARY_HOME would
- // therefore expand an arbitrary env var into the command (and, if that var's value carries a
- // separator, re-introduce a metacharacter AFTER this guard ran) — a delayed-expansion injection.
- // Reject it here; legitimate Windows paths never contain `!`.
- if (/[&|<>^"%!\r\n]/.test(value)) {
- throw new Error("unsafe character in service path; refusing to build the schtasks task command");
- }
- }
- /** The pattern a `whoami /user` SID must match before it is trusted as the task principal UserId. */
- const WINDOWS_SID_PATTERN = /^S-1-[0-9]+(-[0-9]+)+$/;
- /** The staged task-definition XML file name written under honeycomb's state dir. */
- export const STAGED_TASK_XML_NAME = "honeycomb-task.xml" as const;
- /** Resolve `<SystemRoot>\System32` (the fixed, trusted dir the whoami/conhost binaries live in). */
- function windowsSystem32Dir(env: NodeJS.ProcessEnv): string {
- const systemRoot = (env.SystemRoot ?? env.SYSTEMROOT ?? "").trim();
- // win32.join, not join: these are Windows paths by definition, and the CI quality gate
- // also runs this code on POSIX hosts where the generic join would emit forward slashes.
- return win32.join(systemRoot.length > 0 ? systemRoot : "C:\\Windows", "System32");
- }
- /** The absolute `conhost.exe` path (`--headless` runs the action with NO visible console window). */
- function conhostPath(env: NodeJS.ProcessEnv = process.env): string {
- return win32.join(windowsSystem32Dir(env), "conhost.exe");
- }
- /**
- * Parse the SID out of `whoami /user /fo csv /nh` output. The row is
- * `"DOMAIN\\user","S-1-5-21-..."`; we take the LAST comma-separated field, strip the surrounding
- * quotes, and return it only when it matches {@link WINDOWS_SID_PATTERN}. Returns `null` on any
- * shape we do not recognise (the caller then falls back to `DOMAIN\\USER`).
- */
- function parseWhoamiSid(csv: string): string | null {
- const line = csv.trim().split(/\r?\n/).pop() ?? "";
- const lastField = line.split(",").pop() ?? "";
- const candidate = lastField.trim().replace(/^"+/, "").replace(/"+$/, "").trim();
- return WINDOWS_SID_PATTERN.test(candidate) ? candidate : null;
- }
- /**
- * Resolve the current user's identity for the task's `<LogonTrigger><UserId>` AND its
- * `<Principal id="Author"><UserId>` (PRD-064h Windows Administrator-Protection fix). Windows 11 25H2
- * with Administrator Protection refuses an UNSCOPED any-user `/SC ONLOGON` trigger without
- * elevation; scoping BOTH the trigger and the principal to the current user's SID is the proven,
- * non-elevated recipe.
- *
- * Resolution:
- * 1. Fixed-argv `<SystemRoot>\System32\whoami.exe /user /fo csv /nh` through the injected runner
- * (never bare `whoami`, never a shell). A returned SID is regex-validated ⇒ it carries no XML
- * metacharacter ⇒ it is safe as raw XML text.
- * 2. Fallback to `${USERDOMAIN}\\${USERNAME}` (XML-escaped, since a `DOMAIN\\user` becomes XML
- * text and could in principle carry an escapable character).
- * 3. If neither resolves, THROW: the documented "service path unavailable" signal, so runtime.ts
- * falls back to the safe detached spawn instead of registering an unusable task.
- */
- export function resolveWindowsUserId(runner: ServiceRunner, env: NodeJS.ProcessEnv = process.env): string {
- try {
- const out = runner.run(win32.join(windowsSystem32Dir(env), "whoami.exe"), ["/user", "/fo", "csv", "/nh"]);
- const sid = parseWhoamiSid(out);
- if (sid !== null) return sid;
- } catch {
- // whoami missing / errored, fall through to the DOMAIN\USER env fallback below.
- }
- const domain = (env.USERDOMAIN ?? "").trim();
- const user = (env.USERNAME ?? "").trim();
- if (user.length > 0) return xmlEscape(domain.length > 0 ? `${domain}\\${user}` : user);
- throw new Error("cannot resolve the current Windows user SID/account for the scheduled-task principal");
- }
- /**
- * Resolve the staged task-XML path under honeycomb's state dir (`<fleetRoot>/honeycomb/`), validated
- * to stay CONTAINED within that dir (the same hardening {@link containedUnitPath} applies to the
- * launchd/systemd unit files). `spec.fleetRoot` is the caller-resolved root; when absent we fall
- * back to {@link honeycombStateDir}. A throw is the "service path unavailable" fallback signal.
- */
- export function stagedTaskXmlPath(spec: ServiceSpec): string {
- const stateDir = spec.fleetRoot !== undefined ? join(spec.fleetRoot, PRODUCT_SLUG) : honeycombStateDir();
- const resolvedBase = normalize(resolve(stateDir));
- const candidate = normalize(resolve(resolvedBase, STAGED_TASK_XML_NAME));
- const baseWithSep = resolvedBase.endsWith(sep) ? resolvedBase : resolvedBase + sep;
- if (candidate !== resolvedBase && !candidate.startsWith(baseWithSep)) {
- throw new Error("resolved staged task XML path escapes the honeycomb state dir");
- }
- return candidate;
- }
- /**
- * Render the per-user Scheduled Task definition XML (Task schema 1.2), the SID-scoped replacement for
- * the legacy inline `/TR` command (PRD-064h Windows Administrator-Protection fix). The `userId`
- * (from {@link resolveWindowsUserId}) scopes BOTH the `<LogonTrigger>` and the `<Principal>` to the
- * current user, which is what lets a non-elevated `schtasks /Create /XML` succeed on Windows 11 25H2.
- *
- * The action runs `conhost.exe --headless cmd /v:on /c "..."` so the task fires with NO visible
- * console window. The inner `cmd` does `cd /d <workspace>` + `set HONEYCOMB_WORKSPACE=<workspace>`
- * (+ optional `set APIARY_HOME=<root>`, PRD-072d) then runs `node <flags> <entry>` INSIDE A BOUNDED
- * RELAUNCH LOOP. Every embedded path passes {@link assertCmdSafe} (the value is re-parsed by cmd.exe)
- * AND is XML-escaped (the value is XML text).
- *
- * ── Why the relaunch loop (the auto-restart fix) ─────────────────────────────
- * `conhost.exe --headless` ALWAYS reports exit code 0 to Task Scheduler regardless of the child's
- * real exit code (empirically verified). So the task's `<RestartOnFailure>` — which fires ONLY on a
- * NON-ZERO Last Result — can NEVER observe a daemon crash and never restarts it: the task sits Ready
- * with Last Result 0 and the daemon stays dead. The restart therefore must live INSIDE the cmd, where
- * the real errorlevel is visible: `for /l %i in (1,1,60) do (node … & if !errorlevel! equ 0 (exit /b 0)
- * & timeout /t 5 …)` relaunches node on a NON-ZERO exit (a crash / the daemon's `uncaughtException`
- * net exiting 1) with a 5s backoff, and BREAKS on a clean exit 0 so a deliberate `daemon stop` is not
- * fought. `/v:on` enables the delayed `!errorlevel!` read. This is the conhost-independent equivalent
- * of systemd `Restart=on-failure` / launchd `KeepAlive`. `StartWhenAvailable`, `ExecutionTimeLimit
- * PT0S`, and the task's own `RestartOnFailure` (PT1M x 999) remain as the liveness floor / belt-and-
- * suspenders for the rare case the conhost host process itself dies non-zero.
- */
- export function renderScheduledTaskXml(spec: ServiceSpec, userId: string, conhost: string = conhostPath()): string {
- // SECURITY: the `<Arguments>` embeds a cmd.exe-parsed string, so refuse any path with a cmd
- // metacharacter before it is embedded (a poisoned HONEYCOMB_WORKSPACE / cwd / HONEYCOMB_DAEMON_ENTRY
- // / APIARY_HOME must never inject a command). A throw makes runtime.ts fall back to the safe spawn.
- assertCmdSafe(spec.workspace);
- assertCmdSafe(spec.nodePath);
- assertCmdSafe(spec.entry);
- if (spec.fleetRoot !== undefined) assertCmdSafe(spec.fleetRoot);
- if (spec.logPath !== undefined) assertCmdSafe(spec.logPath);
- const nodeFlags = spec.nodeFlags.length > 0 ? `${spec.nodeFlags.join(" ")} ` : "";
- // cmd's `set VAR=value && next` captures EVERYTHING up to `&&`, INCLUDING the space before it, into
- // VAR — so an unquoted `set APIARY_HOME=<root> && ...` pins a TRAILING SPACE onto the value, and the
- // daemon then resolves a divergent `<root> /honeycomb` state dir that doctor's registry can never
- // find (fleet telemetry reads as "missing" ⇒ the dashboard shows honeycomb degraded forever). The
- // fix is the canonical cmd idiom: quote the whole `VAR=value` assignment so the space before `&&`
- // stays OUTSIDE the value. `set "VAR=C:\...\path with spaces"` also preserves spaces WITHIN a path.
- const apiaryHomeSet = spec.fleetRoot !== undefined ? `set "${APIARY_HOME_ENV}=${spec.fleetRoot}" && ` : "";
- // The inner command: cd + env pin + node entry, WRAPPED IN A CONHOST-INDEPENDENT RELAUNCH LOOP.
- //
- // WHY THE LOOP (the auto-restart fix) — the task's Action is `conhost.exe --headless cmd /c ...`,
- // and `conhost --headless` ALWAYS reports exit code 0 to Task Scheduler regardless of the child's
- // real code (empirically verified: `exit 7` under conhost --headless → Last Result 0). So the
- // task's `<RestartOnFailure>` — which fires ONLY on a NON-ZERO Last Result — can NEVER see a crash
- // and never restarts the daemon. The fix must live INSIDE the cmd (where the real errorlevel is
- // visible), independent of the code conhost forwards.
- //
- // The loop re-launches node whenever it exits with a NON-ZERO errorlevel (a crash / the daemon's
- // `uncaughtException` net exiting 1), after a short backoff, up to a bounded count. A CLEAN exit
- // (errorlevel 0 — `honeycomb daemon stop`, a graceful SIGTERM) breaks the loop so a deliberate stop
- // is NOT fought. The daemon's own single-instance lock + stale-lock reclaim make a relaunch safe.
- // `delims=` + delayed expansion (`cmd /v:on`) read `!errorlevel!` inside the loop body. This mirrors
- // the OS supervisor contract (systemd `Restart=on-failure`, launchd `KeepAlive`) that conhost breaks
- // on Windows. The bound (60) with PT1M framing caps a hard boot-loop; the task's own PT1M x999 stays
- // as a belt-and-suspenders for the (rare) case the whole conhost host itself dies non-zero.
- // These are intentional cmd operators, not user-derived text. Do NOT caret-escape them: `^>`
- // turns redirection into a literal argv token, causing Node to receive `>> <log> 2>&1` and leaving
- // the service log unwritten. The surrounding task XML escapes `>`/`&` as markup after this command
- // is assembled, while assertCmdSafe above keeps the interpolated log path non-executable.
- const redirect = spec.logPath !== undefined ? ` >> "${spec.logPath}" 2>&1` : "";
- const nodeInvoke = `"${spec.nodePath}" ${nodeFlags}"${spec.entry}"${redirect}`;
- // NOTE `%i` (single, not `%%i`): the loop runs on the cmd COMMAND LINE (conhost passes a command
- // string, not a `.bat` file), where `for` uses a single `%`. `%%i` is a batch-file-only escaping and
- // errors ("%%i was unexpected at this time") on the command line. The counter var is unreferenced —
- // `%i` is only the loop's iteration variable; the body relaunches node until a clean (0) exit.
- const relaunchLoop =
- `for /l %i in (1,1,60) do (` +
- `${nodeInvoke} & ` +
- `if !errorlevel! equ 0 (exit /b 0) & ` +
- `timeout /t 5 /nobreak >nul` +
- `)`;
- const innerCmd = `cmd /v:on /c "cd /d "${spec.workspace}" && set "HONEYCOMB_WORKSPACE=${spec.workspace}" && ${apiaryHomeSet}${relaunchLoop}"`;
- // conhost --headless <inner> => no console window pops when the task runs (proven probe: Result 0).
- const args = xmlEscape(`--headless ${innerCmd}`);
- const command = xmlEscape(conhost);
- // UTF-16 declaration: the file is staged as utf16le + BOM (schtasks /XML requirement, see the
- // register path); the declaration must agree with the on-disk encoding or schtasks rejects it.
- return `<?xml version="1.0" encoding="UTF-16"?>
- <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
- <RegistrationInfo>
- <Description>Honeycomb primary daemon (127.0.0.1:3850)</Description>
- <URI>\\${SERVICE_TASK_NAME}</URI>
- </RegistrationInfo>
- <Triggers>
- <LogonTrigger>
- <Enabled>true</Enabled>
- <UserId>${userId}</UserId>
- </LogonTrigger>
- </Triggers>
- <Principals>
- <Principal id="Author">
- <UserId>${userId}</UserId>
- <LogonType>InteractiveToken</LogonType>
- <RunLevel>LeastPrivilege</RunLevel>
- </Principal>
- </Principals>
- <Settings>
- <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
- <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
- <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
- <AllowHardTerminate>true</AllowHardTerminate>
- <StartWhenAvailable>true</StartWhenAvailable>
- <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
- <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
- <Enabled>true</Enabled>
- <Hidden>false</Hidden>
- Note: Usual in code (tag names in paths and patterns): Contains a <hidden> block, a common wrapper for instructions hidden in a tool description
- Line 677 on GitHub
- <RestartOnFailure>
- <Interval>PT1M</Interval>
- <Count>999</Count>
- </RestartOnFailure>
- </Settings>
- <Actions Context="Author">
- <Exec>
- <Command>${command}</Command>
- <Arguments>${args}</Arguments>
- </Exec>
- </Actions>
- </Task>
- `;
- }
- /**
- * Build the `schtasks /Create` argv that registers the task from the STAGED XML definition
- * (`schtasks /Create /XML <file> /TN <name> /F`). This is the non-elevated recipe proven on Windows
- * 11 25H2 with Administrator Protection: the SID-scoped XML (see {@link renderScheduledTaskXml})
- * replaces the inline `/SC ONLOGON /TR ...` form that Windows now refuses without elevation. `/F` is
- * idempotent (overwrites an existing task). Returned as ARGV (not a string) so the injected runner
- * shells out fixed-argv and a test asserts the exact tokens.
- */
- export function buildSchtasksCreateArgs(xmlPath: string): readonly string[] {
- return ["/Create", "/XML", xmlPath, "/TN", SERVICE_TASK_NAME, "/F"];
- }
- /** The outcome of a service operation, what happened, for the CLI to report honestly. */
- export interface ServiceOpResult {
- /** True when the operation completed via the service manager. */
- readonly ok: boolean;
- /** The manager that handled it (for logging / status). */
- readonly manager: ServiceManager;
- }
- /** The daemon-service controller the lifecycle drives (register / start / stop / restart / status). */
- export interface DaemonServiceController {
- readonly manager: ServiceManager;
- /** Register the service unit + load/enable it so the manager supervises it (idempotent). */
- register(spec: ServiceSpec): ServiceOpResult;
- /** Deregister the service. Throws when required process termination cannot be verified. */
- unregister(spec: ServiceSpec): ServiceOpResult;
- /**
- * Best-effort removal of the PRE-decision-#32 LEGACY unit/label for this manager (PRD-003b
- * uninstall). The `register` path already deregisters the legacy unit on migration; `uninstall`
- * reuses THAT same cleanup so a full removal also strips a lingering legacy unit. Idempotent and
- * never throws (a missing legacy unit is success). Optional on the seam (additive); callers guard
- * with `?.`.
- */
- unregisterLegacy?(spec: ServiceSpec): void;
- /** Ask the manager to (re)start the daemon, the rung-1 path Doctor calls (AC-064h.5). */
- restart(spec: ServiceSpec): ServiceOpResult;
- /** Ask the manager to stop the daemon. */
- stop(spec: ServiceSpec): ServiceOpResult;
- /** True iff the service is currently REGISTERED with the manager (unit present / task exists). */
- isRegistered(spec: ServiceSpec): boolean;
- /** True iff the manager reports the registered service instance is actively running. */
- isRunning?(spec: ServiceSpec): boolean;
- }
- /** Resolve the home dir for a spec (explicit `home` wins; else `os.homedir()`). */
- function specHome(spec: ServiceSpec): string {
- return spec.home ?? homedir();
- }
- /**
- * Build the per-OS {@link DaemonServiceController} over an injected {@link ServiceRunner}. The
- * controller owns the per-manager argv + file paths; the runner owns the actual shell-out / file IO.
- * Every `run` is fixed-argv; a throw from the runner propagates so the caller falls back to spawn.
- */
- export function createDaemonServiceController(
- manager: ServiceManager,
- runner: ServiceRunner = defaultServiceRunner(),
- ): DaemonServiceController {
- if (manager === "launchd") return launchdController(runner);
- if (manager === "systemd-user") return systemdController(runner);
- return schtasksController(runner);
- }
- /** launchd LaunchAgent controller (`launchctl bootstrap`/`bootout`/`kickstart`). */
- function launchdController(runner: ServiceRunner): DaemonServiceController {
- /** The per-user GUI domain target `launchctl` v2 verbs address (`gui/<uid>`). */
- function domain(): string {
- return `gui/${process.getuid?.() ?? 501}`;
- }
- /**
- * Best-effort boot out + remove the legacy `ai.honeycomb.daemon` agent (decision #32 migration on
- * register; PRD-003b legacy cleanup on uninstall). Never throws — a missing legacy agent is success.
- */
- function cleanupLegacy(spec: ServiceSpec): void {
- try {
- runner.run("launchctl", ["bootout", `${domain()}/${LEGACY_SERVICE_LABEL}`]);
- } catch {
- // No legacy agent loaded, fine.
- }
- try {
- runner.removeFile(legacyLaunchdPlistPath(specHome(spec)));
- } catch {
- // Best-effort cleanup only.
- }
- }
- return {
- manager: "launchd",
- register(spec): ServiceOpResult {
- // Decision #32 migration: strip a lingering legacy agent so a re-run never leaves two agents
- // racing over one daemon.
- cleanupLegacy(spec);
- const path = launchdPlistPath(specHome(spec));
- runner.writeFile(path, renderLaunchdPlist(spec));
- // bootstrap loads + (RunAtLoad) starts the agent; the `||` re-bootstrap is handled by callers.
- runner.run("launchctl", ["bootstrap", domain(), path]);
- return { ok: true, manager: "launchd" };
- },
- unregister(spec): ServiceOpResult {
- const path = launchdPlistPath(specHome(spec));
- try {
- runner.run("launchctl", ["bootout", `${domain()}/${SERVICE_LABEL}`]);
- } catch {
- // Not loaded is fine, we still remove the unit file below.
- }
- runner.removeFile(path);
- return { ok: true, manager: "launchd" };
- },
- unregisterLegacy(spec): void {
- cleanupLegacy(spec);
- },
- restart(_spec): ServiceOpResult {
- // kickstart -k kills + restarts the service THROUGH launchd (AC-064h.5: no second spawn).
- runner.run("launchctl", ["kickstart", "-k", `${domain()}/${SERVICE_LABEL}`]);
- return { ok: true, manager: "launchd" };
- },
- stop(_spec): ServiceOpResult {
- // `kill SIGTERM` only terminates the child; KeepAlive=true immediately respawns it.
- // `bootout` unloads the LaunchAgent instance, so `honeycomb daemon stop` actually stops.
- runner.run("launchctl", ["bootout", `${domain()}/${SERVICE_LABEL}`]);
- return { ok: true, manager: "launchd" };
- },
- isRegistered(spec): boolean {
- return runner.fileExists(launchdPlistPath(specHome(spec)));
- },
- isRunning(): boolean {
- try {
- return /\bstate = running\b/u.test(runner.run("launchctl", ["print", `${domain()}/${SERVICE_LABEL}`]));
- } catch {
- return false;
- }
- },
- };
- }
- /** systemd --user controller (`systemctl --user enable --now`/`disable`/`restart`). */
- function systemdController(runner: ServiceRunner): DaemonServiceController {
- const unit = SERVICE_SYSTEMD_UNIT;
- /**
- * Best-effort disable + remove the legacy `ai.honeycomb.daemon.service` unit (decision #32
- * migration on register; PRD-003b legacy cleanup on uninstall). Never throws when absent.
- */
- function cleanupLegacy(spec: ServiceSpec): void {
- try {
- runner.run("systemctl", ["--user", "disable", "--now", LEGACY_SERVICE_SYSTEMD_UNIT]);
- } catch {
- // No legacy unit enabled, fine.
- }
- try {
- runner.removeFile(legacySystemdUnitPath(specHome(spec)));
- } catch {
- // Best-effort cleanup only.
- }
- }
- return {
- manager: "systemd-user",
- register(spec): ServiceOpResult {
- // Decision #32 migration: strip a lingering legacy unit so a re-run never leaves two units
- // racing over one daemon.
- cleanupLegacy(spec);
- const path = systemdUnitPath(specHome(spec));
- runner.writeFile(path, renderSystemdUnit(spec));
- runner.run("systemctl", ["--user", "daemon-reload"]);
- // enable --now installs the boot symlink (start-on-login) AND starts it now.
- runner.run("systemctl", ["--user", "enable", "--now", unit]);
- return { ok: true, manager: "systemd-user" };
- },
- unregister(spec): ServiceOpResult {
- try {
- runner.run("systemctl", ["--user", "disable", "--now", unit]);
- } catch {
- // Not enabled is fine, we still remove the unit file + reload below.
- }
- runner.removeFile(systemdUnitPath(specHome(spec)));
- try {
- runner.run("systemctl", ["--user", "daemon-reload"]);
- } catch {
- // A reload failure on teardown is non-fatal; the unit file is already gone.
- }
- return { ok: true, manager: "systemd-user" };
- },
- unregisterLegacy(spec): void {
- cleanupLegacy(spec);
- },
- restart(_spec): ServiceOpResult {
- // restart goes THROUGH systemd (AC-064h.5: no second spawn, no double-bind).
- runner.run("systemctl", ["--user", "restart", unit]);
- return { ok: true, manager: "systemd-user" };
- },
- stop(_spec): ServiceOpResult {
- runner.run("systemctl", ["--user", "stop", unit]);
- return { ok: true, manager: "systemd-user" };
- },
- isRegistered(spec): boolean {
- return runner.fileExists(systemdUnitPath(specHome(spec)));
- },
- isRunning(): boolean {
- try {
- runner.run("systemctl", ["--user", "is-active", "--quiet", unit]);
- return true;
- } catch {
- return false;
- }
- },
- };
- }
- /** Windows per-user Scheduled Task controller (`schtasks /Create`/`/Delete`/`/Run`/`/End`/`/Query`). */
- function schtasksController(runner: ServiceRunner): DaemonServiceController {
- /**
- * Best-effort end + delete the legacy `HoneycombDaemon` task (decision #32 migration on register;
- * PRD-003b legacy cleanup on uninstall). Never throws when the legacy task is absent.
- */
- function cleanupLegacy(): void {
- try {
- runner.run("schtasks", ["/End", "/TN", LEGACY_SERVICE_TASK_NAME]);
- } catch {
- // No legacy task running, fine.
- }
- try {
- runner.run("schtasks", ["/Delete", "/TN", LEGACY_SERVICE_TASK_NAME, "/F"]);
- } catch {
- // No legacy task registered, fine.
- }
- }
- return {
- manager: "schtasks",
- register(spec): ServiceOpResult {
- // Decision #32 migration: strip a lingering legacy task so a re-run never leaves two tasks
- // racing over one daemon.
- cleanupLegacy();
- try {
- runner.run("schtasks", ["/End", "/TN", SERVICE_TASK_NAME]);
- } catch {
- // Already stopped or absent; exact descendant cleanup below still runs.
- }
- cleanupWindowsDaemon(runner, spec);
- // Administrator-Protection fix: scope the task to the current user (SID) and register it from
- // a STAGED XML definition. `resolveWindowsUserId` throws when it cannot resolve an identity,
- // which propagates as the "service path unavailable" signal (runtime.ts falls back to spawn).
- const userId = resolveWindowsUserId(runner);
- const xmlPath = stagedTaskXmlPath(spec);
- // schtasks /XML wants a UTF-16 file with a BOM; prepend U+FEFF and write utf16le.
- runner.writeFile(xmlPath, `\ufeff${renderScheduledTaskXml(spec, userId)}`, "utf16le");
- // /Create /XML <file> /F is idempotent (overwrites); the XML's LogonTrigger is the boot floor.
- runner.run("schtasks", buildSchtasksCreateArgs(xmlPath));
- // Start it immediately so register == running (the install path expects an up daemon).
- runner.run("schtasks", ["/Run", "/TN", SERVICE_TASK_NAME]);
- return { ok: true, manager: "schtasks" };
- },
- unregister(spec): ServiceOpResult {
- try {
- runner.run("schtasks", ["/End", "/TN", SERVICE_TASK_NAME]);
- } catch {
- // Not running is fine, we still delete the task below.
- }
- cleanupWindowsDaemon(runner, spec);
- try {
- runner.run("schtasks", ["/Delete", "/TN", SERVICE_TASK_NAME, "/F"]);
- } catch {
- // A missing task on delete is success, the goal (no task) already holds.
- }
- try {
- // Best-effort: drop the staged XML definition (a missing file is success).
- runner.removeFile(stagedTaskXmlPath(spec));
- } catch {
- // A containment throw / removal failure never aborts unregister.
- }
- return { ok: true, manager: "schtasks" };
- },
- unregisterLegacy(): void {
- cleanupLegacy();
- },
- restart(spec): ServiceOpResult {
- // AC-064h.5: stop THEN start the SAME task, no second daemon spawn. The single-instance
- // PID/lock guard in the daemon prevents a double-bind even if the old process lingers a beat.
- try {
- runner.run("schtasks", ["/End", "/TN", SERVICE_TASK_NAME]);
- } catch {
- // Already stopped is fine; proceed to /Run.
- }
- cleanupWindowsDaemon(runner, spec);
- runner.run("schtasks", ["/Run", "/TN", SERVICE_TASK_NAME]);
- return { ok: true, manager: "schtasks" };
- },
- stop(spec): ServiceOpResult {
- try {
- runner.run("schtasks", ["/End", "/TN", SERVICE_TASK_NAME]);
- } catch {
- // A task already in Ready state can still have an orphaned Node descendant.
- }
- cleanupWindowsDaemon(runner, spec);
- return { ok: true, manager: "schtasks" };
- },
- isRegistered(_spec): boolean {
- // A registered task answers `/Query` with exit 0; a missing one throws (non-zero) → false.
- try {
- runner.run("schtasks", ["/Query", "/TN", SERVICE_TASK_NAME]);
- return true;
- } catch {
- return false;
- }
- },
- isRunning(spec): boolean {
- try {
- runner.run(WINDOWS_POWERSHELL_PATH, [
- "-NoLogo",
- "-NoProfile",
- "-NonInteractive",
- "-ExecutionPolicy",
- "Bypass",
- "-Command",
- WINDOWS_TASK_RUNNING_SCRIPT,
- SERVICE_TASK_NAME,
- encodedWindowsPath(spec.entry),
- encodedWindowsPath(spec.nodePath),
- encodedWindowsPath(JSON.stringify(spec.nodeFlags)),
- ]);
- return true;
- } catch {
- return false;
- }
- },
- };
- }
src/commands/install.ts · Bundled script · 617 lines · 2 findings marked
- /**
- * `honeycomb install [--ref <code>]` — the bootstrap installer's daemon-up + open-dashboard
- * verb (PRD-050a, a-AC-1..6).
- *
- * ── Why this verb exists (the "open logic lives once" contract, 050a impl-note) ──────────────
- * The two shell entrypoints (`scripts/install/install.sh`, `scripts/install/install.ps1`) own
- * ONLY the host-bootstrap half: detect/install Node+npm (via fnm + a pinned LTS), pull the
- * embedding deps, and `npm i -g @legioncodeinc/honeycomb`. The moment a `honeycomb` bin exists,
- * they hand off to THIS verb for everything between "package installed" and "browser open on the
- * dashboard." That keeps the daemon-ensure + health-gate + dashboard-open logic in ONE place
- * (TypeScript, unit-tested) instead of duplicated across two shell dialects.
- *
- * ── What it does (composes existing seams — D-2 thin client, never a daemon-core import) ─────
- * 1. Ensure the daemon is running, HEALTH-GATED (a-AC-4): reuse {@link ensureDaemonRunning}
- * (021b b-AC-3), which is IDEMPOTENT via the 021a PID/lock guard — an already-healthy daemon
- * is a no-op, never a second bind of 3850 (a-AC-2). If the daemon never becomes reachable
- * within the lifecycle's wait budget, report "daemon didn't start" + how to retry and exit
- * NON-ZERO (a-AC-4) — no raw stack.
- * 2. Persist onboarding `phase: "installed"` + the effective `ref` through the SHARED onboarding
- * module (a-AC-5). The ref is `--ref <code>` when given, else the build-time {@link DEFAULT_REF}
- * (`__HONEYCOMB_REF_DEFAULT__`, default "mario"). 050c's login reads this ref; this verb only
- * PERSISTS it (the device-flow/referral header is 050c's job, not here). The write is fail-soft
- * — an onboarding-write hiccup never fails the install, it only logs a warning.
- * 3. Open the dashboard honestly (a-AC-6) — SOLO mode ONLY. When Hive is present (FLEET mode),
- * the dashboard IS the Hive portal and Hive's own onboarding owns it, so this verb opens
- * NOTHING and prints one plain line saying so (it must never race a second, competing browser
- * window against the tab Hive already opened). In SOLO mode it probes the loopback portal URL
- * (`http://127.0.0.1:3853/`); if reachable it opens the loopback URL (`http://127.0.0.1:3853/`),
- * and if not reachable it opens no browser and prints one plain sentence naming the one command
- * to install Hive. The friendly `honeycomb.local` host was dropped: it does not resolve on a
- * normal machine, so showing it only confused users — the always-correct loopback URL is used.
- *
- * ── Idempotency (a-AC-2) ─────────────────────────────────────────────────────────────────────
- * Re-running is safe: ensure-running short-circuits on an already-healthy daemon (no start, no
- * double-bind), the onboarding write is a stable upsert (phase stays "installed"), and the
- * dashboard is simply re-opened.
- *
- * ── Plain-language errors (parent AC-7) ──────────────────────────────────────────────────────
- * Every handled failure is a single readable line on the OUT sink + a non-zero exit. This module
- * never throws an uncaught error to the bin: the only failure path (daemon-didn't-start) is a
- * clean `{ exitCode: 1 }` with a retry hint.
- */
- import { execFileSync } from "node:child_process";
- import { isAbsolute, resolve } from "node:path";
- import type { Credentials } from "../daemon/runtime/auth/contracts.js";
- import { loadCredentials } from "../daemon/runtime/auth/credentials-store.js";
- import { defaultBrowserOpener, loginWithDeviceFlow } from "../daemon/runtime/auth/deeplake-issuer.js";
- import { resolveRuntimeConfig } from "../daemon/runtime/config.js";
- import {
- DEFAULT_REF,
- loadOnboarding,
- type OnboardingState,
- saveOnboarding,
- } from "../daemon/runtime/onboarding/index.js";
- import { type RegistryBind, registerHoneycombWithDoctor } from "../daemon/runtime/telemetry/fleet-registry.js";
- import { type EmitDeps, emitTelemetry, recordVersionAndEmitUpdated } from "../daemon/runtime/telemetry/index.js";
- import { DAEMON_HOST, DAEMON_PORT, HIVE_HOST, HIVE_PORT } from "../shared/constants.js";
- import { classifyFleet, type FleetClassification, fleetSignalLine } from "../shared/fleet-detection.js";
- import type { CommandResult, OutputSink } from "./contracts.js";
- import { type DaemonVerbDeps, ensureDaemonRunning } from "./daemon.js";
- import type { ConnectorRunner } from "./local-handlers.js";
- /** The portal route hive serves the dashboard SPA at (ADR-0001). */
- export const DASHBOARD_PATH = "/" as const;
- /**
- * The always-correct loopback portal URL (`http://127.0.0.1:3853/`) — the ONLY dashboard URL the
- * SOLO install ever opens. The former friendly `honeycomb.local` host was dropped because it does
- * not resolve on a normal machine (no hosts/mDNS entry ships), so surfacing it only stranded users
- * on a non-resolving address. The daemon binds loopback only; the portal is Hive's, also on loopback.
- */
- export function loopbackDashboardUrl(): string {
- return `http://${HIVE_HOST}:${HIVE_PORT}${DASHBOARD_PATH}`;
- }
- /** The short timeout budget for the local portal reachability probe. */
- const DASHBOARD_PROBE_TIMEOUT_MS = 750;
- /**
- * One plain sentence for the "portal not installed/running" branch (C-6 claim-honesty fix),
- * branched by platform so the named command is actually runnable on the user's shell. The two
- * one-liners are the CANONICAL forms the bootstrap installers document: the POSIX pipe from
- * `scripts/install/install.sh`, and the PowerShell flag-passing invocation from the
- * `scripts/install/install.ps1` header (a bare `irm | iex` pipe cannot see flags, so the
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 85 on GitHub
- * documented `& { ... } --products=` form is the one that works).
- */
- export function dashboardPortalNotRunningMessage(platform: NodeJS.Platform = process.platform): string {
- const command =
- platform === "win32"
- ? 'powershell -c "& { $(irm https://get.theapiary.sh/install.ps1) } --products=honeycomb,doctor,hive"'
- : "curl -fsSL https://get.theapiary.sh | sh -s -- --products=honeycomb,doctor,hive";
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 92 on GitHub
- return `Dashboard portal is not running; install it with ${command}.`;
- }
- /** The C-6 fallback sentence for THIS platform (what `runInstallCommand` actually prints). */
- export const DASHBOARD_PORTAL_NOT_RUNNING_MESSAGE = dashboardPortalNotRunningMessage();
- /**
- * The browser-opener seam (a-AC-6). Returns `true` iff it launched the URL. The production default
- * is {@link openLocalDashboardUrl}; a test injects a recorder so no real browser launches and the
- * loopback URL it opens is asserted by the URLs it was handed.
- */
- export type DashboardOpener = (url: string) => boolean;
- /** The local portal reachability probe seam used before opening a browser tab (C-6). */
- export type DashboardProbe = () => Promise<boolean>;
- /**
- * Open a LOCAL dashboard URL in the OS browser via a fixed-argv `execFileSync` (never a shell) —
- * the SAME safe-open discipline as `defaultBrowserOpener` in `deeplake-issuer.ts`, but admitting an
- * `http:` LOOPBACK URL (the auth opener is https-only because it opens a server-derived OAuth URL;
- * the dashboard URL is a fixed local loopback we construct ourselves, so `http:` is correct and
- * safe here).
- *
- * The guard still REFUSES anything that is not a parsed `http:`/`https:` URL whose host is the
- * loopback IP or `localhost` — so a malformed or non-local URL never reaches an OS opener. On open it
- * uses `open` (darwin) / `rundll32 url.dll,FileProtocolHandler` (win32, which avoids `cmd /c start`
- * re-parsing metacharacters) / `xdg-open` (linux), each fixed-argv. Returns `false` (never throws) on
- * a refused URL or a failed launch, so the caller treats a missing browser as non-fatal and prints
- * the URL instead.
- */
- export function openLocalDashboardUrl(url: string): boolean {
- let safeUrl: string;
- try {
- const parsed = new URL(url);
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
- const host = parsed.hostname;
- const isLocal = host === DAEMON_HOST || host === "localhost" || host === "::1";
- if (!isLocal) return false;
- safeUrl = parsed.href;
- } catch {
- return false;
- }
- try {
- if (process.platform === "darwin") {
- execFileSync("open", [safeUrl], { stdio: "ignore", timeout: 5000, windowsHide: true });
- } else if (process.platform === "win32") {
- execFileSync("rundll32", ["url.dll,FileProtocolHandler", safeUrl], {
- stdio: "ignore",
- timeout: 5000,
- windowsHide: true,
- });
- } else {
- execFileSync("xdg-open", [safeUrl], { stdio: "ignore", timeout: 5000, windowsHide: true });
- }
- return true;
- } catch {
- return false;
- }
- }
- /** The deps the `install` verb runs against — the daemon HTTP+lifecycle seams plus injectable IO. */
- export interface InstallVerbDeps extends DaemonVerbDeps {
- /** The browser opener (a-AC-6). Defaults to {@link openLocalDashboardUrl}; tests inject a recorder. */
- readonly openDashboard?: DashboardOpener;
- /** The loopback portal probe used before any browser open (C-6). */
- readonly probeDashboard?: DashboardProbe;
- /**
- * Override the onboarding-state directory (tests point this at a temp HOME so the real
- * `~/.deeplake/onboarding.json` is never touched). Defaults to the real shared dir.
- */
- readonly dir?: string;
- /** Required onboarding commit seam; production uses the shared onboarding store. */
- readonly persistInstalled?: (ref: string, dir: string | undefined, out: OutputSink) => boolean;
- /** Required Doctor-registration commit seam; production writes Honeycomb's registry entry. */
- readonly registerWithDoctor?: (dir: string | undefined, out: OutputSink) => boolean;
- /**
- * Telemetry chokepoint seam (PRD-050e). The `honeycomb_installed` event emits through here AFTER
- * the user-facing success, fire-and-forget — its injected `fetch`/`dir` let a test assert zero or
- * one network call without touching the real PostHog. The onboarding `dir` is threaded in
- * automatically; a test may inject `telemetry.fetch` to record/throw. Omit it entirely in production
- * — `emitTelemetry`'s defaults apply (and an empty build key makes it a no-op).
- */
- readonly telemetry?: EmitDeps;
- /**
- * PRD-003a: the solo-vs-fleet classifier (a-AC-6). Defaults to the real {@link classifyFleet}
- * (registry read + 127.0.0.1:3853 probe + npm global read). A test injects a fixed result so the
- * fleet-defer vs solo-auto-login branch is driven without touching the network or the npm tree.
- */
- readonly detectFleet?: () => Promise<FleetClassification>;
- /**
- * PRD-003a: read the shared `~/.deeplake/credentials.json` (a-AC-3: only auto-login when it is
- * ABSENT). Defaults to the real {@link loadCredentials}; a test injects a fake so no real
- * credential file is read.
- */
- readonly loadInstallCredentials?: () => Credentials | null;
- /**
- * PRD-003a: run the device-flow login on the SOLO auto-login path (a-AC-3 / a-AC-7). Defaults to
- * {@link defaultInstallDeviceLogin} (the same `loginWithDeviceFlow` `honeycomb login` runs, with
- * the validated browser opener; headless degrades to printing the URL + code and polling). A test
- * injects a recorder so no real browser launches and no real device flow runs.
- */
- readonly runDeviceLogin?: (out: OutputSink) => Promise<boolean>;
- /**
- * The connector engine `honeycomb setup` uses (the 019a `connectorMain` behind the
- * {@link ConnectorRunner} seam). At the END of a successful install this is run BEST-EFFORT to wire
- * the harness hooks so the one-line installer no longer leaves them unwired until a manual
- * `honeycomb setup` (the observed D5-FAIL-until-manual-run gap). Fires in BOTH solo and fleet modes.
- * FAIL-SOFT: a setup failure prints one actionable line and NEVER fails the install. Production binds
- * the real runner (`src/cli/connector-runner.ts`); a test injects a fake. When absent (older
- * install-only tests) the step is a silent no-op.
- */
- readonly connector?: ConnectorRunner;
- }
- /** Parse the effective referral code off the argv tail (`--ref <code>`), else `undefined`. */
- export function parseRefArg(argv: readonly string[]): string | undefined {
- const i = argv.indexOf("--ref");
- if (i !== -1) {
- const next = argv[i + 1];
- if (next !== undefined && !next.startsWith("--") && next.length > 0) return next;
- }
- // Also accept `--ref=<code>` for parity with common CLI conventions.
- const eq = argv.find((a) => a.startsWith("--ref="));
- if (eq !== undefined) {
- const value = eq.slice("--ref=".length);
- if (value.length > 0) return value;
- }
- return undefined;
- }
- /**
- * Resolve the effective ref: the `--ref` override when present, else the build-time
- * {@link DEFAULT_REF} (`__HONEYCOMB_REF_DEFAULT__`, default "mario"). 050c's login reads this.
- */
- export function resolveEffectiveRef(argv: readonly string[]): string {
- return parseRefArg(argv) ?? DEFAULT_REF;
- }
- /**
- * Parse the installer's `--home <path>` / `--home=<path>` pin (PRD-072d / ADR-0003), the chosen
- * fleet-root location. Returns the value, else `undefined` when the flag is absent/empty.
- */
- export function parseHomeArg(argv: readonly string[]): string | undefined {
- const i = argv.indexOf("--home");
- if (i !== -1) {
- const next = argv[i + 1];
- if (next !== undefined && !next.startsWith("--") && next.length > 0) return next;
- }
- const eq = argv.find((a) => a.startsWith("--home="));
- if (eq !== undefined) {
- const value = eq.slice("--home=".length);
- if (value.length > 0) return value;
- }
- return undefined;
- }
- /**
- * Record the installer's `--home=` choice by delivering it as `APIARY_HOME` in the process
- * environment (fleet ADR Resolved decision: the `--home=` pin is delivered as `APIARY_HOME`; there is
- * NO config.json recording step). Setting it here means every downstream fleet-root resolution in
- * THIS install run agrees: the doctor registry entry advertises the overridden root, the service
- * registration pins `APIARY_HOME` into the unit (PRD-072d), and the spawned daemon inherits it.
- * A subsequent re-register with a changed root re-pins the unit. On the Windows LocalSystem enterprise
- * opt-in this is where the installer captures the installing user's home so state never lands under
- * `System32` (the pinned env wins regardless of the service account).
- */
- export function applyHomeOverride(argv: readonly string[], env: NodeJS.ProcessEnv = process.env): void {
- const home = parseHomeArg(argv);
- if (home === undefined) return;
- // The resolver honors ABSOLUTE roots only (a relative value would re-anchor state on the service
- // manager's cwd). A relative `--home=` is resolved against the INSTALLER's cwd here, at capture
- // time, so the user's intent survives and the pinned value is deterministic everywhere downstream.
- env.APIARY_HOME = isAbsolute(home) ? home : resolve(home);
- }
- /**
- * Persist onboarding `phase: "installed"` + the effective `ref` through the SHARED onboarding store
- * (a-AC-5). An IO error returns false; the caller aborts before registration, ready output, or
- * telemetry. Re-running safely retries the same idempotent commit.
- */
- function writeInstalledMarker(ref: string, dir: string | undefined, out: OutputSink): boolean {
- try {
- const current: OnboardingState = loadOnboarding(dir);
- const next: OnboardingState = { ...current, phase: "installed", ref };
- saveOnboarding(next, dir);
- return true;
- } catch {
- // The caller owns the phase-specific error and fail-closed boundary.
- void out;
- return false;
- }
- }
- /**
- * Register (or refresh) honeycomb's entry in doctor's static registry (PRD-071 Contract A /
- * AC-1 / AC-071a.1), declaring honeycomb's identity, `/health` URL, and its fleet telemetry SQLite
- * path so Doctor knows Honeycomb should exist and where to poll it. A write error returns false;
- * the caller aborts before ready output or telemetry. Re-running replaces the entry in place.
- */
- /**
- * Resolve the daemon bind (host/port) the registry entry's `healthUrl` should advertise, from the
- * SAME runtime-config resolution the daemon itself binds with (`HONEYCOMB_PORT` / `HONEYCOMB_HOST`
- * / `HONEYCOMB_BIND`), so a non-default bind advertises the right probe URL. A wildcard listen
- * address (0.0.0.0 / ::) maps to the loopback host: that is the address doctor (same machine)
- * can actually reach a wildcard-bound daemon on. FAIL-SOFT: an invalid env value falls back to the
- * shared default constants rather than failing the install.
- */
- function resolveRegistryBind(): RegistryBind | undefined {
- try {
- const config = resolveRuntimeConfig();
- const host = config.host === "0.0.0.0" || config.host === "::" ? DAEMON_HOST : config.host;
- return { host, port: config.port };
- } catch {
- return undefined;
- }
- }
- function writeDoctorRegistryEntry(dir: string | undefined, out: OutputSink): boolean {
- try {
- const bind = resolveRegistryBind();
- registerHoneycombWithDoctor({
- ...(dir !== undefined ? { homeDir: dir } : {}),
- ...(bind !== undefined ? { bind } : {}),
- });
- return true;
- } catch {
- void out;
- return false;
- }
- }
- /**
- * Probe the loopback dashboard portal (`127.0.0.1:3853`) with a short timeout. Returns `true` when
- * the portal responds at all; status code does not matter because any HTTP response proves the
- * portal process is running and reachable. `timeoutMs` is injectable so a unit test can prove the
- * abort path in milliseconds instead of waiting out the production budget.
- */
- export async function probeLoopbackDashboard(timeoutMs: number = DASHBOARD_PROBE_TIMEOUT_MS): Promise<boolean> {
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), timeoutMs);
- if (typeof timer.unref === "function") timer.unref();
- try {
- await fetch(loopbackDashboardUrl(), { method: "GET", signal: controller.signal });
- return true;
- } catch {
- return false;
- } finally {
- clearTimeout(timer);
- }
- }
- /**
- * Open the SOLO dashboard at the always-correct loopback URL (`http://127.0.0.1:3853/`). The former
- * friendly `honeycomb.local` first-attempt was dropped (it does not resolve on a normal machine, so a
- * user was shown a non-resolving address). ALWAYS prints the URL so a headless/no-browser host still
- * learns where the dashboard lives; a failed launch is non-fatal — the run still succeeds. This is
- * called ONLY in SOLO mode; in FLEET mode Hive's onboarding owns the portal and this never runs.
- */
- function openSoloDashboard(opener: DashboardOpener, out: OutputSink): void {
- const loopback = loopbackDashboardUrl();
- const opened = opener(loopback);
- out(
- opened ? `→ opening dashboard at ${loopback}…` : `→ dashboard is ready at ${loopback} (open it in your browser).`,
- );
- }
- /**
- * Report how the now-running daemon is supervised (PRD-064h, AC-064h.6 surfaced at install). A pure,
- * FAIL-SOFT read of `lifecycle.status()`: when the daemon runs as a registered OS service it prints
- * the supervising manager (the liveness floor); otherwise it notes the detached-spawn fallback. It
- * NEVER changes the install result: no lifecycle seam, or a status read that throws, simply skips
- * the line. The daemon was already registered+started by `ensureDaemonRunning` → `lifecycle.start()`
- * (service-preferred), so this only narrates the outcome.
- */
- async function reportDaemonSupervision(deps: InstallVerbDeps, out: OutputSink): Promise<void> {
- if (deps.lifecycle === undefined) return;
- try {
- const status = await deps.lifecycle.status();
- if (status.serviceManager !== undefined) {
- out(`✓ daemon registered as an OS service (${status.serviceManager}): it restarts on crash and starts on boot.`);
- } else {
- out("note: daemon running as a detached process (OS service registration unavailable on this host).");
- }
- } catch {
- // A status read must never affect the install outcome: swallow and continue.
- }
- }
- /**
- * The production SOLO auto-login (PRD-003a a-AC-3 / a-AC-7): run the SAME device flow `honeycomb
- * login` runs (`loginWithDeviceFlow`) with the validated OS browser opener. It PRINTS the
- * verification URL + user code through the reporter BEFORE any open attempt, and on a headless host
- * the opener simply returns false (never throws) and the flow polls to completion — so a no-browser
- * environment degrades to "print + poll" rather than hanging or crashing (a-AC-7). Resolves `true`
- * on a persisted credential; `loginWithDeviceFlow` throws on failure, which the caller reports.
- */
- async function defaultInstallDeviceLogin(out: OutputSink): Promise<boolean> {
- await loginWithDeviceFlow({
- reporter: { prompt: (line: string): void => out(line) },
- openBrowser: defaultBrowserOpener,
- });
- return true;
- }
- /**
- * The PRD-003a install-time login decision (a-AC-1 / a-AC-3 / a-AC-6 / a-AC-7), run from the install
- * path ONLY (never daemon boot). Classifies solo vs fleet, LOGS which signals fired (a-AC-6), then:
- *
- * - FLEET (Hive detected): print ONE line that login is deferred to Hive onboarding and initiate
- * NOTHING — no browser popup, no prompt (a-AC-1). The daemon sits degraded on /health until
- * Hive-side login writes the shared credential; the 15s SELECT-1 health probe flips it healthy
- * with no restart (a-AC-2).
- * - SOLO with credentials already present: no popup — say the user is already signed in (a-AC-3).
- * - SOLO with NO credentials: auto-open the device-flow popup (a-AC-3); headless degrades to
- * printing the URL + code and polling (a-AC-7).
- *
- * Fail-soft (parent AC-9): this NEVER changes the install exit code. A detection error DEFERS
- * (suppressing a popup wrongly is cheap; opening one wrongly is the bug), and a login failure prints
- * a plain-language "run `honeycomb login`" hint rather than aborting the install.
- */
- async function runInstallLoginStep(deps: InstallVerbDeps, out: OutputSink): Promise<FleetClassification> {
- let classification: FleetClassification;
- try {
- classification = await (deps.detectFleet ?? (() => classifyFleet()))();
- } catch {
- // Detection blew up: DEFER (treat as fleet) so we never pop a wrong browser NOR a competing
- // dashboard window. Actionable line, and the returned fleet classification gates the dashboard
- // step to "open nothing" too.
- out("note: could not determine solo vs fleet mode; deferring login (run `honeycomb login` to sign in).");
- return {
- mode: "fleet",
- signals: { registryHiveEntry: false, hivePortAnswering: false, hiveNpmGlobal: false },
- firedSignals: [],
- };
- }
- // a-AC-6: the classification's inputs (which signals fired) are visible in the install output.
- out(fleetSignalLine(classification));
- if (classification.mode === "fleet") {
- // a-AC-1: defer ALL login initiation to Hive; never open a browser or prompt.
- out("→ login is deferred to Hive onboarding (Hive detected); Honeycomb connects once Hive signs in.");
- return classification;
- }
- // SOLO. Only auto-open when the shared credential is absent (a-AC-3).
- const creds = (deps.loadInstallCredentials ?? loadCredentials)();
- if (creds !== null) {
- out("✓ already signed in (existing credentials found); no browser opened.");
- return classification;
- }
- out("→ no credentials found; opening sign-in…");
- try {
- const ok = await (deps.runDeviceLogin ?? defaultInstallDeviceLogin)(out);
- out(ok ? "✓ signed in." : "note: sign-in did not complete; run `honeycomb login` to finish.");
- } catch (err) {
- // a-AC-9: a login failure is a plain-language, actionable line — never a raw stack, never a fail.
- const reason = err instanceof Error ? err.message : "sign-in failed";
- out(`note: automatic sign-in could not complete (${reason}); run \`honeycomb login\` to sign in.`);
- }
- return classification;
- }
- /**
- * Wire the harness hooks BEST-EFFORT at the end of a successful install (the D5-until-manual-setup
- * fix). Runs the SAME connector engine `honeycomb setup` uses (019a `connectorMain` via the
- * {@link ConnectorRunner} seam), in BOTH solo and fleet modes. FAIL-SOFT: a missing seam is a silent
- * no-op; a setup THROW prints one actionable line and NEVER changes the install exit code. Prints what
- * got wired (or that nothing supported was detected) so the user sees the outcome.
- */
- async function runInstallSetupStep(deps: InstallVerbDeps, out: OutputSink): Promise<void> {
- if (deps.connector === undefined) return;
- try {
- const result = await deps.connector.run({ verb: "setup" });
- if (result.harnesses.length > 0) {
- out(`✓ wired harness hooks: ${result.harnesses.join(", ")}.`);
- } else {
- out(
- "note: no harness hooks were wired (no supported harness detected); run `honeycomb setup` after installing one.",
- );
- }
- } catch (err) {
- // Fail-soft: wiring is best-effort. One actionable line, never a raw stack, never a failed install.
- const reason = err instanceof Error ? err.message : "setup failed";
- out(`note: could not wire harness hooks (${reason}); run \`honeycomb setup\` to wire them.`);
- }
- }
- /**
- * Run `honeycomb install [--ref <code>]` (a-AC-1..6). Health-gates the daemon up (idempotent, no
- * double-bind), persists the onboarding "installed" marker + effective ref, then — in SOLO mode only —
- * opens the dashboard at the loopback URL (in FLEET mode Hive's onboarding owns the portal, so this
- * opens nothing). Every effect goes through an injected seam; a handled failure is a single readable
- * line + a non-zero exit, never a raw stack (parent AC-7).
- */
- export async function runInstallCommand(argv: readonly string[], deps: InstallVerbDeps): Promise<CommandResult> {
- const out: OutputSink = deps.out ?? ((line: string): void => console.log(line));
- const opener = deps.openDashboard ?? openLocalDashboardUrl;
- const probeDashboard = deps.probeDashboard ?? probeLoopbackDashboard;
- const ref = resolveEffectiveRef(argv);
- // PRD-072d: record the `--home=` pin as APIARY_HOME BEFORE the daemon is ensured/registered, so the
- // registry write, the service-unit pin, and the spawned daemon all resolve the chosen fleet root.
- applyHomeOverride(argv);
- // 1) Health-gate the daemon (a-AC-4). ensureDaemonRunning is idempotent (a-AC-2): an already-up
- // daemon returns at once with NO second start/bind; a down daemon is started + waited on the
- // lifecycle's existing budget. The dashboard is opened ONLY after this returns reachable.
- out(`→ starting the Honeycomb daemon on ${DAEMON_HOST}:${DAEMON_PORT}…`);
- const reachable = await ensureDaemonRunning({
- daemon: deps.daemon,
- ...(deps.lifecycle !== undefined ? { lifecycle: deps.lifecycle } : {}),
- out,
- });
- if (!reachable) {
- // a-AC-4: the daemon never bound within the wait budget. Plain-language error + retry hint;
- // NON-ZERO exit; NO dashboard open; NO raw stack.
- out("error: the daemon didn't start (it never became reachable on 127.0.0.1:3850).");
- out(" retry with `honeycomb install`, or run `honeycomb daemon start` to see the startup log.");
- return { exitCode: 1 };
- }
- out(`✓ daemon up on ${DAEMON_HOST}:${DAEMON_PORT}.`);
- // 1b) Report how the daemon is supervised (PRD-064h). `lifecycle.start()` (reached via
- // ensureDaemonRunning above) PREFERS registering the daemon as an OS-native service (launchd /
- // systemd --user / per-user Scheduled Task): the liveness floor that restarts it on crash and
- // starts it on boot, and FALLS BACK to a detached spawn where registration is impossible (CI,
- // locked-down machines). This is a pure, fail-soft READ of the now-running daemon's status so
- // the user learns which path took effect; it NEVER alters the install outcome (a status read
- // that throws is swallowed, and an absent lifecycle seam simply skips the line).
- await reportDaemonSupervision(deps, out);
- // 2) Persist the required onboarding marker. A failed required phase stops the transaction;
- // later conveniences and success telemetry must not run.
- const wrote = (deps.persistInstalled ?? writeInstalledMarker)(ref, deps.dir, out);
- if (!wrote) {
- out("error: install failed during the onboarding-marker phase; fix state-directory permissions and retry.");
- return { exitCode: 1 };
- }
- out(`✓ onboarding marked installed (ref: ${ref}).`);
- // 2b) Register (or refresh) honeycomb's doctor static-registry entry (PRD-071 Contract A).
- if (!(deps.registerWithDoctor ?? writeDoctorRegistryEntry)(deps.dir, out)) {
- out("error: install failed during the Doctor-registration phase; no ready state was reported.");
- return { exitCode: 1 };
- }
- out("✓ registered Honeycomb with Doctor.");
- // 2c) PRD-003a: the solo-vs-fleet login decision (a-AC-1 / a-AC-3 / a-AC-6 / a-AC-7). Fires from
- // the install path ONLY. Fleet → defer to Hive (no popup); solo + no creds → auto device flow;
- // solo + creds → already signed in. Fail-soft: it never changes the install exit code. The
- // returned classification also gates the dashboard-open step below (solo-only).
- const classification = await runInstallLoginStep(deps, out);
- // 2d) PRD-003a follow-through: wire the harness hooks best-effort so the one-line installer no longer
- // leaves them unwired until a manual `honeycomb setup` (the observed D5-FAIL). Runs the SAME
- // connector engine `honeycomb setup` uses, in BOTH solo and fleet modes, fail-soft — a setup
- // failure prints one line and never fails the install.
- await runInstallSetupStep(deps, out);
- // 3) Open the dashboard — SOLO mode ONLY. When Hive is present (FLEET) the dashboard IS the Hive
- // portal and Hive's own onboarding already opened it; opening a SECOND competing window here is
- // the field bug this gate kills. So in fleet mode we open NOTHING and print one plain line.
- // In solo mode we probe the portal first: reachable → open the loopback URL; not reachable →
- // print one plain sentence and open no tab (C-6). FAIL-SOFT: a throwing probe (an injected seam
- // misbehaving) degrades to the not-running branch, never a failed install.
- if (classification.mode === "fleet") {
- out("→ dashboard: the Hive portal owns it; Hive onboarding opened it, so Honeycomb opens nothing here.");
- } else {
- let portalReachable = false;
- try {
- portalReachable = await probeDashboard();
- } catch {
- portalReachable = false;
- }
- if (portalReachable) {
- openSoloDashboard(opener, out);
- } else {
- out(DASHBOARD_PORTAL_NOT_RUNNING_MESSAGE);
- }
- }
- out("✓ Honeycomb is ready.");
- // 4) Emit the `honeycomb_installed` lifecycle event (PRD-050e e-AC-1) — AFTER the user-facing
- // success, NEVER gating it (e-AC-4). FIRE-AND-FORGET through the single chokepoint: the promise is
- // intentionally NOT awaited (`void`), so a slow/timing-out PostHog hop never delays the installer
- // after the success line has printed. All errors are swallowed inside `emitTelemetry`; the
- // onboarding `dir` is threaded so the dedupe ledger lives in the same temp HOME under test. A second
- // install run is a no-op send (e-AC-5, dedupe). Tier-1 → opt-out default; an opt-out env / empty
- // key silences it.
- //
- // ── the-apiary PRD-002c c-AC-5 note: this event is SCOPED, not retired ────────────────────────
- // ADR-0002 moves the install-LIFECYCLE phone-home into the shell scripts (`install_started` /
- // `install_completed` / `install_failed`, fired from `scripts/install/install.sh` /
- // `install.ps1`), which is now the reliable "did an install run happen, and how did it end"
- // signal — it survives a keyless Node build and a pre-CLI failure, neither of which
- // `honeycomb_installed` can ever observe (it only fires from inside a successful run of THIS
- // verb). `honeycomb_installed` is DELIBERATELY KEPT, scoped to a narrower, DIFFERENT meaning:
- // "this machine's `honeycomb` CLI verb completed successfully, ONCE, ever" (e-AC-5's dedupe
- // ledger enforces the "once" — repeat `honeycomb install` runs never re-fire it), correlated to
- // the SAME onboarding `installId`/`ref` the Node-side telemetry and login event
- // (`honeycomb_first_link`) already use. The two surfaces are structurally incapable of double
- // counting the SAME event: they are different event NAMES, sent to the same PostHog project
- // from two independent transports, answering two different questions (funnel/failure-rate over
- // every install attempt, vs. one-time CLI-verb-completion-and-onboarding-correlation per
- // machine). Retiring `honeycomb_installed` outright would lose that onboarding correlation for
- // no gain, so this pass keeps it and documents the split here rather than deleting it.
- //
- // The `honeycomb_updated` version checkpoint (the-apiary lifecycle telemetry) runs in the SAME
- // fire-and-forget chain, SEQUENCED after the installed emit: both mutate the one onboarding
- // state file (ledger / lastVersion), so running them concurrently would race a load/save and
- // lose one write. `recordVersionAndEmitUpdated` is a one-string-compare no-op when the version
- // is unchanged, records the baseline silently on first sighting, and emits `honeycomb_updated`
- // (deduped per event+version) on a real change. Fail-soft always - see version-check.ts.
- const telemetryDeps: EmitDeps = {
- ...(deps.telemetry ?? {}),
- ...(deps.dir !== undefined ? { dir: deps.dir } : {}),
- };
- void (async () => {
- await emitTelemetry("honeycomb_installed", { ref, tier: "tier1" }, telemetryDeps);
- await recordVersionAndEmitUpdated(ref, telemetryDeps);
- })();
- return { exitCode: 0 };
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.