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
stop pasting whole 250KB slashdo bodies into every agent prompt (#3110)
[._.]/ Adam Eivy621e48943e2f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 41a898e09c..13509e49bb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -91,5 +91,6 @@## CoS agents+- **[issue-3110] A task that runs a bundled slashdo workflow no longer pastes the whole 250KB procedure into the agent's prompt.** Dispatching `/do:review` or `/do:better` handed the agent its fully-expanded command body — 258KB, roughly 65k tokens — on every single spawn, which on a smaller model could crowd out or overflow the context the actual work needed. Most of that bulk was never reachable: each of those commands carries all five of slashdo's reviewer loops (Copilot, arbitrary GitHub reviewer, local CLI agent, local model, and the multi-reviewer wrapper) though one run drives exactly one of them. When your reviewers are known — pinned on the task, or set in Code Review Defaults — the unreachable loops are now dropped, cutting 37% off `/do:review` (258KB down to 163KB) and 45% off `/do:depfree`; the run is given an explicit `--review-with` so it can't pick a reviewer whose procedure was left out. Whatever is still oversized is written to disk once and handed to the agent as a file path to read, instead of pasted. Nothing is pruned when the reviewer set isn't known — an over-trimmed prompt that drops the loop the agent needed would be worse than a fat one — and API providers, which have no file tools, still get the body inlined (now with a log line naming the command and its size, so the cost is visible rather than silent).- **Antigravity (agy) agents no longer die on the first-run folder-trust gate.** An agy agent launched in a fresh worktree could fail immediately with `Do you trust the contents of this project?` and a `paste-not-rendered` error, having done nothing. The spawner waits for a positive "input box is live" signal before pasting the task prompt, and for claude that signal — the terminal's bracketed-paste mode turning back on — arrives exactly when its composer appears. agy turns it on much earlier, when it enters full-screen mode, while it is still signing in and before its trust prompt has even drawn. So on any run where agy's sign-in outlasted the startup delay, the prompt was pasted into a screen that wasn't ready; the trust menu then appeared and swallowed it along with all three retries, and because the trust prompt hadn't been seen yet the auto-confirm never fired. agy now additionally waits for its composer footer, which only draws once the trust gate is resolved, so the trust prompt is confirmed first and the prompt lands in the input box. (`--dangerously-skip-permissions` does not bypass this gate, contrary to what the code previously assumed.)- Handshake markers are now matched against a rolling window of recent terminal output rather than a single read, so a prompt or footer that arrives split across two reads is still recognized.diff --git a/server/lib/README.md b/server/lib/README.mdindex f1663f83f9..7c266e60dc 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -130,7 +130,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`), JSONL append/read/write helpers, dir scans, hashes, 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. |+| `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`), JSONL append/read/write helpers, dir scans, hashes, 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. || `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. |@@ -289,7 +289,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. || `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)` (pure renderer; the caller loads the body via `loadSlashdoFile`), `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. |+| `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. || `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 c22a43c6da..ac8ba8bd48 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -141,7 +141,13 @@ export const PATHS = {// only the metadata syncs inside the brain `songs` record; peers lacking a// file render "not on this machine". Covered by backup via data/brain/.brainSongbook: join(INSTALL_ROOT, 'data/brain/songbook'),- slashdo: join(CODE_ROOT, 'lib/slashdo')+ slashdo: join(CODE_ROOT, 'lib/slashdo'),+ // Fully-resolved slashdo command bodies written for CoS agents to READ on+ // demand instead of receiving them pasted into the prompt (issue #3110).+ // Derived cache, never authored: regenerated on first use each process, safe+ // to delete. Anchored to INSTALL_ROOT (not CODE_ROOT) because the pointer+ // handed to an agent must name a path that exists on the running install.+ slashdoResolved: join(INSTALL_ROOT, 'data/cos/slashdo-resolved')};/**@@ -861,17 +867,36 @@ 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) {+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 };}));@@ -925,12 +950,33 @@ function resolveSlashdoConditionals(content, { teams = false } = {}) {* `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 } = {}) {- const cacheKey = `${commandName}::${stripFrontmatter}`;+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`);@@ -939,12 +985,67 @@ export async function loadSlashdoFile(commandName, { stripFrontmatter = false }if (stripFrontmatter) {content = content.replace(/^---[\s\S]*?---\s*/, '');}- content = await resolveSlashdoIncludes(content, join(PATHS.slashdo, 'lib'));+ 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 inliningdiff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.jsindex b781a8e6e4..b78cfb622b 100644--- a/server/lib/slashdoInvocation.js+++ b/server/lib/slashdoInvocation.js@@ -20,6 +20,12 @@* Skill-style hosts (and any provider we can't positively identify) get the* command's markdown body inlined into the prompt instead — the provider-agnostic* fallback that works even when that environment has no slashdo install at all.+ *+ * Those bodies are large (38KB–317KB expanded), so two size controls apply+ * (#3110): unreachable reviewer variants are pruned out of the body+ * (`unreachableReviewerIncludes`), and whatever is still over+ * `SLASHDO_INLINE_BUDGET_CHARS` is handed to file-tool hosts as a path to a+ * resolved copy on disk rather than pasted (`buildSlashdoSection`'s `bodyPath`).*/import { isClaudeProvider, isOpencodeProvider } from './providerModels.js';import { inferTuiCommand } from './tuiHandshake.js';@@ -27,6 +33,89 @@ import { inferTuiCommand } from './tuiHandshake.js';/** slashdo's command namespace — `commands/do/<cmd>.md` in the submodule. */export const SLASHDO_NAMESPACE = 'do';+/**+ * Inline budget for a resolved command body, in characters (issue #3110).+ *+ * Under it the body is inlined as before — the section stays self-contained and+ * the agent needs no extra file read. Over it, a host with file tools gets a+ * pointer at a resolved copy on disk instead (see `buildSlashdoSection`).+ *+ * 24,000 chars ≈ 6k tokens. Every current bundled command is far over it even+ * after pruning (`review` measures 258,260 chars raw, 162,677 pruned to one+ * reviewer loop, 112,269 with every reviewer loop dropped), which is the intent:+ * the budget exists so a future SMALL command still inlines. The budget-pin test+ * in `slashdoInvocation.test.js` asserts this against the measured sizes, so a+ * slashdo release that shrinks a command can't silently flip it back to inlining+ * without someone noticing.+ */+export const SLASHDO_INLINE_BUDGET_CHARS = 24000;++/**+ * slashdo lib includes that are REVIEWER VARIANTS — one loop per reviewer kind,+ * all five pasted into `review` / `better` / `pr` / `release` / `depfree` though+ * a given run drives exactly one. Pruning the unreachable ones is where the real+ * prompt saving is — pruning to a single CLI reviewer measured -37% on `review`,+ * -43% on `pr`, -45% on `depfree`; the file pointer is the backstop for the rest.+ *+ * Keyed by the PortOS reviewer slug (`REVIEWER_VALUES` in `cosValidation.js`) so+ * the keep-set derives from already-resolved run settings. `copilot` and the+ * arbitrary-`@login` loop are GitHub-side; `claude`/`codex`/`antigravity`/`grok`+ * all share slashdo's one local-agent loop; `ollama`/`lmstudio` are the+ * local-model loop. `multi-reviewer-loop` is the wrapper — only reachable with+ * 2+ review sources.+ */+export const SLASHDO_REVIEWER_INCLUDES = Object.freeze({+ copilot: 'copilot-review-loop',+ username: 'github-reviewer-loop',+ localAgent: 'local-agent-review-loop',+ localModel: 'ollama-review-loop',+ multi: 'multi-reviewer-loop',+});++/** Every reviewer-variant include name — the prunable universe. */+export const SLASHDO_REVIEWER_INCLUDE_NAMES = Object.freeze(Object.values(SLASHDO_REVIEWER_INCLUDES));++/** Reviewer slugs that drive slashdo's shared local-agent (spawnable CLI) loop. */+const LOCAL_AGENT_REVIEWERS = new Set(['claude', 'codex', 'antigravity', 'grok']);+/** Reviewer slugs that drive slashdo's local-model (Ollama-style) loop. */+const LOCAL_MODEL_REVIEWERS = new Set(['ollama', 'lmstudio']);++/**+ * Which reviewer-variant includes a run can never reach, given its resolved+ * reviewers — the `skipIncludes` set for `loadSlashdoFile` (#3110).+ *+ * **Defaults to pruning NOTHING** whenever the reviewer set isn't a resolved,+ * recognized list: no array, an empty array, or a list naming a slug this+ * mapping doesn't know. An over-pruned prompt that drops the loop the agent+ * actually needs is far worse than a fat one, so every uncertain case keeps+ * everything.+ *+ * @param {Object} [opts]+ * @param {string[]|null} [opts.reviewers] - resolved keyed reviewer slugs+ * @param {string[]} [opts.usernames] - resolved `@login` reviewers+ * @returns {string[]} include names safe to omit (possibly empty)+ */+export function unreachableReviewerIncludes({ reviewers = null, usernames = [] } = {}) {+ if (!Array.isArray(reviewers)) return [];+ const users = Array.isArray(usernames) ? usernames.filter(Boolean) : [];+ if (!reviewers.length && !users.length) return [];++ const keep = new Set();+ for (const slug of reviewers) {+ if (slug === 'copilot') keep.add(SLASHDO_REVIEWER_INCLUDES.copilot);+ else if (LOCAL_AGENT_REVIEWERS.has(slug)) keep.add(SLASHDO_REVIEWER_INCLUDES.localAgent);+ else if (LOCAL_MODEL_REVIEWERS.has(slug)) keep.add(SLASHDO_REVIEWER_INCLUDES.localModel);+ // An unrecognized slug means this mapping is behind the reviewer enum —+ // keep everything rather than guess which loop it needs.+ else return [];+ }+ if (users.length) keep.add(SLASHDO_REVIEWER_INCLUDES.username);+ // The wrapper is only reachable with more than one review source to sequence.+ if (reviewers.length + users.length > 1) keep.add(SLASHDO_REVIEWER_INCLUDES.multi);++ return SLASHDO_REVIEWER_INCLUDE_NAMES.filter(name => !keep.has(name));+}+/*** The three invocation shapes slashdo's installer produces. `slash-namespaced`* and `slash-flat` are typed as a slash command by the host CLI; `skill` is an@@ -207,11 +296,33 @@ export function resolveSlashdoInvocation({* slashdo consumer here (`loadSlashdoCommand`, the `/do:rpr` and review-loop* inlining), which is why the submodule exists at all: no global install required.*+ * **Over-budget bodies become a pointer (#3110).** When `bodyPath` names a+ * resolved copy on disk and the body exceeds `SLASHDO_INLINE_BUDGET_CHARS`, the+ * section emits the path instead of the text and the agent reads it on demand.+ * This is NOT a token saving by itself — an agent that follows the whole+ * procedure pays the same tokens through `Read`. It is worth doing because a host+ * that can invoke slashdo natively, or that only needs part of the procedure,+ * skips the cost entirely; the prompt-size win comes from pruning unreachable+ * reviewer variants BEFORE this check (`unreachableReviewerIncludes`).+ * `bodyPath` is only ever passed for a host with file tools — an HTTP `api`+ * provider has none, so it always inlines.+ *+ * **`reviewWith` is mandatory whenever the body was pruned.** A pruned body has+ * only the reviewer loop(s) the caller pruned FOR; if the run then resolved some+ * other reviewer from slashdo's own saved defaults, that loop would be missing+ * and the agent would improvise it. Emitting the pin makes the body and the run+ * agree. Callers that prune nothing pass nothing.+ ** @param {ReturnType<typeof resolveSlashdoInvocation>} resolved* @param {string|null} [body] - the command's markdown+ * @param {Object} [opts]+ * @param {string|null} [opts.bodyPath=null] - absolute path to a resolved copy of+ * `body`. Pass only when the host has file tools.+ * @param {string} [opts.reviewWith=''] - reviewer CSV to pin (`codex,copilot`).+ * Required when `body` had reviewer variants pruned out of it.* @returns {string} markdown section, or '' when `resolved` is null*/-export function buildSlashdoSection(resolved, body = null) {+export function buildSlashdoSection(resolved, body = null, { bodyPath = null, reviewWith = '' } = {}) {if (!resolved) return '';// Without explicit args the workflow operates on the task described above —@@ -233,7 +344,18 @@ export function buildSlashdoSection(resolved, body = null) {'```');}- if (body) {+ if (reviewWith) {+ lines.push(+ '',+ `Run this workflow with \`--review-with ${reviewWith}\` — the procedure you were given carries ONLY those reviewers' loops (the others were omitted as unreachable). Do not substitute a different reviewer from a saved slashdo default.`+ );+ }+ if (body && bodyPath && body.length > SLASHDO_INLINE_BUDGET_CHARS) {+ lines.push(+ '',+ `The full procedure is on disk at \`${bodyPath}\` (${Math.round(body.length / 1000)}KB) — too large to paste here. READ THAT FILE before you start and follow it exactly rather than improvising. It is long: read it in sections as you need them, and do not assume a step you have not read.`+ );+ } else if (body) {lines.push('','The full procedure is inlined below — follow it exactly rather than improvising:',diff --git a/server/lib/slashdoInvocation.test.js b/server/lib/slashdoInvocation.test.jsindex a1dcdc698b..53d8e03552 100644--- a/server/lib/slashdoInvocation.test.js+++ b/server/lib/slashdoInvocation.test.js@@ -1,13 +1,18 @@import { describe, it, expect } from 'vitest';import {+ SLASHDO_INLINE_BUDGET_CHARS,SLASHDO_INVOCATION_STYLES,+ SLASHDO_REVIEWER_INCLUDES,+ SLASHDO_REVIEWER_INCLUDE_NAMES,buildSlashdoSection,canTypeSlashCommands,isValidSlashdoCommand,resolveSlashdoInvocation,resolveSlashdoStyle,slashdoSkillName,+ unreachableReviewerIncludes,} from './slashdoInvocation.js';+import { loadSlashdoFile } from './fileUtils.js';describe('isValidSlashdoCommand', () => {it('accepts bare command names', () => {@@ -209,3 +214,160 @@ describe('buildSlashdoSection', () => {expect(section.trim()).not.toBe('');});});++// -----------------------------------------------------------------------------+// Size controls (#3110)+// -----------------------------------------------------------------------------+describe('buildSlashdoSection — inline budget vs file pointer', () => {+ const codex = () => resolveSlashdoInvocation({ command: 'review', providerId: 'codex' });+ const big = 'x'.repeat(SLASHDO_INLINE_BUDGET_CHARS + 1);+ const small = 'y'.repeat(SLASHDO_INLINE_BUDGET_CHARS - 1);+ const PATH = '/install/data/cos/slashdo-resolved/review.md';++ it('emits the pointer and NOT the body when over budget with a file-tools host', () => {+ const section = buildSlashdoSection(codex(), big, { bodyPath: PATH });+ expect(section).toContain(PATH);+ expect(section).not.toContain(big);+ // The directive still has to be actionable on its own.+ expect(section).toContain('do-review');+ expect(section).toMatch(/READ THAT FILE/);+ });++ it('inlines the body when it is under budget even with a path available', () => {+ const section = buildSlashdoSection(codex(), small, { bodyPath: PATH });+ expect(section).toContain(small);+ expect(section).not.toContain(PATH);+ });++ it('inlines an over-budget body when no path is offered (an api provider has no file tools)', () => {+ const section = buildSlashdoSection(codex(), big);+ expect(section).toContain(big);+ expect(section).not.toContain('slashdo-resolved');+ });++ it('pins --review-with whenever the body was pruned, so the run matches the body it got', () => {+ const section = buildSlashdoSection(codex(), big, { bodyPath: PATH, reviewWith: 'codex,copilot' });+ expect(section).toContain('--review-with codex,copilot');+ expect(section).toMatch(/omitted as unreachable/);+ });++ it('omits the pin when nothing was pruned', () => {+ expect(buildSlashdoSection(codex(), small)).not.toContain('--review-with');+ });+});++describe('unreachableReviewerIncludes', () => {+ it('prunes nothing when the reviewer set is unresolved or empty', () => {+ // Absent / empty / non-array all mean "we do not know" — an over-pruned+ // prompt that drops the loop the agent needs is worse than a fat one.+ expect(unreachableReviewerIncludes()).toEqual([]);+ expect(unreachableReviewerIncludes({ reviewers: null })).toEqual([]);+ expect(unreachableReviewerIncludes({ reviewers: [] })).toEqual([]);+ expect(unreachableReviewerIncludes({ reviewers: 'codex' })).toEqual([]);+ });++ it('prunes nothing when the list names a reviewer this mapping does not know', () => {+ // A new REVIEWER_VALUES entry that lands without a mapping row here must+ // degrade to keep-all, not silently drop the loop it needed.+ expect(unreachableReviewerIncludes({ reviewers: ['some-future-reviewer'] })).toEqual([]);+ expect(unreachableReviewerIncludes({ reviewers: ['codex', 'some-future-reviewer'] })).toEqual([]);+ });++ it('keeps only the local-agent loop for a lone CLI reviewer', () => {+ const skipped = unreachableReviewerIncludes({ reviewers: ['codex'] });+ expect(skipped).not.toContain(SLASHDO_REVIEWER_INCLUDES.localAgent);+ // Single reviewer ⇒ the multi-reviewer wrapper is unreachable too.+ expect(skipped).toContain(SLASHDO_REVIEWER_INCLUDES.multi);+ expect(skipped).toContain(SLASHDO_REVIEWER_INCLUDES.copilot);+ expect(skipped).toContain(SLASHDO_REVIEWER_INCLUDES.localModel);+ expect(skipped).toContain(SLASHDO_REVIEWER_INCLUDES.username);+ });++ it('maps every CLI reviewer onto the one shared local-agent loop', () => {+ for (const slug of ['claude', 'codex', 'antigravity', 'grok']) {+ expect(unreachableReviewerIncludes({ reviewers: [slug] }))+ .not.toContain(SLASHDO_REVIEWER_INCLUDES.localAgent);+ }+ });++ it('maps both local-model reviewers onto the local-model loop', () => {+ for (const slug of ['ollama', 'lmstudio']) {+ expect(unreachableReviewerIncludes({ reviewers: [slug] }))+ .not.toContain(SLASHDO_REVIEWER_INCLUDES.localModel);+ }+ });++ it('keeps the multi-reviewer wrapper as soon as there are two review sources', () => {+ expect(unreachableReviewerIncludes({ reviewers: ['codex', 'copilot'] }))+ .not.toContain(SLASHDO_REVIEWER_INCLUDES.multi);+ // One keyed reviewer + one @login is also two sources.+ expect(unreachableReviewerIncludes({ reviewers: ['codex'], usernames: ['octocat'] }))+ .not.toContain(SLASHDO_REVIEWER_INCLUDES.multi);+ });++ it('keeps the arbitrary-@login loop only when a username reviewer is present', () => {+ expect(unreachableReviewerIncludes({ reviewers: ['codex'], usernames: ['octocat'] }))+ .not.toContain(SLASHDO_REVIEWER_INCLUDES.username);+ expect(unreachableReviewerIncludes({ reviewers: ['codex'] }))+ .toContain(SLASHDO_REVIEWER_INCLUDES.username);+ });++ it('never returns a name outside the reviewer-variant universe', () => {+ for (const skipped of [+ unreachableReviewerIncludes({ reviewers: ['codex'] }),+ unreachableReviewerIncludes({ reviewers: ['copilot', 'ollama'] }),+ unreachableReviewerIncludes({ reviewers: ['claude'], usernames: ['octocat'] }),+ ]) {+ for (const name of skipped) expect(SLASHDO_REVIEWER_INCLUDE_NAMES).toContain(name);+ }+ });+});++// -----------------------------------------------------------------------------+// Budget pin — the ONE place these tests touch the vendored submodule (#3110)+// -----------------------------------------------------------------------------+// The budget only does its job if every big command is actually over it. If a+// slashdo release shrinks one under 24,000 chars it would silently flip back to+// being pasted whole, which is exactly the regression this issue removed. These+// assert on measured SIZE, never on the submodule's text, and skip when the+// submodule isn't checked out.+describe('SLASHDO_INLINE_BUDGET_CHARS pin against the bundled commands', () => {+ // Commands whose expanded bodies are large enough that pasting them dominates+ // a prompt (measured 2026-07: 38KB–317KB). Not the whole catalog — small+ // commands like `push` (3KB) are SUPPOSED to stay inlined.+ const OVER_BUDGET_COMMANDS = ['review', 'better', 'better-swift', 'release', 'depfree', 'next', 'replan', 'plan-task'];++ it('every large bundled command is over the budget, even fully pruned', async () => {+ const submodulePresent = await loadSlashdoFile('review', { stripFrontmatter: true }).catch(() => null);+ if (!submodulePresent) return; // submodule not checked out — nothing to pin++ for (const command of OVER_BUDGET_COMMANDS) {+ // Prune EVERY reviewer variant — the smallest body this code can produce.+ const pruned = await loadSlashdoFile(command, {+ stripFrontmatter: true,+ skipIncludes: SLASHDO_REVIEWER_INCLUDE_NAMES,+ });+ expect(pruned, `slashdo ships commands/do/${command}.md`).toBeTruthy();+ expect(+ pruned.length,+ `${command} is ${pruned.length} chars fully pruned — under the ${SLASHDO_INLINE_BUDGET_CHARS} budget, so it would be INLINED again. Either it genuinely shrank (lower the budget deliberately) or the prune is over-eager.`+ ).toBeGreaterThan(SLASHDO_INLINE_BUDGET_CHARS);+ }+ });++ it('pruning unreachable reviewer loops measurably shrinks a reviewer-heavy command', async () => {+ const full = await loadSlashdoFile('review', { stripFrontmatter: true }).catch(() => null);+ if (!full) return;+ // A lone codex reviewer keeps only the local-agent loop.+ const pruned = await loadSlashdoFile('review', {+ stripFrontmatter: true,+ skipIncludes: unreachableReviewerIncludes({ reviewers: ['codex'] }),+ });+ // Shape, not an exact byte count: pruning must be a real double-digit-percent+ // reduction, and must not be a no-op that quietly stopped working.+ expect(pruned.length).toBeLessThan(full.length * 0.75);+ // The kept loop is still there and the omission is announced, not silent.+ expect(pruned).toContain('not applicable to this run');+ expect(pruned).not.toContain(`\`${SLASHDO_REVIEWER_INCLUDES.localAgent}\` omitted`);+ });+});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 5fa5addb89..0e7b6b887f 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -15,10 +15,10 @@ 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, PATHS, tryReadFile } from '../lib/fileUtils.js';-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, resolveReviewUsernames, resolveOptionalReviewers, resolveKeyedReviewers, buildReviewWithArgs } from '../lib/validation.js';+import { readJSONFile, loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody, PATHS, tryReadFile } from '../lib/fileUtils.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, resolveReviewUsernames, resolveOptionalReviewers, resolveKeyedReviewers, buildReviewWithArgs, buildReviewersCsv } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';-import { canTypeSlashCommands, resolveSlashdoInvocation, buildSlashdoSection } from '../lib/slashdoInvocation.js';+import { canTypeSlashCommands, resolveSlashdoInvocation, buildSlashdoSection, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';import { shellQuote } from '../lib/shellQuote.js';import { detectForgeCli } from '../lib/gitForge.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';@@ -303,10 +303,39 @@ export function reconcileSplitContext(task) {* "Auto" — the concrete shape (`/do:x`, `/do-x`, or an Agent Skill selected by* name) is only knowable here, once the scheduler has picked a provider.*- * The command body is inlined for every provider, not just the skill-style ones:- * PortOS ships slashdo as a submodule and only surfaces it as slash commands via- * the repo-local `.claude/commands/do/` symlinks, which don't exist in the- * managed-app workspaces most CoS tasks run in. See `buildSlashdoSection`.+ * The command body travels with the prompt for every provider, not just the+ * skill-style ones: PortOS ships slashdo as a submodule and only surfaces it as+ * slash commands via the repo-local `.claude/commands/do/` symlinks, which don't+ * exist in the managed-app workspaces most CoS tasks run in.+ *+ * **Size control (#3110).** Expanded bodies run 38KB–317KB. Two independent+ * reductions apply, in this order:+ *+ * 1. **Prune unreachable reviewer variants.** `review`/`better`/`pr` each paste+ * all five of slashdo's reviewer loops though one run drives one of them.+ * Pruning to a single CLI reviewer measured -37% on `review` (258,260 →+ * 162,677 chars), -43% on `pr`, and -45% on `depfree`; dropping every reviewer+ * loop reaches -57%. This is where the saving actually is.+ * 2. **Point at a resolved copy on disk when still over budget** — but only for a+ * host with file tools (`cli`/`tui`; an HTTP `api` provider has none and+ * inlines with a warning). On its own this is roughly token-NEUTRAL for an+ * agent that reads the whole procedure; it pays off when the host can invoke+ * slashdo natively or needs only part of the body.+ *+ * Pruning is only sound if the run then uses the reviewers we pruned FOR, so the+ * section emits an explicit `--review-with` pin alongside a pruned body —+ * otherwise the agent could resolve a different reviewer from slashdo's own saved+ * defaults and find that loop missing. No explicit pin ⇒ no prune.+ *+ * "Explicit" means the task pinned reviewers, or the install's Code Review+ * Defaults name something other than a lone `copilot`. A lone `copilot` is NOT+ * treated as explicit for two reasons that point the same way:+ * `pickCodeReviewDefaults` collapses "nothing configured" into `['copilot']`, so+ * it is indistinguishable from an unconfigured install; and pinning+ * `--review-with copilot` on an install with no Copilot review enabled is the+ * #2507 stall. Same suppression `buildReviewWithArgs` already applies to the+ * lone default. So an unconfigured install keeps the whole body and lets slashdo+ * resolve its own reviewer.** Applied to the description (on a COPY — the stored task is untouched) rather* than emitted as its own template slot, because the briefing template renders@@ -315,7 +344,10 @@ export function reconcileSplitContext(task) {** @returns {Promise<Object>} the task, or a copy carrying the invocation*/-async function applySlashdoInvocation(task, { providerId = null, providerCommand = null, leanMode = false } = {}) {+async function applySlashdoInvocation(task, {+ providerId = null, providerCommand = null, leanMode = false, hasFileTools = false,+ defaultReviewers = null, defaultUsernames = null,+} = {}) {const command = task.metadata?.slashdoCommand;const resolved = resolveSlashdoInvocation({command,@@ -326,9 +358,41 @@ async function applySlashdoInvocation(task, { providerId = null, providerCommand});if (!resolved) return task;- const body = await loadSlashdoFile(command, { stripFrontmatter: true }).catch(() => null);+ // Task pin first, install-wide Code Review Defaults second — but a lone+ // `copilot` from the defaults is the unconfigured shape, not a choice (see the+ // doc above), so it doesn't authorize pruning.+ const pinnedUsernames = normalizeReviewUsernames(+ Array.isArray(task.metadata?.usernames) ? task.metadata.usernames : defaultUsernames+ );+ const configuredDefaults = Array.isArray(defaultReviewers)+ && defaultReviewers.length+ && !(defaultReviewers.length === 1 && defaultReviewers[0] === DEFAULT_REVIEWER && !pinnedUsernames.length);+ const pinnedReviewers = Array.isArray(task.metadata?.reviewers) && task.metadata.reviewers.length+ ? task.metadata.reviewers+ : (configuredDefaults ? defaultReviewers : null);+ const skipIncludes = unreachableReviewerIncludes({ reviewers: pinnedReviewers, usernames: pinnedUsernames });++ const body = await loadSlashdoFile(command, { stripFrontmatter: true, skipIncludes }).catch(() => null);if (!body) console.log(`⚠️ Slashdo command body unavailable, sending invocation only: ${command}`);- return { ...task, description: `${task.description}\n\n${buildSlashdoSection(resolved, body)}` };+ const overBudget = !!body && body.length > SLASHDO_INLINE_BUDGET_CHARS;+ // An HTTP `api` provider can't read a file, so an over-budget body is pasted+ // whole. Surface the cost rather than paying it silently.+ if (overBudget && !hasFileTools) {+ console.warn(`⚠️ Inlining ${Math.round(body.length / 1000)}KB slashdo body for API provider (no file tools): ${command}`);+ }+ // Only spend the write when the pointer will actually be used.+ const bodyPath = (overBudget && hasFileTools)+ ? await writeResolvedSlashdoBody(command, body, { skipIncludes }).catch((err) => {+ console.warn(`⚠️ Could not stage slashdo body for ${command}, inlining instead: ${err.message}`);+ return null;+ })+ : null;++ const reviewWith = skipIncludes.length+ ? buildReviewersCsv(normalizeReviewers({ reviewers: pinnedReviewers }), pinnedUsernames, task.metadata?.optionalReviewers)+ : '';+ const section = buildSlashdoSection(resolved, body, { bodyPath, reviewWith });+ return { ...task, description: `${task.description}\n\n${section}` };}/**@@ -926,10 +990,6 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfoconst isTui = providerType === PROVIDER_TYPES.TUI;const leanMode = options.leanMode === true;- // Render a slashdo-backed task's invocation now that the provider is known —- // before the light-path branch below, so both paths carry it.- task = await applySlashdoInvocation(task, { providerId, providerCommand, leanMode });-// Install-wide default reviewer list (Code Review Defaults panel →// `settings.codeReview.reviewers`). Threaded as the `normalizeReviewers`// fallback so a task that pins no `reviewers` (e.g. every app-improve /@@ -939,9 +999,23 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// `['copilot']` (getCodeReviewDefaults returns the copilot fallback), so// behavior is unchanged when nothing is configured. A settings read error// degrades to the hardcoded default inside normalizeReviewers.+ //+ // Resolved BEFORE the slashdo section below, which prunes the reviewer+ // variants a run can't reach out of the command body (#3110).const codeReviewDefaults = await getCodeReviewDefaults().catch(() => null);const defaultReviewers = codeReviewDefaults?.reviewers;+ // Render a slashdo-backed task's invocation now that the provider is known —+ // before the light-path branch below, so both paths carry it. `hasFileTools`+ // is the light/`api` split itself: `cli`/`tui` hosts are agentic CLIs with+ // native file tools (so an over-budget procedure can live on disk), while an+ // HTTP `api` provider has none and must have it pasted (#3110).+ task = await applySlashdoInvocation(task, {+ providerId, providerCommand, leanMode,+ hasFileTools: LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType),+ defaultReviewers, defaultUsernames: codeReviewDefaults?.usernames,+ });+// Preload slashdo's local-agent review-loop recipe once for review-loop// follow-up tasks; both the light/TUI path (via lightOptions) and the full// path (the verbose builder below) reuse this single value to inline the exactdiff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 4a1867784f..e38bc6f578 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -50,6 +50,9 @@ vi.mock('../lib/fileUtils.js', async (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),};});vi.mock('./jira.js', () => ({@@ -67,7 +70,8 @@ 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 } from '../lib/fileUtils.js'; // mocked above — control the inlined body+import { loadSlashdoFile, writeResolvedSlashdoBody } from '../lib/fileUtils.js'; // mocked above — control the inlined body+import { SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';function makeTask(overrides = {}) {return {@@ -1618,7 +1622,9 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {slashdoTask(), {}, '/r', null, isTruthyMeta,{ providerType: 'cli', providerId });expect(prompt).toContain('Investigate, then file the issue.');- expect(vi.mocked(loadSlashdoFile)).toHaveBeenCalledWith('plan-task', { stripFrontmatter: true });+ // `skipIncludes: []` — nothing pruned, since this task pins no reviewers and+ // the mocked defaults are the unconfigured lone-copilot shape (#3110).+ expect(vi.mocked(loadSlashdoFile)).toHaveBeenCalledWith('plan-task', { stripFrontmatter: true, skipIncludes: [] });});it('still emits the invocation when the body cannot be loaded', async () => {@@ -1658,3 +1664,146 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {expect(vi.mocked(loadSlashdoFile)).not.toHaveBeenCalledWith('../../etc/passwd', expect.anything());});});++// -----------------------------------------------------------------------------+// Slashdo prompt-size controls (#3110)+// -----------------------------------------------------------------------------+// Expanded bodies run 38KB–317KB. Two reductions: prune the reviewer variants a+// run can't reach, then hand a file-tools host a path for whatever is still over+// budget. `api` providers have no file tools and keep inlining. Assertions are on+// SHAPE (pointer present / body present / prune set passed), never on the+// submodule's text.+describe('buildAgentPrompt — slashdo prompt-size controls', () => {+ const OVER = 'B'.repeat(SLASHDO_INLINE_BUDGET_CHARS + 500);+ const UNDER = '# Small Procedure\n\nStep one.';+ const slashdoTask = (metadata = {}) => makeTask({+ description: 'Audit the widget API',+ metadata: { slashdoCommand: 'review', ...metadata },+ });++ beforeEach(() => {+ // mockReset (not just a new return value): several tests here assert the+ // staging helper was NOT called, so a prior test's call must not leak in.+ vi.mocked(writeResolvedSlashdoBody).mockReset();+ vi.mocked(loadSlashdoFile).mockReset();+ vi.mocked(loadSlashdoFile).mockResolvedValue(OVER);+ vi.mocked(writeResolvedSlashdoBody).mockResolvedValue('/install/data/cos/slashdo-resolved/review.md');+ vi.mocked(getCodeReviewDefaults).mockResolvedValue({ reviewers: ['copilot'] });+ });++ it('hands a file-tools host a pointer instead of the body when over budget', async () => {+ const prompt = await buildAgentPrompt(+ slashdoTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ expect(prompt).toContain('/install/data/cos/slashdo-resolved/review.md');+ expect(prompt).not.toContain(OVER);+ // Still actionable — the invocation survives.+ expect(prompt).toContain('do-review');+ });++ it('inlines the body when it is under budget, and stages no file', async () => {+ vi.mocked(loadSlashdoFile).mockResolvedValue(UNDER);+ const prompt = await buildAgentPrompt(+ slashdoTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ expect(prompt).toContain('Step one.');+ expect(vi.mocked(writeResolvedSlashdoBody)).not.toHaveBeenCalled();+ });++ it('inlines for an api provider regardless of size — no file tools to read with', async () => {+ vi.mocked(buildPrompt).mockClear();+ await buildAgentPrompt(slashdoTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'api', providerId: 'some-http-provider' });+ const [, context] = vi.mocked(buildPrompt).mock.calls.at(-1);+ expect(context.task.description).toContain(OVER);+ expect(vi.mocked(writeResolvedSlashdoBody)).not.toHaveBeenCalled();+ });++ it('warns once, naming the command and size, when an api provider is handed an over-budget body', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ await buildAgentPrompt(slashdoTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'api', providerId: 'some-http-provider' });+ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn.mock.calls[0][0]).toContain('review');+ expect(warn.mock.calls[0][0]).toMatch(/\d+KB/);+ warn.mockRestore();+ });++ it('falls back to inlining when the resolved copy cannot be staged', async () => {+ vi.mocked(writeResolvedSlashdoBody).mockRejectedValue(new Error('EACCES'));+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const prompt = await buildAgentPrompt(+ slashdoTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ // A failed write must not silently drop the procedure.+ expect(prompt).toContain(OVER);+ expect(warn).toHaveBeenCalled();+ warn.mockRestore();+ });++ describe('reviewer-variant pruning', () => {+ const skipArg = () => vi.mocked(loadSlashdoFile).mock.calls.at(-1)[1].skipIncludes;++ it('prunes unreachable reviewer loops when the task pins its reviewers', async () => {+ await buildAgentPrompt(+ slashdoTask({ reviewers: ['codex'] }), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ const skipped = skipArg();+ expect(skipped).toContain('copilot-review-loop');+ expect(skipped).not.toContain('local-agent-review-loop');+ });++ it('pins --review-with alongside a pruned body so the run matches what it got', async () => {+ const prompt = await buildAgentPrompt(+ slashdoTask({ reviewers: ['codex'] }), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ expect(prompt).toContain('--review-with codex');+ });++ it('prunes from the install Code Review Defaults when the task pins nothing', async () => {+ vi.mocked(getCodeReviewDefaults).mockResolvedValue({ reviewers: ['ollama'] });+ await buildAgentPrompt(+ slashdoTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ expect(skipArg()).not.toContain('ollama-review-loop');+ });++ it('prunes NOTHING on an unconfigured install (a lone copilot default is the unset shape)', async () => {+ // pickCodeReviewDefaults collapses "nothing configured" to ['copilot'], so a+ // lone copilot can't authorize pruning — and pinning --review-with copilot on+ // an install without Copilot review is the #2507 stall.+ vi.mocked(getCodeReviewDefaults).mockResolvedValue({ reviewers: ['copilot'] });+ const prompt = await buildAgentPrompt(+ slashdoTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ expect(skipArg()).toEqual([]);+ expect(prompt).not.toContain('--review-with');+ });++ it('prunes NOTHING when the defaults read fails', async () => {+ vi.mocked(getCodeReviewDefaults).mockRejectedValue(new Error('unreadable'));+ await buildAgentPrompt(+ slashdoTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ expect(skipArg()).toEqual([]);+ });++ it('keeps the @login loop when a username reviewer gates the PR', async () => {+ await buildAgentPrompt(+ slashdoTask({ reviewers: ['codex'], usernames: ['octocat'] }), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ const skipped = skipArg();+ expect(skipped).not.toContain('github-reviewer-loop');+ // Two review sources ⇒ the multi-reviewer wrapper is reachable.+ expect(skipped).not.toContain('multi-reviewer-loop');+ });++ it('keys the staged file on the prune set so two reviewer sets do not share a copy', async () => {+ await buildAgentPrompt(+ slashdoTask({ reviewers: ['codex'] }), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ const [, , opts] = vi.mocked(writeResolvedSlashdoBody).mock.calls.at(-1);+ expect(opts.skipIncludes).toContain('copilot-review-loop');+ });+ });+});diff --git a/server/services/backup.js b/server/services/backup.jsindex c002828da5..1c8b008ba4 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -50,6 +50,7 @@ const queueStateWrite = createFileWriteQueue();export const DEFAULT_EXCLUDES = [{ path: '/browser-profile/', reason: 'Browser CDP profile — cache/cookies, can be several GB', overridable: false },{ path: '/cos/worktrees/', reason: 'Ephemeral agent git worktrees — recreated on demand', overridable: false },+ { path: '/cos/slashdo-resolved/', reason: 'Resolved slashdo command bodies staged for agent prompts — derived from the bundled submodule, regenerated on demand', overridable: false },{ path: '/cos/feature-agents/*/worktree/', reason: 'Per-feature-agent git worktrees — recreated on demand', overridable: false },{ path: '/loras/*.safetensors', reason: 'LoRA adapter weight files — large, re-downloadable. .metadata.json sidecars (Civitai metadata, user-editable name/notes) ARE backed up.', overridable: true },// `**` (not `*`) so both engines' checkpoint dirs match: the torch trainer