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/sync.js CHANGED
@@ -36,6 +36,13 @@ import { genIdentity, authorChange, verifyReceipt, contentHash } from './substra
36
36
  // whole file is the most common thing an agent does, so this fired constantly.
37
37
  import grmLink from './grm-link.cjs' // hands this room's history to GRM, so the ROOM has a memory
38
38
  import { structuralMerge, supports, languageFor } from './icr.js' // validates a judged fork resolution before it may land (parse + dangling refs)
39
+ import { accountFor, sameText, DESCENDS, IDENTICAL, DIVERGED, UNPROVEN } from './hive-pr-staleness.js' // room-versus-branch provenance staleness checks (HIV-P9)
40
+ // HIV-P8. The map key MUST be the string 'obligations' — hive-mcp.js:656 reads that exact key, and
41
+ // a debt written anywhere else would be invisible to hive_owed: a warning nobody can see, which is
42
+ // the defect this ticket is about, one level down.
43
+ import * as RH from './hive-relay-health.js' // HIV-P13; the ONLY producer of the not-syncing diagnosis
44
+ import { checkRelay } from './hive-privacy.js' // HIV-P20; which relay is this, and did anybody choose it
45
+ import * as OB from './hive-obligations.js'
39
46
 
40
47
  // Wire-format/protocol version. Bump when a change makes clients incompatible
41
48
  // (e.g. the v2 per-file-subdoc model). Broadcast via awareness so peers can warn
@@ -405,7 +412,7 @@ export function acquireFolderLock(root, room, log = console.log) {
405
412
  return release
406
413
  }
407
414
 
408
- export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir = '.', name = 'anon', kind = 'human', owner = '', token = '', license = '', log = console.log, syncFiles = true }) {
415
+ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir = '.', name = 'anon', kind = 'human', owner = '', token = '', license = '', log = console.log, syncFiles = true, passive = false }) {
409
416
  // BEFORE ANY DISK OR SOCKET WORK. A name outside the mention grammar joins successfully and is
410
417
  // then unreachable: its mail, its obligations and its wake-on-mention are all silently dead,
411
418
  // and the only symptom is other people being told "@X is NOT in the room" about someone who is
@@ -420,6 +427,23 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
420
427
  e.suggested = nameCheck.suggested
421
428
  throw e
422
429
  }
430
+ // THE SAME PRIVACY GATE hive-mcp.js applies at join, repeated here because this is the
431
+ // real choke point. Every client in the product -- the MCP server, hive-agent.js, the
432
+ // CLIs, every demo script -- reaches the network through this one function, and a guard
433
+ // that lives only in the MCP layer protects only agents that went through the MCP layer.
434
+ // An operator who sets HIVE_RELAY_PIN is entitled to expect it means "this machine",
435
+ // not "this machine, except for the seven scripts that call startSync directly".
436
+ //
437
+ // It throws for the reason the name check above throws: startSync has no failure channel,
438
+ // and a client that half-connects to a relay nobody authorised is the failure this exists
439
+ // to prevent. Refusing here means no socket was opened and no file was published.
440
+ const priv = checkRelay({ relay, env: process.env, dir: path.resolve(dir), fs })
441
+ if (!priv.ok) {
442
+ const e = new Error(`${priv.headline}\n\n${priv.detail}`)
443
+ e.code = 'EHIVERELAYPIN'
444
+ e.qcode = priv.code
445
+ throw e
446
+ }
423
447
  const ROOT = path.resolve(dir)
424
448
  fs.mkdirSync(ROOT, { recursive: true })
425
449
  // FIRST, before any socket or file work: if another client already holds this folder,
@@ -942,9 +966,10 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
942
966
  if (lic) wsParams.license = lic
943
967
  if (name) wsParams.name = String(name).slice(0, 48)
944
968
  if (kind) wsParams.kind = kind
969
+ if (passive) wsParams.passive = 'true'
945
970
  const wsOpts = { WebSocketPolyfill: WebSocket, disableBc: true, params: Object.keys(wsParams).length ? wsParams : undefined }
946
971
  const provider = new WebsocketProvider(relay, room, doc, wsOpts)
947
- provider.awareness.setLocalStateField('user', { name, kind, owner: owner || undefined, v: PROTOCOL_VERSION }) // identity is implicit in the client
972
+ provider.awareness.setLocalStateField('user', { name, kind, owner: owner || undefined, v: PROTOCOL_VERSION, passive: !!passive }) // identity is implicit in the client
948
973
 
949
974
  // ---- relay reachability, said out loud exactly once -------------------------------
950
975
  // y-websocket retries forever and silently. That is the right RECOVERY behaviour and
@@ -1053,12 +1078,14 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1053
1078
  // usually a whole-relay problem rather than a per-file one, so one message naming the
1054
1079
  // count is the useful shape -- one per file would be 800 lines of chat.
1055
1080
  const refusedFiles = new Map() // relPath -> consecutive connection errors, cleared on sync
1081
+ const refusedCodes = new Map() // relPath -> the HTTP status the relay refused with, when it gave one
1056
1082
  let refusalSaidAt = 0
1057
1083
  let refusalTimer = null
1084
+
1058
1085
  function noteRefusals() {
1059
1086
  if (refusalTimer) return
1060
1087
  // Debounced: a full relay refuses every file at once, and we want the total, not the first.
1061
- refusalTimer = setTimeout(() => {
1088
+ refusalTimer = setTimeout(async () => {
1062
1089
  refusalTimer = null
1063
1090
  const stuck = [...refusedFiles.keys()].filter((r) => { const e = fileDocs.get(r); return e && !e.synced })
1064
1091
  // One transient error on one file is a blip, not an outage. Two or more files stuck, or
@@ -1068,17 +1095,120 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1068
1095
  const now = Date.now()
1069
1096
  if (now - refusalSaidAt < 300000) return // at most once every 5 minutes
1070
1097
  refusalSaidAt = now
1071
- const msg =
1072
- `${stuck.length} file(s) cannot connect to the relay and are NOT syncing. ` +
1073
- `They will read as empty until this clears. The usual cause is the relay being full ` +
1074
- `(Q430): Hivecode opens one socket PER FILE, so a large folder can exhaust it alone. ` +
1075
- `Check <relay-http>/health -- connections against limits.maxConnsTotal -- then raise ` +
1076
- `HIVE_MAX_CONNS_TOTAL or narrow what syncs. Do not trust this folder's contents meanwhile.`
1098
+ // HIV-P13. THIS MESSAGE USED TO NAME A CAUSE IT HAD NOT MEASURED.
1099
+ //
1100
+ // It said "the usual cause is the relay being full (Q430)" on the strength of having
1101
+ // observed only that N file docs have synced=false. Measured 21 Sep 2026, at the moment a
1102
+ // third agent printed it for 49 files: the relay reported 56 connections of 512, and
1103
+ // limits.js keys its per-room count on the FILE-room, so any one file held three
1104
+ // connections against a cap of 64. Q430 needed 512 and had 56; Q431 needed 64 and had 3.
1105
+ // Neither refusal could have fired. The real event was the relay dropping its room state
1106
+ // -- /health went rooms 44 -> 0 -> 29 -> 44 over a few minutes -- and every client
1107
+ // reconnecting one socket per file.
1108
+ //
1109
+ // "The relay is full" and "the relay just dropped everyone and we are all reconnecting"
1110
+ // produce an identical symptom and need OPPOSITE responses: a config change, or thirty
1111
+ // seconds of patience. Telling an operator to raise a limit that is 89% free is worse
1112
+ // than saying nothing, because they will do it, see no change, and conclude the product
1113
+ // is broken -- correctly, on the evidence they were given.
1114
+ //
1115
+ // So the client asks the relay instead of guessing, and reports what came back. It also
1116
+ // stops printing the literal string "<relay-http>", which it did for three weeks while
1117
+ // holding the relay URL in scope.
1118
+ // EVIDENCE BEFORE INFERENCE. If the relay actually refused us it said so with a status,
1119
+ // and explain() maps those to the right cause and the right knob -- Q431 to HIVE_SEATS,
1120
+ // Q430 to capacity, 401/403 to the token, 402 to the plan. That is a fact from the relay.
1121
+ // Only when nothing refused us -- the sockets simply never came up, which is what a
1122
+ // dropped-and-reconnecting relay looks like -- is there anything left to infer, and then
1123
+ // we go and ASK rather than assert.
1124
+ const coded = stuck.map((r) => refusedCodes.get(r)).filter(Boolean)
1125
+ const code = coded.length ? coded.sort((a, b) => coded.filter((c) => c === b).length - coded.filter((c) => c === a).length)[0] : null
1126
+ const msg = code
1127
+ ? `${stuck.length} file(s) are not synced and will READ AS EMPTY until this clears. ` +
1128
+ `The relay refused ${coded.length} of them with ${code}: ${explain(code)} ` +
1129
+ `Do not trust this folder's contents meanwhile.`
1130
+ : (await RH.explainNotSyncing(relay, {
1131
+ stuck: stuck.length, what: 'files',
1132
+ trailer: `Nothing refused these connections with a status code, so the cause above is ` +
1133
+ `inferred from the relay's own counters rather than reported by it. ` +
1134
+ `Do not trust this folder's contents meanwhile.`,
1135
+ })).text
1077
1136
  log(`[${name}] !! ${msg}`)
1078
1137
  try { say(`[!] @all ${msg}`) } catch { /* chat may itself be unreachable — the log still carries it */ }
1079
1138
  }, 4000)
1080
1139
  if (refusalTimer.unref) refusalTimer.unref()
1081
1140
  }
1141
+ // HIV-P18. THE DOCUMENTED REMEDY DID NOT EXIST.
1142
+ //
1143
+ // The README told every user: "A file outside the working set is not on your disk yet. It
1144
+ // exists in the room. Reading or claiming the path fetches it." Measured 21 Sep 2026 against
1145
+ // a client holding 8 of a room's 41 files, on a path that WAS in the manifest:
1146
+ //
1147
+ // whyNotShared(mod024.js) -> "" (in scope; edits would reach the room)
1148
+ // claim(mod024.js) -> true ("it's yours")
1149
+ // after claim + 9s -> on disk = false
1150
+ // after release + 9s -> on disk = false
1151
+ // provenanceOf -> 0 receipts, headOf -> null (doc never opened)
1152
+ // public fetch/read/open -> undefined
1153
+ //
1154
+ // Nothing brought the bytes down. The cause is one line in reconcile: `if (disk === null)
1155
+ // return` before openFile, plus a warm-up that only opens files already on local disk. A
1156
+ // manifest entry with no local copy was never opened, so it could never arrive.
1157
+ //
1158
+ // The only thing that DID work was writing to the path -- which is precisely the blind
1159
+ // recreate HIV-P14b guards. So the sole recovery route was the one dangerous action, reached
1160
+ // by an agent that had been told "it's yours" and then saw an empty directory. That is
1161
+ // HIV-P3's class arriving inbound: a claim granted over bytes that cannot move.
1162
+ //
1163
+ // This makes the sentence true. `fetch` opens the doc and RESOLVES WHEN THE CONTENT HAS
1164
+ // LANDED, because an un-awaited open is the same false success one layer down: the caller
1165
+ // reads the directory, sees nothing, and concludes the file is absent.
1166
+ function fetchFile(relPath, { timeoutMs = 15000 } = {}) {
1167
+ const r = String(relPath)
1168
+ if (!canOpen(r)) return Promise.resolve({ ok: false, reason: `${r} is out of your scope` })
1169
+ const full = path.join(ROOT, r)
1170
+ // Already here: report it, and say so rather than implying we went and got it.
1171
+ if (fs.existsSync(full)) return Promise.resolve({ ok: true, alreadyLocal: true, file: r })
1172
+ // Not in the room either. This is the case @Hermes hit, and it is NOT the working-set
1173
+ // case: nothing will ever arrive, so saying "fetching" would be a lie. The two look
1174
+ // identical from an empty directory and have opposite remedies, so they get different
1175
+ // answers here.
1176
+ if (!manifest.has(r)) {
1177
+ return Promise.resolve({
1178
+ ok: false, notInRoom: true, file: r,
1179
+ reason: `${r} is not in this room at all — no client has ever published it, so nothing ` +
1180
+ `can fetch it. This is not a working-set miss. Check the room's .gitignore allow-list ` +
1181
+ `covers the path, then have whoever holds the file write it into their synced folder.`,
1182
+ })
1183
+ }
1184
+ const e = openFile(r)
1185
+ if (!e) return Promise.resolve({ ok: false, reason: `could not open ${r}` })
1186
+ return new Promise((resolve) => {
1187
+ let done = false
1188
+ const finish = (res) => { if (done) return; done = true; clearInterval(iv); clearTimeout(to); resolve(res) }
1189
+ const check = () => {
1190
+ if (!e.synced) return
1191
+ // reconcile() runs on the provider's own sync event and writes to disk. Wait for the
1192
+ // BYTES, not for the flag -- the flag says the socket settled, which is not the claim
1193
+ // being made to the caller.
1194
+ if (fs.existsSync(full)) return finish({ ok: true, file: r, bytes: fs.statSync(full).size })
1195
+ // Synced and still nothing: the room holds this path with empty content. Real, and a
1196
+ // different answer from "not fetched yet".
1197
+ if (e.text.toString() === '') return finish({ ok: true, file: r, empty: true, bytes: 0 })
1198
+ }
1199
+ const iv = setInterval(check, 250)
1200
+ if (iv.unref) iv.unref()
1201
+ const to = setTimeout(() => finish({
1202
+ ok: false, file: r, timedOut: true,
1203
+ reason: `${r} is in the room but did not arrive within ${timeoutMs}ms. The file's own ` +
1204
+ `socket may be refused — hive_status reports filesHeld of roomFiles, and a refused ` +
1205
+ `file doc is indistinguishable from an empty file.`,
1206
+ }), timeoutMs)
1207
+ if (to.unref) to.unref()
1208
+ check()
1209
+ })
1210
+ }
1211
+
1082
1212
  function openFile(relPath) {
1083
1213
  let e = fileDocs.get(relPath)
1084
1214
  if (e) return e
@@ -1125,9 +1255,16 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1125
1255
  // A refused upgrade lands here. The provider will keep retrying by itself, which is the
1126
1256
  // right behaviour and exactly why nothing surfaces it — so count it and let noteRefusals
1127
1257
  // decide whether this is a blip or a relay that will not take us.
1128
- fprovider.on('connection-error', () => {
1258
+ fprovider.on('connection-error', (ev) => {
1129
1259
  if (e.synced) return // already have the content; a later blip is the provider's business
1130
1260
  refusedFiles.set(relPath, (refusedFiles.get(relPath) || 0) + 1)
1261
+ // HIV-P13. THE STATUS CODE WAS THROWN AWAY HERE, and it is the only authoritative evidence
1262
+ // in the whole path. joinRoom in hive-mcp.js already captured it from this same event; this
1263
+ // handler took no argument at all, so noteRefusals had nothing but "N files are quiet" and
1264
+ // had to INFER a cause -- which is how it came to announce Q430 on 21 Sep while the relay
1265
+ // sat at 56 of 512. explain() above maps these codes correctly and has done since 5 Sep.
1266
+ const code = ev && (ev.code || ev.status)
1267
+ if (code) refusedCodes.set(relPath, code)
1131
1268
  noteRefusals()
1132
1269
  })
1133
1270
  // Newly opened counts as used, and opening is the moment the working set can go over
@@ -1237,6 +1374,46 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1237
1374
  // almost every legitimate claim in exactly the rooms that need this guard most, and it would
1238
1375
  // be switched off within a day. So we only judge things we have positive reason to believe
1239
1376
  // are FILES: known to the room, present on disk, or carrying a directory separator.
1377
+ // HIV-P3, 20 Sep 2026. THE GENESIS CASE: the five tests above are all false for a root-level
1378
+ // file that DOES NOT EXIST YET, which is the most common reason anyone claims at all -- you
1379
+ // claim `config.env` precisely because you are about to create it. Found by DeepMind-Agent.
1380
+ // So HIV-27's guard had a hole in exactly the case it was written for: claim succeeds, write
1381
+ // succeeds, the local gate passes because in YOUR folder the file is real, and the bytes never
1382
+ // leave. Born invisible, every signal green.
1383
+ //
1384
+ // THE ONLY QUESTION IS: is this bare string a FILE-TO-BE or a LOGICAL LABEL? Nothing on disk
1385
+ // and nothing in the room can answer it, so this is a guess, and the direction of the guess is
1386
+ // what matters. Guessing "file" too eagerly refuses legitimate region claims -- and under an
1387
+ // allow-list .gitignore that means refusing ALMOST ALL of them, which gets the guard switched
1388
+ // off within a day and costs more than the hole. So every rule here must be one a LABEL would
1389
+ // essentially never satisfy.
1390
+ //
1391
+ // THE DIGIT RULE IS THE LOAD-BEARING ONE and it is not obvious. A trailing dot-segment
1392
+ // containing a LETTER is an extension: .js .env .secret. One that is ALL DIGITS is a version
1393
+ // number: v1.2, release-0.11.6, HIV-P3.5. Without that distinction every ticket id and release
1394
+ // label in this room's own vocabulary gets refused as a file.
1395
+ //
1396
+ // WHAT THIS DOES NOT CLOSE, stated rather than discovered later. Extensionless root files that
1397
+ // are neither conventional nor `*file` shaped -- a bare `config`, `staging`, `hosts` -- are
1398
+ // still read as labels and still go invisible. The hole narrows; it does not close. It cannot
1399
+ // close here, because at claim time the string is all we have. The rest belongs at WRITE time,
1400
+ // where a path that appears on disk inside the room folder is a fact and needs no heuristic.
1401
+ // That is HIV-P8, and it is filed rather than quietly assumed.
1402
+ const EXTENSIONLESS_ROOT_FILES = new Set([
1403
+ 'LICENSE', 'LICENCE', 'README', 'CHANGELOG', 'CHANGES', 'NOTICE', 'AUTHORS', 'CONTRIBUTORS',
1404
+ 'CODEOWNERS', 'COPYING', 'INSTALL', 'CONTRIBUTING', 'VERSION', 'MAINTAINERS', 'TODO',
1405
+ ])
1406
+ const looksLikeFilename = (p) => {
1407
+ if (/\s/.test(p)) return false // "the parser rewrite", "P3 lane"
1408
+ if (/\.[^.]*[A-Za-z][^.]*$/.test(p)) return true // .js .env .secret -- but NOT .2 .5 .6
1409
+ if (EXTENSIONLESS_ROOT_FILES.has(p.toUpperCase())) return true
1410
+ // Makefile, Dockerfile, Rakefile, Gemfile, Procfile, Vagrantfile, Justfile, Caddyfile.
1411
+ // Capital-initial and case-SENSITIVE on purpose: lowercase "profile" and "logfile" are
1412
+ // perfectly ordinary region names and must stay claimable.
1413
+ if (/^[A-Z][A-Za-z]+file$/.test(p)) return true
1414
+ return false
1415
+ }
1416
+
1240
1417
  const whyNotShared = (relPath) => {
1241
1418
  const p = String(relPath || '')
1242
1419
  if (!p) return ''
@@ -1245,6 +1422,7 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1245
1422
  // SKIP counts as positive evidence: those names ARE files by definition, and a control
1246
1423
  // file sits in the room root with no separator in its name, so the heuristics below miss it.
1247
1424
  const isFile = manifest.has(p) || fileDocs.has(p) || SKIP.has(p) || onDisk || p.includes('/')
1425
+ || looksLikeFilename(p) // HIV-P3: the genesis case -- see above
1248
1426
  if (!isFile) return '' // a label, not a path -- not ours to judge
1249
1427
  if (!isSafeRelPath(p)) return `"${p}" is not a safe relative path, so it can never be synced`
1250
1428
  if (SKIP.has(p)) return `${p} is a Hivecode control file, not shared source`
@@ -1260,6 +1438,12 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1260
1438
  // files" (adopt the room's copy) and "this file was created during the session"
1261
1439
  // (a creation race -- merge, never adopt). Populated once, on the first scan.
1262
1440
  const preexisting = new Set()
1441
+ // HIV-P14b. Manifest keys as of our first sync: what the ROOM held before we arrived.
1442
+ // `preexisting` records our DISK, which structurally cannot distinguish "nobody had this file"
1443
+ // from "the room had it all along and we never fetched it". null until the first sync, and null
1444
+ // must never be read as "the room was empty" -- that would classify every joiner's first
1445
+ // creation as a race, which is the bug this exists to fix.
1446
+ let roomAtJoin = null
1263
1447
  let firstScanDone = false
1264
1448
  const shadow = new Map() // relPath -> exact bytes THIS ENGINE last wrote/captured (source-level edit capture)
1265
1449
  // THE SAME THING, FROM THE PREVIOUS SESSION, and the reason it exists:
@@ -1283,15 +1467,28 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1283
1467
  // work (it would look like a deliberate deletion against an up-to-date base).
1284
1468
 
1285
1469
  const rel = (full) => path.relative(ROOT, full).split(path.sep).join('/')
1286
- function walk(d, acc = []) {
1470
+ // HIV-P8: `skipped` collects the files this walk DECLINES to sync, and that second list is the
1471
+ // whole ticket. Everything in this engine is derived from "the files we sync", so every natural
1472
+ // place to notice a born-invisible file is definitionally blind to it: walk() dropped ignored
1473
+ // paths, so scan() never saw them, so reconcile() was never called for them, so the guard at the
1474
+ // top of reconcile() was unreachable for exactly the class of file it names. Hooking there would
1475
+ // have passed a unit test that called reconcile() directly and done nothing in a real session.
1476
+ //
1477
+ // DIRECTORY PRUNING IS UNCHANGED, deliberately. Descending into ignored directories to find
1478
+ // ignored files would walk vendor and build trees on every tick. Measured on a real checkout with
1479
+ // pruning kept: 7934 synced, 256 ignored files visible, 280 directories descended, 191ms for the
1480
+ // whole traversal — and that traversal already happens. We are keeping an answer isIgnored()
1481
+ // already computed instead of discarding it. An ignored file inside an ignored directory stays
1482
+ // unseen, which is the correct trade at that price.
1483
+ function walk(d, acc = [], skipped = []) {
1287
1484
  let entries = []
1288
1485
  try { entries = fs.readdirSync(d, { withFileTypes: true }) } catch { return acc }
1289
1486
  for (const e of entries) {
1290
1487
  if (IGNORE.has(e.name)) continue
1291
1488
  const full = path.join(d, e.name)
1292
1489
  const r = rel(full)
1293
- if (e.isDirectory()) { if (!isIgnored(r + '/')) walk(full, acc) } // prune ignored dirs
1294
- else if (e.isFile()) { if (!isIgnored(r)) acc.push(full) } // skip ignored/secret files
1490
+ if (e.isDirectory()) { if (!isIgnored(r + '/')) walk(full, acc, skipped) } // prune ignored dirs
1491
+ else if (e.isFile()) { if (isIgnored(r)) skipped.push(full); else acc.push(full) }
1295
1492
  }
1296
1493
  return acc
1297
1494
  }
@@ -1441,10 +1638,19 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1441
1638
  // A genuine emptying of a file we HAVE synced still has an ancestor, so it falls through
1442
1639
  // to the merge below and still lands.
1443
1640
  const noHistory = !bases.has(relPath) && !priorShadow.has(relPath)
1641
+ // HIV-P14b tracing, env-gated. Which branch a blind recreate actually takes was guessed
1642
+ // wrong twice from reading the code; this answers it from the running product.
1643
+ if (process.env.HIVE_P14_DEBUG && new RegExp(process.env.HIVE_P14_DEBUG).test(relPath)) {
1644
+ log(`[P14] ${relPath} origin=${origin} synced=${fe.synced} docLen=${docText.length} ` +
1645
+ `diskLen=${disk === null ? 'null' : disk.length} hasBase=${bases.has(relPath)} ` +
1646
+ `priorShadow=${priorShadow.has(relPath)} inManifest=${manifest.has(relPath)} ` +
1647
+ `preexisting=${preexisting.has(relPath)}`)
1648
+ }
1444
1649
  if (docText === '' && (!manifest.has(relPath) || (disk && noHistory))) {
1445
1650
  // the relay has no usable copy of this path -> publish ours (a genuinely new file,
1446
1651
  // or one whose registration outlived the join that promised it)
1447
1652
  if (disk === null) return
1653
+ if (process.env.HIVE_P14_DEBUG) log(`[P14] BRANCH=genesis-publish ${relPath}`)
1448
1654
  fe.doc.transact(() => applyDiff(fe.text, disk))
1449
1655
  stampProvenance(relPath, '', disk) // genesis: sign the file's first content (base = empty)
1450
1656
  manifest.set(relPath, 1)
@@ -1492,6 +1698,72 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1492
1698
  // disjoint additions union (the normal case -- each author added their own
1493
1699
  // block), and a real overlap raises conflict markers for a human to settle
1494
1700
  // instead of the engine quietly picking a winner on arrival order.
1701
+ // HIV-P14b, OPEN AND DELIBERATELY NOT IMPLEMENTED HERE YET.
1702
+ //
1703
+ // There is a third case this dichotomy misses: the path appeared on OUR disk after we
1704
+ // started AND the room already had it before we joined. That is not a race -- the agent
1705
+ // could not see the file (bounded working set, nothing touched it), believed it did not
1706
+ // exist, and wrote one. Measured 21 Sep 2026: agent B recreated mod039.js and agent A's
1707
+ // copy ended up with two const declarations of the same name.
1708
+ //
1709
+ // `preexisting` records our DISK, so it structurally cannot tell those apart; the manifest
1710
+ // as of first sync can. A guard on that was written and REMOVED before shipping, because
1711
+ // the probe showed it never firing -- most likely the manifest is not yet populated at the
1712
+ // instant the base provider reports sync, so the snapshot came back empty. A refusal path
1713
+ // that silently never runs is worse than none: it reads as protection in review and does
1714
+ // nothing in production, which is the defect class this repo keeps hitting.
1715
+ //
1716
+ // What ships instead is the reporting half, which is verified: status() now exposes
1717
+ // filesHeld/roomFiles/filesMissing instead of a full house, and the join announces the gap
1718
+ // with the count and the remedy. An agent told "33 files exist here that you do not have,
1719
+ // reading the path fetches it" will not recreate them. That removes the cause; the guard
1720
+ // is the belt for when it happens anyway, and it lands when it is proven to fire.
1721
+ if (process.env.HIVE_P14_DEBUG) log(`[P14] BRANCH=no-base-block ${relPath} preexisting=${preexisting.has(relPath)}`)
1722
+ // HIV-P14b. A BLIND RECREATE IS NOT A RACE, and the empty-base merge below corrupts it.
1723
+ //
1724
+ // The dichotomy above has a third case: the path appeared on OUR disk after we started AND
1725
+ // the room already had it before we joined. The working set is bounded, nothing touched
1726
+ // that file, so the agent could not see it, concluded it did not exist, and wrote one.
1727
+ //
1728
+ // Measured 21 Sep 2026, traced through the running product. Agent B, holding 8 of a room's
1729
+ // 41 files, wrote mod039.js:
1730
+ // mod039.js origin=remote synced=true docLen=22 diskLen=39 hasBase=false
1731
+ // inManifest=true preexisting=false -> BRANCH=no-base-block
1732
+ // It lands exactly here, `preexisting` is false, and the empty-base merge unions two whole
1733
+ // files into agent A's copy:
1734
+ // export const v39 = 39
1735
+ // export const v39 = "FROM SCRATCH BY B"
1736
+ // Two const declarations of the same name. Invalid code, in someone else's folder, from B
1737
+ // doing the only thing available to it.
1738
+ //
1739
+ // The union is right for what the comment above describes -- two authors adding DIFFERENT
1740
+ // blocks to a file they both just created. It is wrong for two independent whole-file
1741
+ // creations of the same module, which is what a blind recreate always is.
1742
+ //
1743
+ // `roomAtJoin` is the discriminator `preexisting` cannot be: a path in it existed in the
1744
+ // ROOM before we did, however new it is on our disk. The `roomAtJoin &&` guard is
1745
+ // load-bearing -- before first sync it is null, and treating null as an empty room would
1746
+ // classify every joiner's first creation as a race.
1747
+ //
1748
+ // Adopt the room's copy, because it is the real file and the agent needs it to work from,
1749
+ // and snapshot the local draft so nothing the agent wrote is lost. Then say so loudly: the
1750
+ // entire failure was the agent not knowing the file was already there.
1751
+ if (roomAtJoin && roomAtJoin.has(relPath) && !preexisting.has(relPath)) {
1752
+ captureSnapshot(relPath, disk, name, {
1753
+ force: true, kind: 'manual',
1754
+ label: `local draft preserved — ${relPath} already existed in the room before this client joined`,
1755
+ })
1756
+ bases.set(relPath, docText); forkBases.set(relPath, docText); shadow.set(relPath, docText)
1757
+ if (docText !== disk) writeToDisk(relPath, docText)
1758
+ try {
1759
+ say(`⚠ ${relPath} ALREADY EXISTED IN THE ROOM before I joined — I had not fetched it, so it was ` +
1760
+ `written here from scratch. The room's copy is now on disk and my draft was snapshotted. ` +
1761
+ `This folder holds a bounded working set: a file you cannot see may still exist, so read or ` +
1762
+ `claim the path before creating it. hive_status reports filesHeld of roomFiles.`)
1763
+ } catch { }
1764
+ if (process.env.HIVE_P14_DEBUG) log(`[P14] BRANCH=blind-recreate-refused ${relPath}`)
1765
+ return
1766
+ }
1495
1767
  if (!preexisting.has(relPath)) {
1496
1768
  // Terminate both sides before merging. With an empty base there is no shared
1497
1769
  // trailing context, so a side whose last line lacks a newline gets its final
@@ -1499,6 +1771,33 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1499
1771
  // which is worse than failing -- it reads as corruption to whoever opens it.
1500
1772
  const nl = (s) => (s === '' || s.endsWith('\n') ? s : s + '\n')
1501
1773
  const r0 = icrMerge3('', nl(disk), nl(docText), relPath)
1774
+ // HIV-P17: SILENT COLLISION DETECTION on genesis-publish creation race.
1775
+ // The normal merge path (below, ~line 1880) runs fusionReason() to catch merges
1776
+ // that broke valid code or duplicated structure. This creation-race path skipped
1777
+ // that check entirely — a dead-heat race could silently fuse two whole-file
1778
+ // rewrites of the same module and nobody was told. Now we run the same check:
1779
+ // if both inputs parsed but the merged result does not, or if the merge duplicated
1780
+ // structure, refuse it — keep both sides intact and announce loudly.
1781
+ if (!r0.conflict) {
1782
+ const why = fusionReason(r0.text, nl(disk), nl(docText), supports(relPath) ? languageFor(relPath) : null)
1783
+ if (why) {
1784
+ conflicted.add(relPath)
1785
+ // Do NOT write the fused result to doc or disk. The doc already holds docText
1786
+ // (the room's copy) and disk holds the local draft — both are intact. Setting
1787
+ // bases to docText means the next normal edit will merge against the room's copy,
1788
+ // which is the same recovery path the normal-merge refusal uses.
1789
+ bases.set(relPath, docText); forkBases.set(relPath, docText); shadow.set(relPath, docText)
1790
+ if (!manifest.has(relPath)) manifest.set(relPath, 1)
1791
+ if (icrWarned.get(relPath) !== why) {
1792
+ icrWarned.set(relPath, why)
1793
+ log(`[${name}] !! HIV-P17 REFUSED a fused creation-race merge of ${relPath}: ${why}`)
1794
+ try {
1795
+ say(`[!] @all ${relPath}: a creation-race merge was REFUSED because it fused rather than merged — ${why}. Nothing was written: the room's copy and ${name}'s local copy are both intact. Someone must reconcile them deliberately; a plain file write will merge against the other version again, hive_edit replaces it outright.`)
1796
+ } catch { /* the log still carries it */ }
1797
+ }
1798
+ return
1799
+ }
1800
+ }
1502
1801
  if (r0.text !== docText) fe.doc.transact(() => applyDiff(yt, r0.text))
1503
1802
  if (r0.text !== disk) writeToDisk(relPath, r0.text)
1504
1803
  if (r0.conflict) conflicted.add(relPath)
@@ -1533,14 +1832,31 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1533
1832
  try { say(`⚠ ${relPath} changed locally while ${name} was disconnected — the local edit and the room copy were merged${rj.conflict ? ', and CONFLICT markers need resolving' : ''}. Pre-merge local copy is in the file's history.`) } catch { }
1534
1833
  return
1535
1834
  }
1536
- // Genuinely no ancestor (a clone-then-join). Adopt the room's copy, keep ours as a
1537
- // restore point — and SAY SO. This branch used to be the only silent one on this
1538
- // path, which is why the data loss went unnoticed rather than merely being rare.
1539
- captureSnapshot(relPath, disk, name, { force: true, kind: 'manual', label: 'local copy at join (room copy adopted)' })
1540
- writeToDisk(relPath, docText)
1541
- bases.set(relPath, docText); forkBases.set(relPath, docText)
1542
- if (!snappedBase.has(relPath)) { captureSnapshot(relPath, docText, name, { force: true, kind: 'base', label: 'adopted from room at join' }); snappedBase.add(relPath) }
1543
- try { say(`↓ ${relPath} already existed in this room — ${name} adopted the room's copy. The local version before joining is saved in the file's history.`) } catch { }
1835
+ // Genuinely no ancestor (a clone-then-join, or joining with an existing checkout).
1836
+ // HIV-P9: Do NOT adopt the room's copy blindly. Check provenance!
1837
+ // Has the room ever seen what is currently on disk?
1838
+ const receipts = fe && fe.ledger ? fe.ledger.toArray() : []
1839
+ const st = accountFor({ rel: relPath, branchText: disk, roomText: docText, receipts })
1840
+
1841
+ if (st.state === DESCENDS || st.state === IDENTICAL) {
1842
+ // Safe: The room has passed through our disk content, so the room's copy is a true descendant.
1843
+ captureSnapshot(relPath, disk, name, { force: true, kind: 'manual', label: 'local copy at join (room copy adopted)' })
1844
+ writeToDisk(relPath, docText)
1845
+ bases.set(relPath, docText); forkBases.set(relPath, docText)
1846
+ if (!snappedBase.has(relPath)) { captureSnapshot(relPath, docText, name, { force: true, kind: 'base', label: 'adopted from room at join' }); snappedBase.add(relPath) }
1847
+ try { say(`↓ ${relPath} already existed in this room — ${name} adopted the room's copy. The local version before joining is saved in the file's history.`) } catch { }
1848
+ return
1849
+ }
1850
+
1851
+ // DIVERGED or UNPROVEN: The room has NEVER seen local disk's content, or has no proof.
1852
+ // Overwriting disk with docText would cause silent data loss (e.g. wiping out local fixes).
1853
+ // Merging from an empty base would concatenate both copies, creating invalid syntax.
1854
+ // Refuse adoption: keep local disk untouched, keep room doc untouched, snapshot local, and announce loudly.
1855
+ captureSnapshot(relPath, disk, name, { force: true, kind: 'manual', label: `local copy preserved at join (${st.state}: room copy refused)` })
1856
+ bases.set(relPath, disk); forkBases.set(relPath, disk)
1857
+ try {
1858
+ say(`⚠ ${relPath} already existed in room with different content (${st.state}) — room copy was NOT adopted. Local disk was preserved. Resolve deliberately.`)
1859
+ } catch { }
1544
1860
  return
1545
1861
  }
1546
1862
  const base = bases.has(relPath) ? bases.get(relPath) : disk
@@ -1956,7 +2272,7 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
1956
2272
  let myEditing = null, myLastEdit = null
1957
2273
  let editingClearTimer = null
1958
2274
  const warnedAt = new Map() // file -> last time we warned about co-editing it
1959
- const setUserState = () => provider.awareness.setLocalStateField('user', { name, kind, owner: owner || undefined, editing: myEditing || undefined, lastEdit: myLastEdit || undefined, v: PROTOCOL_VERSION })
2275
+ const setUserState = () => provider.awareness.setLocalStateField('user', { name, kind, owner: owner || undefined, editing: myEditing || undefined, lastEdit: myLastEdit || undefined, v: PROTOCOL_VERSION, passive: !!passive })
1960
2276
  function markEditing(relPath) {
1961
2277
  myEditing = { file: relPath, at: Date.now() }
1962
2278
  myLastEdit = myEditing
@@ -2058,16 +2374,106 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
2058
2374
  }
2059
2375
  if (syncFiles) provider.awareness.on('change', () => { renderMembers(); renderClaims(); checkVersions() })
2060
2376
 
2377
+ // HIV-P8: A FILE THAT WILL NEVER LEAVE THIS FOLDER, SAID OUT LOUD.
2378
+ //
2379
+ // HIV-P3 closed the genesis-claim hole at CLAIM time by classifying the claim string, and it
2380
+ // could only ever be a classifier: at claim time a bare string is all there is, and `config`,
2381
+ // `hosts` and `staging` are indistinguishable from ticket labels. At WRITE time there is no
2382
+ // ambiguity left — the file is on disk and isIgnored() is exact. So this is the backstop for
2383
+ // everything the classifier could not decide.
2384
+ //
2385
+ // IT CANNOT REFUSE. The bytes are already written by the time anyone knows, so this is
2386
+ // structurally a warning — and a warning is exactly what every born-invisible incident has
2387
+ // already scrolled past. That is why the claimed case opens an OBLIGATION instead of logging:
2388
+ // an obligation rides hive_wait, backs off, escalates to STALE and shows on the board. It is
2389
+ // un-ignorable by construction and costs nothing while nobody is idle.
2390
+ //
2391
+ // THE TWO GATES ARE THE WHOLE DESIGN, and the numbers are why. On a real checkout there are 256
2392
+ // ignored files. Warning about all of them would open 256 debts on join, each closable only by
2393
+ // its author, and the ledger would be unusable inside one join — the same flooding we spent this
2394
+ // morning clearing forty entries of. So:
2395
+ // CLAIMED the author declared they were working on this path. That is their own stated
2396
+ // intent, already in the CRDT — not a guess about the filename.
2397
+ // NOT PREEXISTING it appeared during this session, rather than having sat there for a week.
2398
+ // Neither alone is sufficient: without the claim gate, 256; without the other, every long-lived
2399
+ // ignored file re-fires on every join.
2400
+ //
2401
+ // THE UNCLAIMED CASE GETS ONE LINE AND NO LEDGER ENTRY. The room rule is CLAIM BEFORE YOU WRITE,
2402
+ // so an unclaimed write is outside the protocol and does not get to consume the ledger. I am not
2403
+ // confident this tier earns its place — a chat line is precisely the signal these incidents
2404
+ // scroll past — but deleting the case entirely is worse than announcing it cheaply.
2405
+ const ENGINE_ID = 'hivecode'
2406
+ const invisibleWarned = new Map() // relPath -> obligation id, or null for the ambient case
2407
+
2408
+ function noticeBornInvisible(ignoredRel) {
2409
+ // DISCHARGE FIRST. A file that has gone away takes its debt with it: the question "this will
2410
+ // never sync" stops being a question when there is nothing left to sync. Left open, the ledger
2411
+ // fills with debts about paths that no longer exist, which is the noise the three-state
2412
+ // lifecycle exists to prevent. Its expiry cannot help here — that only covers names never seen
2413
+ // in the room, and this path was seen, on disk, by us.
2414
+ for (const [r, id] of [...invisibleWarned]) {
2415
+ if (ignoredRel.has(r)) continue
2416
+ if (id) { try { OB.discharge(doc.getMap('obligations'), { id, by: ENGINE_ID }) } catch { } }
2417
+ invisibleWarned.delete(r)
2418
+ }
2419
+ for (const r of ignoredRel) {
2420
+ if (SKIP.has(r)) continue // control files are ours and are supposed to be invisible
2421
+ if (preexisting.has(r)) continue // it was already here; nobody did this during the session
2422
+ if (invisibleWarned.has(r)) continue // once per path, not once per scan tick
2423
+ const holder = coordinator.sense(r)
2424
+ if (holder && holder.by) {
2425
+ let id = null
2426
+ try {
2427
+ const rec = OB.open(doc.getMap('obligations'), {
2428
+ from: ENGINE_ID,
2429
+ to: holder.by,
2430
+ text: `${r} is on disk and claimed by you, but it is ignored by a .gitignore here — ` +
2431
+ `no sync connection is opened for it, so nothing written to it will ever reach the room. ` +
2432
+ `Add it to the allow-list, or confirm the work is deliberately local.`,
2433
+ absent: false,
2434
+ neverSeen: false,
2435
+ })
2436
+ id = rec && rec.id
2437
+ } catch { }
2438
+ invisibleWarned.set(r, id)
2439
+ try {
2440
+ say(`⛔ ${r} is claimed and on disk, but it is ignored by a .gitignore here — its bytes will never leave this folder.`)
2441
+ } catch { }
2442
+ } else {
2443
+ invisibleWarned.set(r, null)
2444
+ try {
2445
+ say(`· ${r} was created here but is ignored by a .gitignore — it stays local, and no other agent will see it.`)
2446
+ } catch { }
2447
+ }
2448
+ }
2449
+ }
2450
+
2061
2451
  function scan() {
2062
- const diskFulls = walk(ROOT)
2452
+ const skippedFulls = []
2453
+ const diskFulls = walk(ROOT, [], skippedFulls)
2063
2454
  const diskRel = new Set(diskFulls.map(rel))
2455
+ const ignoredRel = new Set(skippedFulls.map(rel))
2064
2456
  // Snapshot the starting file set BEFORE the first reconcile pass touches anything.
2065
2457
  // Everything here pre-dates our participation; anything that shows up later was
2066
2458
  // authored while we were connected. See `preexisting`.
2067
2459
  // The ancestor must be loaded BEFORE any path can reach reconcile(), and this is the
2068
2460
  // one place guaranteed to run first exactly once. Loading it later would mean the first
2069
2461
  // scan's reconciles see no ancestor — precisely the bug this is here to close.
2070
- if (!firstScanDone) { loadPriorShadow(); for (const r of diskRel) preexisting.add(r); firstScanDone = true }
2462
+ //
2463
+ // HIV-P8: THE UNION IS NOT A DETAIL. `preexisting` used to be seeded from diskRel alone, and
2464
+ // diskRel comes from walk(), which dropped ignored files — so `preexisting.has(r)` was
2465
+ // permanently FALSE for every ignored path, whether it was created a second ago or had been
2466
+ // sitting there for a week. Any check phrased as "ignored AND not preexisting" therefore
2467
+ // reduced to "ignored", and a client joining a real checkout would have opened an obligation
2468
+ // for each of its 256 ignored files, about files nobody touched. Seeding the union is what
2469
+ // makes "not preexisting" mean what it says: authored during this session.
2470
+ if (!firstScanDone) {
2471
+ loadPriorShadow()
2472
+ for (const r of diskRel) preexisting.add(r)
2473
+ for (const r of ignoredRel) preexisting.add(r)
2474
+ firstScanDone = true
2475
+ }
2476
+ noticeBornInvisible(ignoredRel)
2071
2477
  for (const full of diskFulls) {
2072
2478
  const r = rel(full)
2073
2479
  if (SKIP.has(r)) continue
@@ -2127,6 +2533,14 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
2127
2533
 
2128
2534
  provider.on('sync', (s) => {
2129
2535
  if (!s || !syncFiles) return
2536
+ // HIV-P14b. Snapshot what the room already had, once. Measured: the manifest IS populated at
2537
+ // this point -- a fresh joiner's observer fires with 13 of 13 entries before the sync event,
2538
+ // so reading it here is sound. (That was checked because the first version of this guard was
2539
+ // wrongly assumed to be failing for this reason.)
2540
+ if (!roomAtJoin) {
2541
+ roomAtJoin = new Set()
2542
+ try { for (const k of manifest.keys()) roomAtJoin.add(k) } catch { }
2543
+ }
2130
2544
  writeToDisk(RULES_FILE, HIVE_RULES_TEXT) // the law is always present in the room
2131
2545
  writeToDisk(AGENTS_FILE, AGENT_MANUAL_TEXT) // so an agent opening this folder learns how to join + behave
2132
2546
  // Connect to every file I'm granted AND have not excluded; each file-room's sync pulls
@@ -2162,6 +2576,31 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
2162
2576
  renderClaims() // unconditional: "nothing is claimed" is the answer an arriving agent needs most
2163
2577
  scan()
2164
2578
  log(`[${name}] folder sync active on ${ROOT} (room "${room}") as ${kind}. ${manifest.size} files.`)
2579
+ // HIV-P14. SAY THE GAP OUT LOUD, ONCE, AT JOIN.
2580
+ //
2581
+ // The working set is bounded on purpose, and the documented trade is that "a file outside it
2582
+ // does not arrive until something touches it". For a human reading a folder that is fine. For
2583
+ // an AI agent it is not, because an agent decides what exists by listing its directory: a
2584
+ // file it cannot see is a file it believes does not exist, and it writes one. Measured 21 Sep
2585
+ // 2026, a 40-file room and MAX_OPEN=8: the joiner held 7 files, reported "filesSynced 8/8",
2586
+ // said nothing, and its agent recreated a file the room already had.
2587
+ //
2588
+ // Nothing here changes the cap. It tells the agent the number it needs in order to ASK,
2589
+ // which is the one thing that makes "until something touches it" true.
2590
+ setTimeout(() => {
2591
+ try {
2592
+ const want = [...manifest.keys()].filter((r) => canOpen(r) && !SKIP.has(r))
2593
+ const have = want.filter((r) => fs.existsSync(path.join(ROOT, r)))
2594
+ const short = want.length - have.length
2595
+ if (short <= 0) return
2596
+ log(`[${name}] !! THIS FOLDER IS INCOMPLETE ON PURPOSE. The room has ${want.length} files; ` +
2597
+ `${have.length} are on disk here and ${short} are NOT. The working set is bounded to ` +
2598
+ `${MAX_OPEN} open files (HIVE_MAX_OPEN_FILES), because one socket is opened per file and a ` +
2599
+ `relay admits a limited number. A missing file EXISTS — it simply has not been fetched. ` +
2600
+ `Do not treat it as absent and do not create it: reading or claiming the path fetches it. ` +
2601
+ `hive_status reports filesHeld of roomFiles, and hive_read_board lists what the room holds.`)
2602
+ } catch { }
2603
+ }, 4000).unref?.()
2165
2604
  if (!scanTimer) {
2166
2605
  startWatch()
2167
2606
  scanTimer = setInterval(scan, watcher ? 2000 : 400) // watch handles fast path; scan is the net
@@ -2265,7 +2704,26 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
2265
2704
  isPaused, // is a participant currently paused?
2266
2705
  controls, // the live control map
2267
2706
  // --- hive coordination: claim a region BEFORE editing (collision prevention) ---
2268
- claim: (region, intent) => { const r = String(region), i = String(intent || 'edit'); myIntents.set(r, i); return coordinator.acquire(r, i) }, // true iff you hold it (my intent recorded either way — it's what my receipts sign)
2707
+ // HIV-P18: a claim is a promise about BYTES, so granting one over bytes the claimer cannot
2708
+ // see is the same false success we shut in the outbound direction (HIV-27: a claim whose
2709
+ // writes could never leave). The claim itself is unchanged -- callers and every existing
2710
+ // suite still get the same boolean -- but it now also starts the fetch the README has been
2711
+ // promising, so an agent that claims a path it does not hold actually receives it instead of
2712
+ // finding an empty directory and creating the file from scratch.
2713
+ claim: (region, intent) => {
2714
+ const r = String(region), i = String(intent || 'edit')
2715
+ myIntents.set(r, i)
2716
+ const held = coordinator.acquire(r, i)
2717
+ // Fire-and-forget on purpose: claim's contract is synchronous and changing that would
2718
+ // break every caller. Use fetch(path) directly when you need to WAIT for the bytes.
2719
+ if (held) { try { fetchFile(r).catch(() => {}) } catch { } }
2720
+ return held
2721
+ }, // true iff you hold it (my intent recorded either way — it's what my receipts sign)
2722
+ // HIV-P18: bring a file the room has but this folder does not. Resolves when the BYTES have
2723
+ // landed, and distinguishes "outside the working set" (fetchable) from "not in the room at
2724
+ // all" (nothing will ever arrive) -- two states that look identical from an empty directory
2725
+ // and have opposite remedies.
2726
+ fetch: fetchFile,
2269
2727
  // RELEASE IS A HANDOFF, AND A HANDOFF CAN BE REFUSED.
2270
2728
  //
2271
2729
  // Until the room sets `gate:cmd`, this behaves exactly as it always did and returns
@@ -2367,7 +2825,7 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
2367
2825
  const u = s.user
2368
2826
  if (!u || !u.name) continue
2369
2827
  const prev = seen.get(u.name) || {}
2370
- seen.set(u.name, { ...prev, ...u, editing: u.editing || prev.editing, owner: u.owner || prev.owner })
2828
+ seen.set(u.name, { ...prev, ...u, editing: u.editing || prev.editing, owner: u.owner || prev.owner, passive: !!(u.passive || prev.passive) })
2371
2829
  }
2372
2830
  return [...seen.values()]
2373
2831
  },
@@ -2386,11 +2844,42 @@ export function startSync({ relay = 'ws://localhost:1234', room = 'default', dir
2386
2844
  // whose own socket the relay refused. They are not slow, they are not arriving, and
2387
2845
  // until they do they read as empty. filesSynced alone shows a shortfall but not a cause.
2388
2846
  const notSyncing = [...refusedFiles.keys()].filter((r) => { const e = fileDocs.get(r); return e && !e.synced })
2847
+ // HIV-P14. THE FULL-HOUSE LIE.
2848
+ //
2849
+ // `files` and `filesSynced` both counted OPEN docs, so a client holding eight of the
2850
+ // room's forty files reported "filesSynced 8/8" -- a complete set. Measured 21 Sep 2026:
2851
+ // a second agent joined a 40-file room, received 7, stayed at 7 for a full minute, and
2852
+ // reported 8/8. Its manifest listed all forty the whole time.
2853
+ //
2854
+ // The bounded working set is deliberate and correct -- one socket per file against a 512
2855
+ // ceiling is the wall, and tests/open-file-cap-test.mjs documents the trade rather than
2856
+ // hiding it: "a file outside the working set does not arrive until something touches it."
2857
+ // What that header does not cover is that FOR AN AGENT, NOTHING EVER TOUCHES IT. An agent
2858
+ // decides what exists by reading its folder; a file it cannot see is a file it believes
2859
+ // does not exist, so it writes one from scratch. Measured consequence, same probe: agent B
2860
+ // created mod039.js, and agent A's copy ended up holding two const declarations of the
2861
+ // same name -- invalid code, in someone else's folder, from B doing the only reasonable
2862
+ // thing available to it.
2863
+ //
2864
+ // So the trade stays and the reporting changes. `files` keeps meaning open docs, because
2865
+ // tests/open-file-cap-test.mjs:71 pins it as the proof the cap is respected. What is added
2866
+ // is the pair that was missing: what the ROOM has, and what this client actually HOLDS.
2867
+ const roomFiles = (() => { try { return [...manifest.keys()].filter((r) => canOpen(r)).length } catch { return 0 } })()
2868
+ const held = (() => {
2869
+ let n = 0
2870
+ try { for (const r of manifest.keys()) { if (canOpen(r) && fs.existsSync(path.join(ROOT, r))) n++ } } catch { }
2871
+ return n
2872
+ })()
2389
2873
  return {
2390
2874
  connected: !!provider.wsconnected,
2391
2875
  connecting: !!provider.wsconnecting,
2392
2876
  files: fileDocs.size,
2393
2877
  filesSynced: synced,
2878
+ // The honest pair. `filesHeld` of `roomFiles` is the number a joiner needs, and the one
2879
+ // that says 7 of 40 where filesSynced said 8 of 8.
2880
+ roomFiles,
2881
+ filesHeld: held,
2882
+ filesMissing: Math.max(0, roomFiles - held),
2394
2883
  notSyncing: notSyncing.length,
2395
2884
  notSyncingFiles: notSyncing.slice(0, 20),
2396
2885
  // The working set and its bound. `openCap` x agents must stay under the relay's