Skip to content
Back to search

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/legioncodeinc--honeycomb/badge.svg)](/listings/legioncodeinc--honeycomb)

HTML

<a href="/listings/legioncodeinc--honeycomb"><img src="/api/listings/legioncodeinc--honeycomb/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

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)

  1. {
  2. "name": "honeycomb",
  3. "owner": {
  4. "name": "Honeycomb"
  5. },
  6. "metadata": {
  7. "description": "Honeycomb — persistent memory daemon and thin harness clients for AI coding assistants",
  8. "version": "0.22.1"
  9. },
  10. "plugins": [
  11. {
  12. "name": "honeycomb",
  13. "description": "Honeycomb Claude Code plugin — captures session activity and provides cross-session memory through the local daemon",
  14. "version": "0.22.1",
  15. "source": "./harnesses/claude-code"
  16. }
  17. ]
  18. }
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)

  1. <!-- ─────────────────────────────── HERO ─────────────────────────────── -->
  2. <p align="center">
  3. <picture>
  4. <source media="(prefers-color-scheme: dark)" srcset="assets/brand/honeycomb-wordmark-on-dark.svg">
  5. <img src="assets/brand/honeycomb-wordmark-black.svg" alt="Honeycomb" height="84">
  6. </picture>
  7. </p>
  8. <h1 align="center">Honeycomb</h1>
  9. <p align="center">
  10. <strong>Shared, persistent memory for your AI coding agents.</strong><br>
  11. What one harness learns, every other one recalls, across sessions, tools, devices, and teammates.
  12. </p>
  13. <p align="center">
  14. <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>
  15. <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">
  16. <img src="https://img.shields.io/badge/OS-windows%20%7C%20macos%20%7C%20linux-6E6A62?style=flat-square" alt="Windows, macOS, Linux">
  17. </p>
  18. <p align="center">
  19. <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>
  20. <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>
  21. <a href="https://deeplake.ai"><img src="https://img.shields.io/badge/powered%20by-Deeplake-ff5a1f?style=flat-square" alt="Powered by Deeplake"></a>
  22. </p>
  23. <p align="center">
  24. <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>
  25. <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>
  26. </p>
  27. <!-- ────────────────────────────── PARTNERS ────────────────────────────── -->
  28. <p align="center">
  29. <a href="https://github.com/legioncodeinc">
  30. <picture>
  31. <source media="(prefers-color-scheme: dark)" srcset="assets/brand/legion-logo-dark.svg">
  32. <img src="assets/brand/legion-logo-light.svg" alt="Legion Code" height="34">
  33. </picture>
  34. </a>
  35. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  36. <a href="https://github.com/activeloopai">
  37. <picture>
  38. <source media="(prefers-color-scheme: dark)" srcset="assets/brand/activeloop-full-mark-logo-on-dark.svg">
  39. <img src="assets/brand/activeloop-full-mark-logo.svg" alt="Activeloop" height="26">
  40. </picture>
  41. </a>
  42. </p>
  43. <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>
  44. <img src="assets/brand/divider-major.svg" width="100%" height="6">
  45. 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.
  46. 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?*
  47. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  48. > **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)**.
  49. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  50. <table>
  51. <tr>
  52. <td width="50%" valign="top">
  53. #### 🛹 For AI Augmented Devs
  54. 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.
  55. </td>
  56. <td width="50%" valign="top">
  57. #### 🏢 For Enterprise Teams
  58. 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.
  59. </td>
  60. </tr>
  61. </table>
  62. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  63. ## ✨ What makes Honeycomb different
  64. 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.
  65. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  66. - **🧠 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)*
  67. - **🎯 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)*
  68. - **🍯 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)*
  69. - **🌼 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)*
  70. - **🕸️ 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)*
  71. - **🔀 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)*
  72. - **🗺️ 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)*
  73. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  74. ## 🚀 Install (one command)
  75. 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.
  76. ```bash
  77. # macOS / Linux
  78. curl -fsSL https://get.theapiary.sh | sh
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 107 on GitHub
  79. ```
  80. ```powershell
  81. # Windows (PowerShell)
  82. irm https://get.theapiary.sh/install.ps1 | iex
  83. ```
  84. 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:
  85. 1. The dashboard loads in a **pre-auth setup state**. No token ever touches your shell.
  86. 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.
  87. 3. Done. The same running daemon lights up its Deeplake-backed surfaces, and capture and recall go live.
  88. > 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).
  89. <details>
  90. <summary><strong>Prefer to build from source?</strong></summary>
  91. ```bash
  92. git clone https://github.com/legioncodeinc/honeycomb.git
  93. cd honeycomb
  94. npm install
  95. npm run build # tsc + esbuild → bundle/cli.js, daemon, harness, MCP, embed bundles
  96. node bundle/cli.js setup # detect your assistants, wire hooks, start the daemon
  97. node bundle/cli.js status # check the daemon and your environment
  98. ```
  99. `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`.
  100. > **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.
  101. </details>
  102. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  103. ## 🖥️ Using the dashboard
  104. 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.
  105. <!-- screenshot pending: drop honeycomb dashboard capture into assets/screenshots/dashboard.png -->
  106. <img src="assets/screenshots/dashboard.png" alt="Honeycomb dashboard" width="100%">
  107. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  108. ## ⌨️ Using the CLI
  109. One unified `honeycomb` binary drives everything. Run `honeycomb --help` for the full list; these are the core verbs:
  110. ```bash
  111. honeycomb install # one-shot install on a fresh machine
  112. honeycomb setup # detect your coding assistants and wire hooks
  113. honeycomb status # daemon + environment health at a glance
  114. honeycomb login # sign in via the Deeplake device flow, any time
  115. honeycomb start # start the installed OS service and verify health
  116. honeycomb stop # stop the installed OS service
  117. honeycomb restart # restart through the OS service and verify health
  118. honeycomb service-install # install/reconcile only the OS service
  119. honeycomb service-uninstall # remove only the OS service; preserve state/registration
  120. honeycomb register # idempotently upsert Honeycomb in Doctor's registry
  121. honeycomb logs # last 100 service-log lines, then follow
  122. honeycomb telemetry # read-only telemetry state and delivery summary
  123. honeycomb update --check # compare installed and approved release versions
  124. honeycomb daemon start|stop|status # legacy process-level compatibility commands
  125. honeycomb uninstall --yes # confirmed full removal of Honeycomb-owned state
  126. honeycomb remember "<fact>" # write a memory from anywhere
  127. honeycomb recall "<query>" # search the shared memory
  128. honeycomb sessions # browse captured sessions
  129. honeycomb skill # list, inspect, and sync mined skills
  130. honeycomb goal # track goals across sessions
  131. honeycomb sources # manage capture sources
  132. honeycomb graph # query the codebase and knowledge graphs
  133. honeycomb dashboard # open the dashboard (Hive portal, :3853)
  134. ```
  135. A few lifecycle notes:
  136. - **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.
  137. - **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.
  138. - **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.
  139. - **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.
  140. - **`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).
  141. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  142. ## 🐝 First memory, shared across tools
  143. ```bash
  144. # Capture a decision once…
  145. honeycomb remember "we deploy from the prd-022 branch, never from main"
  146. # …recall it anywhere: same daemon, same Deeplake, any harness
  147. honeycomb recall "how do we deploy"
  148. ```
  149. Write it from Claude Code; recall it from Cursor tomorrow on a different laptop. That's the whole point.
  150. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  151. ## 🏗️ How it works
  152. 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.
  153. ```mermaid
  154. flowchart TB
  155. CC["Claude Code"] --> TC
  156. CU["Cursor"] --> TC
  157. CX["Codex"] --> TC
  158. HE["Hermes"] --> TC
  159. PI["pi"] --> TC
  160. OC["OpenClaw"] --> TC
  161. TC["thin clients<br/>hooks · CLI · MCP · SDK"] --> HTTP["loopback HTTP<br/>127.0.0.1:3850"]
  162. HTTP --> D["honeycomb daemon<br/>capture · recall · skillify · pollinate · session priming<br/>sole storage client, owns your credentials"]
  163. D --> DL["Activeloop Deeplake<br/>Tier 1 · Tier 2 · Tier 3<br/>BM25 + semantic vectors"]
  164. ```
  165. - **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.
  166. - **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.
  167. - **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.
  168. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  169. ## 🧠 The three-tier memory system
  170. 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:
  171. | Tier | What it is | When it's used |
  172. |---|---|---|
  173. | **Tier 1 · Key** | One keyword-dense sentence per session or fact. The index. | Skimmed at session start during priming. |
  174. | **Tier 2 · Summary** | A distilled recap: goals, decisions, blockers, outcomes. Carries the semantic embedding. | Pulled when a key looks relevant. |
  175. | **Tier 3 · Raw** | The full session dialogue: exact turns and tool calls, never rewritten. | Resolved when the agent needs ground truth. |
  176. 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.
  177. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  178. ## 💎 Why Deeplake makes the difference
  179. 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:
  180. - **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.
  181. - **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.
  182. - **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.
  183. - **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.
  184. > 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.
  185. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  186. ## 🔌 Supported harnesses
  187. Honeycomb supports 3 harnesses in production (Claude Code, Codex, Cursor). Hermes, pi, and OpenClaw are in progress.
  188. | Supported today | In progress |
  189. |---|---|
  190. | **Claude Code**, **Cursor**, **Codex** | **Hermes**, **pi**, **OpenClaw** |
  191. `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.
  192. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  193. ## 🎛️ Other interfaces
  194. Beyond the CLI, three more ways to reach the same daemon and the same shared memory:
  195. - **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.
  196. - **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.
  197. - **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.
  198. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  199. <h2 align="center"><a href="https://ideas.theapiary.sh">📍 Status & Roadmap</a></h2>
  200. Honeycomb is **production ready (v0.4.x)** and fully tested in live scenarios. We document what's real and flag what's opt-in.
  201. **Production today**
  202. - Capture-to-recall, proven end-to-end and live-tested against Deeplake (`npm run smoke:golden-path` with credentials).
  203. - One-command install → guided dashboard setup, the loopback daemon, the unified CLI, per-harness hooks, the MCP server, and the SDK.
  204. - Three-tier memory, session priming, skillify + propagation, the pollinating loop, the knowledge graph, and the codebase graph.
  205. - 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.
  206. **Opt-in / by design**
  207. - **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.
  208. - **The distillation pipeline is off by default** to avoid surprise model spend; enable it when you want background summarization and graph extraction.
  209. - 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.
  210. Full documentation and guides live at **[theapiary.sh](https://theapiary.sh)**; vote on what ships next at **[ideas.theapiary.sh](https://ideas.theapiary.sh)**.
  211. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  212. ## 🛠️ Development
  213. ```bash
  214. npm install # dependencies
  215. npm run build # tsc + esbuild → bundle/cli.js, the daemon, harness, MCP, and embed bundles
  216. npm run ci # the gate: typecheck + duplication (jscpd) + tests (vitest) + SQL-safety audit
  217. ```
  218. `npm run ci` is the quality gate every change must pass.
  219. <img src="assets/brand/divider-major.svg" width="100%" height="6">
  220. ## 🙏 Credits
  221. Honeycomb exists because two halves fit together:
  222. - **[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.
  223. - **[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.
  224. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  225. ## License
  226. Honeycomb is licensed under the **GNU Affero General Public License v3.0 or later** ([AGPL-3.0-or-later](LICENSE)).
  227. 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.
  228. © 2026 Legion Code Inc.
  229. <img src="assets/brand/divider-minor.svg" width="100%" height="3">
  230. <p align="center">
  231. <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>
  232. </p>
  233. <p align="center"><strong>I am Legion. We are Legion.</strong></p>
  234. <p align="center">#vibewithlegion</p>
src/cli/daemon-service.ts · Bundled script · 1,017 lines · 1 finding marked
  1. /**
  2. * The primary-daemon OS-native service helper, PRD-064h (AC-064h.1..6).
  3. *
  4. * ── Why this module exists (OD-1 / 064h) ─────────────────────────────────────
  5. * The shipped daemon lifecycle (`src/cli/runtime.ts`) brings the daemon up by a DETACHED
  6. * `spawn()`, which dies with the machine and is not restarted on crash. 064h makes the OS
  7. * service manager the LIVENESS FLOOR: it restarts the daemon on crash and starts it on boot,
  8. * while Doctor stays the intelligent healing layer above it. This module is the small,
  9. * pure, per-OS surface that registers / unregisters / starts / stops / restarts / reports the
  10. * daemon as a userland service:
  11. * - macOS → launchd LaunchAgent (`~/Library/LaunchAgents/<label>.plist`, `launchctl`)
  12. * - Linux → systemd `--user` unit (`~/.config/systemd/user/<unit>.service`, `systemctl --user`)
  13. * - Windows→ per-user Scheduled Task (no admin / no UAC, the resolved default), `schtasks`
  14. *
  15. * ── Design rules (binding) ───────────────────────────────────────────────────
  16. * 1. ADDITIVE + FALLBACK. This module never replaces the detached spawn; `runtime.ts` prefers
  17. * service mode when a manager is available and falls back to spawn where registration is
  18. * impossible (CI, locked-down corp machines, the existing tests). {@link detectServiceManager}
  19. * returns `null` on those hosts, which is the signal `runtime.ts` reads to fall back.
  20. * 2. CHEAP, SIDE-EFFECT-FREE DETECTION. {@link detectServiceManager} only reads `platform` + a
  21. * couple of env probes (it does NOT shell out, write files, or spawn work). An explicit
  22. * `HONEYCOMB_DAEMON_SERVICE=spawn` opt-out forces the spawn fallback everywhere.
  23. * 3. WRITABLE WORKSPACE PINNED INTO THE UNIT (AC-064h.4). The generated unit pins BOTH the
  24. * working directory and `HONEYCOMB_WORKSPACE` to the caller-resolved writable workspace, so a
  25. * service-started daemon never boots from `C:\WINDOWS\system32` (the documented "secrets 502"
  26. * class). The workspace is RESOLVED BY THE CALLER (`runtime.ts`, which owns the writable-probe)
  27. * and threaded in, this module never re-resolves it.
  28. * 4. ARGV BEHIND AN INJECTED RUNNER (test discipline). Every shell-out to `launchctl` /
  29. * `systemctl` / `schtasks` goes through an injected {@link ServiceRunner}, so a unit test
  30. * asserts the exact argv WITHOUT executing anything. The default runner (used only in
  31. * production) is the lazy `createRequire`-loaded `node:child_process` `execFileSync`, never a
  32. * shell string, always fixed-argv.
  33. *
  34. * ── Scope boundary ───────────────────────────────────────────────────────────
  35. * This is the PRIMARY daemon's service. Doctor's OWN service is 064b (a sibling, separate
  36. * unit). The two share the same approach and acceptably-duplicated templates; this module lives
  37. * in the MAIN package (`src/`) and does not import from `doctor/`.
  38. */
  39. import { createRequire } from "node:module";
  40. import { homedir } from "node:os";
  41. import { join, normalize, resolve, sep, win32 } from "node:path";
  42. import { PRODUCT_SLUG } from "../shared/constants.js";
  43. import { APIARY_HOME_ENV, honeycombStateDir } from "../shared/fleet-root.js";
  44. /** The three OS service managers this module can target (the resolved per-OS default). */
  45. export type ServiceManager = "launchd" | "systemd-user" | "schtasks";
  46. /**
  47. * The label / unit / task name the daemon's service is registered under (one per host family).
  48. * Decision #32 (2026-07-02, nectar `library/requirements/PRD-DECISIONS-AND-DEFAULTS.md`): the
  49. * fleet-wide scheme is reverse-DNS `com.legioncode.<shortname>` with the product short name
  50. * `honeycomb`, superseding the shipped `ai.honeycomb.daemon` / `HoneycombDaemon` names.
  51. */
  52. export const SERVICE_LABEL = "com.legioncode.honeycomb" as const;
  53. /** The systemd --user unit name (decision #32: `<shortname>.service`). */
  54. export const SERVICE_SYSTEMD_UNIT = "honeycomb.service" as const;
  55. /** The Windows Scheduled Task name (decision #32: the bare short name). */
  56. export const SERVICE_TASK_NAME = "honeycomb" as const;
  57. /** The pre-decision-#32 launchd label, deregistered on register (migration path). */
  58. export const LEGACY_SERVICE_LABEL = "ai.honeycomb.daemon" as const;
  59. /** The pre-decision-#32 systemd unit name (the old label + `.service`), deregistered on register. */
  60. export const LEGACY_SERVICE_SYSTEMD_UNIT = "ai.honeycomb.daemon.service" as const;
  61. /** The pre-decision-#32 Windows task name, deregistered on register. */
  62. export const LEGACY_SERVICE_TASK_NAME = "HoneycombDaemon" as const;
  63. /**
  64. * The opt-out env var that forces the detached-spawn fallback regardless of the host. Set
  65. * `HONEYCOMB_DAEMON_SERVICE=spawn` to disable OS-service mode (CI, locked-down machines, or a user
  66. * who simply prefers the old lifecycle). Any other value (or unset) keeps auto-detection.
  67. */
  68. export const SERVICE_MODE_ENV = "HONEYCOMB_DAEMON_SERVICE" as const;
  69. /** Fixed host for exact-identity cleanup after Task Scheduler ends its conhost wrapper. */
  70. export const WINDOWS_POWERSHELL_PATH = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" as const;
  71. /** Shared PowerShell 5-safe decoder and exact expected-command builder. */
  72. const WINDOWS_HONEYCOMB_IDENTITY_SETUP_SCRIPT =
  73. "$ErrorActionPreference='Stop'; " +
  74. "$entry=[IO.Path]::GetFullPath([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($entry64))); " +
  75. "$node=[IO.Path]::GetFullPath([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($node64))); " +
  76. "$flagsJson=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($flags64)); " +
  77. "$decodedFlags=ConvertFrom-Json -InputObject $flagsJson; " +
  78. "if($null -eq $decodedFlags){$flagItems=@()}elseif($decodedFlags -is [System.Array]){$flagItems=$decodedFlags}else{$flagItems=@($decodedFlags)}; " +
  79. "$flags=@(); foreach($flag in $flagItems){if($flag -isnot [string]){throw 'Honeycomb node flags must be strings.'}; $flags+=[string]$flag}; " +
  80. "$dq=[char]34; $tokenPattern={ param([string]$value) " +
  81. "$plain=[Regex]::Escape($value); $quoted=[Regex]::Escape(($dq+$value+$dq)); " +
  82. "if($value.Contains(' ')){ $fragmented=[Regex]::Escape(($value -replace ' ',($dq+' '+$dq))); return '(?:'+$quoted+'|'+$fragmented+')' }; " +
  83. "return '(?:'+$quoted+'|'+$plain+')' }; " +
  84. "$expectedParts=@($node); foreach($flag in $flags){$expectedParts+=$flag}; $expectedParts+=$entry; " +
  85. "$patterns=@(); foreach($part in $expectedParts){$patterns+=(& $tokenPattern ([string]$part))}; " +
  86. "$expectedPattern='^\\s*'+($patterns -join '\\s+')+'\\s*$'; $expected=$expectedParts -join ' '; ";
  87. /**
  88. * `schtasks /End` can leave the Node daemon alive beneath `conhost --headless`. Paths are supplied
  89. * as UTF-16/base64 argv values, never interpolated into this fixed script. The filter requires the
  90. * exact Node executable and exact Honeycomb daemon entry before terminating a process.
  91. */
  92. export const WINDOWS_HONEYCOMB_PROCESS_CLEANUP_SCRIPT =
  93. "& { param([string]$entry64,[string]$node64,[string]$flags64); " +
  94. WINDOWS_HONEYCOMB_IDENTITY_SETUP_SCRIPT +
  95. "$matching={ @((Get-CimInstance Win32_Process | Where-Object { " +
  96. "$_.Name -ieq 'node.exe' -and $_.CommandLine -and $_.ExecutablePath -and " +
  97. "[StringComparer]::OrdinalIgnoreCase.Equals([IO.Path]::GetFullPath($_.ExecutablePath),$node) -and " +
  98. "[Regex]::IsMatch($_.CommandLine,$expectedPattern,[Text.RegularExpressions.RegexOptions]::IgnoreCase) " +
  99. "})) }; " +
  100. "@(& $matching) | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction Stop }; " +
  101. "Start-Sleep -Milliseconds 100; " +
  102. "$remaining=@(& $matching); if($remaining.Count -ne 0){ throw 'Honeycomb daemon process remained after stop.' } }";
  103. /**
  104. * Non-destructive PowerShell 5 regression probe using the exact production decoder/comparator.
  105. * It never enumerates or stops processes: success means the supplied synthetic identity matches.
  106. */
  107. export const WINDOWS_HONEYCOMB_PROCESS_IDENTITY_PROBE_SCRIPT =
  108. "& { param([string]$entry64,[string]$node64,[string]$flags64,[string]$actualExe64,[string]$actualCommand64); " +
  109. WINDOWS_HONEYCOMB_IDENTITY_SETUP_SCRIPT +
  110. "$actualExe=[IO.Path]::GetFullPath([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($actualExe64))); " +
  111. "$actualCommand=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($actualCommand64)); " +
  112. "if(-not [StringComparer]::OrdinalIgnoreCase.Equals($actualExe,$node)){exit 4}; " +
  113. "if(-not [Regex]::IsMatch($actualCommand,$expectedPattern,[Text.RegularExpressions.RegexOptions]::IgnoreCase)){exit 5}; " +
  114. "Write-Output $expected }";
  115. function windowsCommandTokenPattern(value: string): string {
  116. const escaped = value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
  117. const quoted = `"${value}"`.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
  118. if (!value.includes(" ")) return `(?:${quoted}|${escaped})`;
  119. const fragmented = value.replaceAll(" ", '" "').replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
  120. return `(?:${quoted}|${fragmented})`;
  121. }
  122. export function matchesWindowsDaemonProcess(
  123. executablePath: string,
  124. commandLine: string,
  125. spec: ServiceSpec,
  126. ): boolean {
  127. if (!win32.isAbsolute(executablePath) || !win32.isAbsolute(spec.nodePath)) return false;
  128. const executableMatches = win32.normalize(executablePath).toLowerCase() === win32.normalize(spec.nodePath).toLowerCase();
  129. const expected = [spec.nodePath, ...spec.nodeFlags, spec.entry].map(windowsCommandTokenPattern).join("\\s+");
  130. return executableMatches && new RegExp(`^\\s*${expected}\\s*$`, "iu").test(commandLine);
  131. }
  132. /** Fixed PowerShell probe: success only while the task and its exact Honeycomb Node descendant run. */
  133. export const WINDOWS_TASK_RUNNING_SCRIPT =
  134. "& { param([string]$taskName,[string]$entry64,[string]$node64,[string]$flags64); " +
  135. WINDOWS_HONEYCOMB_IDENTITY_SETUP_SCRIPT +
  136. "$task=Get-ScheduledTask -TaskName $taskName -ErrorAction Stop; " +
  137. "if([string]$task.State -ne 'Running'){ exit 3 }; " +
  138. "$matching=@((Get-CimInstance Win32_Process | Where-Object { " +
  139. "$_.Name -ieq 'node.exe' -and $_.CommandLine -and $_.ExecutablePath -and " +
  140. "[StringComparer]::OrdinalIgnoreCase.Equals([IO.Path]::GetFullPath($_.ExecutablePath),$node) -and " +
  141. "[Regex]::IsMatch($_.CommandLine,$expectedPattern,[Text.RegularExpressions.RegexOptions]::IgnoreCase) " +
  142. "})); if($matching.Count -ne 1){ exit 4 } }";
  143. function encodedWindowsPath(value: string): string {
  144. return Buffer.from(value, "utf16le").toString("base64");
  145. }
  146. function cleanupWindowsDaemon(runner: ServiceRunner, spec: ServiceSpec): void {
  147. runner.run(WINDOWS_POWERSHELL_PATH, [
  148. "-NoLogo",
  149. "-NoProfile",
  150. "-NonInteractive",
  151. "-ExecutionPolicy",
  152. "Bypass",
  153. "-Command",
  154. WINDOWS_HONEYCOMB_PROCESS_CLEANUP_SCRIPT,
  155. encodedWindowsPath(spec.entry),
  156. encodedWindowsPath(spec.nodePath),
  157. encodedWindowsPath(JSON.stringify(spec.nodeFlags)),
  158. ]);
  159. }
  160. /**
  161. * Detect the OS service manager available on this host, or `null` when service registration is not
  162. * available / not wanted (→ the caller falls back to the detached spawn).
  163. *
  164. * CHEAP + SIDE-EFFECT-FREE (critical directive): reads `platform` + a couple of env vars only. It
  165. * does NOT shell out to probe for `launchctl`/`systemctl`/`schtasks`, write any file, or spawn any
  166. * work, so it is safe to call on every `start()` / `install`. The honest "is the binary actually
  167. * present" check is deferred to the runner (a `register` that shells out fails loudly and the caller
  168. * falls back); a cheap heuristic here is enough to PICK the manager.
  169. *
  170. * - `HONEYCOMB_DAEMON_SERVICE=spawn` → `null` (explicit opt-out; the spawn fallback).
  171. * - darwin → `launchd` (LaunchAgents are always available per-user on macOS).
  172. * - linux → `systemd-user` ONLY when a user systemd is plausibly present. We require a
  173. * positive signal (`XDG_RUNTIME_DIR` set, the conventional `systemctl --user` bus dir) rather
  174. * than assuming systemd, a container / CI box without a user bus returns `null` and falls back
  175. * to spawn, which keeps CI on the existing path.
  176. * - win32 → `schtasks` (the per-user Scheduled Task default; no admin needed).
  177. * - anything else → `null` (spawn fallback).
  178. */
  179. export function detectServiceManager(
  180. env: NodeJS.ProcessEnv = process.env,
  181. platform: NodeJS.Platform = process.platform,
  182. ): ServiceManager | null {
  183. // Explicit opt-out wins everywhere, this is how CI / locked-down hosts force the spawn path.
  184. if ((env[SERVICE_MODE_ENV] ?? "").trim().toLowerCase() === "spawn") return null;
  185. if (platform === "darwin") return "launchd";
  186. if (platform === "win32") return "schtasks";
  187. if (platform === "linux") {
  188. // Require a positive user-systemd signal. `XDG_RUNTIME_DIR` is set by a logind user session
  189. // (where `systemctl --user` works); its absence (a bare CI container) means no user bus, so we
  190. // fall back to spawn rather than registering a unit that can never start.
  191. const xdg = (env.XDG_RUNTIME_DIR ?? "").trim();
  192. if (xdg.length > 0) return "systemd-user";
  193. return null;
  194. }
  195. return null;
  196. }
  197. /**
  198. * Select the native manager for explicit service inspection/control. Unlike
  199. * {@link detectServiceManager}, this deliberately ignores spawn-mode preference and Linux user-bus
  200. * heuristics: explicit lifecycle and destructive removal must inspect the known platform identity
  201. * and fail loudly when that inspection is unavailable.
  202. */
  203. export function serviceManagerForPlatform(platform: NodeJS.Platform = process.platform): ServiceManager | null {
  204. if (platform === "darwin") return "launchd";
  205. if (platform === "win32") return "schtasks";
  206. if (platform === "linux") return "systemd-user";
  207. return null;
  208. }
  209. /**
  210. * The injected shell-out seam (test discipline). A `register`/`unregister`/`control` runs the
  211. * service manager through this; a unit test passes a recorder so the exact argv is asserted WITHOUT
  212. * executing. The default ({@link defaultServiceRunner}) shells out fixed-argv via `execFileSync`.
  213. *
  214. * `run` returns the captured stdout (trimmed) on success and THROWS on a non-zero exit / missing
  215. * binary, the caller (`runtime.ts`) treats a throw as "service path unavailable" and falls back.
  216. */
  217. export interface ServiceRunner {
  218. /** Run `cmd` with fixed `args`. Returns trimmed stdout. Throws on failure / missing binary. */
  219. run(cmd: string, args: readonly string[]): string;
  220. /**
  221. * Write a unit/plist/task file to `path` with `contents`. `encoding` defaults to `utf8`
  222. * (launchd/systemd); the Windows task XML is written as `utf16le` (schtasks `/XML` requires a
  223. * UTF-16 file with a BOM, else it fails with "unable to switch the encoding"). Throws on failure.
  224. */
  225. writeFile(path: string, contents: string, encoding?: BufferEncoding): void;
  226. /** Remove a unit/plist file at `path`. Never throws (a missing file is success). */
  227. removeFile(path: string): void;
  228. /** True iff `path` exists (used to report service status for file-based managers). */
  229. fileExists(path: string): boolean;
  230. }
  231. /**
  232. * The production {@link ServiceRunner}: fixed-argv `execFileSync` + `node:fs`, loaded lazily through
  233. * `createRequire` so this module stays import-light and the bundle's static-analysis (the OpenClaw
  234. * ClawHub scanner forbids bare `spawn`/`execFileSync`) never sees a top-level child_process import.
  235. * Never a shell string, every call is `(cmd, args[])`, so a metacharacter in a path can never be
  236. * re-parsed by a shell.
  237. */
  238. export function defaultServiceRunner(): ServiceRunner {
  239. const require = createRequire(import.meta.url);
  240. // Lazy, indirected requires (ClawHub-clean): resolved at call time, never a top-level import.
  241. const cp = require("node:child_process") as typeof import("node:child_process");
  242. const fs = require("node:fs") as typeof import("node:fs");
  243. return {
  244. run(cmd: string, args: readonly string[]): string {
  245. const out = cp.execFileSync(cmd, [...args], {
  246. encoding: "utf8",
  247. stdio: ["ignore", "pipe", "pipe"],
  248. timeout: 15_000,
  249. windowsHide: true,
  250. });
  251. return typeof out === "string" ? out.trim() : "";
  252. },
  253. writeFile(path: string, contents: string, encoding: BufferEncoding = "utf8"): void {
  254. fs.mkdirSync(join(path, ".."), { recursive: true });
  255. fs.writeFileSync(path, contents, { encoding });
  256. },
  257. removeFile(path: string): void {
  258. try {
  259. fs.rmSync(path, { force: true });
  260. } catch {
  261. // A missing unit on unregister is success, the goal (no unit) already holds.
  262. }
  263. },
  264. fileExists(path: string): boolean {
  265. try {
  266. return fs.existsSync(path);
  267. } catch {
  268. return false;
  269. }
  270. },
  271. };
  272. }
  273. /**
  274. * The inputs the unit/plist/XML templates are rendered from. RESOLVED BY THE CALLER (`runtime.ts`)
  275. * and threaded in, this module never resolves the workspace or the entry on its own.
  276. */
  277. export interface ServiceSpec {
  278. /** Absolute path to the Node binary the service launches (`process.execPath` in production). */
  279. readonly nodePath: string;
  280. /** Absolute path to the bundled `daemon/index.js` the service runs. */
  281. readonly entry: string;
  282. /** Extra Node flags prepended to the entry (e.g. `--experimental-sqlite`). */
  283. readonly nodeFlags: readonly string[];
  284. /**
  285. * The guaranteed-WRITABLE workspace pinned into the unit's working-dir AND `HONEYCOMB_WORKSPACE`
  286. * (AC-064h.4). Resolved by `runtime.ts` (which owns the create-write-unlink probe); never
  287. * `C:\WINDOWS\system32`. Both are pinned as defense-in-depth (the daemon resolves its `.secrets/`
  288. * root from `HONEYCOMB_WORKSPACE ?? cwd`, so either alone would suffice).
  289. */
  290. readonly workspace: string;
  291. /** The home dir the file-based unit paths resolve under. Defaults to `os.homedir()`. */
  292. readonly home?: string;
  293. /**
  294. * The RESOLVED fleet root (ADR-0003 / PRD-072d) pinned into the unit's environment as
  295. * `APIARY_HOME`, beside `HONEYCOMB_WORKSPACE`. The caller (`src/cli/runtime.ts`) resolves it once
  296. * at registration time (`resolveFleetRoot`), so a service-launched daemon resolves the SAME root
  297. * the installing CLI resolved, including the Windows LocalSystem opt-in (which resolves
  298. * `os.homedir()` to `System32\config\systemprofile` without the pin). Pin-always: the caller sets
  299. * it unconditionally for determinism; when absent the renderers simply omit the env line.
  300. */
  301. readonly fleetRoot?: string;
  302. /** Authoritative product-owned service log consumed by `honeycomb logs`. */
  303. readonly logPath?: string;
  304. }
  305. /**
  306. * Assert that a resolved unit/plist path stays CONTAINED within `home`, then return it
  307. * (PRD-064 Aikido SAST hardening). The `home` here is `spec.home ?? os.homedir()` - a
  308. * caller-supplied, variable-derived base - so the unit-path builders below thread it
  309. * through this validator before the path ever reaches a file syscall (`writeFileSync` /
  310. * `rmSync` / `existsSync` in {@link defaultServiceRunner}). The fixed sub-segments are
  311. * literals we control, so the ONLY way the result escapes `home` is a hostile `home`,
  312. * which we reject. Built-ins only (node:path). Mirrors doctor/src/safe-path.ts.
  313. */
  314. function containedUnitPath(home: string, segments: readonly string[]): string {
  315. const resolvedHome = normalize(resolve(home));
  316. const candidate = normalize(resolve(resolvedHome, ...segments));
  317. const homeWithSep = resolvedHome.endsWith(sep) ? resolvedHome : resolvedHome + sep;
  318. if (candidate !== resolvedHome && !candidate.startsWith(homeWithSep)) {
  319. // A throw is this module's documented "service path unavailable" signal; runtime.ts
  320. // falls back to the safe detached spawn rather than touching an out-of-home unit file.
  321. throw new Error("resolved service unit path escapes the home dir");
  322. }
  323. return candidate;
  324. }
  325. /** Resolve the launchd LaunchAgent plist path (`~/Library/LaunchAgents/<label>.plist`). */
  326. export function launchdPlistPath(home: string): string {
  327. return containedUnitPath(home, ["Library", "LaunchAgents", `${SERVICE_LABEL}.plist`]);
  328. }
  329. /** Resolve the systemd --user unit path (`~/.config/systemd/user/honeycomb.service`). */
  330. export function systemdUnitPath(home: string): string {
  331. return containedUnitPath(home, [".config", "systemd", "user", SERVICE_SYSTEMD_UNIT]);
  332. }
  333. /** The PRE-decision-#32 LaunchAgent plist path, removed on register (migration path). */
  334. export function legacyLaunchdPlistPath(home: string): string {
  335. return containedUnitPath(home, ["Library", "LaunchAgents", `${LEGACY_SERVICE_LABEL}.plist`]);
  336. }
  337. /** The PRE-decision-#32 systemd unit path, removed on register (migration path). */
  338. export function legacySystemdUnitPath(home: string): string {
  339. return containedUnitPath(home, [".config", "systemd", "user", LEGACY_SERVICE_SYSTEMD_UNIT]);
  340. }
  341. /**
  342. * XML-escape a value bound into XML text (a launchd plist `<string>`, or the Windows task XML's
  343. * `<Command>`/`<Arguments>`/`<UserId>`). Escapes all five predefined XML entities (`& < > " '`); the
  344. * apostrophe matters on Windows because a path such as `C:\Users\O'Brien\...` passes the cmd-safety
  345. * guard (`'` is not a cmd metacharacter) yet still has to be escaped once it becomes XML text.
  346. */
  347. function xmlEscape(value: string): string {
  348. return value
  349. .replace(/&/g, "&amp;")
  350. .replace(/</g, "&lt;")
  351. .replace(/>/g, "&gt;")
  352. .replace(/"/g, "&quot;")
  353. .replace(/'/g, "&apos;");
  354. }
  355. /**
  356. * Render the launchd LaunchAgent plist (AC-064h.4: pins `WorkingDirectory` + the `HONEYCOMB_WORKSPACE`
  357. * env to the writable workspace; `KeepAlive`+`RunAtLoad` make launchd the liveness floor ,
  358. * restart-on-crash + start-on-login).
  359. */
  360. export function renderLaunchdPlist(spec: ServiceSpec): string {
  361. const argv = [spec.nodePath, ...spec.nodeFlags, spec.entry];
  362. const argvXml = argv.map((a) => `\t\t<string>${xmlEscape(a)}</string>`).join("\n");
  363. return `<?xml version="1.0" encoding="UTF-8"?>
  364. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  365. <plist version="1.0">
  366. <dict>
  367. <key>Label</key>
  368. <string>${SERVICE_LABEL}</string>
  369. <key>ProgramArguments</key>
  370. <array>
  371. ${argvXml}
  372. </array>
  373. <key>WorkingDirectory</key>
  374. <string>${xmlEscape(spec.workspace)}</string>
  375. <key>EnvironmentVariables</key>
  376. <dict>
  377. <key>HONEYCOMB_WORKSPACE</key>
  378. <string>${xmlEscape(spec.workspace)}</string>${
  379. spec.fleetRoot !== undefined
  380. ? `\n\t\t<key>${APIARY_HOME_ENV}</key>\n\t\t<string>${xmlEscape(spec.fleetRoot)}</string>`
  381. : ""
  382. }
  383. </dict>
  384. <key>RunAtLoad</key>
  385. <true/>
  386. <key>KeepAlive</key>
  387. <true/>
  388. <key>ProcessType</key>
  389. <string>Background</string>
  390. ${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>` : ""}
  391. </dict>
  392. </plist>
  393. `;
  394. }
  395. /**
  396. * Render the systemd --user unit (AC-064h.4: `WorkingDirectory` + `Environment=HONEYCOMB_WORKSPACE`
  397. * pin the writable workspace; `Restart=always`+`RestartSec` + the `[Install] WantedBy` make systemd
  398. * the liveness floor, restart-on-crash + start-on-login when the unit is `enable`d).
  399. */
  400. export function renderSystemdUnit(spec: ServiceSpec): string {
  401. // systemd parses these fields itself (there is no shell), including `%` specifiers and `$VAR`
  402. // expansion in ExecStart. Reject those expansion carriers and quote/escape every variable token so
  403. // an env-derived workspace/fleet root/log path cannot inject a unit directive or alter argv.
  404. const systemdToken = (value: string): string => {
  405. if (/[\u0000-\u001f\u007f%$]/u.test(value)) throw new Error("unsafe character in systemd service value");
  406. return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
  407. };
  408. const execStart = [spec.nodePath, ...spec.nodeFlags, spec.entry].map(systemdToken).join(" ");
  409. const apiaryHomeLine =
  410. spec.fleetRoot !== undefined ? `\nEnvironment=${systemdToken(`${APIARY_HOME_ENV}=${spec.fleetRoot}`)}` : "";
  411. const logLines =
  412. spec.logPath !== undefined
  413. ? `\nStandardOutput=${systemdToken(`append:${spec.logPath}`)}\nStandardError=${systemdToken(`append:${spec.logPath}`)}`
  414. : "";
  415. return `[Unit]
  416. Description=Honeycomb primary daemon (127.0.0.1:3850)
  417. After=network.target
  418. [Service]
  419. Type=simple
  420. ExecStart=${execStart}
  421. WorkingDirectory=${systemdToken(spec.workspace)}
  422. Environment=${systemdToken(`HONEYCOMB_WORKSPACE=${spec.workspace}`)}${apiaryHomeLine}
  423. Restart=always
  424. RestartSec=5${logLines}
  425. [Install]
  426. WantedBy=default.target
  427. `;
  428. }
  429. /**
  430. * Reject a path bound into the Windows task command string if it carries a cmd.exe
  431. * metacharacter (PRD-064h security hardening). Even though the task is now registered from a staged
  432. * XML definition (not an inline `/TR`), the action's `<Arguments>` still embeds a `cmd /c "..."`
  433. * string that cmd.exe RE-PARSES at every logon. `spec.workspace` is derived from
  434. * `HONEYCOMB_WORKSPACE` / the CLI cwd (src/cli/runtime.ts resolveDaemonWorkspace), and `spec.entry`
  435. * can be overridden via `HONEYCOMB_DAEMON_ENTRY`, so a path containing `& | < > ^ " % !` (or a CR/LF)
  436. * would break out of the intended command and execute arbitrary commands under the user's login
  437. * session on every boot. We THROW on such a path; a throw is this module's documented "service path
  438. * unavailable" signal, so runtime.ts falls back to the safe detached spawn (which passes the
  439. * workspace as a real argv/env value, never a shell string) rather than registering a poisoned task.
  440. * Legitimate Windows paths never contain these characters. XML escaping ({@link xmlEscape}) is a
  441. * SECOND, independent layer applied after this guard because the values also become XML text.
  442. */
  443. function assertCmdSafe(value: string): void {
  444. // cmd.exe command separators / redirection / escape / env-expansion / quote, plus CR/LF.
  445. // `!` is a metacharacter ONLY under delayed expansion, but the scheduled-task action now runs
  446. // `cmd /v:on` (renderScheduledTaskXml, for the relaunch loop's `!errorlevel!` read), which makes
  447. // `!VAR!` expand at execution time on the SAME command line these paths are embedded in. An
  448. // unfiltered `!` in a poisoned HONEYCOMB_WORKSPACE / HONEYCOMB_DAEMON_ENTRY / APIARY_HOME would
  449. // therefore expand an arbitrary env var into the command (and, if that var's value carries a
  450. // separator, re-introduce a metacharacter AFTER this guard ran) — a delayed-expansion injection.
  451. // Reject it here; legitimate Windows paths never contain `!`.
  452. if (/[&|<>^"%!\r\n]/.test(value)) {
  453. throw new Error("unsafe character in service path; refusing to build the schtasks task command");
  454. }
  455. }
  456. /** The pattern a `whoami /user` SID must match before it is trusted as the task principal UserId. */
  457. const WINDOWS_SID_PATTERN = /^S-1-[0-9]+(-[0-9]+)+$/;
  458. /** The staged task-definition XML file name written under honeycomb's state dir. */
  459. export const STAGED_TASK_XML_NAME = "honeycomb-task.xml" as const;
  460. /** Resolve `<SystemRoot>\System32` (the fixed, trusted dir the whoami/conhost binaries live in). */
  461. function windowsSystem32Dir(env: NodeJS.ProcessEnv): string {
  462. const systemRoot = (env.SystemRoot ?? env.SYSTEMROOT ?? "").trim();
  463. // win32.join, not join: these are Windows paths by definition, and the CI quality gate
  464. // also runs this code on POSIX hosts where the generic join would emit forward slashes.
  465. return win32.join(systemRoot.length > 0 ? systemRoot : "C:\\Windows", "System32");
  466. }
  467. /** The absolute `conhost.exe` path (`--headless` runs the action with NO visible console window). */
  468. function conhostPath(env: NodeJS.ProcessEnv = process.env): string {
  469. return win32.join(windowsSystem32Dir(env), "conhost.exe");
  470. }
  471. /**
  472. * Parse the SID out of `whoami /user /fo csv /nh` output. The row is
  473. * `"DOMAIN\\user","S-1-5-21-..."`; we take the LAST comma-separated field, strip the surrounding
  474. * quotes, and return it only when it matches {@link WINDOWS_SID_PATTERN}. Returns `null` on any
  475. * shape we do not recognise (the caller then falls back to `DOMAIN\\USER`).
  476. */
  477. function parseWhoamiSid(csv: string): string | null {
  478. const line = csv.trim().split(/\r?\n/).pop() ?? "";
  479. const lastField = line.split(",").pop() ?? "";
  480. const candidate = lastField.trim().replace(/^"+/, "").replace(/"+$/, "").trim();
  481. return WINDOWS_SID_PATTERN.test(candidate) ? candidate : null;
  482. }
  483. /**
  484. * Resolve the current user's identity for the task's `<LogonTrigger><UserId>` AND its
  485. * `<Principal id="Author"><UserId>` (PRD-064h Windows Administrator-Protection fix). Windows 11 25H2
  486. * with Administrator Protection refuses an UNSCOPED any-user `/SC ONLOGON` trigger without
  487. * elevation; scoping BOTH the trigger and the principal to the current user's SID is the proven,
  488. * non-elevated recipe.
  489. *
  490. * Resolution:
  491. * 1. Fixed-argv `<SystemRoot>\System32\whoami.exe /user /fo csv /nh` through the injected runner
  492. * (never bare `whoami`, never a shell). A returned SID is regex-validated ⇒ it carries no XML
  493. * metacharacter ⇒ it is safe as raw XML text.
  494. * 2. Fallback to `${USERDOMAIN}\\${USERNAME}` (XML-escaped, since a `DOMAIN\\user` becomes XML
  495. * text and could in principle carry an escapable character).
  496. * 3. If neither resolves, THROW: the documented "service path unavailable" signal, so runtime.ts
  497. * falls back to the safe detached spawn instead of registering an unusable task.
  498. */
  499. export function resolveWindowsUserId(runner: ServiceRunner, env: NodeJS.ProcessEnv = process.env): string {
  500. try {
  501. const out = runner.run(win32.join(windowsSystem32Dir(env), "whoami.exe"), ["/user", "/fo", "csv", "/nh"]);
  502. const sid = parseWhoamiSid(out);
  503. if (sid !== null) return sid;
  504. } catch {
  505. // whoami missing / errored, fall through to the DOMAIN\USER env fallback below.
  506. }
  507. const domain = (env.USERDOMAIN ?? "").trim();
  508. const user = (env.USERNAME ?? "").trim();
  509. if (user.length > 0) return xmlEscape(domain.length > 0 ? `${domain}\\${user}` : user);
  510. throw new Error("cannot resolve the current Windows user SID/account for the scheduled-task principal");
  511. }
  512. /**
  513. * Resolve the staged task-XML path under honeycomb's state dir (`<fleetRoot>/honeycomb/`), validated
  514. * to stay CONTAINED within that dir (the same hardening {@link containedUnitPath} applies to the
  515. * launchd/systemd unit files). `spec.fleetRoot` is the caller-resolved root; when absent we fall
  516. * back to {@link honeycombStateDir}. A throw is the "service path unavailable" fallback signal.
  517. */
  518. export function stagedTaskXmlPath(spec: ServiceSpec): string {
  519. const stateDir = spec.fleetRoot !== undefined ? join(spec.fleetRoot, PRODUCT_SLUG) : honeycombStateDir();
  520. const resolvedBase = normalize(resolve(stateDir));
  521. const candidate = normalize(resolve(resolvedBase, STAGED_TASK_XML_NAME));
  522. const baseWithSep = resolvedBase.endsWith(sep) ? resolvedBase : resolvedBase + sep;
  523. if (candidate !== resolvedBase && !candidate.startsWith(baseWithSep)) {
  524. throw new Error("resolved staged task XML path escapes the honeycomb state dir");
  525. }
  526. return candidate;
  527. }
  528. /**
  529. * Render the per-user Scheduled Task definition XML (Task schema 1.2), the SID-scoped replacement for
  530. * the legacy inline `/TR` command (PRD-064h Windows Administrator-Protection fix). The `userId`
  531. * (from {@link resolveWindowsUserId}) scopes BOTH the `<LogonTrigger>` and the `<Principal>` to the
  532. * current user, which is what lets a non-elevated `schtasks /Create /XML` succeed on Windows 11 25H2.
  533. *
  534. * The action runs `conhost.exe --headless cmd /v:on /c "..."` so the task fires with NO visible
  535. * console window. The inner `cmd` does `cd /d <workspace>` + `set HONEYCOMB_WORKSPACE=<workspace>`
  536. * (+ optional `set APIARY_HOME=<root>`, PRD-072d) then runs `node <flags> <entry>` INSIDE A BOUNDED
  537. * RELAUNCH LOOP. Every embedded path passes {@link assertCmdSafe} (the value is re-parsed by cmd.exe)
  538. * AND is XML-escaped (the value is XML text).
  539. *
  540. * ── Why the relaunch loop (the auto-restart fix) ─────────────────────────────
  541. * `conhost.exe --headless` ALWAYS reports exit code 0 to Task Scheduler regardless of the child's
  542. * real exit code (empirically verified). So the task's `<RestartOnFailure>` — which fires ONLY on a
  543. * NON-ZERO Last Result — can NEVER observe a daemon crash and never restarts it: the task sits Ready
  544. * with Last Result 0 and the daemon stays dead. The restart therefore must live INSIDE the cmd, where
  545. * the real errorlevel is visible: `for /l %i in (1,1,60) do (node … & if !errorlevel! equ 0 (exit /b 0)
  546. * & timeout /t 5 …)` relaunches node on a NON-ZERO exit (a crash / the daemon's `uncaughtException`
  547. * net exiting 1) with a 5s backoff, and BREAKS on a clean exit 0 so a deliberate `daemon stop` is not
  548. * fought. `/v:on` enables the delayed `!errorlevel!` read. This is the conhost-independent equivalent
  549. * of systemd `Restart=on-failure` / launchd `KeepAlive`. `StartWhenAvailable`, `ExecutionTimeLimit
  550. * PT0S`, and the task's own `RestartOnFailure` (PT1M x 999) remain as the liveness floor / belt-and-
  551. * suspenders for the rare case the conhost host process itself dies non-zero.
  552. */
  553. export function renderScheduledTaskXml(spec: ServiceSpec, userId: string, conhost: string = conhostPath()): string {
  554. // SECURITY: the `<Arguments>` embeds a cmd.exe-parsed string, so refuse any path with a cmd
  555. // metacharacter before it is embedded (a poisoned HONEYCOMB_WORKSPACE / cwd / HONEYCOMB_DAEMON_ENTRY
  556. // / APIARY_HOME must never inject a command). A throw makes runtime.ts fall back to the safe spawn.
  557. assertCmdSafe(spec.workspace);
  558. assertCmdSafe(spec.nodePath);
  559. assertCmdSafe(spec.entry);
  560. if (spec.fleetRoot !== undefined) assertCmdSafe(spec.fleetRoot);
  561. if (spec.logPath !== undefined) assertCmdSafe(spec.logPath);
  562. const nodeFlags = spec.nodeFlags.length > 0 ? `${spec.nodeFlags.join(" ")} ` : "";
  563. // cmd's `set VAR=value && next` captures EVERYTHING up to `&&`, INCLUDING the space before it, into
  564. // VAR — so an unquoted `set APIARY_HOME=<root> && ...` pins a TRAILING SPACE onto the value, and the
  565. // daemon then resolves a divergent `<root> /honeycomb` state dir that doctor's registry can never
  566. // find (fleet telemetry reads as "missing" ⇒ the dashboard shows honeycomb degraded forever). The
  567. // fix is the canonical cmd idiom: quote the whole `VAR=value` assignment so the space before `&&`
  568. // stays OUTSIDE the value. `set "VAR=C:\...\path with spaces"` also preserves spaces WITHIN a path.
  569. const apiaryHomeSet = spec.fleetRoot !== undefined ? `set "${APIARY_HOME_ENV}=${spec.fleetRoot}" && ` : "";
  570. // The inner command: cd + env pin + node entry, WRAPPED IN A CONHOST-INDEPENDENT RELAUNCH LOOP.
  571. //
  572. // WHY THE LOOP (the auto-restart fix) — the task's Action is `conhost.exe --headless cmd /c ...`,
  573. // and `conhost --headless` ALWAYS reports exit code 0 to Task Scheduler regardless of the child's
  574. // real code (empirically verified: `exit 7` under conhost --headless → Last Result 0). So the
  575. // task's `<RestartOnFailure>` — which fires ONLY on a NON-ZERO Last Result — can NEVER see a crash
  576. // and never restarts the daemon. The fix must live INSIDE the cmd (where the real errorlevel is
  577. // visible), independent of the code conhost forwards.
  578. //
  579. // The loop re-launches node whenever it exits with a NON-ZERO errorlevel (a crash / the daemon's
  580. // `uncaughtException` net exiting 1), after a short backoff, up to a bounded count. A CLEAN exit
  581. // (errorlevel 0 — `honeycomb daemon stop`, a graceful SIGTERM) breaks the loop so a deliberate stop
  582. // is NOT fought. The daemon's own single-instance lock + stale-lock reclaim make a relaunch safe.
  583. // `delims=` + delayed expansion (`cmd /v:on`) read `!errorlevel!` inside the loop body. This mirrors
  584. // the OS supervisor contract (systemd `Restart=on-failure`, launchd `KeepAlive`) that conhost breaks
  585. // on Windows. The bound (60) with PT1M framing caps a hard boot-loop; the task's own PT1M x999 stays
  586. // as a belt-and-suspenders for the (rare) case the whole conhost host itself dies non-zero.
  587. // These are intentional cmd operators, not user-derived text. Do NOT caret-escape them: `^>`
  588. // turns redirection into a literal argv token, causing Node to receive `>> <log> 2>&1` and leaving
  589. // the service log unwritten. The surrounding task XML escapes `>`/`&` as markup after this command
  590. // is assembled, while assertCmdSafe above keeps the interpolated log path non-executable.
  591. const redirect = spec.logPath !== undefined ? ` >> "${spec.logPath}" 2>&1` : "";
  592. const nodeInvoke = `"${spec.nodePath}" ${nodeFlags}"${spec.entry}"${redirect}`;
  593. // NOTE `%i` (single, not `%%i`): the loop runs on the cmd COMMAND LINE (conhost passes a command
  594. // string, not a `.bat` file), where `for` uses a single `%`. `%%i` is a batch-file-only escaping and
  595. // errors ("%%i was unexpected at this time") on the command line. The counter var is unreferenced —
  596. // `%i` is only the loop's iteration variable; the body relaunches node until a clean (0) exit.
  597. const relaunchLoop =
  598. `for /l %i in (1,1,60) do (` +
  599. `${nodeInvoke} & ` +
  600. `if !errorlevel! equ 0 (exit /b 0) & ` +
  601. `timeout /t 5 /nobreak >nul` +
  602. `)`;
  603. const innerCmd = `cmd /v:on /c "cd /d "${spec.workspace}" && set "HONEYCOMB_WORKSPACE=${spec.workspace}" && ${apiaryHomeSet}${relaunchLoop}"`;
  604. // conhost --headless <inner> => no console window pops when the task runs (proven probe: Result 0).
  605. const args = xmlEscape(`--headless ${innerCmd}`);
  606. const command = xmlEscape(conhost);
  607. // UTF-16 declaration: the file is staged as utf16le + BOM (schtasks /XML requirement, see the
  608. // register path); the declaration must agree with the on-disk encoding or schtasks rejects it.
  609. return `<?xml version="1.0" encoding="UTF-16"?>
  610. <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  611. <RegistrationInfo>
  612. <Description>Honeycomb primary daemon (127.0.0.1:3850)</Description>
  613. <URI>\\${SERVICE_TASK_NAME}</URI>
  614. </RegistrationInfo>
  615. <Triggers>
  616. <LogonTrigger>
  617. <Enabled>true</Enabled>
  618. <UserId>${userId}</UserId>
  619. </LogonTrigger>
  620. </Triggers>
  621. <Principals>
  622. <Principal id="Author">
  623. <UserId>${userId}</UserId>
  624. <LogonType>InteractiveToken</LogonType>
  625. <RunLevel>LeastPrivilege</RunLevel>
  626. </Principal>
  627. </Principals>
  628. <Settings>
  629. <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
  630. <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
  631. <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
  632. <AllowHardTerminate>true</AllowHardTerminate>
  633. <StartWhenAvailable>true</StartWhenAvailable>
  634. <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
  635. <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
  636. <Enabled>true</Enabled>
  637. <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
  638. <RestartOnFailure>
  639. <Interval>PT1M</Interval>
  640. <Count>999</Count>
  641. </RestartOnFailure>
  642. </Settings>
  643. <Actions Context="Author">
  644. <Exec>
  645. <Command>${command}</Command>
  646. <Arguments>${args}</Arguments>
  647. </Exec>
  648. </Actions>
  649. </Task>
  650. `;
  651. }
  652. /**
  653. * Build the `schtasks /Create` argv that registers the task from the STAGED XML definition
  654. * (`schtasks /Create /XML <file> /TN <name> /F`). This is the non-elevated recipe proven on Windows
  655. * 11 25H2 with Administrator Protection: the SID-scoped XML (see {@link renderScheduledTaskXml})
  656. * replaces the inline `/SC ONLOGON /TR ...` form that Windows now refuses without elevation. `/F` is
  657. * idempotent (overwrites an existing task). Returned as ARGV (not a string) so the injected runner
  658. * shells out fixed-argv and a test asserts the exact tokens.
  659. */
  660. export function buildSchtasksCreateArgs(xmlPath: string): readonly string[] {
  661. return ["/Create", "/XML", xmlPath, "/TN", SERVICE_TASK_NAME, "/F"];
  662. }
  663. /** The outcome of a service operation, what happened, for the CLI to report honestly. */
  664. export interface ServiceOpResult {
  665. /** True when the operation completed via the service manager. */
  666. readonly ok: boolean;
  667. /** The manager that handled it (for logging / status). */
  668. readonly manager: ServiceManager;
  669. }
  670. /** The daemon-service controller the lifecycle drives (register / start / stop / restart / status). */
  671. export interface DaemonServiceController {
  672. readonly manager: ServiceManager;
  673. /** Register the service unit + load/enable it so the manager supervises it (idempotent). */
  674. register(spec: ServiceSpec): ServiceOpResult;
  675. /** Deregister the service. Throws when required process termination cannot be verified. */
  676. unregister(spec: ServiceSpec): ServiceOpResult;
  677. /**
  678. * Best-effort removal of the PRE-decision-#32 LEGACY unit/label for this manager (PRD-003b
  679. * uninstall). The `register` path already deregisters the legacy unit on migration; `uninstall`
  680. * reuses THAT same cleanup so a full removal also strips a lingering legacy unit. Idempotent and
  681. * never throws (a missing legacy unit is success). Optional on the seam (additive); callers guard
  682. * with `?.`.
  683. */
  684. unregisterLegacy?(spec: ServiceSpec): void;
  685. /** Ask the manager to (re)start the daemon, the rung-1 path Doctor calls (AC-064h.5). */
  686. restart(spec: ServiceSpec): ServiceOpResult;
  687. /** Ask the manager to stop the daemon. */
  688. stop(spec: ServiceSpec): ServiceOpResult;
  689. /** True iff the service is currently REGISTERED with the manager (unit present / task exists). */
  690. isRegistered(spec: ServiceSpec): boolean;
  691. /** True iff the manager reports the registered service instance is actively running. */
  692. isRunning?(spec: ServiceSpec): boolean;
  693. }
  694. /** Resolve the home dir for a spec (explicit `home` wins; else `os.homedir()`). */
  695. function specHome(spec: ServiceSpec): string {
  696. return spec.home ?? homedir();
  697. }
  698. /**
  699. * Build the per-OS {@link DaemonServiceController} over an injected {@link ServiceRunner}. The
  700. * controller owns the per-manager argv + file paths; the runner owns the actual shell-out / file IO.
  701. * Every `run` is fixed-argv; a throw from the runner propagates so the caller falls back to spawn.
  702. */
  703. export function createDaemonServiceController(
  704. manager: ServiceManager,
  705. runner: ServiceRunner = defaultServiceRunner(),
  706. ): DaemonServiceController {
  707. if (manager === "launchd") return launchdController(runner);
  708. if (manager === "systemd-user") return systemdController(runner);
  709. return schtasksController(runner);
  710. }
  711. /** launchd LaunchAgent controller (`launchctl bootstrap`/`bootout`/`kickstart`). */
  712. function launchdController(runner: ServiceRunner): DaemonServiceController {
  713. /** The per-user GUI domain target `launchctl` v2 verbs address (`gui/<uid>`). */
  714. function domain(): string {
  715. return `gui/${process.getuid?.() ?? 501}`;
  716. }
  717. /**
  718. * Best-effort boot out + remove the legacy `ai.honeycomb.daemon` agent (decision #32 migration on
  719. * register; PRD-003b legacy cleanup on uninstall). Never throws — a missing legacy agent is success.
  720. */
  721. function cleanupLegacy(spec: ServiceSpec): void {
  722. try {
  723. runner.run("launchctl", ["bootout", `${domain()}/${LEGACY_SERVICE_LABEL}`]);
  724. } catch {
  725. // No legacy agent loaded, fine.
  726. }
  727. try {
  728. runner.removeFile(legacyLaunchdPlistPath(specHome(spec)));
  729. } catch {
  730. // Best-effort cleanup only.
  731. }
  732. }
  733. return {
  734. manager: "launchd",
  735. register(spec): ServiceOpResult {
  736. // Decision #32 migration: strip a lingering legacy agent so a re-run never leaves two agents
  737. // racing over one daemon.
  738. cleanupLegacy(spec);
  739. const path = launchdPlistPath(specHome(spec));
  740. runner.writeFile(path, renderLaunchdPlist(spec));
  741. // bootstrap loads + (RunAtLoad) starts the agent; the `||` re-bootstrap is handled by callers.
  742. runner.run("launchctl", ["bootstrap", domain(), path]);
  743. return { ok: true, manager: "launchd" };
  744. },
  745. unregister(spec): ServiceOpResult {
  746. const path = launchdPlistPath(specHome(spec));
  747. try {
  748. runner.run("launchctl", ["bootout", `${domain()}/${SERVICE_LABEL}`]);
  749. } catch {
  750. // Not loaded is fine, we still remove the unit file below.
  751. }
  752. runner.removeFile(path);
  753. return { ok: true, manager: "launchd" };
  754. },
  755. unregisterLegacy(spec): void {
  756. cleanupLegacy(spec);
  757. },
  758. restart(_spec): ServiceOpResult {
  759. // kickstart -k kills + restarts the service THROUGH launchd (AC-064h.5: no second spawn).
  760. runner.run("launchctl", ["kickstart", "-k", `${domain()}/${SERVICE_LABEL}`]);
  761. return { ok: true, manager: "launchd" };
  762. },
  763. stop(_spec): ServiceOpResult {
  764. // `kill SIGTERM` only terminates the child; KeepAlive=true immediately respawns it.
  765. // `bootout` unloads the LaunchAgent instance, so `honeycomb daemon stop` actually stops.
  766. runner.run("launchctl", ["bootout", `${domain()}/${SERVICE_LABEL}`]);
  767. return { ok: true, manager: "launchd" };
  768. },
  769. isRegistered(spec): boolean {
  770. return runner.fileExists(launchdPlistPath(specHome(spec)));
  771. },
  772. isRunning(): boolean {
  773. try {
  774. return /\bstate = running\b/u.test(runner.run("launchctl", ["print", `${domain()}/${SERVICE_LABEL}`]));
  775. } catch {
  776. return false;
  777. }
  778. },
  779. };
  780. }
  781. /** systemd --user controller (`systemctl --user enable --now`/`disable`/`restart`). */
  782. function systemdController(runner: ServiceRunner): DaemonServiceController {
  783. const unit = SERVICE_SYSTEMD_UNIT;
  784. /**
  785. * Best-effort disable + remove the legacy `ai.honeycomb.daemon.service` unit (decision #32
  786. * migration on register; PRD-003b legacy cleanup on uninstall). Never throws when absent.
  787. */
  788. function cleanupLegacy(spec: ServiceSpec): void {
  789. try {
  790. runner.run("systemctl", ["--user", "disable", "--now", LEGACY_SERVICE_SYSTEMD_UNIT]);
  791. } catch {
  792. // No legacy unit enabled, fine.
  793. }
  794. try {
  795. runner.removeFile(legacySystemdUnitPath(specHome(spec)));
  796. } catch {
  797. // Best-effort cleanup only.
  798. }
  799. }
  800. return {
  801. manager: "systemd-user",
  802. register(spec): ServiceOpResult {
  803. // Decision #32 migration: strip a lingering legacy unit so a re-run never leaves two units
  804. // racing over one daemon.
  805. cleanupLegacy(spec);
  806. const path = systemdUnitPath(specHome(spec));
  807. runner.writeFile(path, renderSystemdUnit(spec));
  808. runner.run("systemctl", ["--user", "daemon-reload"]);
  809. // enable --now installs the boot symlink (start-on-login) AND starts it now.
  810. runner.run("systemctl", ["--user", "enable", "--now", unit]);
  811. return { ok: true, manager: "systemd-user" };
  812. },
  813. unregister(spec): ServiceOpResult {
  814. try {
  815. runner.run("systemctl", ["--user", "disable", "--now", unit]);
  816. } catch {
  817. // Not enabled is fine, we still remove the unit file + reload below.
  818. }
  819. runner.removeFile(systemdUnitPath(specHome(spec)));
  820. try {
  821. runner.run("systemctl", ["--user", "daemon-reload"]);
  822. } catch {
  823. // A reload failure on teardown is non-fatal; the unit file is already gone.
  824. }
  825. return { ok: true, manager: "systemd-user" };
  826. },
  827. unregisterLegacy(spec): void {
  828. cleanupLegacy(spec);
  829. },
  830. restart(_spec): ServiceOpResult {
  831. // restart goes THROUGH systemd (AC-064h.5: no second spawn, no double-bind).
  832. runner.run("systemctl", ["--user", "restart", unit]);
  833. return { ok: true, manager: "systemd-user" };
  834. },
  835. stop(_spec): ServiceOpResult {
  836. runner.run("systemctl", ["--user", "stop", unit]);
  837. return { ok: true, manager: "systemd-user" };
  838. },
  839. isRegistered(spec): boolean {
  840. return runner.fileExists(systemdUnitPath(specHome(spec)));
  841. },
  842. isRunning(): boolean {
  843. try {
  844. runner.run("systemctl", ["--user", "is-active", "--quiet", unit]);
  845. return true;
  846. } catch {
  847. return false;
  848. }
  849. },
  850. };
  851. }
  852. /** Windows per-user Scheduled Task controller (`schtasks /Create`/`/Delete`/`/Run`/`/End`/`/Query`). */
  853. function schtasksController(runner: ServiceRunner): DaemonServiceController {
  854. /**
  855. * Best-effort end + delete the legacy `HoneycombDaemon` task (decision #32 migration on register;
  856. * PRD-003b legacy cleanup on uninstall). Never throws when the legacy task is absent.
  857. */
  858. function cleanupLegacy(): void {
  859. try {
  860. runner.run("schtasks", ["/End", "/TN", LEGACY_SERVICE_TASK_NAME]);
  861. } catch {
  862. // No legacy task running, fine.
  863. }
  864. try {
  865. runner.run("schtasks", ["/Delete", "/TN", LEGACY_SERVICE_TASK_NAME, "/F"]);
  866. } catch {
  867. // No legacy task registered, fine.
  868. }
  869. }
  870. return {
  871. manager: "schtasks",
  872. register(spec): ServiceOpResult {
  873. // Decision #32 migration: strip a lingering legacy task so a re-run never leaves two tasks
  874. // racing over one daemon.
  875. cleanupLegacy();
  876. try {
  877. runner.run("schtasks", ["/End", "/TN", SERVICE_TASK_NAME]);
  878. } catch {
  879. // Already stopped or absent; exact descendant cleanup below still runs.
  880. }
  881. cleanupWindowsDaemon(runner, spec);
  882. // Administrator-Protection fix: scope the task to the current user (SID) and register it from
  883. // a STAGED XML definition. `resolveWindowsUserId` throws when it cannot resolve an identity,
  884. // which propagates as the "service path unavailable" signal (runtime.ts falls back to spawn).
  885. const userId = resolveWindowsUserId(runner);
  886. const xmlPath = stagedTaskXmlPath(spec);
  887. // schtasks /XML wants a UTF-16 file with a BOM; prepend U+FEFF and write utf16le.
  888. runner.writeFile(xmlPath, `\ufeff${renderScheduledTaskXml(spec, userId)}`, "utf16le");
  889. // /Create /XML <file> /F is idempotent (overwrites); the XML's LogonTrigger is the boot floor.
  890. runner.run("schtasks", buildSchtasksCreateArgs(xmlPath));
  891. // Start it immediately so register == running (the install path expects an up daemon).
  892. runner.run("schtasks", ["/Run", "/TN", SERVICE_TASK_NAME]);
  893. return { ok: true, manager: "schtasks" };
  894. },
  895. unregister(spec): ServiceOpResult {
  896. try {
  897. runner.run("schtasks", ["/End", "/TN", SERVICE_TASK_NAME]);
  898. } catch {
  899. // Not running is fine, we still delete the task below.
  900. }
  901. cleanupWindowsDaemon(runner, spec);
  902. try {
  903. runner.run("schtasks", ["/Delete", "/TN", SERVICE_TASK_NAME, "/F"]);
  904. } catch {
  905. // A missing task on delete is success, the goal (no task) already holds.
  906. }
  907. try {
  908. // Best-effort: drop the staged XML definition (a missing file is success).
  909. runner.removeFile(stagedTaskXmlPath(spec));
  910. } catch {
  911. // A containment throw / removal failure never aborts unregister.
  912. }
  913. return { ok: true, manager: "schtasks" };
  914. },
  915. unregisterLegacy(): void {
  916. cleanupLegacy();
  917. },
  918. restart(spec): ServiceOpResult {
  919. // AC-064h.5: stop THEN start the SAME task, no second daemon spawn. The single-instance
  920. // PID/lock guard in the daemon prevents a double-bind even if the old process lingers a beat.
  921. try {
  922. runner.run("schtasks", ["/End", "/TN", SERVICE_TASK_NAME]);
  923. } catch {
  924. // Already stopped is fine; proceed to /Run.
  925. }
  926. cleanupWindowsDaemon(runner, spec);
  927. runner.run("schtasks", ["/Run", "/TN", SERVICE_TASK_NAME]);
  928. return { ok: true, manager: "schtasks" };
  929. },
  930. stop(spec): ServiceOpResult {
  931. try {
  932. runner.run("schtasks", ["/End", "/TN", SERVICE_TASK_NAME]);
  933. } catch {
  934. // A task already in Ready state can still have an orphaned Node descendant.
  935. }
  936. cleanupWindowsDaemon(runner, spec);
  937. return { ok: true, manager: "schtasks" };
  938. },
  939. isRegistered(_spec): boolean {
  940. // A registered task answers `/Query` with exit 0; a missing one throws (non-zero) → false.
  941. try {
  942. runner.run("schtasks", ["/Query", "/TN", SERVICE_TASK_NAME]);
  943. return true;
  944. } catch {
  945. return false;
  946. }
  947. },
  948. isRunning(spec): boolean {
  949. try {
  950. runner.run(WINDOWS_POWERSHELL_PATH, [
  951. "-NoLogo",
  952. "-NoProfile",
  953. "-NonInteractive",
  954. "-ExecutionPolicy",
  955. "Bypass",
  956. "-Command",
  957. WINDOWS_TASK_RUNNING_SCRIPT,
  958. SERVICE_TASK_NAME,
  959. encodedWindowsPath(spec.entry),
  960. encodedWindowsPath(spec.nodePath),
  961. encodedWindowsPath(JSON.stringify(spec.nodeFlags)),
  962. ]);
  963. return true;
  964. } catch {
  965. return false;
  966. }
  967. },
  968. };
  969. }
src/commands/install.ts · Bundled script · 617 lines · 2 findings marked
  1. /**
  2. * `honeycomb install [--ref <code>]` — the bootstrap installer's daemon-up + open-dashboard
  3. * verb (PRD-050a, a-AC-1..6).
  4. *
  5. * ── Why this verb exists (the "open logic lives once" contract, 050a impl-note) ──────────────
  6. * The two shell entrypoints (`scripts/install/install.sh`, `scripts/install/install.ps1`) own
  7. * ONLY the host-bootstrap half: detect/install Node+npm (via fnm + a pinned LTS), pull the
  8. * embedding deps, and `npm i -g @legioncodeinc/honeycomb`. The moment a `honeycomb` bin exists,
  9. * they hand off to THIS verb for everything between "package installed" and "browser open on the
  10. * dashboard." That keeps the daemon-ensure + health-gate + dashboard-open logic in ONE place
  11. * (TypeScript, unit-tested) instead of duplicated across two shell dialects.
  12. *
  13. * ── What it does (composes existing seams — D-2 thin client, never a daemon-core import) ─────
  14. * 1. Ensure the daemon is running, HEALTH-GATED (a-AC-4): reuse {@link ensureDaemonRunning}
  15. * (021b b-AC-3), which is IDEMPOTENT via the 021a PID/lock guard — an already-healthy daemon
  16. * is a no-op, never a second bind of 3850 (a-AC-2). If the daemon never becomes reachable
  17. * within the lifecycle's wait budget, report "daemon didn't start" + how to retry and exit
  18. * NON-ZERO (a-AC-4) — no raw stack.
  19. * 2. Persist onboarding `phase: "installed"` + the effective `ref` through the SHARED onboarding
  20. * module (a-AC-5). The ref is `--ref <code>` when given, else the build-time {@link DEFAULT_REF}
  21. * (`__HONEYCOMB_REF_DEFAULT__`, default "mario"). 050c's login reads this ref; this verb only
  22. * PERSISTS it (the device-flow/referral header is 050c's job, not here). The write is fail-soft
  23. * — an onboarding-write hiccup never fails the install, it only logs a warning.
  24. * 3. Open the dashboard honestly (a-AC-6) — SOLO mode ONLY. When Hive is present (FLEET mode),
  25. * the dashboard IS the Hive portal and Hive's own onboarding owns it, so this verb opens
  26. * NOTHING and prints one plain line saying so (it must never race a second, competing browser
  27. * window against the tab Hive already opened). In SOLO mode it probes the loopback portal URL
  28. * (`http://127.0.0.1:3853/`); if reachable it opens the loopback URL (`http://127.0.0.1:3853/`),
  29. * and if not reachable it opens no browser and prints one plain sentence naming the one command
  30. * to install Hive. The friendly `honeycomb.local` host was dropped: it does not resolve on a
  31. * normal machine, so showing it only confused users — the always-correct loopback URL is used.
  32. *
  33. * ── Idempotency (a-AC-2) ─────────────────────────────────────────────────────────────────────
  34. * Re-running is safe: ensure-running short-circuits on an already-healthy daemon (no start, no
  35. * double-bind), the onboarding write is a stable upsert (phase stays "installed"), and the
  36. * dashboard is simply re-opened.
  37. *
  38. * ── Plain-language errors (parent AC-7) ──────────────────────────────────────────────────────
  39. * Every handled failure is a single readable line on the OUT sink + a non-zero exit. This module
  40. * never throws an uncaught error to the bin: the only failure path (daemon-didn't-start) is a
  41. * clean `{ exitCode: 1 }` with a retry hint.
  42. */
  43. import { execFileSync } from "node:child_process";
  44. import { isAbsolute, resolve } from "node:path";
  45. import type { Credentials } from "../daemon/runtime/auth/contracts.js";
  46. import { loadCredentials } from "../daemon/runtime/auth/credentials-store.js";
  47. import { defaultBrowserOpener, loginWithDeviceFlow } from "../daemon/runtime/auth/deeplake-issuer.js";
  48. import { resolveRuntimeConfig } from "../daemon/runtime/config.js";
  49. import {
  50. DEFAULT_REF,
  51. loadOnboarding,
  52. type OnboardingState,
  53. saveOnboarding,
  54. } from "../daemon/runtime/onboarding/index.js";
  55. import { type RegistryBind, registerHoneycombWithDoctor } from "../daemon/runtime/telemetry/fleet-registry.js";
  56. import { type EmitDeps, emitTelemetry, recordVersionAndEmitUpdated } from "../daemon/runtime/telemetry/index.js";
  57. import { DAEMON_HOST, DAEMON_PORT, HIVE_HOST, HIVE_PORT } from "../shared/constants.js";
  58. import { classifyFleet, type FleetClassification, fleetSignalLine } from "../shared/fleet-detection.js";
  59. import type { CommandResult, OutputSink } from "./contracts.js";
  60. import { type DaemonVerbDeps, ensureDaemonRunning } from "./daemon.js";
  61. import type { ConnectorRunner } from "./local-handlers.js";
  62. /** The portal route hive serves the dashboard SPA at (ADR-0001). */
  63. export const DASHBOARD_PATH = "/" as const;
  64. /**
  65. * The always-correct loopback portal URL (`http://127.0.0.1:3853/`) — the ONLY dashboard URL the
  66. * SOLO install ever opens. The former friendly `honeycomb.local` host was dropped because it does
  67. * not resolve on a normal machine (no hosts/mDNS entry ships), so surfacing it only stranded users
  68. * on a non-resolving address. The daemon binds loopback only; the portal is Hive's, also on loopback.
  69. */
  70. export function loopbackDashboardUrl(): string {
  71. return `http://${HIVE_HOST}:${HIVE_PORT}${DASHBOARD_PATH}`;
  72. }
  73. /** The short timeout budget for the local portal reachability probe. */
  74. const DASHBOARD_PROBE_TIMEOUT_MS = 750;
  75. /**
  76. * One plain sentence for the "portal not installed/running" branch (C-6 claim-honesty fix),
  77. * branched by platform so the named command is actually runnable on the user's shell. The two
  78. * one-liners are the CANONICAL forms the bootstrap installers document: the POSIX pipe from
  79. * `scripts/install/install.sh`, and the PowerShell flag-passing invocation from the
  80. * `scripts/install/install.ps1` header (a bare `irm | iex` pipe cannot see flags, so the
  81. * documented `& { ... } --products=` form is the one that works).
  82. */
  83. export function dashboardPortalNotRunningMessage(platform: NodeJS.Platform = process.platform): string {
  84. const command =
  85. platform === "win32"
  86. ? 'powershell -c "& { $(irm https://get.theapiary.sh/install.ps1) } --products=honeycomb,doctor,hive"'
  87. : "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
  88. return `Dashboard portal is not running; install it with ${command}.`;
  89. }
  90. /** The C-6 fallback sentence for THIS platform (what `runInstallCommand` actually prints). */
  91. export const DASHBOARD_PORTAL_NOT_RUNNING_MESSAGE = dashboardPortalNotRunningMessage();
  92. /**
  93. * The browser-opener seam (a-AC-6). Returns `true` iff it launched the URL. The production default
  94. * is {@link openLocalDashboardUrl}; a test injects a recorder so no real browser launches and the
  95. * loopback URL it opens is asserted by the URLs it was handed.
  96. */
  97. export type DashboardOpener = (url: string) => boolean;
  98. /** The local portal reachability probe seam used before opening a browser tab (C-6). */
  99. export type DashboardProbe = () => Promise<boolean>;
  100. /**
  101. * Open a LOCAL dashboard URL in the OS browser via a fixed-argv `execFileSync` (never a shell) —
  102. * the SAME safe-open discipline as `defaultBrowserOpener` in `deeplake-issuer.ts`, but admitting an
  103. * `http:` LOOPBACK URL (the auth opener is https-only because it opens a server-derived OAuth URL;
  104. * the dashboard URL is a fixed local loopback we construct ourselves, so `http:` is correct and
  105. * safe here).
  106. *
  107. * The guard still REFUSES anything that is not a parsed `http:`/`https:` URL whose host is the
  108. * loopback IP or `localhost` — so a malformed or non-local URL never reaches an OS opener. On open it
  109. * uses `open` (darwin) / `rundll32 url.dll,FileProtocolHandler` (win32, which avoids `cmd /c start`
  110. * re-parsing metacharacters) / `xdg-open` (linux), each fixed-argv. Returns `false` (never throws) on
  111. * a refused URL or a failed launch, so the caller treats a missing browser as non-fatal and prints
  112. * the URL instead.
  113. */
  114. export function openLocalDashboardUrl(url: string): boolean {
  115. let safeUrl: string;
  116. try {
  117. const parsed = new URL(url);
  118. if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
  119. const host = parsed.hostname;
  120. const isLocal = host === DAEMON_HOST || host === "localhost" || host === "::1";
  121. if (!isLocal) return false;
  122. safeUrl = parsed.href;
  123. } catch {
  124. return false;
  125. }
  126. try {
  127. if (process.platform === "darwin") {
  128. execFileSync("open", [safeUrl], { stdio: "ignore", timeout: 5000, windowsHide: true });
  129. } else if (process.platform === "win32") {
  130. execFileSync("rundll32", ["url.dll,FileProtocolHandler", safeUrl], {
  131. stdio: "ignore",
  132. timeout: 5000,
  133. windowsHide: true,
  134. });
  135. } else {
  136. execFileSync("xdg-open", [safeUrl], { stdio: "ignore", timeout: 5000, windowsHide: true });
  137. }
  138. return true;
  139. } catch {
  140. return false;
  141. }
  142. }
  143. /** The deps the `install` verb runs against — the daemon HTTP+lifecycle seams plus injectable IO. */
  144. export interface InstallVerbDeps extends DaemonVerbDeps {
  145. /** The browser opener (a-AC-6). Defaults to {@link openLocalDashboardUrl}; tests inject a recorder. */
  146. readonly openDashboard?: DashboardOpener;
  147. /** The loopback portal probe used before any browser open (C-6). */
  148. readonly probeDashboard?: DashboardProbe;
  149. /**
  150. * Override the onboarding-state directory (tests point this at a temp HOME so the real
  151. * `~/.deeplake/onboarding.json` is never touched). Defaults to the real shared dir.
  152. */
  153. readonly dir?: string;
  154. /** Required onboarding commit seam; production uses the shared onboarding store. */
  155. readonly persistInstalled?: (ref: string, dir: string | undefined, out: OutputSink) => boolean;
  156. /** Required Doctor-registration commit seam; production writes Honeycomb's registry entry. */
  157. readonly registerWithDoctor?: (dir: string | undefined, out: OutputSink) => boolean;
  158. /**
  159. * Telemetry chokepoint seam (PRD-050e). The `honeycomb_installed` event emits through here AFTER
  160. * the user-facing success, fire-and-forget — its injected `fetch`/`dir` let a test assert zero or
  161. * one network call without touching the real PostHog. The onboarding `dir` is threaded in
  162. * automatically; a test may inject `telemetry.fetch` to record/throw. Omit it entirely in production
  163. * — `emitTelemetry`'s defaults apply (and an empty build key makes it a no-op).
  164. */
  165. readonly telemetry?: EmitDeps;
  166. /**
  167. * PRD-003a: the solo-vs-fleet classifier (a-AC-6). Defaults to the real {@link classifyFleet}
  168. * (registry read + 127.0.0.1:3853 probe + npm global read). A test injects a fixed result so the
  169. * fleet-defer vs solo-auto-login branch is driven without touching the network or the npm tree.
  170. */
  171. readonly detectFleet?: () => Promise<FleetClassification>;
  172. /**
  173. * PRD-003a: read the shared `~/.deeplake/credentials.json` (a-AC-3: only auto-login when it is
  174. * ABSENT). Defaults to the real {@link loadCredentials}; a test injects a fake so no real
  175. * credential file is read.
  176. */
  177. readonly loadInstallCredentials?: () => Credentials | null;
  178. /**
  179. * PRD-003a: run the device-flow login on the SOLO auto-login path (a-AC-3 / a-AC-7). Defaults to
  180. * {@link defaultInstallDeviceLogin} (the same `loginWithDeviceFlow` `honeycomb login` runs, with
  181. * the validated browser opener; headless degrades to printing the URL + code and polling). A test
  182. * injects a recorder so no real browser launches and no real device flow runs.
  183. */
  184. readonly runDeviceLogin?: (out: OutputSink) => Promise<boolean>;
  185. /**
  186. * The connector engine `honeycomb setup` uses (the 019a `connectorMain` behind the
  187. * {@link ConnectorRunner} seam). At the END of a successful install this is run BEST-EFFORT to wire
  188. * the harness hooks so the one-line installer no longer leaves them unwired until a manual
  189. * `honeycomb setup` (the observed D5-FAIL-until-manual-run gap). Fires in BOTH solo and fleet modes.
  190. * FAIL-SOFT: a setup failure prints one actionable line and NEVER fails the install. Production binds
  191. * the real runner (`src/cli/connector-runner.ts`); a test injects a fake. When absent (older
  192. * install-only tests) the step is a silent no-op.
  193. */
  194. readonly connector?: ConnectorRunner;
  195. }
  196. /** Parse the effective referral code off the argv tail (`--ref <code>`), else `undefined`. */
  197. export function parseRefArg(argv: readonly string[]): string | undefined {
  198. const i = argv.indexOf("--ref");
  199. if (i !== -1) {
  200. const next = argv[i + 1];
  201. if (next !== undefined && !next.startsWith("--") && next.length > 0) return next;
  202. }
  203. // Also accept `--ref=<code>` for parity with common CLI conventions.
  204. const eq = argv.find((a) => a.startsWith("--ref="));
  205. if (eq !== undefined) {
  206. const value = eq.slice("--ref=".length);
  207. if (value.length > 0) return value;
  208. }
  209. return undefined;
  210. }
  211. /**
  212. * Resolve the effective ref: the `--ref` override when present, else the build-time
  213. * {@link DEFAULT_REF} (`__HONEYCOMB_REF_DEFAULT__`, default "mario"). 050c's login reads this.
  214. */
  215. export function resolveEffectiveRef(argv: readonly string[]): string {
  216. return parseRefArg(argv) ?? DEFAULT_REF;
  217. }
  218. /**
  219. * Parse the installer's `--home <path>` / `--home=<path>` pin (PRD-072d / ADR-0003), the chosen
  220. * fleet-root location. Returns the value, else `undefined` when the flag is absent/empty.
  221. */
  222. export function parseHomeArg(argv: readonly string[]): string | undefined {
  223. const i = argv.indexOf("--home");
  224. if (i !== -1) {
  225. const next = argv[i + 1];
  226. if (next !== undefined && !next.startsWith("--") && next.length > 0) return next;
  227. }
  228. const eq = argv.find((a) => a.startsWith("--home="));
  229. if (eq !== undefined) {
  230. const value = eq.slice("--home=".length);
  231. if (value.length > 0) return value;
  232. }
  233. return undefined;
  234. }
  235. /**
  236. * Record the installer's `--home=` choice by delivering it as `APIARY_HOME` in the process
  237. * environment (fleet ADR Resolved decision: the `--home=` pin is delivered as `APIARY_HOME`; there is
  238. * NO config.json recording step). Setting it here means every downstream fleet-root resolution in
  239. * THIS install run agrees: the doctor registry entry advertises the overridden root, the service
  240. * registration pins `APIARY_HOME` into the unit (PRD-072d), and the spawned daemon inherits it.
  241. * A subsequent re-register with a changed root re-pins the unit. On the Windows LocalSystem enterprise
  242. * opt-in this is where the installer captures the installing user's home so state never lands under
  243. * `System32` (the pinned env wins regardless of the service account).
  244. */
  245. export function applyHomeOverride(argv: readonly string[], env: NodeJS.ProcessEnv = process.env): void {
  246. const home = parseHomeArg(argv);
  247. if (home === undefined) return;
  248. // The resolver honors ABSOLUTE roots only (a relative value would re-anchor state on the service
  249. // manager's cwd). A relative `--home=` is resolved against the INSTALLER's cwd here, at capture
  250. // time, so the user's intent survives and the pinned value is deterministic everywhere downstream.
  251. env.APIARY_HOME = isAbsolute(home) ? home : resolve(home);
  252. }
  253. /**
  254. * Persist onboarding `phase: "installed"` + the effective `ref` through the SHARED onboarding store
  255. * (a-AC-5). An IO error returns false; the caller aborts before registration, ready output, or
  256. * telemetry. Re-running safely retries the same idempotent commit.
  257. */
  258. function writeInstalledMarker(ref: string, dir: string | undefined, out: OutputSink): boolean {
  259. try {
  260. const current: OnboardingState = loadOnboarding(dir);
  261. const next: OnboardingState = { ...current, phase: "installed", ref };
  262. saveOnboarding(next, dir);
  263. return true;
  264. } catch {
  265. // The caller owns the phase-specific error and fail-closed boundary.
  266. void out;
  267. return false;
  268. }
  269. }
  270. /**
  271. * Register (or refresh) honeycomb's entry in doctor's static registry (PRD-071 Contract A /
  272. * AC-1 / AC-071a.1), declaring honeycomb's identity, `/health` URL, and its fleet telemetry SQLite
  273. * path so Doctor knows Honeycomb should exist and where to poll it. A write error returns false;
  274. * the caller aborts before ready output or telemetry. Re-running replaces the entry in place.
  275. */
  276. /**
  277. * Resolve the daemon bind (host/port) the registry entry's `healthUrl` should advertise, from the
  278. * SAME runtime-config resolution the daemon itself binds with (`HONEYCOMB_PORT` / `HONEYCOMB_HOST`
  279. * / `HONEYCOMB_BIND`), so a non-default bind advertises the right probe URL. A wildcard listen
  280. * address (0.0.0.0 / ::) maps to the loopback host: that is the address doctor (same machine)
  281. * can actually reach a wildcard-bound daemon on. FAIL-SOFT: an invalid env value falls back to the
  282. * shared default constants rather than failing the install.
  283. */
  284. function resolveRegistryBind(): RegistryBind | undefined {
  285. try {
  286. const config = resolveRuntimeConfig();
  287. const host = config.host === "0.0.0.0" || config.host === "::" ? DAEMON_HOST : config.host;
  288. return { host, port: config.port };
  289. } catch {
  290. return undefined;
  291. }
  292. }
  293. function writeDoctorRegistryEntry(dir: string | undefined, out: OutputSink): boolean {
  294. try {
  295. const bind = resolveRegistryBind();
  296. registerHoneycombWithDoctor({
  297. ...(dir !== undefined ? { homeDir: dir } : {}),
  298. ...(bind !== undefined ? { bind } : {}),
  299. });
  300. return true;
  301. } catch {
  302. void out;
  303. return false;
  304. }
  305. }
  306. /**
  307. * Probe the loopback dashboard portal (`127.0.0.1:3853`) with a short timeout. Returns `true` when
  308. * the portal responds at all; status code does not matter because any HTTP response proves the
  309. * portal process is running and reachable. `timeoutMs` is injectable so a unit test can prove the
  310. * abort path in milliseconds instead of waiting out the production budget.
  311. */
  312. export async function probeLoopbackDashboard(timeoutMs: number = DASHBOARD_PROBE_TIMEOUT_MS): Promise<boolean> {
  313. const controller = new AbortController();
  314. const timer = setTimeout(() => controller.abort(), timeoutMs);
  315. if (typeof timer.unref === "function") timer.unref();
  316. try {
  317. await fetch(loopbackDashboardUrl(), { method: "GET", signal: controller.signal });
  318. return true;
  319. } catch {
  320. return false;
  321. } finally {
  322. clearTimeout(timer);
  323. }
  324. }
  325. /**
  326. * Open the SOLO dashboard at the always-correct loopback URL (`http://127.0.0.1:3853/`). The former
  327. * friendly `honeycomb.local` first-attempt was dropped (it does not resolve on a normal machine, so a
  328. * user was shown a non-resolving address). ALWAYS prints the URL so a headless/no-browser host still
  329. * learns where the dashboard lives; a failed launch is non-fatal — the run still succeeds. This is
  330. * called ONLY in SOLO mode; in FLEET mode Hive's onboarding owns the portal and this never runs.
  331. */
  332. function openSoloDashboard(opener: DashboardOpener, out: OutputSink): void {
  333. const loopback = loopbackDashboardUrl();
  334. const opened = opener(loopback);
  335. out(
  336. opened ? `→ opening dashboard at ${loopback}…` : `→ dashboard is ready at ${loopback} (open it in your browser).`,
  337. );
  338. }
  339. /**
  340. * Report how the now-running daemon is supervised (PRD-064h, AC-064h.6 surfaced at install). A pure,
  341. * FAIL-SOFT read of `lifecycle.status()`: when the daemon runs as a registered OS service it prints
  342. * the supervising manager (the liveness floor); otherwise it notes the detached-spawn fallback. It
  343. * NEVER changes the install result: no lifecycle seam, or a status read that throws, simply skips
  344. * the line. The daemon was already registered+started by `ensureDaemonRunning` → `lifecycle.start()`
  345. * (service-preferred), so this only narrates the outcome.
  346. */
  347. async function reportDaemonSupervision(deps: InstallVerbDeps, out: OutputSink): Promise<void> {
  348. if (deps.lifecycle === undefined) return;
  349. try {
  350. const status = await deps.lifecycle.status();
  351. if (status.serviceManager !== undefined) {
  352. out(`✓ daemon registered as an OS service (${status.serviceManager}): it restarts on crash and starts on boot.`);
  353. } else {
  354. out("note: daemon running as a detached process (OS service registration unavailable on this host).");
  355. }
  356. } catch {
  357. // A status read must never affect the install outcome: swallow and continue.
  358. }
  359. }
  360. /**
  361. * The production SOLO auto-login (PRD-003a a-AC-3 / a-AC-7): run the SAME device flow `honeycomb
  362. * login` runs (`loginWithDeviceFlow`) with the validated OS browser opener. It PRINTS the
  363. * verification URL + user code through the reporter BEFORE any open attempt, and on a headless host
  364. * the opener simply returns false (never throws) and the flow polls to completion — so a no-browser
  365. * environment degrades to "print + poll" rather than hanging or crashing (a-AC-7). Resolves `true`
  366. * on a persisted credential; `loginWithDeviceFlow` throws on failure, which the caller reports.
  367. */
  368. async function defaultInstallDeviceLogin(out: OutputSink): Promise<boolean> {
  369. await loginWithDeviceFlow({
  370. reporter: { prompt: (line: string): void => out(line) },
  371. openBrowser: defaultBrowserOpener,
  372. });
  373. return true;
  374. }
  375. /**
  376. * The PRD-003a install-time login decision (a-AC-1 / a-AC-3 / a-AC-6 / a-AC-7), run from the install
  377. * path ONLY (never daemon boot). Classifies solo vs fleet, LOGS which signals fired (a-AC-6), then:
  378. *
  379. * - FLEET (Hive detected): print ONE line that login is deferred to Hive onboarding and initiate
  380. * NOTHING — no browser popup, no prompt (a-AC-1). The daemon sits degraded on /health until
  381. * Hive-side login writes the shared credential; the 15s SELECT-1 health probe flips it healthy
  382. * with no restart (a-AC-2).
  383. * - SOLO with credentials already present: no popup — say the user is already signed in (a-AC-3).
  384. * - SOLO with NO credentials: auto-open the device-flow popup (a-AC-3); headless degrades to
  385. * printing the URL + code and polling (a-AC-7).
  386. *
  387. * Fail-soft (parent AC-9): this NEVER changes the install exit code. A detection error DEFERS
  388. * (suppressing a popup wrongly is cheap; opening one wrongly is the bug), and a login failure prints
  389. * a plain-language "run `honeycomb login`" hint rather than aborting the install.
  390. */
  391. async function runInstallLoginStep(deps: InstallVerbDeps, out: OutputSink): Promise<FleetClassification> {
  392. let classification: FleetClassification;
  393. try {
  394. classification = await (deps.detectFleet ?? (() => classifyFleet()))();
  395. } catch {
  396. // Detection blew up: DEFER (treat as fleet) so we never pop a wrong browser NOR a competing
  397. // dashboard window. Actionable line, and the returned fleet classification gates the dashboard
  398. // step to "open nothing" too.
  399. out("note: could not determine solo vs fleet mode; deferring login (run `honeycomb login` to sign in).");
  400. return {
  401. mode: "fleet",
  402. signals: { registryHiveEntry: false, hivePortAnswering: false, hiveNpmGlobal: false },
  403. firedSignals: [],
  404. };
  405. }
  406. // a-AC-6: the classification's inputs (which signals fired) are visible in the install output.
  407. out(fleetSignalLine(classification));
  408. if (classification.mode === "fleet") {
  409. // a-AC-1: defer ALL login initiation to Hive; never open a browser or prompt.
  410. out("→ login is deferred to Hive onboarding (Hive detected); Honeycomb connects once Hive signs in.");
  411. return classification;
  412. }
  413. // SOLO. Only auto-open when the shared credential is absent (a-AC-3).
  414. const creds = (deps.loadInstallCredentials ?? loadCredentials)();
  415. if (creds !== null) {
  416. out("✓ already signed in (existing credentials found); no browser opened.");
  417. return classification;
  418. }
  419. out("→ no credentials found; opening sign-in…");
  420. try {
  421. const ok = await (deps.runDeviceLogin ?? defaultInstallDeviceLogin)(out);
  422. out(ok ? "✓ signed in." : "note: sign-in did not complete; run `honeycomb login` to finish.");
  423. } catch (err) {
  424. // a-AC-9: a login failure is a plain-language, actionable line — never a raw stack, never a fail.
  425. const reason = err instanceof Error ? err.message : "sign-in failed";
  426. out(`note: automatic sign-in could not complete (${reason}); run \`honeycomb login\` to sign in.`);
  427. }
  428. return classification;
  429. }
  430. /**
  431. * Wire the harness hooks BEST-EFFORT at the end of a successful install (the D5-until-manual-setup
  432. * fix). Runs the SAME connector engine `honeycomb setup` uses (019a `connectorMain` via the
  433. * {@link ConnectorRunner} seam), in BOTH solo and fleet modes. FAIL-SOFT: a missing seam is a silent
  434. * no-op; a setup THROW prints one actionable line and NEVER changes the install exit code. Prints what
  435. * got wired (or that nothing supported was detected) so the user sees the outcome.
  436. */
  437. async function runInstallSetupStep(deps: InstallVerbDeps, out: OutputSink): Promise<void> {
  438. if (deps.connector === undefined) return;
  439. try {
  440. const result = await deps.connector.run({ verb: "setup" });
  441. if (result.harnesses.length > 0) {
  442. out(`✓ wired harness hooks: ${result.harnesses.join(", ")}.`);
  443. } else {
  444. out(
  445. "note: no harness hooks were wired (no supported harness detected); run `honeycomb setup` after installing one.",
  446. );
  447. }
  448. } catch (err) {
  449. // Fail-soft: wiring is best-effort. One actionable line, never a raw stack, never a failed install.
  450. const reason = err instanceof Error ? err.message : "setup failed";
  451. out(`note: could not wire harness hooks (${reason}); run \`honeycomb setup\` to wire them.`);
  452. }
  453. }
  454. /**
  455. * Run `honeycomb install [--ref <code>]` (a-AC-1..6). Health-gates the daemon up (idempotent, no
  456. * double-bind), persists the onboarding "installed" marker + effective ref, then — in SOLO mode only —
  457. * opens the dashboard at the loopback URL (in FLEET mode Hive's onboarding owns the portal, so this
  458. * opens nothing). Every effect goes through an injected seam; a handled failure is a single readable
  459. * line + a non-zero exit, never a raw stack (parent AC-7).
  460. */
  461. export async function runInstallCommand(argv: readonly string[], deps: InstallVerbDeps): Promise<CommandResult> {
  462. const out: OutputSink = deps.out ?? ((line: string): void => console.log(line));
  463. const opener = deps.openDashboard ?? openLocalDashboardUrl;
  464. const probeDashboard = deps.probeDashboard ?? probeLoopbackDashboard;
  465. const ref = resolveEffectiveRef(argv);
  466. // PRD-072d: record the `--home=` pin as APIARY_HOME BEFORE the daemon is ensured/registered, so the
  467. // registry write, the service-unit pin, and the spawned daemon all resolve the chosen fleet root.
  468. applyHomeOverride(argv);
  469. // 1) Health-gate the daemon (a-AC-4). ensureDaemonRunning is idempotent (a-AC-2): an already-up
  470. // daemon returns at once with NO second start/bind; a down daemon is started + waited on the
  471. // lifecycle's existing budget. The dashboard is opened ONLY after this returns reachable.
  472. out(`→ starting the Honeycomb daemon on ${DAEMON_HOST}:${DAEMON_PORT}…`);
  473. const reachable = await ensureDaemonRunning({
  474. daemon: deps.daemon,
  475. ...(deps.lifecycle !== undefined ? { lifecycle: deps.lifecycle } : {}),
  476. out,
  477. });
  478. if (!reachable) {
  479. // a-AC-4: the daemon never bound within the wait budget. Plain-language error + retry hint;
  480. // NON-ZERO exit; NO dashboard open; NO raw stack.
  481. out("error: the daemon didn't start (it never became reachable on 127.0.0.1:3850).");
  482. out(" retry with `honeycomb install`, or run `honeycomb daemon start` to see the startup log.");
  483. return { exitCode: 1 };
  484. }
  485. out(`✓ daemon up on ${DAEMON_HOST}:${DAEMON_PORT}.`);
  486. // 1b) Report how the daemon is supervised (PRD-064h). `lifecycle.start()` (reached via
  487. // ensureDaemonRunning above) PREFERS registering the daemon as an OS-native service (launchd /
  488. // systemd --user / per-user Scheduled Task): the liveness floor that restarts it on crash and
  489. // starts it on boot, and FALLS BACK to a detached spawn where registration is impossible (CI,
  490. // locked-down machines). This is a pure, fail-soft READ of the now-running daemon's status so
  491. // the user learns which path took effect; it NEVER alters the install outcome (a status read
  492. // that throws is swallowed, and an absent lifecycle seam simply skips the line).
  493. await reportDaemonSupervision(deps, out);
  494. // 2) Persist the required onboarding marker. A failed required phase stops the transaction;
  495. // later conveniences and success telemetry must not run.
  496. const wrote = (deps.persistInstalled ?? writeInstalledMarker)(ref, deps.dir, out);
  497. if (!wrote) {
  498. out("error: install failed during the onboarding-marker phase; fix state-directory permissions and retry.");
  499. return { exitCode: 1 };
  500. }
  501. out(`✓ onboarding marked installed (ref: ${ref}).`);
  502. // 2b) Register (or refresh) honeycomb's doctor static-registry entry (PRD-071 Contract A).
  503. if (!(deps.registerWithDoctor ?? writeDoctorRegistryEntry)(deps.dir, out)) {
  504. out("error: install failed during the Doctor-registration phase; no ready state was reported.");
  505. return { exitCode: 1 };
  506. }
  507. out("✓ registered Honeycomb with Doctor.");
  508. // 2c) PRD-003a: the solo-vs-fleet login decision (a-AC-1 / a-AC-3 / a-AC-6 / a-AC-7). Fires from
  509. // the install path ONLY. Fleet → defer to Hive (no popup); solo + no creds → auto device flow;
  510. // solo + creds → already signed in. Fail-soft: it never changes the install exit code. The
  511. // returned classification also gates the dashboard-open step below (solo-only).
  512. const classification = await runInstallLoginStep(deps, out);
  513. // 2d) PRD-003a follow-through: wire the harness hooks best-effort so the one-line installer no longer
  514. // leaves them unwired until a manual `honeycomb setup` (the observed D5-FAIL). Runs the SAME
  515. // connector engine `honeycomb setup` uses, in BOTH solo and fleet modes, fail-soft — a setup
  516. // failure prints one line and never fails the install.
  517. await runInstallSetupStep(deps, out);
  518. // 3) Open the dashboard — SOLO mode ONLY. When Hive is present (FLEET) the dashboard IS the Hive
  519. // portal and Hive's own onboarding already opened it; opening a SECOND competing window here is
  520. // the field bug this gate kills. So in fleet mode we open NOTHING and print one plain line.
  521. // In solo mode we probe the portal first: reachable → open the loopback URL; not reachable →
  522. // print one plain sentence and open no tab (C-6). FAIL-SOFT: a throwing probe (an injected seam
  523. // misbehaving) degrades to the not-running branch, never a failed install.
  524. if (classification.mode === "fleet") {
  525. out("→ dashboard: the Hive portal owns it; Hive onboarding opened it, so Honeycomb opens nothing here.");
  526. } else {
  527. let portalReachable = false;
  528. try {
  529. portalReachable = await probeDashboard();
  530. } catch {
  531. portalReachable = false;
  532. }
  533. if (portalReachable) {
  534. openSoloDashboard(opener, out);
  535. } else {
  536. out(DASHBOARD_PORTAL_NOT_RUNNING_MESSAGE);
  537. }
  538. }
  539. out("✓ Honeycomb is ready.");
  540. // 4) Emit the `honeycomb_installed` lifecycle event (PRD-050e e-AC-1) — AFTER the user-facing
  541. // success, NEVER gating it (e-AC-4). FIRE-AND-FORGET through the single chokepoint: the promise is
  542. // intentionally NOT awaited (`void`), so a slow/timing-out PostHog hop never delays the installer
  543. // after the success line has printed. All errors are swallowed inside `emitTelemetry`; the
  544. // onboarding `dir` is threaded so the dedupe ledger lives in the same temp HOME under test. A second
  545. // install run is a no-op send (e-AC-5, dedupe). Tier-1 → opt-out default; an opt-out env / empty
  546. // key silences it.
  547. //
  548. // ── the-apiary PRD-002c c-AC-5 note: this event is SCOPED, not retired ────────────────────────
  549. // ADR-0002 moves the install-LIFECYCLE phone-home into the shell scripts (`install_started` /
  550. // `install_completed` / `install_failed`, fired from `scripts/install/install.sh` /
  551. // `install.ps1`), which is now the reliable "did an install run happen, and how did it end"
  552. // signal — it survives a keyless Node build and a pre-CLI failure, neither of which
  553. // `honeycomb_installed` can ever observe (it only fires from inside a successful run of THIS
  554. // verb). `honeycomb_installed` is DELIBERATELY KEPT, scoped to a narrower, DIFFERENT meaning:
  555. // "this machine's `honeycomb` CLI verb completed successfully, ONCE, ever" (e-AC-5's dedupe
  556. // ledger enforces the "once" — repeat `honeycomb install` runs never re-fire it), correlated to
  557. // the SAME onboarding `installId`/`ref` the Node-side telemetry and login event
  558. // (`honeycomb_first_link`) already use. The two surfaces are structurally incapable of double
  559. // counting the SAME event: they are different event NAMES, sent to the same PostHog project
  560. // from two independent transports, answering two different questions (funnel/failure-rate over
  561. // every install attempt, vs. one-time CLI-verb-completion-and-onboarding-correlation per
  562. // machine). Retiring `honeycomb_installed` outright would lose that onboarding correlation for
  563. // no gain, so this pass keeps it and documents the split here rather than deleting it.
  564. //
  565. // The `honeycomb_updated` version checkpoint (the-apiary lifecycle telemetry) runs in the SAME
  566. // fire-and-forget chain, SEQUENCED after the installed emit: both mutate the one onboarding
  567. // state file (ledger / lastVersion), so running them concurrently would race a load/save and
  568. // lose one write. `recordVersionAndEmitUpdated` is a one-string-compare no-op when the version
  569. // is unchanged, records the baseline silently on first sighting, and emits `honeycomb_updated`
  570. // (deduped per event+version) on a real change. Fail-soft always - see version-check.ts.
  571. const telemetryDeps: EmitDeps = {
  572. ...(deps.telemetry ?? {}),
  573. ...(deps.dir !== undefined ? { dir: deps.dir } : {}),
  574. };
  575. void (async () => {
  576. await emitTelemetry("honeycomb_installed", { ref, tier: "tier1" }, telemetryDeps);
  577. await recordVersionAndEmitUpdated(ref, telemetryDeps);
  578. })();
  579. return { exitCode: 0 };
  580. }

Ratings and comments

Sign in to rate this skill.

Sign in

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