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
fix: close three scanner gaps the log-level guard review found (#7945)
[._.]/ Adam Eivydf6d06ebe7fa
diff --git a/server/lib/README.md b/server/lib/README.mdindex 89a13c26e8..af2f69d300 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -605,7 +605,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `apiCatalog.js` | Searchable projection of the Express route inventory (`getApiRouteCatalog()` from `apiRouteGraph.js`): domain, access, side-effect, contract coverage, summaries, and Express-to-OpenAPI path conversion. || `apiRouteGraph.js` | Static scan of the mounted HTTP route graph — `server/index.js` `app.use('/api/…', router)` mounts → route-module imports → `router.use(prefix, child)` → `router.<method>('<path>')`, including aliased mounts, local subrouters, factory returns and composed `toolkit.routes.<x>` routers. `buildApiRouteCatalog({ repoRoot? })` → `{ derivedFrom, mounts, routes: [{ method, path, mountPath, sources }], stats }`; `getApiRouteCatalog()` derives it on first use and caches it for the process (read by the API Explorer, the internal OpenAPI document and `apiRouteParity.test.js`); `scanRouteGraph()` adds `declarationKeys` / `duplicateDeclarationKeys` (`routeDeclarationKey`) for the coverage guard in `apiRouteGraph.test.js`. Never committed — see "Generated manifests" in `server/AGENTS.md`. || `socketEventCatalog.js` | Searchable projection of the cached Socket.IO inventory: direction, domain, and runtime-schema coverage. |-| `sourceScan.js` | Lexer-assisted primitives shared by the whole-tree source-scan guard suites, so the timer rule and the socket rule cannot drift on what "owns its rejection" means. `blankLiterals(src)` blanks comment/string/template/regex CONTENT to spaces while preserving length, so a brace inside a literal cannot skew a bracket walk and a caller can still read a literal (a socket event name) out of the original string at the same offset; `matchBracket(src, open)` returns the index past the matching `)`/`]`/`}`; `parseCallbackAt(blanked, from, limit)` parses the function expression at `from` (`async`/`function`/either arrow spelling, skipping the parameter list as a unit so a `= {}` default is not mistaken for the body) and returns `{isAsync, start, text}`; `unguardedAwaits(body)` returns the awaited chains that neither sit inside a `try`/`catch` nor END in `.catch(…)`. `blankComments(src)` is the weaker LINE-based stripper the per-line `child_process` rule needs. Callers: `childProcess.guards.test.js`, `server/timerCallbackConventions.test.js`, `server/sockets/asyncHandlerGuard.test.js`, `server/process-safety-net.test.js`. |+| `sourceScan.js` | Lexer-assisted primitives shared by the whole-tree source-scan guard suites, so the timer rule and the socket rule cannot drift on what "owns its rejection" means. `blankLiterals(src)` blanks comment/string/template/regex CONTENT to spaces while preserving length, so a brace inside a literal cannot skew a bracket walk and a caller can still read a literal (a socket event name) out of the original string at the same offset; `matchBracket(src, open)` returns the index past the matching `)`/`]`/`}`; `parseCallbackAt(blanked, from, limit)` parses the function expression at `from` (`async`/`function`/either arrow spelling, skipping the parameter list as a unit so a `= {}` default is not mistaken for the body) and returns `{isAsync, start, text}`; `unguardedAwaits(body)` returns the awaited chains that neither sit inside a `try`/`catch` nor END in `.catch(…)`. `blankComments(src)` is the weaker LINE-based stripper the per-line `child_process` rule needs. `blankCommentBodies(src)` is the complement — comments blanked, literal TEXT kept — for a caller that reads a message string and must not see a marker written in a comment beside it. Callers: `childProcess.guards.test.js`, `server/timerCallbackConventions.test.js`, `server/logLevelConventions.test.js`, `server/sockets/asyncHandlerGuard.test.js`, `server/process-safety-net.test.js`. || `apiOperationContracts.js` | Detailed operation metadata for intentionally public APIs. It consumes the canonical route Zod contracts and feeds both public and internal OpenAPI documents. || `apiRegistry.js` | Single source of truth for which PortOS services are externally-callable HTTP APIs (`voice`, `sdapi`). `API_REGISTRY` declares each API's `publicPrefixes` (read/compute-safe surface only) + defaults; `isRegistryPublic(settings, path)` tells `authGate` when an `exposed && !requireAuth` API re-opens its prefix; `resolveApiAccess(settings)` merges persisted `apiAccess` flags for the Settings UI + OpenAPI docs. || `arrayUtils.js` | `asArray(value)` — returns an array unchanged, or a fresh empty array for non-array inputs. `shuffle(arr, random?)` — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never `arr.sort(() => Math.random() - 0.5)`, which is biased. Shared by `meatspacePostCognitive.js` (Schulte table / mental rotation) and `meatspacePostMemory.js` (memory drill generators). `dedupeByKey(items, keyOf, pick?)` — one survivor per key, first-seen order. **Required before any multi-row `INSERT … ON CONFLICT (key) DO UPDATE`**: Postgres refuses the whole statement ("ON CONFLICT DO UPDATE command cannot affect row a second time") when its VALUES list names one conflict key twice, and the rows a batcher joins usually come from something that promises no uniqueness (a disk scan, a peer payload). `DO NOTHING` upserts are exempt. `pick(held, candidate)` defaults to last-seen-wins (what a sequential one-row upsert loop leaves); pass a comparator when the table's conflict rule isn't "latest write" — `memorySync.applyRemoteChanges` keeps the newest `updatedAt` so a peer's payload ordering can't flip a last-writer-wins outcome. Used by `services/mediaAssetIndex/db.js` and `services/memorySync.js`. |diff --git a/server/lib/sourceScan.js b/server/lib/sourceScan.jsindex 7f793a61b9..ab57837e51 100644--- a/server/lib/sourceScan.js+++ b/server/lib/sourceScan.js@@ -36,13 +36,41 @@ export function blankComments(src) {return src.split('\n').map((line) => (/^\s*(\/\/|\*|\/\*)/.test(line) ? '' : line));}+// Keywords a regex literal may directly follow. A `/` after one of these is+// never division, because a keyword cannot be an operand — `await /[)]/.test(s)`+// and `return /a/` both open a regex. Reading one as division blanked nothing,+// so the regex body's own brackets skewed the caller's bracket walk.+const KEYWORDS_BEFORE_REGEX = new Set([+ 'await', 'case', 'delete', 'do', 'else', 'in', 'instanceof', 'new', 'of',+ 'return', 'throw', 'typeof', 'void', 'yield',+]);++/**+ * The identifier ending at `end` (exclusive) in the character ARRAY `chars`, or+ * '' when the preceding character is not an identifier character. Reads the+ * PARTIALLY BLANKED output, so a keyword spelled inside an already-blanked+ * string or comment is invisible here — which is the point.+ */+function wordEndingAt(chars, end) {+ let start = end;+ while (start > 0 && /[A-Za-z0-9_$]/.test(chars[start - 1])) start -= 1;+ // `obj.in` / `obj.return` are property reads, not keywords.+ if (start > 0 && chars[start - 1] === '.') return '';+ return chars.slice(start, end).join('');+}+/*** True when a `/` at this position opens a regex literal rather than division.* A regex can only follow a position where an operand cannot: an operator, an- * opening bracket, a statement boundary, or the start of the file.+ * opening bracket, a statement boundary, a keyword, or the start of the file.*/-function regexCanStartAfter(prev) {- return prev === '' || '(,=:[!&|?{};+-*%~^<>'.includes(prev);+function regexCanStartAfter(prev, chars, at) {+ if (prev === '' || '(,=:[!&|?{};+-*%~^<>'.includes(prev)) return true;+ if (!/[A-Za-z0-9_$]/.test(prev)) return false;+ // Step back over the whitespace between the keyword and the `/`.+ let end = at;+ while (end > 0 && /\s/.test(chars[end - 1])) end -= 1;+ return KEYWORDS_BEFORE_REGEX.has(wordEndingAt(chars, end));}/**@@ -52,12 +80,18 @@ function regexCanStartAfter(prev) {* sees code only — and a caller that needs a literal's text (a socket event* name, say) can still read it out of the original string at the same offset.* @param {string} src+ * @param {{keepLiteralText?: boolean}} [options] `keepLiteralText` leaves+ * string/template/regex CONTENT in place and blanks only comments — reach it+ * through `blankCommentBodies`. The lex is identical either way, so the two+ * modes cannot disagree about where a comment ends and a literal begins.* @returns {string} same length as `src`*/-export function blankLiterals(src) {+export function blankLiterals(src, { keepLiteralText = false } = {}) {const out = src.split('');const n = src.length;const blank = (i) => { if (i < n && src[i] !== '\n') out[i] = ' '; };+ // Blanks a character belonging to a LITERAL rather than to a comment.+ const blankLit = keepLiteralText ? () => {} : blank;// Brace depths of the code regions opened by `${` inside template literals,// so a nested template resumes correctly at its closing `}`.const templateStack = [];@@ -73,17 +107,17 @@ export function blankLiterals(src) {const c = src[i];if (inTemplate) {- if (c === '\\') { blank(i); blank(i + 1); i += 2; continue; }- if (c === '`') { blank(i); i += 1; inTemplate = false; prevSignificant = '`'; continue; }+ if (c === '\\') { blankLit(i); blankLit(i + 1); i += 2; continue; }+ if (c === '`') { blankLit(i); i += 1; inTemplate = false; prevSignificant = '`'; continue; }if (c === '$' && src[i + 1] === '{') {- blank(i); blank(i + 1); i += 2;+ blankLit(i); blankLit(i + 1); i += 2;templateStack.push(braceDepth);braceDepth = 0;inTemplate = false;prevSignificant = '{';continue;}- blank(i); i += 1; continue;+ blankLit(i); i += 1; continue;}if (c === '/' && src[i + 1] === '/') {@@ -97,29 +131,29 @@ export function blankLiterals(src) {}if (c === "'" || c === '"') {const quote = c;- blank(i); i += 1;+ blankLit(i); i += 1;while (i < n && src[i] !== quote) {- if (src[i] === '\\') { blank(i); i += 1; }- blank(i); i += 1;+ if (src[i] === '\\') { blankLit(i); i += 1; }+ blankLit(i); i += 1;}- blank(i); i += 1;+ blankLit(i); i += 1;prevSignificant = quote;continue;}- if (c === '`') { blank(i); i += 1; inTemplate = true; continue; }- if (c === '/' && regexCanStartAfter(prevSignificant)) {- blank(i); i += 1;+ if (c === '`') { blankLit(i); i += 1; inTemplate = true; continue; }+ if (c === '/' && regexCanStartAfter(prevSignificant, out, i)) {+ blankLit(i); i += 1;let inClass = false;while (i < n && src[i] !== '\n') {- if (src[i] === '\\') { blank(i); blank(i + 1); i += 2; continue; }+ if (src[i] === '\\') { blankLit(i); blankLit(i + 1); i += 2; continue; }if (src[i] === '[') inClass = true;else if (src[i] === ']') inClass = false;else if (src[i] === '/' && !inClass) break;- blank(i); i += 1;+ blankLit(i); i += 1;}- blank(i); i += 1;+ blankLit(i); i += 1;// Blank the flags too so `gi` can't be read as an identifier.- while (i < n && /[a-z]/.test(src[i])) { blank(i); i += 1; }+ while (i < n && /[a-z]/.test(src[i])) { blankLit(i); i += 1; }prevSignificant = ')';continue;}@@ -127,7 +161,8 @@ export function blankLiterals(src) {if (c === '{') braceDepth += 1;else if (c === '}') {if (braceDepth === 0 && templateStack.length > 0) {- blank(i); i += 1;+ // Closes a `${…}` hole, so it is part of the template literal.+ blankLit(i); i += 1;braceDepth = templateStack.pop();inTemplate = true;continue;@@ -141,6 +176,22 @@ export function blankLiterals(src) {return out.join('');}+/**+ * Blank COMMENT bodies only, leaving string/template/regex text in place and+ * preserving length. The complement to `blankLiterals`, for a caller that reads+ * a construct's literal TEXT (a log message and the marker emoji in it) and+ * must not be fooled by that same marker appearing in a comment beside it.+ *+ * Shares one lexer with `blankLiterals`, so the two agree by construction about+ * where a comment ends and a literal begins — a second, independent+ * comment-stripper is exactly how a `//` inside a string starts eating code.+ * @param {string} src+ * @returns {string} same length as `src`+ */+export function blankCommentBodies(src) {+ return blankLiterals(src, { keepLiteralText: true });+}+/*** Index just PAST the bracket matching the `(`, `[` or `{` at `open`, or -1.* Assumes `src` has been through `blankLiterals`, so a bracket inside a stringdiff --git a/server/logLevelConventions.test.js b/server/logLevelConventions.test.jsindex dfb8af026f..768117e757 100644--- a/server/logLevelConventions.test.js+++ b/server/logLevelConventions.test.js@@ -41,7 +41,8 @@* ## What this guard CANNOT see** It is a lexer-assisted source scan, not a scope-aware AST pass. It reads the- * ARGUMENT TEXT of a literal `console.log(` call, which means:+ * ARGUMENT TEXT (comment bodies blanked) of a literal `console.log(` call,+ * which means:** - A message built into a variable first (`const line = `FAILMARK …`;* console.log(line);`) is invisible. That is the same shape the mixed-sink@@ -62,7 +63,7 @@ import { execFileSync } from 'child_process';import { readFileSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { blankLiterals, matchBracket } from './lib/sourceScan.js';+import { blankCommentBodies, blankLiterals, matchBracket } from './lib/sourceScan.js';const SERVER_ROOT = dirname(fileURLToPath(import.meta.url));@@ -76,14 +77,18 @@ const FAILURE_MARKERS = [CROSS_MARK, NO_ENTRY];const CONSOLE_LOG_OPEN = /\bconsole\s*\.\s*log\s*\(/g;/**- * Every `console.log(…)` call in `src`, as `{ line, args }` where `args` is the- * RAW argument text (literals intact — the markers live inside template- * strings, which `blankLiterals` would erase). Call boundaries come from the- * BLANKED copy so a `)` inside a string cannot end the span early and a- * multi-line call is captured whole rather than by a fixed line window.+ * Every `console.log(…)` call in `src`, as `{ line, args }` where `args` keeps+ * the literal text (the markers live inside template strings, which+ * `blankLiterals` would erase) but has COMMENT bodies blanked, so a marker+ * written in a comment beside the message is not read as part of it.+ *+ * Call boundaries come from the fully BLANKED copy, so a `)` inside a string or+ * a regex character class cannot end the span early and a multi-line call is+ * captured whole rather than by a fixed line window.*/export function consoleLogCalls(src) {const blanked = blankLiterals(src);+ const codeOnly = blankCommentBodies(src);const calls = [];for (const match of blanked.matchAll(CONSOLE_LOG_OPEN)) {const open = blanked.indexOf('(', match.index);@@ -91,8 +96,9 @@ export function consoleLogCalls(src) {if (close === -1) continue;calls.push({line: src.slice(0, match.index).split('\n').length,- // `close` is one past the matching `)`, so `close - 1` drops it.- args: src.slice(open + 1, close - 1),+ // `close` is one past the matching `)`, so `close - 1` drops it. Both+ // copies preserve length, so the span indexes either one.+ args: codeOnly.slice(open + 1, close - 1),});}return calls;@@ -105,7 +111,11 @@ export function findMislabeledFailureLogs(src) {.map(({ line, args }) => `line ${line}: ${args.replace(/\s+/g, ' ').trim().slice(0, 120)}`);}-const trackedServerSources = () => execFileSync('git', ['ls-files', '*.js'], {+// Every module extension the tree actually ships, not just `.js`: the operator+// scripts under `server/scripts/` are `.mjs`, and one of them was logging a+// failure through `console.log` while a `*.js`-only scan reported the tree+// clean.+const trackedServerSources = () => execFileSync('git', ['ls-files', '*.js', '*.mjs', '*.cjs'], {cwd: SERVER_ROOT,encoding: 'utf8',maxBuffer: 64 * 1024 * 1024,@@ -118,6 +128,12 @@ describe('failure lines log at error level (#7945)', () => {expect(trackedServerSources().length).toBeGreaterThan(200);});+ it('scans every module extension the tree ships, not only .js', () => {+ // `server/scripts/` is `.mjs`, and a `*.js`-only glob called the tree clean+ // while one of those scripts logged a failure through console.log.+ expect(trackedServerSources().filter((f) => f.endsWith('.mjs')).length).toBeGreaterThan(0);+ });+it('finds the console.log calls it is meant to read', () => {// Proves the extractor still recognizes real call sites — without this the// scan below could go vacuously green if `consoleLogCalls` stopped matching.@@ -214,6 +230,42 @@ describe('the failure-log recognizer', () => {`)).toEqual([]);});+ it('ignores a marker in a comment INSIDE the call', () => {+ // A comment explaining the rule sits in the argument span, so a raw-text+ // marker search reports the message it documents as a violation.+ expect(findMislabeledFailureLogs(+ `console.log(/* ${CROSS_MARK} never here */ 'fine');`,+ )).toEqual([]);+ expect(findMislabeledFailureLogs(`+ console.log(+ // ${CROSS_MARK} would be wrong on this line+ 'fine',+ );+ `)).toEqual([]);+ // …but a marker in the MESSAGE is still found when a comment shares the span.+ expect(findMislabeledFailureLogs(+ `console.log(/* explained below */ \`${CROSS_MARK} failed\`);`,+ )).toHaveLength(1);+ });++ it('is not skewed by a regex literal that follows a keyword', () => {+ // `await /…/` is a regex, not division. Read as division it blanks nothing,+ // so the `)` inside the character class ends the span early and the marker+ // after it disappears.+ expect(findMislabeledFailureLogs(+ `async function f() { console.log(await /[)]/.test(s), \`${CROSS_MARK} failed\`); }`,+ )).toHaveLength(1);+ expect(findMislabeledFailureLogs(+ `function f() { console.log(typeof x, /[)]/.test(s), \`${CROSS_MARK} failed\`); }`,+ )).toHaveLength(1);+ // Division after an identifier must still read as division, or the rest of+ // the file would be swallowed as regex body.+ expect(findMislabeledFailureLogs(`+ const ratio = total / count;+ console.log(\`${CROSS_MARK} failed at \${ratio}\`);+ `)).toHaveLength(1);+ });+// Bypass probe: the scan is only worth its runtime if a reintroduced// violation in a REAL tracked file actually turns it red. Mutate a file's// source in memory and assert the same predicate the tree-wide scan uses.diff --git a/server/scripts/moltbook-claim.mjs b/server/scripts/moltbook-claim.mjsindex 3f0c8a8d4c..6d6a7c5fa2 100644--- a/server/scripts/moltbook-claim.mjs+++ b/server/scripts/moltbook-claim.mjs@@ -57,7 +57,7 @@ while (attempt < MAX_ATTEMPTS) {}const detail = data.details ? ` (${data.details})` : '';- console.log(`❌ [${timestamp}] Attempt ${attempt} — ${data.error}${detail} — retrying in ${BACKOFF_MS / 1000}s`);+ console.error(`❌ [${timestamp}] Attempt ${attempt} — ${data.error}${detail} — retrying in ${BACKOFF_MS / 1000}s`);await sleep(BACKOFF_MS);}