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: move slashdo command loading out of fileUtils into its own lib module
[._.]/ Adam Eivyb218350e1e50
diff --git a/server/lib/README.md b/server/lib/README.mdindex 47d3b9d615..0e66abb3b5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -133,7 +133,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, JSONL append/read/write helpers, dir scans, hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. Also the slashdo loaders: `loadSlashdoFile(cmd, {stripFrontmatter, skipIncludes})` / `loadSlashdoLib(name, {teams})` resolve the `` !`cat ~/.claude/lib/…` `` includes + `if:teams` conditionals (PortOS inlines these into CoS prompts WITHOUT running slashdo's installer), with `skipIncludes` pruning lib includes the run can never reach (each leaves a one-line "not applicable" marker — #3110); `writeResolvedSlashdoBody(cmd, body, {skipIncludes})` → absolute path, writing the already-loaded body under `PATHS.slashdoResolved` (`data/cos/slashdo-resolved/`, gitignored derived cache) at most once per (command, body) per process, so a file-tool host can be handed a path instead of a 250KB paste. Most paths/file work goes through here. |+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, JSONL append/read/write helpers, dir scans, hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. || `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. || `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |@@ -299,6 +299,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). || `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and `WORKFLOW_OWNS_ITS_OWN_GIT` (the shared run-shape defaults). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. Mirrored in `client/src/lib/slashdoCatalog.js` (button styling only), pinned by `slashdoCatalog.test.js`. || `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. Over `SLASHDO_INLINE_BUDGET_CHARS` (24,000) with a `bodyPath` it emits a filesystem pointer instead of the text — #3110), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. |+| `slashdoLoader.js` | Loads bundled slashdo command/lib markdown (`lib/slashdo/` submodule) and resolves it the way slashdo's own per-environment installer would, since PortOS inlines these bodies into CoS-agent prompts WITHOUT running that installer. `loadSlashdoFile(cmd, {stripFrontmatter, skipIncludes})` / `loadSlashdoLib(name, {teams})` resolve the `` !`cat ~/.claude/lib/…` `` includes + `if:teams` conditionals, with `skipIncludes` pruning lib includes the run can never reach (each leaves a one-line "not applicable" marker — #3110); `writeResolvedSlashdoBody(cmd, body, {skipIncludes})` → absolute path, writing the already-loaded body under `PATHS.slashdoResolved` (`data/cos/slashdo-resolved/`, gitignored derived cache) at most once per (command, body) per process, so a file-tool host can be handed a path instead of a 250KB paste. Split out of `fileUtils.js` (a generic file-utilities module) as its own feature module — pairs with `slashdoInvocation.js`, which resolves how a workflow is TYPED per host CLI rather than how its body is loaded. || `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. || `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `agentImportCycles.test.js` (acyclicity) and `sprites/animationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). || `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. |diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 3713eaf725..cd926bf7c6 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -867,208 +867,6 @@ export function formatDuration(ms) {return `${mins}m`;}-/**- * The include name (`<name>` of `lib/<name>.md`) for a matched `!`cat`` directive,- * with the `.md` extension dropped so callers name libs the way slashdo does- * (`local-agent-review-loop`, not `local-agent-review-loop.md`).- */-function slashdoIncludeName(relPath) {- return relPath.replace(/^.*\//, '').replace(/\.md$/, '');-}--/**- * Resolve all `!`cat ~/.claude/lib/<name>`` include directives in `content` by- * inlining the referenced slashdo lib file. Iterates so an inlined lib that- * itself carries a `!`cat`` include is resolved too (bounded to avoid a cyclic- * include spinning forever). Shared by loadSlashdoFile and loadSlashdoLib.- *- * `skipInclude(name)` (optional) prunes an include the run can never reach —- * see `loadSlashdoFile`'s `skipIncludes`. A skipped include is replaced with a- * one-line "not applicable" note rather than deleted, so the agent sees that a- * section was intentionally withheld instead of silently reading a procedure- * with a hole in it and improvising the missing branch.- */-async function resolveSlashdoIncludes(content, libDir, { skipInclude = null } = {}) {- for (let pass = 0; pass < 5; pass++) {- const matches = [...content.matchAll(/!`cat ~\/.claude\/lib\/([^`]+)`/g)];- if (matches.length === 0) break;- const replacements = await Promise.all(matches.map(async (match) => {- const name = slashdoIncludeName(match[1]);- if (skipInclude?.(name)) {- return { pattern: match[0], content: `_(\`${name}\` omitted — not applicable to this run.)_` };- }- const libContent = await readFile(join(libDir, match[1]), 'utf-8').catch(() => null);- return { pattern: match[0], content: libContent };- }));- let changed = false;- for (const { pattern, content: libContent } of replacements) {- // Replace via a function, NOT a string: a string replacement makes- // String.replace interpret `$&`/`$\``/`$'`/`$n` tokens, and the shell-heavy- // lib files are full of `$` — a bare-string replacement both corrupts the- // inlined text and balloons it (a `$\`` token splices in everything before- // the match, blowing a 66KB command up to ~2.5MB). A function replacer- // inserts libContent verbatim.- if (libContent) { content = content.replace(pattern, () => libContent); changed = true; }- }- if (!changed) break;- }- return content;-}--/**- * Resolve slashdo's `<!-- if:<cap> -->…<!-- else -->…<!-- /if:<cap> -->`- * conditional blocks — the same templating slashdo's own installer resolves- * per target environment (see `lib/slashdo/src/transformer.js`). PortOS inlines- * slashdo markdown into CoS-agent prompts WITHOUT going through that installer,- * so unless we resolve these here the agent receives BOTH branches verbatim- * (e.g. the Claude-Code-only "in-process Agent tool" reviewer branch AND the- * `claude -p` subprocess branch), which is self-contradictory and makes a- * headless agent improvise its own reviewer invocation.- *- * Only the `teams` capability is recognized (matching slashdo's- * CONDITIONAL_CAPABILITIES). `teams=false` keeps the `else` branch — the- * subprocess (`claude -p …`) reviewer path that works from any host — which is- * the correct choice for PortOS's headless CoS agents (they have no in-process- * Agent tool and are not billing against an interactive Claude Code plan).- * Unknown capabilities are left untouched so a stray comment never deletes- * content. Blocks do not nest.- */-function resolveSlashdoConditionals(content, { teams = false } = {}) {- const blockRe = /<!--\s*if:([a-zA-Z]+)\s*-->\n?([\s\S]*?)(?:<!--\s*else\s*-->\n?([\s\S]*?))?<!--\s*\/if:\1\s*-->\n?/g;- return content.replace(blockRe, (match, cap, ifContent, elseContent = '') => {- if (cap !== 'teams') return match;- return teams ? ifContent : elseContent;- });-}--/**- * Load a slashdo command markdown file, resolving !`cat ~/.claude/lib/...`- * includes AND the `<!-- if:teams -->` conditional blocks (to the non-teams- * `else` branch — see resolveSlashdoConditionals). Both are needed because- * PortOS inlines these command bodies into headless CoS-agent prompts without- * running slashdo's own installer: e.g. `commands/do/better.md` ships an- * `if:teams` block, and a `/do:better` CoS dispatch would otherwise hand the- * agent both contradictory branches. Optionally strips YAML frontmatter.- *- * `skipIncludes` prunes named lib includes the run can never reach (issue- * #3110). Most of a big command body is reviewer/mode VARIANTS — `review` and- * `better` each pull all five reviewer loops (~152KB of the 258KB body) though a- * given run drives exactly one of them. Passing the unreachable names here is- * where the real prompt saving comes from; each skipped include leaves a- * one-line "not applicable" marker in its place (see `resolveSlashdoIncludes`).- * Callers derive the set from already-resolved run settings and must default to- * skipping NOTHING when they can't — an over-pruned prompt that drops the loop- * the agent actually needs is far worse than a fat one.- *- * Cached: slashdo files are static within a server lifetime (submodule updates- * require restart). Cache resets on process restart, which is the right behavior.- * The cache key carries the skip set, so two runs with different reviewer sets- * don't serve each other's pruned body.- *- * @param {string} commandName - bare command name (`review`)- * @param {Object} [opts]- * @param {boolean} [opts.stripFrontmatter=false]- * @param {string[]} [opts.skipIncludes=[]] - lib include names to prune- * @returns {Promise<string|null>} null when the command file doesn't exist- */-const slashdoFileCache = new Map();-export async function loadSlashdoFile(commandName, { stripFrontmatter = false, skipIncludes = [] } = {}) {- // Sorted so `[a, b]` and `[b, a]` hit the same cache entry.- const skipSet = new Set(Array.isArray(skipIncludes) ? skipIncludes.filter(n => typeof n === 'string' && n) : []);- const skipKey = [...skipSet].sort().join(',');- const cacheKey = `${commandName}::${stripFrontmatter}::${skipKey}`;- if (slashdoFileCache.has(cacheKey)) return slashdoFileCache.get(cacheKey);-- const cmdPath = join(PATHS.slashdo, 'commands/do', `${commandName}.md`);- let content = await readFile(cmdPath, 'utf-8').catch(() => null);- if (!content) return null;- if (stripFrontmatter) {- content = content.replace(/^---[\s\S]*?---\s*/, '');- }- content = await resolveSlashdoIncludes(content, join(PATHS.slashdo, 'lib'), {- skipInclude: skipSet.size ? (name) => skipSet.has(name) : null,- });- content = resolveSlashdoConditionals(content);- slashdoFileCache.set(cacheKey, content);- return content;-}--/**- * Write an already-loaded, fully-resolved slashdo command body to disk and return- * its absolute path, so an agent with file tools can READ the procedure instead of- * receiving it pasted into its prompt (issue #3110).- *- * Why a resolved COPY and not `lib/slashdo/commands/do/<cmd>.md` directly: the- * shipped file's `` !`cat ~/.claude/lib/…` `` includes are unresolved and a- * codex/grok host has no `~/.claude/lib` to resolve them against, so pointing at- * the submodule hands the agent a procedure with holes in it.- *- * Takes the body rather than re-loading it, so the caller's single- * `loadSlashdoFile` result is the one thing written *and* rendered — no way for- * the file on disk and the size the caller measured to disagree.- *- * Written at most once per (command, body) per process: the path→body pair is- * memoized, so repeat dispatches of the same command skip the write entirely.- *- * @param {string} commandName - bare command name (`review`)- * @param {string} body - the resolved markdown to write- * @param {Object} [opts]- * @param {string[]} [opts.skipIncludes=[]] - the prune set that produced `body`;- * folded into the filename so two runs with different reviewer sets don't- * overwrite each other's copy.- * @returns {Promise<string|null>} absolute path, or null for an empty body or a- * command name that isn't a bare, path-inert segment- */-const slashdoResolvedPathCache = new Map();-export async function writeResolvedSlashdoBody(commandName, body, { skipIncludes = [] } = {}) {- if (!body) return null;- // Callers reach here through `resolveSlashdoInvocation`, which already rejects- // anything that isn't a bare command — but this one WRITES a file, so it keeps- // its own guard rather than trusting the call site. Mirrors- // `isValidSlashdoCommand`'s shape (kept local to avoid an import cycle back- // into slashdoInvocation.js, which is a consumer of this module's loaders).- if (!/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/.test(commandName || '')) {- console.warn(`⚠️ Refusing to stage a slashdo body for a non-bare command name: ${commandName}`);- return null;- }-- // The skip set changes the CONTENT, so it has to change the filename too —- // otherwise two runs with different reviewer sets fight over one file and the- // second agent reads the first one's pruned procedure. A short hash keeps the- // common (unpruned) name clean while staying collision-free.- const skipKey = [...new Set(Array.isArray(skipIncludes) ? skipIncludes.filter(Boolean) : [])].sort().join(',');- const suffix = skipKey ? `-${createHash('sha256').update(skipKey).digest('hex').slice(0, 8)}` : '';- const filePath = join(PATHS.slashdoResolved, `${commandName}${suffix}.md`);-- if (slashdoResolvedPathCache.get(filePath) === body) return filePath;- await atomicWrite(filePath, body);- slashdoResolvedPathCache.set(filePath, body);- return filePath;-}--/**- * Load a slashdo *lib* file (`lib/slashdo/lib/<name>.md`) — the shared- * procedure fragments that command files `!`cat``-include — for inlining- * directly into a CoS-agent prompt. Same include + conditional resolution as- * loadSlashdoFile; the differences are that this reads the `lib/` dir (not- * `commands/do/`) and exposes the `teams` override (loadSlashdoFile always- * resolves to the non-teams branch). Defaults to the non-teams (`else`) branch- * so a headless agent gets the subprocess reviewer invocation, not both.- */-const slashdoLibCache = new Map();-export async function loadSlashdoLib(libName, { teams = false } = {}) {- const cacheKey = `${libName}::${teams}`;- if (slashdoLibCache.has(cacheKey)) return slashdoLibCache.get(cacheKey);-- const libDir = join(PATHS.slashdo, 'lib');- let content = await readFile(join(libDir, `${libName}.md`), 'utf-8').catch(() => null);- if (!content) return null;- content = await resolveSlashdoIncludes(content, libDir);- content = resolveSlashdoConditionals(content, { teams });- slashdoLibCache.set(cacheKey, content);- return content;-}-export function formatBytes(bytes) {if (!bytes) return '0 B';const units = ['B', 'KB', 'MB', 'GB', 'TB'];diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex fe29cabdf7..4850e1b743 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -53,8 +53,6 @@ import {saveBase64Upload,saveImageUpload,serveLocalFile,- loadSlashdoLib,- loadSlashdoFile,} from './fileUtils.js';import { copyFileSync, existsSync, mkdirSync } from 'fs';import { dirname } from 'path';@@ -63,61 +61,6 @@ import { fileURLToPath } from 'url';const __dirname_test = dirname(fileURLToPath(import.meta.url));describe('fileUtils', () => {- // Regression guard for the CoS review-loop bug: PortOS inlines slashdo lib- // markdown into headless CoS-agent prompts WITHOUT going through slashdo's- // own per-environment installer, so it must resolve the `<!-- if:teams -->`- // conditionals itself. Leaving both branches in shipped a self-contradictory- // reviewer spec (in-process Agent tool AND `claude -p`) to a codex agent,- // which then improvised its own `claude` invocation via a dozen probe calls.- describe('slashdo loaders (loadSlashdoFile / loadSlashdoLib)', () => {- // Driven from controlled fixtures via the mocked `readFile`, NOT the vendored- // submodule's live content — so the assertions can't drift with a slashdo- // version bump. Each test resets `readFile` to clean real-delegation first: a- // `mockRejectedValueOnce` leaked from an earlier suite would otherwise null out- // a load and fail here (the flake that reddened CI), and the reset also lets- // `mockResolvedValueOnce` feed a fixture as the next read.- let realReadFile;- beforeEach(async () => {- realReadFile = (await vi.importActual('fs/promises')).readFile;- vi.mocked(fsPromises.readFile).mockReset();- vi.mocked(fsPromises.readFile).mockImplementation((...args) => realReadFile(...args));- });-- it('loadSlashdoLib resolves if:teams to the else branch by default and the if branch under teams:true', async () => {- const fixture = 'A<!-- if:teams -->IF<!-- else -->ELSE<!-- /if:teams -->B';- vi.mocked(fsPromises.readFile).mockResolvedValueOnce(fixture);- expect(await loadSlashdoLib('cond-fixture-else')).toBe('AELSEB');- vi.mocked(fsPromises.readFile).mockResolvedValueOnce(fixture);- expect(await loadSlashdoLib('cond-fixture-if', { teams: true })).toBe('AIFB');- });-- it('loadSlashdoLib leaves a non-teams conditional block untouched', async () => {- const fixture = 'A<!-- if:other -->X<!-- /if:other -->B';- vi.mocked(fsPromises.readFile).mockResolvedValueOnce(fixture);- expect(await loadSlashdoLib('cond-fixture-other')).toBe(fixture);- });-- it('loadSlashdoLib returns null for a lib file that does not exist', async () => {- expect(await loadSlashdoLib('no-such-lib-file-xyz')).toBeNull();- });-- it('loadSlashdoFile inlines includes with $-tokens verbatim and resolves conditionals', async () => {- // A shell-heavy lib whose `$&` / `$`-backtick tokens must survive a- // String.replace (a bare-string replacement would interpret them and splice- // pre-match content in, corrupting the text and ballooning the output).- const libBody = 'run claude -p "$LOCAL_PROMPT" $& $`tail';- const cmdBody = 'HEAD\n!`cat ~/.claude/lib/some-lib.md`\n<!-- if:teams -->TEAMS<!-- else -->SUB<!-- /if:teams -->\nTAIL';- vi.mocked(fsPromises.readFile)- .mockResolvedValueOnce(cmdBody) // the command file- .mockResolvedValueOnce(libBody); // the included lib- const body = await loadSlashdoFile('cmd-fixture-dollar');- expect(body).toContain('claude -p "$LOCAL_PROMPT" $& $`tail'); // $-tokens verbatim, no blowup- expect(body).toContain('SUB'); // else branch kept- expect(body).not.toContain('TEAMS'); // if branch stripped- expect(body).not.toMatch(/<!--\s*(if:|else|\/if:)/); // markers gone- });- });-describe('isValidJSON', () => {it('should return true for valid JSON object', () => {expect(isValidJSON('{"key": "value"}')).toBe(true);diff --git a/server/lib/index.js b/server/lib/index.jsindex 072e1e2721..f6868b25e0 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -270,6 +270,7 @@ export * from './shellQuote.js';export * from './sidecarProcess.js';export * from './slashdoCatalog.js';export * from './slashdoInvocation.js';+export * from './slashdoLoader.js';export * from './singleFlight.js';export * from './staticImportGraph.js';export * from './streamBackpressure.js';diff --git a/server/lib/slashdoInvocation.test.js b/server/lib/slashdoInvocation.test.jsindex f914534042..79005e692d 100644--- a/server/lib/slashdoInvocation.test.js+++ b/server/lib/slashdoInvocation.test.js@@ -12,7 +12,7 @@ import {slashdoSkillName,unreachableReviewerIncludes,} from './slashdoInvocation.js';-import { loadSlashdoFile } from './fileUtils.js';+import { loadSlashdoFile } from './slashdoLoader.js';describe('isValidSlashdoCommand', () => {it('accepts bare command names', () => {diff --git a/server/lib/slashdoLoader.js b/server/lib/slashdoLoader.jsnew file mode 100644index 0000000000..713fa817f3--- /dev/null+++ b/server/lib/slashdoLoader.js@@ -0,0 +1,216 @@+/**+ * Slashdo command/lib loading — inlines bundled slashdo markdown (submodule at+ * `lib/slashdo/`) into CoS-agent prompts WITHOUT running slashdo's own+ * per-environment installer, so this module resolves the same `!`cat``+ * include directives and `<!-- if:teams -->` conditionals that installer would+ * otherwise handle. Split out of `fileUtils.js` (a generic file-utilities+ * module) because this is one cohesive feature, not a generic file helper —+ * see `slashdoInvocation.js` for the sibling module covering invocation-style+ * resolution (how a workflow is TYPED per host CLI) rather than loading.+ */+import { readFile } from 'fs/promises';+import { createHash } from 'crypto';+import { join } from 'path';+import { atomicWrite, PATHS } from './fileUtils.js';++/**+ * The include name (`<name>` of `lib/<name>.md`) for a matched `!`cat`` directive,+ * with the `.md` extension dropped so callers name libs the way slashdo does+ * (`local-agent-review-loop`, not `local-agent-review-loop.md`).+ */+function slashdoIncludeName(relPath) {+ return relPath.replace(/^.*\//, '').replace(/\.md$/, '');+}++/**+ * Resolve all `!`cat ~/.claude/lib/<name>`` include directives in `content` by+ * inlining the referenced slashdo lib file. Iterates so an inlined lib that+ * itself carries a `!`cat`` include is resolved too (bounded to avoid a cyclic+ * include spinning forever). Shared by loadSlashdoFile and loadSlashdoLib.+ *+ * `skipInclude(name)` (optional) prunes an include the run can never reach —+ * see `loadSlashdoFile`'s `skipIncludes`. A skipped include is replaced with a+ * one-line "not applicable" note rather than deleted, so the agent sees that a+ * section was intentionally withheld instead of silently reading a procedure+ * with a hole in it and improvising the missing branch.+ */+async function resolveSlashdoIncludes(content, libDir, { skipInclude = null } = {}) {+ for (let pass = 0; pass < 5; pass++) {+ const matches = [...content.matchAll(/!`cat ~\/.claude\/lib\/([^`]+)`/g)];+ if (matches.length === 0) break;+ const replacements = await Promise.all(matches.map(async (match) => {+ const name = slashdoIncludeName(match[1]);+ if (skipInclude?.(name)) {+ return { pattern: match[0], content: `_(\`${name}\` omitted — not applicable to this run.)_` };+ }+ const libContent = await readFile(join(libDir, match[1]), 'utf-8').catch(() => null);+ return { pattern: match[0], content: libContent };+ }));+ let changed = false;+ for (const { pattern, content: libContent } of replacements) {+ // Replace via a function, NOT a string: a string replacement makes+ // String.replace interpret `$&`/`$\``/`$'`/`$n` tokens, and the shell-heavy+ // lib files are full of `$` — a bare-string replacement both corrupts the+ // inlined text and balloons it (a `$\`` token splices in everything before+ // the match, blowing a 66KB command up to ~2.5MB). A function replacer+ // inserts libContent verbatim.+ if (libContent) { content = content.replace(pattern, () => libContent); changed = true; }+ }+ if (!changed) break;+ }+ return content;+}++/**+ * Resolve slashdo's `<!-- if:<cap> -->…<!-- else -->…<!-- /if:<cap> -->`+ * conditional blocks — the same templating slashdo's own installer resolves+ * per target environment (see `lib/slashdo/src/transformer.js`). PortOS inlines+ * slashdo markdown into CoS-agent prompts WITHOUT going through that installer,+ * so unless we resolve these here the agent receives BOTH branches verbatim+ * (e.g. the Claude-Code-only "in-process Agent tool" reviewer branch AND the+ * `claude -p` subprocess branch), which is self-contradictory and makes a+ * headless agent improvise its own reviewer invocation.+ *+ * Only the `teams` capability is recognized (matching slashdo's+ * CONDITIONAL_CAPABILITIES). `teams=false` keeps the `else` branch — the+ * subprocess (`claude -p …`) reviewer path that works from any host — which is+ * the correct choice for PortOS's headless CoS agents (they have no in-process+ * Agent tool and are not billing against an interactive Claude Code plan).+ * Unknown capabilities are left untouched so a stray comment never deletes+ * content. Blocks do not nest.+ */+function resolveSlashdoConditionals(content, { teams = false } = {}) {+ const blockRe = /<!--\s*if:([a-zA-Z]+)\s*-->\n?([\s\S]*?)(?:<!--\s*else\s*-->\n?([\s\S]*?))?<!--\s*\/if:\1\s*-->\n?/g;+ return content.replace(blockRe, (match, cap, ifContent, elseContent = '') => {+ if (cap !== 'teams') return match;+ return teams ? ifContent : elseContent;+ });+}++/**+ * Load a slashdo command markdown file, resolving !`cat ~/.claude/lib/...`+ * includes AND the `<!-- if:teams -->` conditional blocks (to the non-teams+ * `else` branch — see resolveSlashdoConditionals). Both are needed because+ * PortOS inlines these command bodies into headless CoS-agent prompts without+ * running slashdo's own installer: e.g. `commands/do/better.md` ships an+ * `if:teams` block, and a `/do:better` CoS dispatch would otherwise hand the+ * agent both contradictory branches. Optionally strips YAML frontmatter.+ *+ * `skipIncludes` prunes named lib includes the run can never reach (issue+ * #3110). Most of a big command body is reviewer/mode VARIANTS — `review` and+ * `better` each pull all five reviewer loops (~152KB of the 258KB body) though a+ * given run drives exactly one of them. Passing the unreachable names here is+ * where the real prompt saving comes from; each skipped include leaves a+ * one-line "not applicable" marker in its place (see `resolveSlashdoIncludes`).+ * Callers derive the set from already-resolved run settings and must default to+ * skipping NOTHING when they can't — an over-pruned prompt that drops the loop+ * the agent actually needs is far worse than a fat one.+ *+ * Cached: slashdo files are static within a server lifetime (submodule updates+ * require restart). Cache resets on process restart, which is the right behavior.+ * The cache key carries the skip set, so two runs with different reviewer sets+ * don't serve each other's pruned body.+ *+ * @param {string} commandName - bare command name (`review`)+ * @param {Object} [opts]+ * @param {boolean} [opts.stripFrontmatter=false]+ * @param {string[]} [opts.skipIncludes=[]] - lib include names to prune+ * @returns {Promise<string|null>} null when the command file doesn't exist+ */+const slashdoFileCache = new Map();+export async function loadSlashdoFile(commandName, { stripFrontmatter = false, skipIncludes = [] } = {}) {+ // Sorted so `[a, b]` and `[b, a]` hit the same cache entry.+ const skipSet = new Set(Array.isArray(skipIncludes) ? skipIncludes.filter(n => typeof n === 'string' && n) : []);+ const skipKey = [...skipSet].sort().join(',');+ const cacheKey = `${commandName}::${stripFrontmatter}::${skipKey}`;+ if (slashdoFileCache.has(cacheKey)) return slashdoFileCache.get(cacheKey);++ const cmdPath = join(PATHS.slashdo, 'commands/do', `${commandName}.md`);+ let content = await readFile(cmdPath, 'utf-8').catch(() => null);+ if (!content) return null;+ if (stripFrontmatter) {+ content = content.replace(/^---[\s\S]*?---\s*/, '');+ }+ content = await resolveSlashdoIncludes(content, join(PATHS.slashdo, 'lib'), {+ skipInclude: skipSet.size ? (name) => skipSet.has(name) : null,+ });+ content = resolveSlashdoConditionals(content);+ slashdoFileCache.set(cacheKey, content);+ return content;+}++/**+ * Write an already-loaded, fully-resolved slashdo command body to disk and return+ * its absolute path, so an agent with file tools can READ the procedure instead of+ * receiving it pasted into its prompt (issue #3110).+ *+ * Why a resolved COPY and not `lib/slashdo/commands/do/<cmd>.md` directly: the+ * shipped file's `` !`cat ~/.claude/lib/…` `` includes are unresolved and a+ * codex/grok host has no `~/.claude/lib` to resolve them against, so pointing at+ * the submodule hands the agent a procedure with holes in it.+ *+ * Takes the body rather than re-loading it, so the caller's single+ * `loadSlashdoFile` result is the one thing written *and* rendered — no way for+ * the file on disk and the size the caller measured to disagree.+ *+ * Written at most once per (command, body) per process: the path→body pair is+ * memoized, so repeat dispatches of the same command skip the write entirely.+ *+ * @param {string} commandName - bare command name (`review`)+ * @param {string} body - the resolved markdown to write+ * @param {Object} [opts]+ * @param {string[]} [opts.skipIncludes=[]] - the prune set that produced `body`;+ * folded into the filename so two runs with different reviewer sets don't+ * overwrite each other's copy.+ * @returns {Promise<string|null>} absolute path, or null for an empty body or a+ * command name that isn't a bare, path-inert segment+ */+const slashdoResolvedPathCache = new Map();+export async function writeResolvedSlashdoBody(commandName, body, { skipIncludes = [] } = {}) {+ if (!body) return null;+ // Callers reach here through `resolveSlashdoInvocation`, which already rejects+ // anything that isn't a bare command — but this one WRITES a file, so it keeps+ // its own guard rather than trusting the call site. Mirrors+ // `isValidSlashdoCommand`'s shape (kept local to avoid an import cycle back+ // into slashdoInvocation.js, which is a consumer of this module's loaders).+ if (!/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/.test(commandName || '')) {+ console.warn(`⚠️ Refusing to stage a slashdo body for a non-bare command name: ${commandName}`);+ return null;+ }++ // The skip set changes the CONTENT, so it has to change the filename too —+ // otherwise two runs with different reviewer sets fight over one file and the+ // second agent reads the first one's pruned procedure. A short hash keeps the+ // common (unpruned) name clean while staying collision-free.+ const skipKey = [...new Set(Array.isArray(skipIncludes) ? skipIncludes.filter(Boolean) : [])].sort().join(',');+ const suffix = skipKey ? `-${createHash('sha256').update(skipKey).digest('hex').slice(0, 8)}` : '';+ const filePath = join(PATHS.slashdoResolved, `${commandName}${suffix}.md`);++ if (slashdoResolvedPathCache.get(filePath) === body) return filePath;+ await atomicWrite(filePath, body);+ slashdoResolvedPathCache.set(filePath, body);+ return filePath;+}++/**+ * Load a slashdo *lib* file (`lib/slashdo/lib/<name>.md`) — the shared+ * procedure fragments that command files `!`cat``-include — for inlining+ * directly into a CoS-agent prompt. Same include + conditional resolution as+ * loadSlashdoFile; the differences are that this reads the `lib/` dir (not+ * `commands/do/`) and exposes the `teams` override (loadSlashdoFile always+ * resolves to the non-teams branch). Defaults to the non-teams (`else`) branch+ * so a headless agent gets the subprocess reviewer invocation, not both.+ */+const slashdoLibCache = new Map();+export async function loadSlashdoLib(libName, { teams = false } = {}) {+ const cacheKey = `${libName}::${teams}`;+ if (slashdoLibCache.has(cacheKey)) return slashdoLibCache.get(cacheKey);++ const libDir = join(PATHS.slashdo, 'lib');+ let content = await readFile(join(libDir, `${libName}.md`), 'utf-8').catch(() => null);+ if (!content) return null;+ content = await resolveSlashdoIncludes(content, libDir);+ content = resolveSlashdoConditionals(content, { teams });+ slashdoLibCache.set(cacheKey, content);+ return content;+}diff --git a/server/lib/slashdoLoader.test.js b/server/lib/slashdoLoader.test.jsnew file mode 100644index 0000000000..1c0cbc641e--- /dev/null+++ b/server/lib/slashdoLoader.test.js@@ -0,0 +1,69 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import * as fsPromises from 'fs/promises';+// Mock fs/promises so the fixture-driven tests below control exactly what+// `readFile` returns, independent of the vendored slashdo submodule's live+// content — so assertions can't drift with a slashdo version bump. Defaults to+// delegating to the real implementation.+vi.mock('fs/promises', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ readFile: vi.fn((...args) => actual.readFile(...args)),+ };+});+import { loadSlashdoLib, loadSlashdoFile } from './slashdoLoader.js';++// Regression guard for the CoS review-loop bug: PortOS inlines slashdo lib+// markdown into headless CoS-agent prompts WITHOUT going through slashdo's+// own per-environment installer, so it must resolve the `<!-- if:teams -->`+// conditionals itself. Leaving both branches in shipped a self-contradictory+// reviewer spec (in-process Agent tool AND `claude -p`) to a codex agent,+// which then improvised its own `claude` invocation via a dozen probe calls.+describe('slashdo loaders (loadSlashdoFile / loadSlashdoLib)', () => {+ // Driven from controlled fixtures via the mocked `readFile`, NOT the vendored+ // submodule's live content — so the assertions can't drift with a slashdo+ // version bump. Each test resets `readFile` to clean real-delegation first: a+ // `mockRejectedValueOnce` leaked from an earlier suite would otherwise null out+ // a load and fail here (the flake that reddened CI), and the reset also lets+ // `mockResolvedValueOnce` feed a fixture as the next read.+ let realReadFile;+ beforeEach(async () => {+ realReadFile = (await vi.importActual('fs/promises')).readFile;+ vi.mocked(fsPromises.readFile).mockReset();+ vi.mocked(fsPromises.readFile).mockImplementation((...args) => realReadFile(...args));+ });++ it('loadSlashdoLib resolves if:teams to the else branch by default and the if branch under teams:true', async () => {+ const fixture = 'A<!-- if:teams -->IF<!-- else -->ELSE<!-- /if:teams -->B';+ vi.mocked(fsPromises.readFile).mockResolvedValueOnce(fixture);+ expect(await loadSlashdoLib('cond-fixture-else')).toBe('AELSEB');+ vi.mocked(fsPromises.readFile).mockResolvedValueOnce(fixture);+ expect(await loadSlashdoLib('cond-fixture-if', { teams: true })).toBe('AIFB');+ });++ it('loadSlashdoLib leaves a non-teams conditional block untouched', async () => {+ const fixture = 'A<!-- if:other -->X<!-- /if:other -->B';+ vi.mocked(fsPromises.readFile).mockResolvedValueOnce(fixture);+ expect(await loadSlashdoLib('cond-fixture-other')).toBe(fixture);+ });++ it('loadSlashdoLib returns null for a lib file that does not exist', async () => {+ expect(await loadSlashdoLib('no-such-lib-file-xyz')).toBeNull();+ });++ it('loadSlashdoFile inlines includes with $-tokens verbatim and resolves conditionals', async () => {+ // A shell-heavy lib whose `$&` / `$`-backtick tokens must survive a+ // String.replace (a bare-string replacement would interpret them and splice+ // pre-match content in, corrupting the text and ballooning the output).+ const libBody = 'run claude -p "$LOCAL_PROMPT" $& $`tail';+ const cmdBody = 'HEAD\n!`cat ~/.claude/lib/some-lib.md`\n<!-- if:teams -->TEAMS<!-- else -->SUB<!-- /if:teams -->\nTAIL';+ vi.mocked(fsPromises.readFile)+ .mockResolvedValueOnce(cmdBody) // the command file+ .mockResolvedValueOnce(libBody); // the included lib+ const body = await loadSlashdoFile('cmd-fixture-dollar');+ expect(body).toContain('claude -p "$LOCAL_PROMPT" $& $`tail'); // $-tokens verbatim, no blowup+ expect(body).toContain('SUB'); // else branch kept+ expect(body).not.toContain('TEAMS'); // if branch stripped+ expect(body).not.toMatch(/<!--\s*(if:|else|\/if:)/); // markers gone+ });+});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 4617c3c431..19746eebe4 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -15,7 +15,8 @@ import { buildPrompt } from './promptService.js';import { getToolsSummaryForPrompt } from './tools.js';import { getActiveProvider } from './providers.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';-import { readJSONFile, loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody, PATHS, tryReadFile, expandHome } from '../lib/fileUtils.js';+import { readJSONFile, PATHS, tryReadFile, expandHome } from '../lib/fileUtils.js';+import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, resolveReviewUsernames, resolveOptionalReviewers, resolveReviewerMaxRounds, resolveReviewerModels, reviewerModelsFromDefaults, resolveKeyedReviewers, buildReviewWithArgs, buildReviewersCsv } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { canTypeSlashCommands, resolveSlashdoInvocation, buildSlashdoSection, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 69d5f2d810..82db750504 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -49,10 +49,16 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {const actual = await importOriginal();return {...actual,- loadSlashdoFile: vi.fn().mockResolvedValue(null),// getAppWorkspace reads data/apps.json through this — mocked so the tilde// tests below never touch the real registry.readJSONFile: vi.fn(actual.readJSONFile),+ };+});+vi.mock('../lib/slashdoLoader.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ loadSlashdoFile: vi.fn().mockResolvedValue(null),// #3110 — staging the resolved copy is real disk I/O; mocked so tests can// assert the pointer path without writing under data/.writeResolvedSlashdoBody: vi.fn().mockResolvedValue(null),@@ -73,7 +79,7 @@ import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullimport { getCodeReviewDefaults } from './codeReview.js'; // mocked above — control the configured defaultimport { isTruthyMeta } from './agentState.js';import { buildPrompt } from './promptService.js'; // mocked above — inspect call args-import { loadSlashdoFile, writeResolvedSlashdoBody } from '../lib/fileUtils.js'; // mocked above — control the inlined body+import { loadSlashdoFile, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js'; // mocked above — control the inlined bodyimport { SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';function makeTask(overrides = {}) {diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 014b54bb58..3ff92af24c 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -17,7 +17,8 @@ import { emitLog, cosEvents } from './cosEvents.js';import { updateAgent, completeAgent } from './cosAgents.js';import { initProviderStatus } from './providerStatus.js';import { onCosRunnerEvent, initCosRunnerConnection, isRunnerAvailable } from './cosRunnerClient.js';-import { loadSlashdoFile, PATHS } from '../lib/fileUtils.js';+import { PATHS } from '../lib/fileUtils.js';+import { loadSlashdoFile } from '../lib/slashdoLoader.js';import { getRunnerOutputBatcher, flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';import { syncRunnerAgents } from './agentRunnerSync.js';import { handleAgentCompletion, spawnAgentForTask } from './agentLifecycle.js';diff --git a/server/services/taskPromptService.js b/server/services/taskPromptService.jsindex 02120e880d..11579fa375 100644--- a/server/services/taskPromptService.js+++ b/server/services/taskPromptService.js@@ -25,7 +25,8 @@* so existing importers of taskPromptService are unaffected by the leaf split.*/-import { loadSlashdoFile, PATHS } from '../lib/fileUtils.js';+import { PATHS } from '../lib/fileUtils.js';+import { loadSlashdoFile } from '../lib/slashdoLoader.js';import { getTaskInterval } from './taskSchedule.js';import {DEFAULT_TASK_PROMPTS,diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex 588e538fd9..9b791ed137 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -12,7 +12,6 @@ tryReadFile: vi.fn().mockResolvedValue(null),ensureDir: vi.fn().mockResolvedValue(),ensureDirs: vi.fn().mockResolvedValue(),readJSONFile: vi.fn(),- loadSlashdoFile: vi.fn().mockResolvedValue(''),safeJSONParse: (content, fallback) => { try { return JSON.parse(content); } catch { return fallback; } },// atomicWrite replaced the raw writeFile(JSON.stringify) schedule-save site (#1837);// route it through the mocked fs/promises.writeFile so the tests that read@@ -28,6 +27,13 @@ tryReadFile: vi.fn().mockResolvedValue(null),safeDate: (d) => d ? new Date(d).getTime() : 0}))+// slashdoLoader mock: taskPromptService.js reads the bundled command body+// through loadSlashdoFile — stub it the same way the prior fileUtils mock did,+// now that the slashdo loaders live in their own module (#3110's home moved).+vi.mock('../lib/slashdoLoader.js', () => ({+ loadSlashdoFile: vi.fn().mockResolvedValue(''),+}))+vi.mock('fs/promises', () => ({writeFile: vi.fn().mockResolvedValue(),readFile: vi.fn().mockRejectedValue(new Error('readFile not mocked')),@@ -1050,7 +1056,7 @@ describe('taskSchedule', () => {})it('should substitute {slashdoReplan} with the bundled replan command body', async () => {- const { loadSlashdoFile } = await import('../lib/fileUtils.js')+ const { loadSlashdoFile } = await import('../lib/slashdoLoader.js')loadSlashdoFile.mockResolvedValueOnce('# Replan Command\n\nSentinel body for substitution test.')const prompt = await getTaskPrompt('do-replan')expect(prompt).not.toContain('{slashdoReplan}')