hivecode-mcp 0.11.6 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core.js CHANGED
@@ -2,20 +2,20 @@
2
2
  // in test.js. Keeping these here (instead of copy-pasted) means a fix in one
3
3
  // place fixes everywhere, and the tests exercise the REAL code.
4
4
 
5
- // Minimal text diff: replace only the changed middle, preserving the common
6
- // prefix/suffix. Applied to a Y.Text so edits stay small (good for CRDT churn).
7
- export function applyDiff(ytext, next) {
8
- const cur = ytext.toString()
9
- if (cur === next) return false
10
- let p = 0
11
- while (p < cur.length && p < next.length && cur[p] === next[p]) p++
12
- let s = 0
13
- while (s < cur.length - p && s < next.length - p && cur[cur.length - 1 - s] === next[next.length - 1 - s]) s++
14
- if (cur.length - p - s > 0) ytext.delete(p, cur.length - p - s)
15
- const ins = next.slice(p, next.length - s)
16
- if (ins) ytext.insert(p, ins)
17
- return true
18
- }
5
+ import reconcilePkg from './reconcile.cjs'
6
+
7
+ export const {
8
+ applyDiff,
9
+ hasConflictMarkers,
10
+ stripConflictMarkers,
11
+ merge3,
12
+ summarizeChange,
13
+ changedRange,
14
+ symbolsIn,
15
+ icrMerge3,
16
+ createReconciler,
17
+ reconcile
18
+ } = reconcilePkg
19
19
 
20
20
  // Optimistic concurrency: is a write based on `expected` still safe to apply?
21
21
  // Returns the new version on success, or { stale, current } if the region moved.
@@ -89,135 +89,3 @@ export function mergeEdit(base, mine, current) {
89
89
  return { conflict: true } // same lines changed two ways -> re-reason on `current`
90
90
  }
91
91
 
92
- // Detect REAL git-style conflict markers in a file. Line-anchored on purpose:
93
- // it requires an opening `<<<<<<< ` AND a closing `>>>>>>> ` each at the start
94
- // of a line. This is what merge3 emits. A naive `text.includes('<<<<<<<')`
95
- // false-positives on any file that merely MENTIONS the markers (e.g. a README
96
- // documenting conflict resolution), which would announce a phantom conflict on
97
- // every sync. (Found by a live two-agent test, 2026-06-19.)
98
- export function hasConflictMarkers(text) {
99
- return /^<<<<<<< /m.test(text || '') && /^>>>>>>> /m.test(text || '')
100
- }
101
-
102
- // Strip and de-nest conflict markers to prevent exponential 2^N code ballooning
103
- export function stripConflictMarkers(text, prefer = 'local') {
104
- if (!text || !hasConflictMarkers(text)) return text || ''
105
- const lines = text.split('\n')
106
- const out = []
107
- let inConflict = false
108
- let inTheirs = false
109
- const localBlock = []
110
- const theirsBlock = []
111
-
112
- for (let i = 0; i < lines.length; i++) {
113
- const line = lines[i]
114
- if (/^<<<<<<< /.test(line)) {
115
- inConflict = true
116
- inTheirs = false
117
- localBlock.length = 0
118
- theirsBlock.length = 0
119
- continue
120
- }
121
- if (/^=======$/.test(line) && inConflict) {
122
- inTheirs = true
123
- continue
124
- }
125
- if (/^>>>>>>> /.test(line) && inConflict) {
126
- inConflict = false
127
- out.push(...(prefer === 'theirs' ? theirsBlock : localBlock))
128
- continue
129
- }
130
- if (inConflict) {
131
- if (inTheirs) theirsBlock.push(line)
132
- else localBlock.push(line)
133
- } else {
134
- out.push(line)
135
- }
136
- }
137
- return out.join('\n')
138
- }
139
-
140
- // --- 3-way merge for the SYNC layer (disk <-> shared doc) ---
141
- // Same idea as mergeEdit, but instead of bailing with { conflict } it always
142
- // returns text: disjoint edits merge cleanly; overlapping edits are wrapped in
143
- // git-style conflict markers so BOTH versions survive and a human/AI resolves.
144
- // De-nests existing conflict blocks to prevent exponential duplication.
145
- // merge3(base, mine, theirs) -> { text, conflict }
146
- export function merge3(base, mine, theirs) {
147
- if (mine === theirs) return { text: mine, conflict: false }
148
- if (base === theirs) return { text: mine, conflict: false } // only I changed
149
- if (base === mine) return { text: theirs, conflict: false } // only they changed
150
-
151
- // De-nest stale conflict markers so conflict blocks never wrap exponentially
152
- const cleanBase = hasConflictMarkers(base) ? stripConflictMarkers(base, 'local') : (base || '')
153
- const cleanMine = hasConflictMarkers(mine) ? stripConflictMarkers(mine, 'local') : (mine || '')
154
- const cleanTheirs = hasConflictMarkers(theirs) ? stripConflictMarkers(theirs, 'theirs') : (theirs || '')
155
-
156
- if (cleanMine === cleanTheirs) return { text: cleanMine, conflict: false }
157
- if (cleanBase === cleanTheirs) return { text: cleanMine, conflict: false }
158
- if (cleanBase === cleanMine) return { text: cleanTheirs, conflict: false }
159
-
160
- const b = cleanBase.split('\n')
161
- const mr = changedRange(b, cleanMine.split('\n'))
162
- const tr = changedRange(b, cleanTheirs.split('\n'))
163
- if (mr.endBase <= tr.startBase || tr.endBase <= mr.startBase) {
164
- const out = b.slice()
165
- for (const e of [mr, tr].sort((x, y) => y.startBase - x.startBase)) {
166
- out.splice(e.startBase, e.endBase - e.startBase, ...e.newLines)
167
- }
168
- return { text: out.join('\n'), conflict: false }
169
- }
170
- // Overlap: reconstruct each side's lines over the union region [start,end).
171
- const start = Math.min(mr.startBase, tr.startBase)
172
- const end = Math.max(mr.endBase, tr.endBase)
173
- const mineBlock = [...b.slice(start, mr.startBase), ...mr.newLines, ...b.slice(mr.endBase, end)]
174
- const theirsBlock = [...b.slice(start, tr.startBase), ...tr.newLines, ...b.slice(tr.endBase, end)]
175
- const out = [
176
- ...b.slice(0, start),
177
- '<<<<<<< local (yours)',
178
- ...mineBlock,
179
- '=======',
180
- ...theirsBlock,
181
- '>>>>>>> incoming (theirs)',
182
- ...b.slice(end),
183
- ]
184
- return { text: out.join('\n'), conflict: true }
185
- }
186
-
187
- // --- Rewrite detection for the auto-board ---
188
- // Classify a change as a small PATCH (grep-and-edit, the common case) vs a
189
- // wholesale REWRITE, and pull out the symbol names the new version defines in
190
- // the changed region. The sync layer uses this to AUTO-record what an agent did
191
- // on a rewrite — so other agents learn of it even when the agent forgets to say.
192
- // summarizeChange(base, next) -> { isRewrite, changedLines, totalLines, symbols }
193
- export function summarizeChange(base, next) {
194
- const b = (base || '').split('\n')
195
- const n = (next || '').split('\n')
196
- if (!base) return { isRewrite: false, changedLines: n.length, totalLines: n.length, symbols: symbolsIn(next || '') }
197
- const r = changedRange(b, n)
198
- const churn = Math.max(r.endBase - r.startBase, r.newLines.length) // lines replaced or added
199
- const total = Math.max(b.length, n.length)
200
- // a rewrite = at least half the file churned (and more than a couple of lines)
201
- const isRewrite = total > 0 && churn >= 4 && churn / total >= 0.5
202
- return { isRewrite, changedLines: churn, totalLines: total, symbols: symbolsIn(r.newLines.join('\n')) }
203
- }
204
-
205
- // Best-effort "what was defined here" across common languages — for the board.
206
- function symbolsIn(text) {
207
- const names = new Set()
208
- const add = (re) => { let m; while ((m = re.exec(text)) && names.size < 8) names.add(m[1]) }
209
- add(/\bfunction\s+(\w+)/g) // function foo
210
- add(/\bclass\s+(\w+)/g) // class Foo
211
- add(/\bdef\s+(\w+)/g) // def foo (python)
212
- add(/\b(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=/g) // const foo =
213
- return [...names].slice(0, 8)
214
- }
215
-
216
- // Which base line-range an edit replaced, and the replacement lines.
217
- export function changedRange(base, other) {
218
- let p = 0
219
- while (p < base.length && p < other.length && base[p] === other[p]) p++
220
- let s = 0
221
- while (s < base.length - p && s < other.length - p && base[base.length - 1 - s] === other[other.length - 1 - s]) s++
222
- return { startBase: p, endBase: base.length - s, newLines: other.slice(p, other.length - s) }
223
- }
package/docs/MCP.md CHANGED
@@ -15,7 +15,7 @@ Add Hivecode to your MCP client config. The command runs this repo's server.
15
15
  "hivecode": {
16
16
  "command": "node",
17
17
  "args": ["C:/Users/G1/Desktop/N/hive-mcp.js"],
18
- "env": { "HIVE_RELAY": "wss://livecode-xoss.onrender.com" }
18
+ "env": { "HIVE_RELAY": "wss://hivecode-relay.onrender.com" }
19
19
  }
20
20
  }
21
21
  }
@@ -0,0 +1,253 @@
1
+ # Run your own relay
2
+
3
+ Hivecode is **three pieces, and only one of them needs hosting: the relay.** Run that one
4
+ server and your team's source never reaches a machine you do not own.
5
+
6
+ This is the supported path for any team that cannot send its code to a third party. It is
7
+ also the only path that does not depend on somebody else's uptime.
8
+
9
+ For the click-by-click cloud deploy see [DEPLOY.md](DEPLOY.md). For how it all works under
10
+ the hood see [ARCHITECTURE.md](ARCHITECTURE.md). For tokens and scopes see [RBAC.md](RBAC.md).
11
+
12
+ ---
13
+
14
+ > **You install one package, not a repository.** `npx hivecode-relay` downloads the relay and
15
+ > nothing else — no agent client, no editor extension, no test suite, no build tooling. It is a
16
+ > separate npm package from `hivecode-mcp`, which is what your developers and agents install.
17
+
18
+ ## What you actually host
19
+
20
+ Only the relay. It is plain Node with no native dependencies, it holds **no canonical copy
21
+ of your code**, and it never writes your files to disk unless you turn persistence on (which
22
+ you should — see below). It passes CRDT updates between clients in the same room and enforces
23
+ access at the handshake. The editor extension and the agent MCP server run on each
24
+ participant's own machine.
25
+
26
+ ```
27
+ You host ONE relay ─────► wss://your-relay.example.com
28
+ ▲ ▲ ▲
29
+ humans humans AI agents
30
+ (VS Code) (VS Code) (MCP)
31
+ all pointed at your relay
32
+ ```
33
+
34
+ ---
35
+
36
+ ## Step 1 — Start the relay
37
+
38
+ ```bash
39
+ npx hivecode-relay
40
+ ```
41
+
42
+ That is the whole command. It starts the relay with **persistence on**, prints the join link,
43
+ and prints the exact settings each teammate needs. Useful flags:
44
+
45
+ | Flag | Default | What it does |
46
+ |---|---|---|
47
+ | `--port 1234` | `1234` | Port to listen on. |
48
+ | `--data ./hive-data` | `./hive-data` | Where rooms are persisted. |
49
+ | `--room my-project` | random | Print the link for a named room instead of a random one. |
50
+ | `--secret <string>` | none | Turn on **auth-required** mode: only holders of a minted token may connect. |
51
+ | `--seats 25` | `25` | Connection budget. See *How much can one relay handle?* below. |
52
+
53
+ Three ways to run it, in increasing order of "a real team depends on this":
54
+
55
+ **A. On a laptop or a box on your LAN.** `npx hivecode-relay`, hand out the `ws://192.168.x.x:1234`
56
+ address it prints. Good for a trial, a workshop, or a co-located team. It is **not encrypted**
57
+ — fine inside a network you trust, not fine across the internet.
58
+
59
+ **B. On your own server, behind TLS.** Run it behind a reverse proxy that terminates TLS and
60
+ upgrades WebSockets, and hand out the `wss://` address. This is the normal production shape.
61
+
62
+ **C. On a container host.** The included [`Dockerfile`](../Dockerfile) works on Fly.io, Railway,
63
+ Render, Cloud Run or anything else that runs containers. [`render.yaml`](../render.yaml) makes
64
+ Render one-click; the walkthrough is in [DEPLOY.md](DEPLOY.md).
65
+
66
+ You deploy once. After that it stays up.
67
+
68
+ ### A remote team, keeping it private
69
+
70
+ A relay on a laptop is reachable only from that network. For teammates in other places there
71
+ are three real options, and they are **not** equally private:
72
+
73
+ | Option | Private? | Stays up? | Setup |
74
+ |---|---|---|---|
75
+ | **Private network (Tailscale or similar)** — relay on any team machine, teammates join the same private network and use its `100.x.y.z` or `*.ts.net` address | **Yes.** WireGuard end to end; nothing outside the network can even reach the relay | Only while that machine is on | Each person installs the app and logs in once |
76
+ | **Your own server** — a small cloud VM or office box in *your* account, TLS terminated on it | **Yes.** You run every machine the traffic touches | Yes | One-time server setup |
77
+ | **Public tunnel** (`cloudflared tunnel --url http://localhost:1234`, ngrok) | **No.** The tunnel provider decrypts traffic at its edge, and the URL is public | Only while the laptop is on; quick tunnels get a new URL every restart | One command |
78
+
79
+ A public tunnel works — verified end to end: two clients synced a file through a Cloudflare
80
+ quick tunnel, and a client holding the URL but no token was refused. Use it for a trial, and
81
+ **always with `--secret`**, because a public URL on an open relay is an open room. `hive_status`
82
+ says so on every join: `YOUR RELAY — through a public tunnel`.
83
+
84
+ ---
85
+
86
+ ## Step 2 — Point EVERY client at it
87
+
88
+ This is the step teams get half-right, so it is worth being blunt about what "half-right"
89
+ costs. There are two kinds of client and they read two different settings:
90
+
91
+ | Client | Setting | Where |
92
+ |---|---|---|
93
+ | **Human** (VS Code) | `hivecode.relayUrl` | VS Code settings |
94
+ | **AI agent** (MCP) | `HIVE_RELAY` | the `env` block of the agent's MCP server config |
95
+
96
+ **If you set one and forget the other, nothing fails.** The agent falls back to the public
97
+ relay this build ships as a default, joins a room with the same name, reports `connected`,
98
+ and publishes your files there. Your humans are on your relay, your agent is on ours, and
99
+ every status line on both sides is green.
100
+
101
+ So set the pin as well:
102
+
103
+ ```
104
+ HIVE_RELAY_PIN = wss://your-relay.example.com
105
+ ```
106
+
107
+ `HIVE_RELAY` is a *default*. `HIVE_RELAY_PIN` is a *rule*: this machine may only ever talk
108
+ to these relays, and any attempt to connect anywhere else is refused **before the socket
109
+ opens**, with error **Q550**, having published nothing. Set it on every machine — humans'
110
+ and agents' alike — and a stale link, a typo'd host or a forgotten environment variable
111
+ becomes a loud refusal instead of a silent upload.
112
+
113
+ Two more knobs:
114
+
115
+ - `HIVE_RELAY_PIN` accepts a comma-separated list, for teams with a staging relay and a
116
+ production one.
117
+ - `HIVE_PRIVATE=1` refuses the shipped public default (**Q551**) even when no pin is set.
118
+ Use it as a belt-and-braces setting on a machine that must never reach our relay.
119
+
120
+ A pin that cannot be parsed is **refused (Q552)**, never ignored. A typo that silently
121
+ degraded to "no pin" would leave you believing a machine was locked down when it was not.
122
+
123
+ ---
124
+
125
+ ## Step 3 — Create a room and invite people
126
+
127
+ A connection is encoded as a **join link**:
128
+
129
+ ```
130
+ wss://your-relay.example.com|room-myproject
131
+ └──── your relay ────┘ └──── room id ────┘
132
+ ```
133
+
134
+ 1. `npx hivecode-relay --room myproject` prints the link.
135
+ 2. Share it with teammates and agents.
136
+ 3. **Humans** run **Hivecode: Join a Session** in VS Code and paste it.
137
+ 4. **Agents** get it as the `link` argument to `hive_join`.
138
+ 5. Same link = same room = one live codebase for everyone.
139
+
140
+ ---
141
+
142
+ ## Step 4 — Add AI agents
143
+
144
+ Agents join through the MCP server. Register it once in the agent's host (Claude Code,
145
+ Cursor, Windsurf, or your own bot):
146
+
147
+ ```json
148
+ {
149
+ "mcpServers": {
150
+ "hivecode": {
151
+ "command": "npx",
152
+ "args": ["-y", "hivecode-mcp"],
153
+ "env": {
154
+ "HIVE_RELAY": "wss://your-relay.example.com",
155
+ "HIVE_RELAY_PIN": "wss://your-relay.example.com"
156
+ }
157
+ }
158
+ }
159
+ }
160
+ ```
161
+
162
+ Then hand it the join link. It appears in the room as an `ai` member, scoped to exactly the
163
+ folders you invited it to. See [JOIN_WITH_AGENT.md](JOIN_WITH_AGENT.md) and [MCP.md](MCP.md).
164
+
165
+ ---
166
+
167
+ ## Step 5 — Check that it is actually private
168
+
169
+ Do not take a green join as evidence. Two checks, thirty seconds:
170
+
171
+ **1. Ask each client where it is.** `hive_status` reports a `privacy` field next to
172
+ `connected`:
173
+
174
+ ```
175
+ privacy: "PRIVATE — relay on your network" ← yours
176
+ privacy: "PUBLIC RELAY — not yours" ← ours. Your files are on our server.
177
+ ```
178
+
179
+ A human client shows the same thing in the join banner: `relay: <url> [VERDICT]`.
180
+
181
+ **2. Ask your relay who is on it.** `curl http://your-relay:1234/health` reports
182
+ `connections` and `rooms`. The number of connections should account for everybody. If a
183
+ teammate says they are in the room and your relay's count did not move, they are in
184
+ *a* room — just not on your relay.
185
+
186
+ You can prove the whole path on your own machine in about a minute:
187
+
188
+ ```bash
189
+ node tests/self-host-test.mjs
190
+ ```
191
+
192
+ That suite starts a real relay, syncs a real file between two real clients through it,
193
+ asserts the relay's own counters moved, and asserts that a pinned client refuses the public
194
+ relay. It is the evidence behind every claim on this page.
195
+
196
+ ---
197
+
198
+ ## Step 6 — Lock it down before you invite anyone real
199
+
200
+ | Env var | Why you want it |
201
+ |---|---|
202
+ | `HIVE_AUTH_MODE=required` + `HIVE_JWT_SECRET=<secret>` | Every connection must present a valid token. This is your invite-only control. `npx hivecode-relay --secret <secret>` sets both. Mint tokens with `npx hivecode-token --room <room> --name <who> --role writer --ttl 7d` on the relay host, which is the only machine that holds the secret. See [RBAC.md](RBAC.md). |
203
+ | `HIVE_PERSIST_DIR=/var/data/hive` | **Important.** Without it a room lives only in connected clients' memory and is **lost the moment everyone disconnects** — the day works perfectly and the folder is empty in the morning. `npx hivecode-relay` turns this on by default; `node server.js` does not. |
204
+ | `HIVE_SEATS=<n>` | Connection budget for the whole relay. The default free-tier ceiling is 8 per room, which is **not** 8 people — see below. |
205
+ | `HIVE_AUDIT_FILE=./audit.log` | One line per admit and reject. This is your evidence of who connected and when. |
206
+ | `RENDER_EXTERNAL_URL` (auto on Render) | Keeps a free-tier host warm so the first join is not a 30-second cold start. |
207
+
208
+ > ⚠️ **An open relay on a public IP is a public relay.** Without `HIVE_AUTH_MODE=required`,
209
+ > anyone who can reach the port and guesses a room id can read and write your files. On a
210
+ > laptop or a private LAN that is a reasonable trade. On a public IP it is not.
211
+
212
+ ---
213
+
214
+ ## How much can one relay handle?
215
+
216
+ **Count connections, not people.** Each participant holds one base-room socket **plus one
217
+ per open file**, so a five-person team is not five connections — it is up to
218
+ `participants × (1 + HIVE_MAX_OPEN_FILES)`. The client caps its own working set at
219
+ `HIVE_MAX_OPEN_FILES` (default 128) for exactly this reason.
220
+
221
+ Two different ceilings refuse you, with two different remedies:
222
+
223
+ | You see | Meaning | Fix |
224
+ |---|---|---|
225
+ | **Q430** (503) | the whole relay is at `maxConnsTotal` (512) | `HIVE_MAX_CONNS_TOTAL` — **`HIVE_SEATS` does not help here** |
226
+ | **Q431** (429) | one room is at its per-room cap | `HIVE_SEATS` |
227
+
228
+ - **A focused team (~10 humans and their agents in one room): comfortably**, on a small
229
+ always-on instance (≈1 vCPU / 1–2 GB). Free tiers are fine for a trial.
230
+ - **Hundreds of concurrent users across many rooms:** scale the instance up, or — the natural
231
+ model — let each team run its own relay so the load distributes.
232
+
233
+ Two operational rules:
234
+
235
+ 1. **Turn on persistence** before real users join.
236
+ 2. **Do not redeploy the relay while people are working** — a restart drops everyone. Deploy
237
+ from a stable tag, off-hours.
238
+
239
+ ---
240
+
241
+ ## What self-hosting does not give you
242
+
243
+ Said plainly, because discovering it later is worse:
244
+
245
+ - **Uptime is yours.** Nobody is paged when your box dies at 2am.
246
+ - **`ws://` is plaintext.** Self-hosting is not encryption. Put TLS in front of it.
247
+ - **An open relay is open.** Running it yourself controls *where* the bytes go, not *who*
248
+ may fetch them. That is what `HIVE_AUTH_MODE=required` is for.
249
+ - **Path scoping needs auth mode.** The `--paths` globs in a token are only enforced when the
250
+ relay runs in `required` mode. On an open relay every token is ignored, so a "scoped" agent
251
+ gets the whole room.
252
+ - **Mixed client versions do not sync.** Everyone on the relay must be on the same Hivecode
253
+ version; announce yours on join.