30 KiB
Package: bare-os-booter
Former DOCUMENTATION.md §§12.1–12.9 plus §12.7a (REPL completion). Reference index →
12. Package: bare-os-booter
12.1 packages/bare-os-booter/package.json
Resolved hyperstack (hoisted root lockfile, illustrative): after npm install at the repo root, node_modules/protomux and node_modules/hyperswarm versions are pinned in package-lock.json and guarded by packages/bare-os-booter/test.runtime.js (fixtures/protomux-hyperswarm-lock.json, **schema 2** metadata row). Intentional upgrades require bumping that fixture alongside the lockfile.
Hyperbee guest hints: ctx.bareOsHyperbeeGuestHint() (when BARE_OS_HYPERBEE_GUEST_INDEX is set) returns read-only JSON aligned with optional hyperbee2-style guest indexes — see ADR-hyperbee-guest-index.md; the stock kernel does not import Hyperbee by default.
main—./index.jsscripts.start/dev—bare index.jsscripts.test—brittle-bare test.identity.jsthennode --require ./scripts/bare-node-test-shim.cjs … brittle-node test.js(shim supplies a chainableBare.on, stubsbare-thread/bare-workereven when ESM resolves them by absolute path, Bare-stylebare-typebinding + Nodeutil.inspectstand-in forbare-inspect;openssl/ssh-keygendelegates lazy-loadbare-cryptoso the main suite does not import native addons at startup)dependencies— Same hyperstack as seeder +bare-os-protocol+bare-crypto(identity account + vault AEAD) +@qvac/sdk(local QVAC LLM for/bin/agent; leanqvac.config.json= llamacpp completion only). SetBARE_OS_SKIP_QVAC=1or pack with--skip-qvacto stub natives. Bridge:ctx.bareOsQvacAvailable/Status/LoadModel/UnloadModel/Complete(lib/bare-os-qvac-host.mjs); pack graph viabare-os-qvac-pack-anchor.mjs. Models download on first agent use (not seeded in the system image).devDependencies—brittleimports—#host-fs/#host-pathresolve tobare-fs/bare-pathunder Bare and Node’s built-infs/pathunder the default condition (packageimportscannot targetnode:URLs). First-party sources import#host-*only (CI forbids barefrom 'fs'/from 'path').urlmaps tobare-url/node:url.**#bare-os-boot-manifest-sig** selects Bare vs Node Ed25519 verify helper.pear.stage.ignore— Includestest.js,test.identity.js,.test-dataso tests are not staged
Pear + npm workspaces: dependencies are hoisted to the repo root; Pear’s dev bundle often does not follow a single symlinked node_modules tree. scripts/ensure-pear-node-modules.mjs (run from the repo root) rebuilds packages/bare-os-booter/node_modules by symlinking each top-level package from the root node_modules (matching npm’s flat hoist). pear.stage.include lists node_modules so the staged Hyperdrive uses node_modules/<pkg> paths (Bare require('bare-node-net') and similar resolve correctly; ../../node_modules alone did not). For bare-ssh2, bare-net (Bare TCP) and the bare-node-* shims it loads are direct dependencies of the booter so versions match the vendored bare-ssh2 tree and Pear staging always sees them. npm run os:booter runs the script before pear run. After npm install at the root, re-run the script if hoisted packages change.
12.2 packages/bare-os-booter/lib/host/paths.js
packageRootDir(metaUrl)— Same as seeder (Pear RTI /swapDir/cwd).defaultBootCorestorePath/defaultLocalSeedCorestorePath—BARE_OS_BOOT_STORE/BARE_OS_LOCAL_SEED, or underhostDataRoot()(BARE_OS_HOST_DATAor~/.bare-os):corestore/booterandcorestore/seederrespectively. Same signature stability as the seeder helper.
12.2a Boot modularity (loader, capabilities, lifecycle)
lib/bare-os-kernel-loader.js—loadOsFromPeers,loadOsFromOfflineLkg: seed capability handshake + optional RPC wave, MBR read, system Hyperdrive open/replicate,/boot/init.jsfetch, personal drive mount (when not lazy). Invoked fromindex.jsinside the boot timeout race.lib/bare-os-capability-registry.js—KERNEL_CAPABILITY_SEED_STRICT_ROWS,buildStockKernelCapabilityWords,freezeKernelCapabilityWordsFromCapabilities: single place for stock capability word math used by the booter and loader.lib/bare-os-lifecycle-manager.js—exitHostProcess,teardownBareOsBootResources:Bare.exitdeferral and ordered HDMS → swarm → drives → Corestore teardown (Pear heap safety).lib/bare-os-posix-errno.js— POSIX-inspired errno names used by syscall //procJSON surfaces.
See also Kernel subsystem map and ADR 0001.
12.2b Corestore / swarm suspend–resume bridge
lib/corestore-host-lifecycle.js— Registers one-shot hooks so guestctx.bareOsRegisterSuspendHook/bareOsRegisterResumeHookcall hostcorestore/hyperswarm**suspend()**/**resume()**when those methods exist (mobile sleep, Pear lifecycle). Corestore 7.12+ no longer flushes onsuspend(); the hook **flush()**es open sessions first. Host stores are constructed withlib/corestore-opts.jstreeCache(maxSize: 8192). Non-goal (stock booter): automaticcorestore-snapshot/ frozen peer images from the guest — operators replicate Hyperdrives via swarm + personal-drive export of keys when needed;bareOsCorestoreSnapshotOperatorHintin/procis an advisory field only (no guest RPC that invokescorestore-snapshot).
12.3 packages/bare-os-booter/index.js
Imports — Hyperswarm, Protomux, protocol, ./lib/p2p/swarm-disk.js, ./lib/boot/kernel-runner.js, ./lib/boot/bare-os-kernel-loader.js, ./lib/security/bare-os-capability-registry.js, ./lib/host/bare-os-lifecycle-manager.js, ./lib/vfs/vfs.js, ./lib/shell/shell.js, ./lib/host/paths.js, ./lib/tools/bare-os-ipc.js, ./lib/ctx/bare-os-runtime-caps.js, stdio/readline/repl/boot-splash helpers, ./lib/identity/identity-session.js.
bootStorePath() — defaultBootCorestorePath(_pkg, import.meta.url).
createReadLine()
- If
BARE_OS_SKIP_REPL === '1': returnsasync () => null. - Else prefers fish-style /
bare-readlineraw TTY editing when stdin is a TTY; falls back to a stream line reader (nonode:readlinein the stock boot path). - On failure: warns and returns
async () => null.
executeKernel(disk, store, swarm, initSource) (store/swarm unused but kept for signature symmetry / future use)
- Builds
shellEnvwith guest defaults:USER/LOGNAME=guest,HOME/PWD=/home/guest,UID/GID=65534,BARE_OS_IDENTITY=guest,BARE_OS_EXIT_STATUS=0,BARE_OS_CTX_API_VERSION,PATH=/bin,SHELL,HOSTNAME,0. When the host sets any of the keys listed under “host → session passthrough” in Environment variables and POSIX appendix, those values are copied intoshellEnv. SetsBARE_OS_BOOT_PROFILE_RESOLVEDfromBARE_OS_BOOT_PROFILEor the first line of/etc/bare-os/profile, andBARE_OS_SESSION_ID(random UUID). Seeds/run/bare-os/boot.jsonfieldsimageDigest,pearChannel,pearReleasefromBARE_OS_IMAGE_DIGEST,BARE_OS_PEAR_CHANNEL/PEAR_CHANNEL,BARE_OS_PEAR_RELEASEwhen present. createBareOsIpc({ maxFifoBytes, maxChannels?, perChannelMaxBytes?, ipcRpcToken?, enableFanout?, maxJsonRpcLineBytes?, posixMqDefaultMaxmsg?, posixMqDefaultMaxBytes?, posixMqMaxmsgCeiling? })(bare-os-ipc.js) — FIFOs under/run/bare-os/ipc/<name>; optional per-name byte caps fromBARE_OS_IPC_CHANNEL_MAX_BYTES; optional global channel capBARE_OS_IPC_MAX_CHANNELS(host passthrough); POSIX MQ defaults fromBARE_OS_POSIX_MQ_MAX_MSGS/BARE_OS_POSIX_MQ_MSG_BYTES; JSON-RPC with optional token and line cap; fan-out**fanoutPublish/fanoutSubscribe**;statsincludes fan-out counts, quota telemetry, and operator backpressure snapshots when caps exposefeatures.ipcFanout.createVfs(drive, personalDrive, shellEnv, vfsMountRef, vfsOptions)→ctx.vfs(sameenvobject asctx.env).vfsOptionssupplyprocSnapshot, dynamic/proc/*and/sys/*text (quotas JSON,bare_os_featureswithbits–bits5when advertised,bare_os_net_summary,bare_os_host_os,bare_os_sync_window,bare_os_debug, net/disk stubs, session stats),bootProfileText,sessionText,initdRunText,bootReadyJsonText, mount map for/proc/mounts,bootStartedMsfor/proc/uptime, etc. Exposesvfs.watch(logicalPath)for Hyperdrive-backed paths whenBARE_OS_VFS_WATCHis not0. Operator blind-relay sketches (blind_relay_router,blind_pairing_sketch,relay_geo_hint) return schema 1 JSON withoperatorRedacted: trueuntil the host setsBARE_OS_PROC_BLIND_PEER_RELAY_HINTS.kernel-runner: whenBARE_OS_BARE_SUBPROCESS_BRIDGEis set,BARE_OS_BARE_SUBPROCESS_TIMEOUT_MScan defaultrunBintimeouts.applyGuestEnv(ctx)thenensureGuestHome(ctx)— normalizesctx.identityand seeds/.bare/(and a guest marker) on the personal drive.createReadLine()always resolves stdio first and returnsstdout(may benull) alongsidereadLineso the kernel can write to the same stream as the REPL (includingbare-stdiounder Pear).- Builds
ctx:bareOsCtxApiVersion(frombare-os-ctx-api.js),bareOsRuntimeCaps(frozen snapshot frombare-os-runtime-caps.js: pipeline limits,quotas, pseudo path list, feature flags such asvfsWatch,ipcRpcJson,initdSocketActivation),bareOsIpc,disk,drive,personalDrive,vfs,env,console,b4a,topic: topicKey(),readLine,writeScreen(str),bareOsSubscribeBootEvent/bareOsEmitBootEvent,bareOsSubscribeHdmsLifecycle,bareOsAwaitInitdUnits,bareOsPublishBootReady,execLine→ wrapsexecShellLinewith optional audit (BARE_OS_AUDIT,BARE_OS_AUDIT_JSON, redaction),**execLinedepth cap** (BARE_OS_EXEC_MAX_DEPTH), then the shell (returns'ok'or'exit'; updatesBARE_OS_EXIT_STATUSinvfs.env; bareexitline sets status thenrequestBooterExit),**runBinCommand(argv)**→ delegates to**runBinCommand(this, argv)** fromkernel-runner.js(for/bin/timeand similar), plus identity hooks for/binand builtins:applyUnlock(passphrase)— load/.bare/account, decrypt, unlock session.applyRegister(passphrase)— create account file, unlock.applyLogin({ publicKey, secretKey })— set session from an already-decoded keypair.applyLogout({ save? })— optionalsaveruns encrypted vault snapshot first (seeidentity-session.js).saveVault()— encrypt personal-drive files into/.bare/vault/(skips/.bare,bin,boot, history paths).registerKernelShutdownHook(fn)— register async/sync teardown beforestopBareInitdwhen the REPL session cleans up.
- After
createKernelReplSession: wiresreadLine,console,execLine,suspendReplForSubprocess/resumeReplAfterSubprocess, attachesctx.tui/ctx.sdk(omit withBARE_OS_TUI=0; image source/lib/bare-os/tui.js), thenawait startBareInitd(ctx)(stock units includekernel-logger,bare-os-www— loopback static HTTP for~/.www—bare-holesail(managed~/.holesail/state.json:seed,key, stockbare-www-*/bare-ssh-*rows),bare-cron,bare-openssh,bare-os-chatwhen enabled, …). - Sets
disk.osafter initd withcreateBareOsDiskOsBridge(searchLocalwith optional path manifest, whitelistedexecRpc/bare_os.*,disk_os_hintsschema 3,replication_operator_sketchschema 7, cap-gatedreplication_operator_intentwhenBARE_OS_DISK_OS_OPERATOR_INTENT_RPC=1) — peers useSwarmDiskmessages 3–6; seebare-os-disk-os-bridge.jsand §12.4. ctx.bareOsHrpcRequest(stock) — validatesservice,method, objectpayload; optionalBARE_OS_HRPC_ALLOWLIST_JSON; built-in routeskernel.ping,kernel.capabilities,vfs.readText,bare_os.echo,bare_os.disk_os_hints,bare_os.search_local,bare_os.replication_operator_sketch,bare_os.replication_snapshot,bare_os.pkg_index_get(**BARE_OS_HRPC_ROUTE_TABLE_SCHEMA_VERSION3**).BARE_OS_HRPC_EMIT_UNLISTEDforwards unknown routes toprocess.emit('bare-os:hrpc-request', …)on Node when enabled.try { await runKernelFromSource(...) } finally { await session.cleanup() }— cleanup runsbareInitdShutdownActiveUnitsReverse,runKernelShutdownHooks,stopBareInitd, fish TTY teardown.
boot-splash.js — TTY splash (disabled when stdout is not a TTY or BARE_OS_NO_SPLASH=1): initial full-screen clear and hidden cursor, then centered redraws from the top-left without erasing the whole screen each tick (reduces flicker); one full clear again if the terminal is resized. Vertically and horizontally centered “card” (Unicode box frame when wide enough; compact rules on very narrow widths). On very wide terminals the framed card (and progress bar) width is capped so the bar does not span the entire display. Layout scales with stdout.columns / stdout.rows (sensible fallbacks): more log lines on tall terminals (capped), word-wrapped phase text, ANSI-safe centering. createBootSplash(stdout, { bootLimitMs?, tagline?, footerLines? }) — optional tagline and dim footerLines; **main()** passes booter and protocol package versions. Braille spinner, elapsed boot timer, bar vs BARE_OS_BOOT_TIMEOUT_MS (default 60s), shimmer title. prepareForKernel() stops the splash ticker, clears again, and shows the cursor before the fish shell; fail() centers a wrapped error message.
loadOsFromPeers(disk, store, swarm, splash) (network boot path used by main())
- Optional pre-MBR
disk.rpc('bare_os', 'capabilities', …)when peers exist andBARE_OS_SEED_RPC_HANDSHAKEis not0/false; result stored ondisk.seedCapabilityInfo;BARE_OS_SEED_CAP_STRICT/BARE_OS_SEED_CAP_FAILtighten failure behavior. disk.read(0)→parseMbr.- Stores boot provenance as
disk.mbrKeysHexanddisk.bootMbr512(exact 512-byte copy) for later peer-assist eligibility. - For each MBR key:
Hyperdrive(store, driveKey),ready(), replicate on alldisk.peers’ mux streams, join drive discovery,findingPeers+swarm.flush, poll up to 30×200ms for/boot/init.js. - On success:
initPersonalDrive,splash.prepareForKernel(),executeKernel.
Peer-assist helper path: lib/bare-os-peer-system-seed.js computes peerSystemSeedMirror eligibility and builds snapshot mirrors with buildPeerSeedSnapshots (including mbr_layout from seedMbrLayout). When eligible, index.js writes bootMbr512 into localRAM and serves mirrored bare_os.* RPC responses through disk.os for cold joiners.
main()
resolveStdio()→createBootSplash,splash.start()(initial clear).Corestore(bootStorePath()),Hyperswarm,SwarmDisk, jointopicKey().- Wait until
disk.peers.size > 0orBARE_OS_BOOT_TIMEOUT_MSelapses (default 60000). There is no local seed fallback; without peers, boot fails. Promise.racebetweenloadOsFromPeersand the remaining time within the same deadline so the whole network boot finishes within the limit.finally:swarm.destroy()first, then close drives andstore(each in try/catch).exitHostProcess:Bare.exitorprocess.exit.
Entry: main().catch(…).
12.4 packages/bare-os-booter/lib/p2p/swarm-disk.js
SwarmDisk class
State: localRAM, peers (Set of { chan, mux, socket, id }), pendingReads, pendingSearches, pendingRpc, counters, drive, personalDrive, os, seedCapabilityInfo (last bare_os.capabilities handshake or error object), mbrKeysHex (MBR-derived key list), bootMbr512 (boot-time 512-byte copy), seedMbrLayout (optional bare_os.mbr_layout snapshot), and peerSystemSeedActive (helper mirroring active).
initPersonalDrive(store, swarm, Hyperdrive)
store.namespace('bare-os-personal-v1'), newHyperdrive(localStore), ensure writable, structured host log (seeemitSwarmDiskHostLog— stderr JSON whenBARE_OS_BOOT_TRACE=json|ndjson, else stderr /console.warn),swarm.join(personalDrive.discoveryKey).
addPeer(mux, socket)
- Builds
contextwithonread/ondata/ongossip/onsearchreq/onsearchres/onrpcreq/onrpcreswired to Protomux messages 0–6 (same order as seeder + hyper-os style): read request, data, gossip buffer, search req/res, RPC req/res. chan.open(), track peer, handshake-basedpeer.id, remove peer onmux.streamclose.- If
this.drive/this.personalDriveset,replicate(mux.stream, { live: true, download: true })for system drive.
read(index)
- If
localRAM.has(index), return cached. - Else broadcast message 0 to all peers, single consumer callback from message 1, 60s timeout.
search(query)
- Fan-out message 3 to all peers with a single correlation id per
search()call.pendingSearchesholds an aggregate state: each peer response appends matches until all peers have answered or a 3s timeout fires, then the map entry is cleared. Concurrent searches use distinct ids (searchIdCounter), so operations do not overwrite each other’s callbacks.
rpc(module, method, args?, timeoutMs?)
- Sends message 5 to the first peer in
peers; awaits message 6; parsesresultas JSON when possible. Used for the pre-bootbare_os.capabilitieshandshake and operator tooling.
12.5 packages/bare-os-booter/lib/boot/kernel-runner.js
AsyncFunction=Object.getPrototypeOf(async function () {}).constructor.
runKernelFromSource(source, ctx)
new AsyncFunction('ctx', source + guard + 'return start(ctx)')where guard checkstypeof start === 'function'.
runBinCommand(ctx, argv)
- Host delegates first —
host-delegate-registry.jsregistersgit,curl,wget,openssl,ssh-keygen,tar,systemctl/bare-initctl/journalctl,warc,archive(ustar front-end),hrpc,bundlebee,sidecar, andpear-runtime-matrixviahost-bridge-cli.js, with static imports (Pear-safe). Each delegate checksBARE_OS_DELEGATE_ALLOW; denied kinds exit 126.curlandwgetare Fetch-based subsets (not libcurl / full GNU wget);/bin/curland/bin/wgeton the image callctx.bareOsRunCurlCli/ctx.bareOsRunWgetCliwhen present—see HTTP: curl and wget./bin/systemctland/bin/journalctlcallctx.bareOsRunSystemctlCliwhen present (same backend as the host delegate). Host bridge CLIs:hrpc probeprintsbareOsHrpcAllowlistProbe()(optionalBARE_OS_HRPC_ALLOWLIST_JSON);hrpc requestalways callsctx.bareOsHrpcRequest(stock handler supports validated built-in routes such askernel.ping,kernel.capabilities,vfs.readText; host overrides remain supported andBARE_OS_HRPC_BRIDGE_WIRED=1still advertises host bridge capability).bundlebee hintemitsbare-os:bundlebee-cli;bundlebee statusprintsBARE_OS_BUNDLEBEE_STAGE_JSON.sidecar cap <class>callsbareOsSidecarResourceCap.pear-runtime-matrixprintsbareOsPearRuntimeMatrixProbe()(optionalBARE_OS_PEAR_RUNTIME_MATRIX_JSON).BARE_OS_SIDECAR_BRIDGE_WIRED/BARE_OS_BUNDLEBEE_CLI_WIREDare advertised viabareOsHostCapabilityfor operator probes. - If
argv[0]isgit(or a POSIX path whose basename isgit, but not./gitor../git), delegates torunGitCliingit-cli.js. - If
argv[0]iscurlunder the same basename rules, delegates torunCurlCliincurl-cli.js. - If
argv[0]iswgetunder the same basename rules, delegates torunWgetCliinwget-cli.js. - If
argv[0]contains/, resolves withctx.vfs.resolveLogical,route, loads script bytes from the routed Hyperdrive (getwithfollow). - Else walks
$PATH(ctx.vfs.env.PATH, default/bin), joining each directory withunix-path-resolve(dir, cmd)(not three-argument resolve), loads from systemctx.driveonly. - Builds
AsyncFunction('ctx','argv', ...)with the script source plusif (typeof run === 'function') await run(ctx, argv)(top-level statements run first; optionalrunmatches/binutilities). - Unknown command:
ctx.console.log('unknown command: ...').
resolveBinInPath(ctx, name) — returns the first PATH hit on the system drive (absolute /bin/... path string) or null; used by shell command -v / type.
12.6 packages/bare-os-booter/lib/vfs/vfs.js
createVfs(systemDrive, personalDrive, env, mntRef?, vfsOptions?)
- Logical paths under
$HOME(booter default/home/guest; afterlogin,/home/<pubkey-prefix>) map to the personal Hyperdrive under/.bare-os/home/<basename>/…;/var/logand/tmpmap to/.bare-os/var/log/…and/.bare-os/tmp/…with the same basename. Read-only synthetic/procand/sys(optionalvfsOptionsfor version/cmdline, quotas JSON, net/disk stubs,/run/bare-os/*text providers, mount map, union policy, seed handshake, virtual registry, etc.). Optional union read overlays via envBARE_OS_VFS_UNION_PREFIXES; optionalBARE_OS_VFS_UNION_WRITE_DENYblocks writes under those prefixes. All other absolute paths use the system drive (read-mostly OS image). resolveLogical(p)—unix-path-resolve(cwd, p)so cwd + relative segments work (theunix-path-resolvepackage only accepts two path arguments).- API:
getcwd,chdir(rejects regular files),readFile,writeFile/unlink(personal only),exists,readdir,stat/lstat,readlink,symlink,chmod,mkdir(recursive via.bareos_emptymarker),rmdir(empty dirs; marker-aware),rm(recursive tree walk),route,resolveLogical,env,watch(logicalPath)(Hyperdrive-backed paths only; throws on pseudo/proc/**/sys**/**/run//dev** and on virtual**$HOME**,/var,/mntroots). - Hyperdrive quirk:
entry/get/existsusestd(path, false)and throw on path'/'(Invalid filename: /). The VFS special-cases drive path'/'(logical/and personal$HOMEroot) forchdir,stat,exists,isRegularFile, and blocksreadFile/put/delon that key. - Bare / Pear: do not rely on global
TextEncoder/TextDecoderin booterlib/*.js; this tree usesb4afor UTF-8 where needed (pseudo/proccontent, symlink size invfs-posix-meta.js,systemctllog tailing, etc.).
12.7 packages/bare-os-booter/lib/shell/shell.js
defaultShellAliases— includesll,la,l,..,...as the baseline merged from~/.barerc.tokenize/expandWord/parsePipeline— POSIX-ish words,'...',"...",\,|,||,&&,;,>,>>,<;$VARand${VAR}; pipelines split on|;;splits lists;&&/||short-circuit usingctx.exitCode(left-associative).execShellLine(ctx, line)— semicolon-separated lists, then per segment AND-OR chains of pipelines; leadingNAME=valueassignments (blocked forctx.shellReadonlyVars), redirections, builtinsalias,barerc(barerc reloadre-parses~/.barercand reapplies theme),unalias,cd,export,unset,readonly,umask,:,command,type,login,logout,exit,jobs,fg,wait, elserunBinCommand. OptionalBARE_OS_SHELL_CMDSUBSTenables bounded$(…); optionalBARE_OS_SHELL_STREAMING/BARE_OS_SHELL_STREAMING_MULTrelax pipeline capture caps. Trailing**&** at list depth runs prior segments in the background (async jobs table).command -v/-VandtypeuseresolveBinInPath.login/logoutcall the samectx.applyRegister/ctx.applyUnlock/ctx.applyLogouthooks as/bin/loginand/bin/logout. Capturesconsole.logfor pipes and file redirection;>/>>target paths viactx.vfs.writeFile(personal tree). Returns'exit'when theexitbuiltin runs. After each completed line (except empty input),syncBareOsExitStatusEnvwritesctx.exitCodetovfs.env.BARE_OS_EXIT_STATUS;expandWordmaps**$?**/**${?}** to that value.listBareOsShellBuiltins(env)— stable list of builtin names for highlighting and completion parity (includes optionalreadwhenBARE_OS_SHELL_READ_BUILTINis set).
12.7a REPL line editor and completion
Narrative reference: Shell completion and REPL editor.
lib/repl-session.js—createKernelReplSession: chooses Fish-stylecreateFishReadLinewhen**BARE_OS_FISH≠0**, TTY raw mode works, andBARE_OS_SKIP_REPLis off; wiresctx.console/ctx.readLine/writeScreento the same stdout as the prompt.lib/fish-readline.js— History file on the personal drive, ghost suggestions, reverse search, Tab menu or inline cycling (BARE_OS_COMPACT_MENU/ narrow columns), Ctrl+Space man preview, save/restore cursor + erase-to-EOS so menu redraws do not stack stale lines.lib/completion-engine.js—parseCompletionContext,gatherCompletionItems,completeLine,rankCompletionItems,suggestGhostFromHistory, VFS timeouts,/share/man/man.jsoncache,ctx.bareOsRegisterCompleterregistry.
12.8 packages/bare-os-booter/lib/identity/identity-account.js
- On-disk
/.bare/account(v2): magicBAREOS01, version2, 32-byte Ed25519 public key (bare-crypto), 16-byte PBKDF2 salt, 4-byte iteration count (big-endian), ChaCha20-Poly1305 seal of the 64-byte Ed25519 private key material (nonce + ciphertext + tag). Passphrase stretching: PBKDF2-SHA256 (210000iterations by default). v1 (libsodium) files are rejected with a message to runlogin --new. - **
encodeAccount/decodeAccount/encodeNewAccount**,**sealBytes/openBytes**,vaultKeyFromSecret,hashUtf8Path— shared byidentity-session.js(vault snapshots use the same AEAD).
12.9 packages/bare-os-booter/lib/identity/identity-session.js
applyGuestEnv/applyUnlockedEnv— setctx.vfs.env(BARE_OS_PUBLIC_KEY,BARE_OS_IDENTITY,USER,HOME, derivedUID/GIDfrom pubkey hash for logged-in users) andvfs.chdirto the new home.applyUnlockedEnvcallsloadBarercafter unlock (createSkeletonIfMissing: trueon first login) so~/.barercapplies without restarting the session. Both paths callbareOsResetShellIdentityState(clear simulatedshellBackgroundJobs),syncVfsIdentitySession(vfs.bareOsIdentitySession, warm-cache invalidation,ctx.bareOsInvalidateWarmReadCaches('identity-switch')when present), optionalctx.bareOsReloadFishHistoryForIdentity(fish readline), optionalscrubGuestWorkspaceswhen**BARE_OS_GUEST_SCRUB=1**.migrateLegacyPersonalHomeIfNeeded— lifts legacy flat/personal-drive entries into the active/.bare-os/home/<segment>/…once per segment; records/.bare-os/migration/legacy-root-v1.json. Guest skips when/.bare/accountexists unlessBARE_OS_PERSONAL_ROOT_MIGRATE=guest.BARE_OS_PERSONAL_ROOT_MIGRATE=skipdisables all lifts;unlocked-onlyskips guest lifts.registerIdentity/unlockIdentity/logoutIdentity/saveVaultToDrive— personal Hyperdrive persistence and encrypted vault index under/.bare/vault/.saveVaultToDriveskips otherbare-os/acct/…subtrees whenBARE_OS_PERSONAL_ACCT_PREFIXis on so vault export does not bundle sibling accounts.