Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-5833]): collapse server-side .env helpers onto portosEnv
[._.]/ Adam Eivycfc10713a6f7
diff --git a/server/lib/README.md b/server/lib/README.mdindex 43b1e1ff51..6aec9f018a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -228,6 +228,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. || `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, directory helpers, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. || `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |+| `portosEnv.js` | Single server-side helper for PortOS's own `.env` (`PORTOS_ENV_PATH` anchored to `installRoot` per #1947, `parseEnvContents`, `readPortosEnvValue`, `upsertPortosEnvLine` + `upsertEnvLine`), with replacer-function guard for `$`-patterns and `process.env` wins precedence; `scripts/lib/envFile.js` stays as the zero-dependency boundary copy. || `secretText.js` | `scrubSecretTokens(text)` — replace credential-SHAPED substrings (prefixed API keys, GitHub/Slack tokens, JWTs, AWS key ids, pasted Bearer headers, 48+-char hex) with `[REDACTED]` in free text bound for an LLM provider or a world-readable artifact; `scrubSecretTokensDeep(value)` walks arrays/plain objects and scrubs every string value. Value-side counterpart to the operator-action ledger's key-based `redactPayload` and `commandSecurity.js#redactOutput`'s JSON patterns; conservative so prose, 40-hex git SHAs, and short ids survive. || `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). || `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 0978235428..ca8ca638f1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -220,6 +220,7 @@ export * from './agentInstructionsFile.js';export * from './fileCore.js';export * as fileUtils from './fileUtils.js';export * from './fileWriteQueue.js';+export * from './portosEnv.js';export * from './homePath.js';export * from './jsonIo.js';export * from './mimeTypes.js';diff --git a/server/lib/portosEnv.js b/server/lib/portosEnv.jsnew file mode 100644index 0000000000..5ea1ead762--- /dev/null+++ b/server/lib/portosEnv.js@@ -0,0 +1,151 @@+/**+ * Single server-side helper for reading/writing PortOS's own `.env`.+ *+ * PortOS records machine-local runtime state (e.g. `LLM_BACKEND`,+ * `VLLM_QWEN_PROJECT_DIR`) in the install's `.env` so it survives restarts+ * without a dotenv loader. The file lives at the **install root**, not the+ * executing checkout's root: a server booted from a CoS agent worktree+ * (`PORTOS_DATA_ROOT` pinned, #1947) has no `.env` in its own checkout, and+ * anchoring to `PATHS.root` there would write a throwaway file the real+ * install never reads.+ *+ * **Precedence (settled here, once):** an exported `process.env` value is this+ * run's decision and wins; the `.env` record is durable memory and loses. A+ * stale/invalid `.env` marker must never mask a valid `process.env` override —+ * validate each source before falling through, don't `||` on mere presence.+ * See `localLlm.js#getBackend` and `vllmQwenProject.js#resolveVllmProjectDir`+ * for the two call sites that apply this rule.+ *+ * `scripts/lib/envFile.js` stays as is — its header states it must have zero+ * dependencies and must not import from `server/lib`, because it runs+ * before/around `npm install`. Two implementations across that boundary is the+ * correct number; four is not.+ *+ * Values containing `$&` / `$`` / `$'` are written via a replacer *function*+ * so `String.replace` does not expand them.+ */++import { readFileSync } from 'fs';+import { join } from 'path';+import { PATHS, atomicWrite } from './fileUtils.js';+import { escapeRegExp } from './textUtils.js';++/**+ * PortOS's own `.env` — where machine-local state is recorded.+ *+ * Anchored to `installRoot`, not `root` (#1947). What is recorded here is+ * machine-local runtime state, so it belongs to the install and not to+ * whichever checkout loaded the code.+ */+export const PORTOS_ENV_PATH = join(PATHS.installRoot || PATHS.root || '', '.env');++function getDefaultEnvPath() {+ return join(PATHS.installRoot || PATHS.root || '', '.env');+}++/**+ * Which keys a `.env` already mentions.+ *+ * Deliberately keyed on *mention*, not on truthiness: a commented-out key is+ * treated as absent (it is not in effect), while a key set to the empty string+ * is treated as present, because an operator who wrote `EXTRA_ARGS=` meant it.+ *+ * @param {string} contents+ * @returns {Map<string, string>} key → value, with surrounding quotes stripped+ */+export function parseEnvContents(contents) {+ const found = new Map();+ for (const line of String(contents || '').split('\n')) {+ const trimmed = line.trim();+ if (!trimmed || trimmed.startsWith('#')) continue;+ const idx = trimmed.indexOf('=');+ if (idx <= 0) continue;+ const key = trimmed.slice(0, idx).trim();+ let value = trimmed.slice(idx + 1).trim();+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {+ value = value.slice(1, -1);+ }+ if (!found.has(key)) found.set(key, value);+ }+ return found;+}++/**+ * Add lines to the end of a `.env`, or return it unchanged when there are none.+ *+ * The separator is the whole point: a file not ending in a newline would splice+ * the first new key onto the operator's last line and silently corrupt both.+ *+ * @param {string} base+ * @param {string[]} lines+ * @returns {string}+ */+function appendEnvLines(base, lines) {+ const text = String(base || '');+ if (lines.length === 0) return text;+ const separator = text.length === 0 || text.endsWith('\n') ? '' : '\n';+ return `${text}${separator}${lines.join('\n')}\n`;+}++/**+ * Set ONE key, replacing the line that already declares it.+ *+ * The replacement is a FUNCTION, not a string. A value carrying one of+ * String.replace's special $-patterns would otherwise be expanded into the+ * surrounding text instead of written literally.+ *+ * @param {string} contents+ * @param {string} key+ * @param {string} value+ * @returns {string}+ */+export function upsertEnvLine(contents, key, value) {+ const text = String(contents || '');+ const pattern = new RegExp(`^${escapeRegExp(key)}=.*$`, 'm');+ return pattern.test(text)+ ? text.replace(pattern, () => `${key}=${value}`)+ : appendEnvLines(text, [`${key}=${value}`]);+}++/**+ * Read a single key from the PortOS `.env` file.+ *+ * @param {string} key - env var name+ * @param {string} [envPath] - absolute path to the .env file (injectable for tests)+ * @returns {string|null} value, or null when missing/unreadable+ */+export function readPortosEnvValue(key, envPath) {+ const path = envPath ?? getDefaultEnvPath();+ let contents = '';+ try {+ contents = readFileSync(path, 'utf8');+ } catch {+ return null;+ }+ const found = parseEnvContents(contents);+ return found.has(key) ? found.get(key) : null;+}++/**+ * Set (or add) a single key in the PortOS `.env` file.+ *+ * Async over `atomicWrite`, with the replacer-function guard for `$`-patterns.+ * If the key already exists, its line is replaced in-place; otherwise it is+ * appended with proper newline handling.+ *+ * @param {string} key - env var name+ * @param {string} value - unquoted value to write+ * @param {string} [envPath] - absolute path to the .env file (injectable for tests)+ * @returns {Promise<void>}+ */+export async function upsertPortosEnvLine(key, value, envPath) {+ const path = envPath ?? getDefaultEnvPath();+ let contents = '';+ try {+ contents = readFileSync(path, 'utf8');+ } catch {+ // no .env yet+ }+ const next = upsertEnvLine(contents, key, value);+ await atomicWrite(path, next);+}diff --git a/server/lib/vaultCrypto.js b/server/lib/vaultCrypto.jsindex c46d46b34e..02048065f9 100644--- a/server/lib/vaultCrypto.js+++ b/server/lib/vaultCrypto.js@@ -20,22 +20,23 @@import { randomBytes, createCipheriv, createDecipheriv } from 'crypto';import { readFileSync } from 'fs';import { chmod } from 'fs/promises';-import { join } from 'path';-import { PATHS, tryReadFile, atomicWrite } from './fileUtils.js';+import { tryReadFile, atomicWrite } from './fileUtils.js';import { createSingleFlight } from './singleFlight.js';+import { PORTOS_ENV_PATH } from './portosEnv.js';const CIPHER = 'aes-256-gcm';const IV_BYTES = 12;const KEY_BYTES = 32;const FORMAT_VERSION = 'v1';-// Anchor to the INSTALL root, not the code root: the encrypted rows live in-// the ONE install-shared Postgres, so the key must live next to that data. A-// server booted from a CoS git worktree (PORTOS_DATA_ROOT pinned, #1947) has-// no .env in its checkout — anchoring to PATHS.root there would mint a-// throwaway key in the worktree, encrypt shared rows with it, and destroy the-// key when the worktree is pruned (irreversible PII loss).-const DEFAULT_ENV_PATH = join(PATHS.installRoot, '.env');+// Path is the canonical one from `portosEnv.js` (#1947). Vault retains its own+// read/write pair because `readKeyFromEnvFile` must find the first *valid* key+// among possibly several `PRIVACY_VAULT_KEY=` lines (an uncommented `.env.example`+// placeholder is invalid), while `provisionVaultKey` must atomically drop *all*+// invalid lines before appending the new key — both are more than the generic+// `readPortosEnvValue` / `upsertPortosEnvLine` helpers do. The path constant+// is shared so the file identity stays single.+const DEFAULT_ENV_PATH = PORTOS_ENV_PATH;// Test hook: unit tests point this at a temp .env so the read-path fallback// below never touches (or is satisfied by) the real install's key.diff --git a/server/lib/vllmQwenProject.js b/server/lib/vllmQwenProject.jsindex 0996b1bb8d..84f5f0dbb6 100644--- a/server/lib/vllmQwenProject.js+++ b/server/lib/vllmQwenProject.js@@ -38,7 +38,6 @@* live" is one question and one module should answer it.*/-import { readFileSync } from 'fs';import { readdir, stat } from 'fs/promises';import { homedir } from 'os';import { join } from 'path';@@ -47,9 +46,8 @@ import { join } from 'path';// replace that whole aggregate with a small literal, and a module-level// `PATHS.root` read through it explodes at import time in a suite that never// touches this file.-import { atomicWrite } from './fileCore.js';import { PATHS } from './paths.js';-import { parseEnvContents, upsertEnvLine } from './vllmQwenProvision.js';+import { PORTOS_ENV_PATH, readPortosEnvValue, upsertPortosEnvLine } from './portosEnv.js';/** Operator override for where the compose project was cloned. */export const VLLM_PROJECT_DIR_ENV = 'VLLM_QWEN_PROJECT_DIR';@@ -57,16 +55,9 @@ export const VLLM_PROJECT_DIR_ENV = 'VLLM_QWEN_PROJECT_DIR';/** The directory name upstream's README uses, inside whichever home holds it. */export const VLLM_PROJECT_LEAF = 'qwen-serving';-/**- * PortOS's own `.env` — where an auto-detected project directory is recorded.- *- * `installRoot`, not `root`: what is recorded here is machine-local runtime state- * ("where this machine's WSL project lives"), so it belongs to the install and- * not to whichever checkout loaded the code. A server booted from a CoS agent- * worktree has no `.env` in its own tree (`lib/paths.js`, #1947), and anchoring- * to `root` there would write a throwaway file the real install never reads.- */-export const PORTOS_ENV_PATH = join(PATHS.installRoot, '.env');+// Re-export for backwards compat — consumers that imported PORTOS_ENV_PATH+// from here keep working; `portosEnv.js` is the source of truth (#1947).+export { PORTOS_ENV_PATH };/*** Operator override for the HuggingFace cache holding the weights — the answer@@ -99,15 +90,13 @@ export const vllmDefaultProjectDir = (env = process.env) => join(resolveHome(env* @returns {string}*/export function readRecordedVllmProjectDir(envPath = PORTOS_ENV_PATH) {- let contents = '';- try { contents = readFileSync(envPath, 'utf8'); } catch { return ''; }- return parseEnvContents(contents).get(VLLM_PROJECT_DIR_ENV) || '';+ return readPortosEnvValue(VLLM_PROJECT_DIR_ENV, envPath) || '';}/*** Remember where this project was placed, so nothing has to detect it twice.*- * `upsertEnvLine` rather than an append: a file accumulating one line per+ * `upsertPortosEnvLine` rather than an append: a file accumulating one line per* provisioning run is a config whose meaning depends on which reader opens it* (some take the first mention, some the last). Atomic, because PortOS's `.env`* also carries the database password and a half-written truncate is readable by@@ -117,9 +106,7 @@ export function readRecordedVllmProjectDir(envPath = PORTOS_ENV_PATH) {* @param {string} [envPath]*/export async function recordVllmProjectDir(dir, envPath = PORTOS_ENV_PATH) {- let contents = '';- try { contents = readFileSync(envPath, 'utf8'); } catch { /* no .env yet */ }- await atomicWrite(envPath, upsertEnvLine(contents, VLLM_PROJECT_DIR_ENV, dir));+ await upsertPortosEnvLine(VLLM_PROJECT_DIR_ENV, dir, envPath);}/** Compose file names the upstream project may ship under. */diff --git a/server/lib/vllmQwenProvision.js b/server/lib/vllmQwenProvision.jsindex 13cd2a336d..6037f794a5 100644--- a/server/lib/vllmQwenProvision.js+++ b/server/lib/vllmQwenProvision.js@@ -37,7 +37,7 @@import { randomBytes } from 'crypto';import { vllmExtraArgs } from './qwenAgentParsers.js';-import { escapeRegExp } from './textUtils.js';+import { parseEnvContents, upsertEnvLine } from './portosEnv.js';/** Bytes of entropy in a generated key — matches the doc's `openssl rand -hex 24`. */const API_KEY_BYTES = 24;@@ -96,45 +96,11 @@ export function vllmEnvDefaults({ apiKey, wsl2 = false }) {];}-/**- * Which keys a `.env` already mentions.- *- * Deliberately keyed on *mention*, not on truthiness: a commented-out key is- * treated as absent (it is not in effect), while a key set to the empty string- * is treated as present, because an operator who wrote `EXTRA_ARGS=` meant it.- * Collapsing those two into one state is the footgun this module exists to- * avoid — its whole contract is that it never overrules a decision already in- * the file.- *- * @param {string} contents- * @returns {Map<string, string>} key → value, with surrounding quotes stripped- */-export function parseEnvContents(contents) {- const found = new Map();- for (const line of String(contents || '').split('\n')) {- const trimmed = line.trim();- if (!trimmed || trimmed.startsWith('#')) continue;- const idx = trimmed.indexOf('=');- if (idx <= 0) continue;- const key = trimmed.slice(0, idx).trim();- let value = trimmed.slice(idx + 1).trim();- if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {- value = value.slice(1, -1);- }- // First mention wins, matching how a shell sourcing the file top-to-bottom- // would NOT — but compose reads the last one. Either way the value is the- // operator's, and this module only needs to know it must not add the key.- if (!found.has(key)) found.set(key, value);- }- return found;-}-/*** Add lines to the end of a `.env`, or return it unchanged when there are none.** The separator is the whole point: a file not ending in a newline would splice* the first new key onto the operator's last line and silently corrupt both.- * Shared by the two writers below so that guard is written once.** @param {string} base* @param {string[]} lines@@ -147,32 +113,10 @@ function appendEnvLines(base, lines) {return `${text}${separator}${lines.join('\n')}\n`;}-/**- * Set ONE key, replacing the line that already declares it.- *- * The complement of `mergeEnvFileContents`: that one is additive by contract and- * never overrules the operator, which is exactly wrong for a value PortOS owns- * and re-derives (`vllmQwenProject.js`'s recorded project directory). Everything- * else in the file is left byte for byte.- *- * The replacement is a FUNCTION, not a string. A value carrying one of- * String.replace's special $-patterns would otherwise be expanded into the- * surrounding text instead of written literally — `scripts/lib/envFile.js`- * learned that on a password, and this is the same fix kept next to the parser- * it belongs with.- *- * @param {string} contents- * @param {string} key- * @param {string} value- * @returns {string}- */-export function upsertEnvLine(contents, key, value) {- const text = String(contents || '');- const pattern = new RegExp(`^${escapeRegExp(key)}=.*$`, 'm');- return pattern.test(text)- ? text.replace(pattern, () => `${key}=${value}`)- : appendEnvLines(text, [`${key}=${value}`]);-}+// Re-export parse helpers from the canonical server-side .env helper so+// existing deep imports (`…/vllmQwenProvision.js`) keep working after the+// collapse onto `portosEnv.js`. New code should import from `portosEnv.js`.+export { parseEnvContents, upsertEnvLine } from './portosEnv.js';/*** Append the missing defaults to an existing `.env`, changing nothing else.diff --git a/server/services/credentialInventory.js b/server/services/credentialInventory.jsindex 475b7af7d3..5e874ce044 100644--- a/server/services/credentialInventory.js+++ b/server/services/credentialInventory.js@@ -18,7 +18,7 @@ import { join } from 'node:path';import { CREDENTIALS } from '../lib/credentialRegistry.js';import { INSTANCE_FEATURES } from '../lib/instanceFeatureRegistry.js';import { PATHS, readJSONFile } from '../lib/fileUtils.js';-import { parseEnvContents } from '../lib/vllmQwenProvision.js';+import { parseEnvContents } from '../lib/portosEnv.js';import { getSettings } from './settings.js';export const CREDENTIAL_SOURCES = Object.freeze([diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 4b68759552..fb0e299ce6 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -26,13 +26,14 @@*/import { execFile } from '../lib/childProcess.js';import { promisify } from 'util'-import { readFileSync, createWriteStream } from 'fs'+import { createWriteStream } from 'fs'import { rm } from 'fs/promises'import { join } from 'path'import { tmpdir } from 'os'import { pipeline } from 'stream/promises'import { Readable } from 'stream'-import { PATHS, atomicWrite, ensureDir, pathExists, sleep } from '../lib/fileUtils.js'+import { ensureDir, pathExists, sleep } from '../lib/fileUtils.js'+import { readPortosEnvValue, upsertPortosEnvLine } from '../lib/portosEnv.js'import { ServerError } from '../lib/errorHandler.js'import { assessDownloadPreflight, diskInsufficientError, DOWNLOAD_VERDICTS } from '../lib/downloadPreflight.js'import { compareSemver } from '../lib/versionUtils.js'@@ -52,7 +53,6 @@ import { getProviderById, getAllProviders, updateProvider, refreshProviderModelsimport { getSettings } from './settings.js'const execFileAsync = promisify(execFile)-const ENV_PATH = join(PATHS.root, '.env')const DEFAULT_BACKEND = 'ollama'// `lms get` blocks until the download finishes — generous but finite so a@@ -135,46 +135,23 @@ async function detectInstallSource(backend) {// ---- active-backend marker (.env LLM_BACKEND) ---------------------------------function readEnv() {- const result = {}- let content = ''- try { content = readFileSync(ENV_PATH, 'utf8') } catch { return result }- for (const line of content.split('\n')) {- const trimmed = line.trim()- if (!trimmed || trimmed.startsWith('#')) continue- const idx = trimmed.indexOf('=')- if (idx === -1) continue- let value = trimmed.slice(idx + 1).trim()- if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {- value = value.slice(1, -1)- }- result[trimmed.slice(0, idx).trim()] = value- }- return result-}-/**- * The active local-LLM backend, read fresh from `.env` each call. `.env` wins- * when valid; otherwise a valid `process.env` override wins (a stale/invalid- * `.env` marker must not mask a valid runtime env override — validate each- * source before falling through, don't `||` on mere presence).+ * The active local-LLM backend, read fresh from `.env` each call.+ *+ * **Precedence (settled in `server/lib/portosEnv.js`):** an exported+ * `process.env` value is this run's decision and wins; the `.env` record is+ * durable memory and loses. Validate each source before falling through.*/export function getBackend() {- const fromFile = readEnv().LLM_BACKEND+ const fromEnv = process.env.LLM_BACKEND+ if (isBackend(fromEnv)) return fromEnv+ const fromFile = readPortosEnvValue('LLM_BACKEND')if (isBackend(fromFile)) return fromFile- if (isBackend(process.env.LLM_BACKEND)) return process.env.LLM_BACKENDreturn DEFAULT_BACKEND}async function writeBackend(backend) {- let content = ''- try { content = readFileSync(ENV_PATH, 'utf8') } catch { /* no .env yet */ }- if (/^LLM_BACKEND=/m.test(content)) {- content = content.replace(/^LLM_BACKEND=.*/m, `LLM_BACKEND=${backend}`)- } else {- content = `LLM_BACKEND=${backend}\n${content}`- }- await atomicWrite(ENV_PATH, content)+ await upsertPortosEnvLine('LLM_BACKEND', backend)}/**diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex 7acfdab58d..6cd92d6ac3 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -197,10 +197,10 @@ describe('localLlm', () => {process.env.LLM_BACKEND = 'lmstudio'; // cleared by beforeEachexpect(svc.getBackend()).toBe('lmstudio');});- it('prefers a valid .env marker over a process.env override', () => {+ it('prefers a valid process.env override over a .env marker', () => {writeEnv('LLM_BACKEND=ollama\n');process.env.LLM_BACKEND = 'lmstudio';- expect(svc.getBackend()).toBe('ollama');+ expect(svc.getBackend()).toBe('lmstudio');});});