Skip to content

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

test: make the CoS runner safety-net guard read code, not the comment above the call (#5685)

[._.]/ Adam Eivy40e55d7ec6a5
diff --git a/server/lib/README.md b/server/lib/README.md
index 68911cfb33..abe6008cd4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -441,7 +441,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `apiAccessPolicy.js` | Shared always-public path and gated non-`/api` prefix policy consumed by both `authGate` and API discovery. |
| `apiCatalog.js` | Searchable projection of the generated Express route manifest: domain, access, side-effect, contract coverage, summaries, and Express-to-OpenAPI path conversion. |
| `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`. |
+| `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`. |
| `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` | `shuffle(arr)` — 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/process-safety-net.test.js b/server/process-safety-net.test.js
index 54dd0d15a8..096ab6682d 100644
--- a/server/process-safety-net.test.js
+++ b/server/process-safety-net.test.js
@@ -3,9 +3,35 @@ import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { setupProcessErrorHandlers } from './lib/errorHandler.js';
+import { blankLiterals } from './lib/sourceScan.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
-const read = (rel) => readFileSync(join(__dirname, rel), 'utf8');
+// Read CODE, not prose: `blankLiterals` blanks comment/string/regex content to
+// spaces (preserving line structure), so a rule *described* in a comment can
+// neither satisfy nor defeat the scan. Without it the cos-runner arm below was
+// green on the explanatory comment above the real call, and deleting the call
+// changed nothing (#5685).
+const toCode = (src) => blankLiterals(src.replace(/\r\n/g, '\n'));
+const read = (rel) => toCode(readFileSync(join(__dirname, rel), 'utf8'));
+
+// A top-level call statement — the only shape that actually arms the net in an
+// entry file that boots on import.
+const TOP_LEVEL_CALL = /^[ \t]*setupProcessErrorHandlers\s*\(/m;
+
+const WIRING_GUARDS = [
+ // The main server wires the net from its boot sequence (services/bootstrap.js,
+ // extracted from index.js in #2839) as a NAMED STEP handed to
+ // runPostListenSequence, so the call is nested in the step table rather than at
+ // statement level. That indirection is pinned behaviourally by
+ // bootstrapSequence.test.js ("runs the post-listen steps in order"), so an
+ // identifier-level match is enough here.
+ { rel: 'services/bootstrap.js', pattern: /setupProcessErrorHandlers\s*\(/, shape: 'call' },
+ // The CoS runner arms the net itself, at module top level. Nothing else pins
+ // it, so this guard is the only thing standing between a deleted line and an
+ // unguarded rejection killing the process that supervises every agent run —
+ // require the exact shape that arms it.
+ { rel: 'cos-runner/index.js', pattern: TOP_LEVEL_CALL, shape: 'top-level call statement' },
+];
// Defense-in-depth process-level net (issue #1878). Both long-lived processes —
// the main server and the standalone CoS runner — must wire the SHARED
@@ -15,18 +41,40 @@ const read = (rel) => readFileSync(join(__dirname, rel), 'utf8');
// server.listen) and rather than by importing the helper and mutating the live
// test process's listener set.
describe('process-level safety net (#1878)', () => {
- // The main server wires the net from its boot sequence (services/bootstrap.js,
- // extracted from index.js in #2839) inside the httpServer.listen callback.
- for (const rel of ['services/bootstrap.js', 'cos-runner/index.js']) {
- it(`${rel} wires up setupProcessErrorHandlers`, () => {
- expect(read(rel)).toMatch(/setupProcessErrorHandlers\s*\(/);
+ for (const { rel, pattern, shape } of WIRING_GUARDS) {
+ it(`${rel} wires up setupProcessErrorHandlers (${shape})`, () => {
+ expect(read(rel)).toMatch(pattern);
});
}
+ // The guards above are only as strong as the comment stripping — a source scan
+ // that reads prose is satisfied by a description of the rule it enforces. Run
+ // the same predicates through the SAME `toCode` the guards use, over a fixture
+ // whose only occurrences are commented out, and assert they see nothing; then
+ // over the same fixture plus a real call, so the probe cannot pass by being
+ // blind to everything. Dropping the stripper from `toCode` fails this too.
+ it('a commented-out call does not satisfy the wiring guards (bypass probe)', () => {
+ // The block-comment arm deliberately puts the call at the START of its own
+ // line: a line-leading `//` would be rejected by TOP_LEVEL_CALL's own shape
+ // even with the stripping gone, so only this fixture makes the probe prove
+ // the stripping rather than the anchor.
+ const commentedOnly = [
+ '// setupProcessErrorHandlers(io); the main server passes io; the runner does not',
+ '/*',
+ 'setupProcessErrorHandlers();',
+ '*/',
+ 'startRunner();',
+ ].join('\n');
+ for (const { pattern } of WIRING_GUARDS) {
+ expect(toCode(commentedOnly)).not.toMatch(pattern);
+ expect(toCode(`${commentedOnly}\nsetupProcessErrorHandlers();`)).toMatch(pattern);
+ }
+ });
+
// ...and index.js must actually run that boot sequence, or the wiring above
// would be dead code the server never reaches.
it('index.js runs the bootstrap boot sequence', () => {
- expect(read('index.js')).toMatch(/runBootSequence\s*\(/);
+ expect(read('index.js')).toMatch(/^[ \t]*runBootSequence\s*\(/m);
});
// The net must never throw while handling a failure — a non-Error throw value