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
feat: load slashdo workflows by phase in agent prompts
[._.]/ Adam Eivy3fc671f719ce
diff --git a/AGENTS.md b/AGENTS.mdindex 7a6ffaa8c0..4dac92276f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -123,7 +123,9 @@ Client- and server-specific conventions live in nested memory files that load wh### Slashdo Commands (`lib/slashdo`)-PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`, providing slash commands (`/do:next`, `/do:review`, `/do:pr`, `/do:push`, `/do:release`, …) without a separate global install. The `.claude/commands/do/` symlinks expose them as project-level slash commands. `/do:next` claims the next PLAN.md item (or GitHub issue with `--issues`) in an isolated worktree and ships a PR. CoS agents can inline a command's content into a prompt via `loadSlashdoCommand(name)` from `server/services/subAgentSpawner.js` (it resolves `!cat` lib includes automatically).+PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`, providing slash commands (`/do:next`, `/do:review`, `/do:pr`, `/do:push`, `/do:release`, …) without a separate global install. The `.claude/commands/do/` symlinks expose them as project-level slash commands. `/do:next` claims the next PLAN.md item (or GitHub issue with `--issues`) in an isolated worktree and ships a PR. CoS agents use the shared slashdo renderer: file-tool hosts receive a short entrypoint with supporting files read by phase; `loadSlashdoCommand(name)` from `server/services/subAgentSpawner.js` remains the eager, self-contained form for other consumers.++Project command symlinks expose slashdo source directly. In that source, `!read lib/<name>.md` means read `lib/slashdo/lib/<name>.md` when the named phase applies; resolve nested library references (including `~/.claude/lib/<name>.md` tokens) against that same bundled package root. These are required reads, not shell commands. Do not preload every phase or depend on a global slashdo installation. Staged CoS bundles instead use paths relative to their entrypoint.## Module Organizationdiff --git a/lib/slashdo b/lib/slashdoindex bce844b6dc..f4e1e8ae1c 160000--- a/lib/slashdo+++ b/lib/slashdo@@ -1 +1 @@-Subproject commit bce844b6dc172f24e7b12fa68994068060280514+Subproject commit f4e1e8ae1c0f0949be661901dbfd742b8bd11a35diff --git a/server/lib/README.md b/server/lib/README.mdindex 8a90270b4b..466b8d3276 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -507,8 +507,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `shellReadinessProbe.js` | `buildReadinessProbe(nonce, shell)` — the round-trip "can this shell actually run commands yet?" probe `createShellSession`'s `waitForPromptReady` sends and watches for, in the dialect the session speaks: POSIX `printf '%s\n' 'PORTOSRDY''<nonce>'` (unchanged), PowerShell `Write-Output ('PORTOSRDY' + '<nonce>')`, `cmd.exe` → `null` (no split-literal concatenation operator exists there, so the caller skips straight to the bounded fallback timer instead of risking an always-matching probe). The split-literal property is load-bearing in every dialect: the probe source never contains the assembled marker, so seeing it in the output can only mean the shell executed the probe. || `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 the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so a filed-issue/printed-report run retains its non-code deliverable posture). 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), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); 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. |+| `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`. With a staged `bodyPath` it emits a filesystem pointer for deferred bundles or bodies over `SLASHDO_INLINE_BUDGET_CHARS` (24,000)), `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), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); 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` | Shared slashdo renderer adapter: `loadSlashdoBundle(cmd, {stripFrontmatter, skipIncludes, defer})` returns an entrypoint and supporting files using the bundled transformer; `loadSlashdoFile` returns a self-contained command; `loadSlashdoLib` expands explicit reads for legacy recipes without traversing see-also links. `writeResolvedSlashdoBody(cmd, body, {files})` stages immutable content-addressed bundles under `PATHS.slashdoResolved`, with relative library paths and the entrypoint written last. Missing required references fail dispatch rather than silently removing workflow gates. || `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 `services/promptRunner.js`'s fallback mark-and-pick. || `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. || `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; `buildStaticImportGraph(rootDir)` → `Map<relPath, relPath[]>` of one directory's internal static edges (recurses into subdirectories, skips `.test.js`); `listModuleFiles(rootDir)` → every non-test `.js` under a directory, keyed by `/`-separated relative path (the same walk the graph builder uses, shared so a layering guard cannot drift from it); `findImportCycles(graph)` → each cycle rendered as `a.js -> b.js -> a.js` (depth-first, so WHICH rings it names depends on where the walk enters a component — fine for an "is this empty?" assertion, unusable as a baseline); `findImportCycleComponents(graph)` → the cyclic strongly-connected components as sorted member lists, traversal-order invariant and therefore baselineable (#5693); `specifierMatchesPackage(spec, pkg)` matches a package or any subpath; `toModuleKey(relPath)` is the one graph-key mint — always `/`-separated, because the keys are built two ways (entry-name concatenation vs `path.relative`) and Windows spells the second one with `\`, which silently dropped every edge into a subdirectory module and made the acyclicity guards pass vacuously there (#5909). 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 `serviceImportCycles.test.js` (the tree-wide cycle ratchet), `agentImportCycles.test.js` and `twinImportCycles.test.js` (per-cluster acyclicity) and `spriteAnimationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). |diff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.jsindex 7d52b469bb..d6d83b247b 100644--- a/server/lib/slashdoInvocation.js+++ b/server/lib/slashdoInvocation.js@@ -17,15 +17,10 @@* bare command name in `metadata.slashdoCommand` and this module resolves the* concrete invocation when the prompt is built.*- * 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`).+ * Every host receives the bundled procedure independently of a global install.+ * File-tool hosts read an entrypoint and phase-specific supporting files; API+ * providers receive a self-contained body. Explicitly pinned reviewer choices+ * prune unreachable variants before either form is rendered.*/import { isClaudeProvider, isOpencodeProvider } from './providerModels.js';import { inferTuiCommand } from './providerVendors.js';@@ -41,35 +36,16 @@ export const SLASHDO_NAMESPACE = 'do';* 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, 198,997 pruned to one- * reviewer, 112,269 with every reviewer include 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.+ * 24,000 chars is approximately 6k tokens. Deferred bundles are always staged+ * because their relative references need a filesystem base, even when the+ * entrypoint is under this limit. Small self-contained commands stay inline.*/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 -23% on `review`,- * -27% on `pr`, -28% on `depfree`; the file pointer is the backstop for the rest.- *- * Keyed by the PortOS reviewer slug (`REVIEWER_VALUES` in `reviewerConfig.js`) so- * the keep-set derives from already-resolved run settings. `copilot` and the- * arbitrary-`@login` loop are GitHub-side; `claude`/`codex`/`antigravity`/`grok`/`cursor`- * all share slashdo's one local-agent loop; `ollama`/`lmstudio` are the- * local-model loop.- *- * `multi-reviewer-loop` is the ORCHESTRATION WRAPPER, not a per-reviewer variant:- * slashdo's commands hand off to it for any non-empty reviewer list, and its own- * spec says `{REVIEW_AGENTS}` "may contain a single entry". So it is listed here- * (it is prunable in principle — a run with no reviewers at all doesn't reach it)- * but `unreachableReviewerIncludes` never drops it once a reviewer resolves.- * Pruning it for a lone reviewer left the inner loop with nothing to dispatch it.+ * Reviewer-specific libraries that can be omitted once the run's reviewers are+ * pinned. CLI reviewers share localAgent; local-model reviewers share localModel.+ * Keep the multi-reviewer dispatcher for every non-empty list, even one reviewer.*/export const SLASHDO_REVIEWER_INCLUDES = Object.freeze({copilot: 'copilot-review-loop',@@ -384,7 +360,7 @@ export function resolveSlashdoInvocation({* @returns {string}*/export function oversizedBodyPointer(bodyPath, body) {- return `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.`;+ return `The procedure entrypoint is on disk at \`${bodyPath}\` (${Math.round(body.length / 1000)}KB). READ THAT FILE before you start. Follow its phase order and required reads; read long procedures in sections as needed.`;}/**@@ -392,25 +368,13 @@ export function oversizedBodyPointer(bodyPath, body) {* caller loads `body` (via `loadSlashdoFile`) and passes it in, so this module* stays side-effect free.*- * The body is inlined for EVERY style, not just `skill`. PortOS bundles slashdo- * as a submodule and only exposes it as slash commands through the repo-local- * `.claude/commands/do/` symlinks — which exist in the PortOS checkout, not in- * the managed-app workspaces most CoS tasks run in, and only for Claude Code.- * So a typed invocation is a shortcut for hosts that happen to have slashdo- * installed, never the thing the prompt depends on. Same posture as every other- * slashdo consumer here (`loadSlashdoCommand`, the `/do:rpr` and review-loop- * inlining), which is why the submodule exists at all: no global install required.+ * The procedure accompanies every invocation style: managed apps need no global+ * slashdo install or PortOS project-command symlinks.*- * **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.+ * A staged body always renders as a pointer, including a short entrypoint with+ * deferred references. Supporting files resolve relative to that entrypoint.+ * `bodyPath` is only passed for hosts with file tools; API providers inline an+ * eager, self-contained body.** **`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@@ -471,8 +435,9 @@ export function buildSlashdoSection(resolved, body = null, {if (reviewerEffortNote) {lines.push('', reviewerEffortNote);}- if (body && bodyPath && body.length > SLASHDO_INLINE_BUDGET_CHARS) {- lines.push('', oversizedBodyPointer(bodyPath, body));+ if (body && bodyPath) {+ lines.push('', oversizedBodyPointer(bodyPath, body),+ 'Resolve supporting-file paths relative to that file. Read each required reference only when its phase or condition applies; do not preload the bundle.');} else if (body) {lines.push('',diff --git a/server/lib/slashdoInvocation.test.js b/server/lib/slashdoInvocation.test.jsindex 854dae22a0..6450d49902 100644--- a/server/lib/slashdoInvocation.test.js+++ b/server/lib/slashdoInvocation.test.js@@ -286,10 +286,11 @@ describe('buildSlashdoSection — inline budget vs file pointer', () => {expect(section).toMatch(/READ THAT FILE/);});- it('inlines the body when it is under budget even with a path available', () => {+ it('uses a staged entrypoint even when it is under budget', () => {const section = buildSlashdoSection(codex(), small, { bodyPath: PATH });- expect(section).toContain(small);- expect(section).not.toContain(PATH);+ expect(section).not.toContain(small);+ expect(section).toContain(PATH);+ expect(section).toContain('relative to that file');});it('inlines an over-budget body when no path is offered (an api provider has no file tools)', () => {@@ -378,53 +379,19 @@ describe('unreachableReviewerIncludes', () => {});});-// ------------------------------------------------------------------------------// 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. Measured- // -23% for a lone CLI reviewer (258,260 → 198,997) — the orchestration- // wrapper is deliberately never pruned, which costs ~37KB of the ceiling.- expect(pruned.length).toBeLessThan(full.length * 0.85);- // 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`);+// The upstream renderer owns reference semantics. Exercise its shipped output+// here when the submodule is initialized; fixtures cover dispatch and staging+// separately without requiring a submodule in every CI shard.+describe('bundled command context budget', () => {+ it('keeps the better entrypoint small and preserves an eager procedure', async () => {+ const { existsSync } = await import('fs');+ if (!existsSync(new URL('../../lib/slashdo/src/transformer.js', import.meta.url))) return;+ const { loadSlashdoBundle } = await import('./slashdoLoader.js');+ const bundle = await loadSlashdoBundle('better', { stripFrontmatter: true });+ const eager = await loadSlashdoFile('better', { stripFrontmatter: true });+ expect(bundle.body.length).toBeLessThan(SLASHDO_INLINE_BUDGET_CHARS);+ expect(Object.keys(bundle.files).length).toBeGreaterThan(0);+ expect(bundle.body.length).toBeLessThan(eager.length / 4);+ expect(eager).not.toMatch(/^!read /m);});});diff --git a/server/lib/slashdoLoader.js b/server/lib/slashdoLoader.jsindex 5e07b6fcb0..b6021fae54 100644--- a/server/lib/slashdoLoader.js+++ b/server/lib/slashdoLoader.js@@ -1,230 +1,88 @@-/**- * 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.- */+/** Shared slashdo rendering and immutable prompt bundles for CoS agents. */import { createHash } from 'crypto';import { join } from 'path';+import { pathToFileURL } from 'url';import { atomicWrite, PATHS, tryReadFile } 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$/, '');+const commandCache = new Map();+const libCache = new Map();+const stagedBodies = new Set();+const isBareName = name => typeof name === 'string'+ && /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/.test(name);+const normalizedSkips = names => [...new Set(Array.isArray(names)+ ? names.filter(name => typeof name === 'string' && name) : [])].sort();++async function renderBundle(content, options) {+ // Load only when a command is requested; an uninitialized submodule must not+ // prevent unrelated server modules from loading. Slashdo owns reference and+ // conditional semantics for installed skills and embedded prompts alike.+ const { default: transformer } = await import(pathToFileURL(join(PATHS.slashdo, 'src/transformer.js')).href);+ return transformer.buildPromptBundle(content, join(PATHS.slashdo, 'lib'), options);}/**- * 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.+ * Load a command and its supporting files. Deferred bodies reference lib/*.md;+ * children reference siblings. Read/staging failures propagate so a missing+ * required procedure cannot silently turn into an invocation-only dispatch.+ * Missing top-level commands return null, matching the existing loader contract.*/-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 tryReadFile(join(libDir, match[1]));- 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;+export async function loadSlashdoBundle(commandName, {+ stripFrontmatter = false, skipIncludes = [], defer = true,+} = {}) {+ if (!isBareName(commandName)) return null;+ const skips = normalizedSkips(skipIncludes);+ const cacheKey = JSON.stringify([commandName, stripFrontmatter, skips, defer]);+ if (commandCache.has(cacheKey)) return commandCache.get(cacheKey);+ let content = await tryReadFile(join(PATHS.slashdo, 'commands/do', `${commandName}.md`));+ if (!content) return null;+ if (stripFrontmatter) content = content.replace(/^---[\s\S]*?---\s*/, '');+ const bundle = await renderBundle(content, { skipIncludes: skips, teams: false, defer });+ commandCache.set(cacheKey, bundle);+ return bundle;}-/**- * 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;- });+/** Self-contained command for consumers without file tools. */+export async function loadSlashdoFile(commandName, options = {}) {+ const bundle = await loadSlashdoBundle(commandName, { ...options, defer: false });+ return bundle?.body ?? null;}/**- * 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+ * Library recipe for legacy inline callers. Follow explicit includes/reads only:+ * expanding see-also links pulls unrelated reviewer workflows into sanitized+ * recipes and multiplies their context. Commands use the complete graph above.*/-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 tryReadFile(cmdPath);- 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;+export async function loadSlashdoLib(libName, { teams = false } = {}) {+ if (!isBareName(libName)) return null;+ const cacheKey = JSON.stringify([libName, teams]);+ if (libCache.has(cacheKey)) return libCache.get(cacheKey);+ const content = await tryReadFile(join(PATHS.slashdo, 'lib', `${libName}.md`));+ const body = content ? (await renderBundle(content, { teams, defer: false, followReferences: false })).body : null;+ libCache.set(cacheKey, body);+ return body;}/**- * 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+ * Stage a resolved body and optional supporting files. Content-addressed paths+ * keep an already-dispatched run stable across submodule updates and different+ * reviewer selections. Publish the entrypoint only after every reference exists.*/-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;+export async function writeResolvedSlashdoBody(commandName, body, { files = {} } = {}) {+ if (!body || !isBareName(commandName)) return null;+ const entries = Object.entries(files).sort(([a], [b]) => a.localeCompare(b));+ for (const [name, content] of entries) {+ if (!/^[a-zA-Z0-9_-][a-zA-Z0-9._-]*\.md$/.test(name) || typeof content !== 'string') {+ throw new Error('Invalid slashdo supporting file');+ }+ }+ const digest = createHash('sha256').update(JSON.stringify([body, entries])).digest('hex');+ const directory = join(PATHS.slashdoResolved, `${commandName}-${digest}`);+ const filePath = entries.length ? join(directory, 'workflow.md') : `${directory}.md`;+ if (stagedBodies.has(filePath)) return filePath;+ for (const [name, content] of entries) {+ await atomicWrite(join(directory, 'lib', name), content);}-- // 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);+ stagedBodies.add(filePath);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 tryReadFile(join(libDir, `${libName}.md`));- // Cache the MISS too. An install whose `lib/slashdo` submodule was never- // initialized (`npm run install:all` is what fetches it) would otherwise- // re-attempt the read on every spawn that asks — and since #3733 that is every- // slashdo-free PR-opening agent, not just review-loop follow-ups.- //- // The cost of caching it: a user who runs `git submodule update --init` by- // hand against a RUNNING server keeps getting `null` until a restart, which- // now degrades those agents' Review Loop section rather than only follow-ups'.- // Accepted rather than papered over with an mtime probe — the recovery is a- // restart the user is already adjacent to, and re-statting a known-missing- // file on every spawn to catch it is the wrong trade. `clearSlashdoCaches()`- // is the hook to add if that ever stops being true.- if (!content) {- slashdoLibCache.set(cacheKey, null);- 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.jsindex 1c0cbc641e..2d10ccdbc8 100644--- a/server/lib/slashdoLoader.test.js+++ b/server/lib/slashdoLoader.test.js@@ -1,69 +1,102 @@-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) => {+import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';+import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++const { fixtureRoot } = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('fs');+ const { tmpdir } = await import('os');+ const { join } = await import('path');+ return { fixtureRoot: mkdtempSync(join(tmpdir(), 'slashdo-loader-')) };+});+vi.mock('./fileUtils.js', async importOriginal => {const actual = await importOriginal();- return {- ...actual,- readFile: vi.fn((...args) => actual.readFile(...args)),- };+ return { ...actual, PATHS: { ...actual.PATHS,+ slashdo: fixtureRoot, slashdoResolved: `${fixtureRoot}/resolved`,+ } };+});+import { loadSlashdoLib, loadSlashdoFile, loadSlashdoBundle, writeResolvedSlashdoBody } from './slashdoLoader.js';++const source = fileURLToPath(new URL('../../lib/slashdo/src', import.meta.url));+const hasSubmodule = existsSync(join(source, 'transformer.js'));+const write = (path, body) => {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, body);+};+beforeAll(() => {+ // The upstream renderer has its own fixture matrix. These exercise the real+ // PortOS adapter and staging boundary when the bundled submodule is available.+ if (hasSubmodule) cpSync(source, join(fixtureRoot, 'src'), { recursive: true });});-import { loadSlashdoLib, loadSlashdoFile } from './slashdoLoader.js';+afterAll(() => rmSync(fixtureRoot, { recursive: true, force: true }));-// 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));+describe.skipIf(!hasSubmodule)('slashdo rendering adapter', () => {+ it('keeps command/lib eager consumers self-contained and resolves host capabilities', async () => {+ const lib = 'run "$PROMPT" $& $`tail\n<!-- if:teams -->IN_PROCESS<!-- else -->SUBPROCESS<!-- /if:teams -->';+ write(join(fixtureRoot, 'lib/example.md'), lib);+ write(join(fixtureRoot, 'commands/do/example.md'), '---\ndescription: Example\n---\n!`cat ~/.claude/lib/example.md`');+ const body = await loadSlashdoFile('example', { stripFrontmatter: true });+ expect(body).toContain('run "$PROMPT" $& $`tail');+ expect(body).toContain('SUBPROCESS');+ expect(body).not.toContain('IN_PROCESS');+ expect(body).not.toContain('description:');+ expect(await loadSlashdoLib('example', { teams: true })).toContain('IN_PROCESS');+ expect(await loadSlashdoLib('example')).toContain('SUBPROCESS');});- 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('keeps inline reviewer recipes limited to explicit reads', async () => {+ write(join(fixtureRoot, 'lib/recipe.md'), 'Recipe\n!read lib/required.md\nSee `lib/unrelated.md`.');+ write(join(fixtureRoot, 'lib/required.md'), 'Required verification');+ write(join(fixtureRoot, 'lib/unrelated.md'), 'Unrelated reviewer workflow');+ const body = await loadSlashdoLib('recipe');+ expect(body).toContain('Required verification');+ expect(body).not.toContain('Unrelated reviewer workflow');+ expect(body).not.toContain('!read');});- 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('stages deferred phase reads and keeps different reviewer bundles independent', async () => {+ write(join(fixtureRoot, 'commands/do/phases.md'), '# Workflow\n!read lib/audit.md\n!read lib/local-agent-review-loop.md');+ write(join(fixtureRoot, 'lib/audit.md'), 'Required audit phase\n!read lib/verify.md');+ write(join(fixtureRoot, 'lib/verify.md'), 'Required verification');+ write(join(fixtureRoot, 'lib/local-agent-review-loop.md'), 'Required local review');+ const full = await loadSlashdoBundle('phases');+ const pruned = await loadSlashdoBundle('phases', { skipIncludes: ['local-agent-review-loop'] });+ const fullPath = await writeResolvedSlashdoBody('phases', full.body, { files: full.files });+ const prunedPath = await writeResolvedSlashdoBody('phases', pruned.body, { files: pruned.files });+ expect(fullPath).not.toBe(prunedPath);+ expect(readFileSync(fullPath, 'utf8')).toContain('lib/audit.md');+ expect(readFileSync(join(dirname(fullPath), 'lib/audit.md'), 'utf8')).toContain('./verify.md');+ expect(readFileSync(join(dirname(fullPath), 'lib/verify.md'), 'utf8')).toContain('Required verification');+ expect(pruned.files).not.toHaveProperty('local-agent-review-loop.md');+ expect(full.files).toHaveProperty('local-agent-review-loop.md');+ const eager = await loadSlashdoFile('phases');+ expect(eager).toContain('Required verification');+ expect(eager).toContain('Required local review');+ expect(eager).not.toContain('!read');});- it('loadSlashdoLib returns null for a lib file that does not exist', async () => {- expect(await loadSlashdoLib('no-such-lib-file-xyz')).toBeNull();+ it('distinguishes absent commands from missing required dependencies', async () => {+ expect(await loadSlashdoFile('no-such-command')).toBeNull();+ write(join(fixtureRoot, 'commands/do/broken.md'), '!read lib/no-such-library.md');+ await expect(loadSlashdoBundle('broken')).rejects.toThrow();+ });+});++describe('immutable slashdo staging', () => {+ it('addresses the entire bundle by content, preserving earlier dispatched procedures', async () => {+ const body = 'Read lib/review.md';+ const oldPath = await writeResolvedSlashdoBody('review', body, { files: { 'review.md': 'Original review' } });+ const newPath = await writeResolvedSlashdoBody('review', body, { files: { 'review.md': 'Updated review' } });+ expect(newPath).not.toBe(oldPath);+ expect(readFileSync(join(dirname(oldPath), 'lib/review.md'), 'utf8')).toBe('Original review');+ expect(readFileSync(join(dirname(newPath), 'lib/review.md'), 'utf8')).toBe('Updated review');+ expect(await writeResolvedSlashdoBody('review', body, { files: { 'review.md': 'Updated review' } })).toBe(newPath);});- 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+ it('rejects unsafe output paths before writing the entrypoint', async () => {+ expect(await writeResolvedSlashdoBody('../outside', 'Body')).toBeNull();+ await expect(writeResolvedSlashdoBody('review', 'Body', { files: { '../outside.md': 'Outside' } })).rejects.toThrow('Invalid slashdo supporting file');+ await expect(writeResolvedSlashdoBody('review', 'Body', { files: { 'invalid.md': null } })).rejects.toThrow('Invalid slashdo supporting file');+ expect(existsSync(join(fixtureRoot, 'outside.md'))).toBe(false);});});diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 2435f90510..47409894e0 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -85,9 +85,14 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {});vi.mock('../lib/slashdoLoader.js', async (importOriginal) => {const actual = await importOriginal();+ const loadFile = vi.fn().mockResolvedValue(null);return {...actual,- loadSlashdoFile: vi.fn().mockResolvedValue(null),+ loadSlashdoFile: loadFile,+ loadSlashdoBundle: vi.fn(async (...args) => {+ const body = await loadFile(...args);+ return body == null ? null : { body, files: {} };+ }),loadSlashdoLib: 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/.@@ -112,7 +117,7 @@ import { buildPrompt } from './promptService.js'; // mocked above — inspect caimport { getMemorySection } from './memoryRetriever.js';import { getDigitalTwinForPrompt } from './digital-twin.js';import { getToolsSummaryForPrompt } from './tools.js';-import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js'; // mocked above — control the inlined body+import { loadSlashdoFile, loadSlashdoLib, loadSlashdoBundle, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js'; // mocked above — control the inlined bodyimport { SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';import { DEFAULT_TASK_PROMPTS } from './taskPromptDefaults.js';// The heading a task-type hook's prompt points at to locate the sentinel path.@@ -3368,6 +3373,40 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {expect(prompt).toContain('do-review');});+ it('stages a small deferred entrypoint so its references resolve outside the managed app', async () => {+ const body = 'Read lib/audit.md when auditing.';+ const files = { 'audit.md': 'Audit procedure' };+ vi.mocked(loadSlashdoBundle).mockResolvedValueOnce({ body, files });+ const prompt = await buildAgentPrompt(+ slashdoTask({ reviewers: ['codex'] }), {}, '/managed-app', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ expect(writeResolvedSlashdoBody).toHaveBeenCalledWith('review', body, { files });+ expect(prompt).toContain('/install/data/cos/slashdo-resolved/review.md');+ expect(prompt).toContain('relative to that file');+ expect(prompt).not.toContain(body);+ expect(prompt).toContain('--review-with codex');+ });++ it('rebuilds an eager body if a deferred bundle cannot be staged', async () => {+ vi.mocked(loadSlashdoBundle).mockResolvedValueOnce({+ body: 'Read lib/audit.md', files: { 'audit.md': 'Audit procedure' },+ });+ vi.mocked(loadSlashdoFile).mockResolvedValueOnce('Complete inline audit procedure');+ vi.mocked(writeResolvedSlashdoBody).mockRejectedValueOnce(new Error('EACCES'));+ const prompt = await buildAgentPrompt(+ slashdoTask(), {}, '/managed-app', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' });+ expect(prompt).toContain('Complete inline audit procedure');+ expect(prompt).not.toContain('Read lib/audit.md');+ });++ it('rejects a missing required procedure instead of dispatching an invocation alone', async () => {+ vi.mocked(loadSlashdoBundle).mockRejectedValueOnce(new Error('Missing required slashdo library: audit.md'));+ await expect(buildAgentPrompt(+ slashdoTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', providerId: 'codex' })).rejects.toThrow('Missing required slashdo library');+ });+it('inlines the body when it is under budget, and stages no file', async () => {vi.mocked(loadSlashdoFile).mockResolvedValue(UNDER);const prompt = await buildAgentPrompt(@@ -3582,14 +3621,6 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {// 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/promptSections/slashdo.js b/server/services/promptSections/slashdo.jsindex e43d2a0523..b1e49cf737 100644--- a/server/services/promptSections/slashdo.js+++ b/server/services/promptSections/slashdo.js@@ -2,7 +2,7 @@* Slashdo invocation expansion for agent prompts.*/-import { loadSlashdoFile, writeResolvedSlashdoBody } from '../../lib/slashdoLoader.js';+import { loadSlashdoFile, loadSlashdoBundle, writeResolvedSlashdoBody } from '../../lib/slashdoLoader.js';import { resolveSlashdoInvocation, buildSlashdoSection, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../../lib/slashdoInvocation.js';import { DEFAULT_REVIEWER, resolveReviewerConfig, buildReviewerEffortNote, buildReviewersCsv } from '../../lib/validation.js';@@ -19,20 +19,9 @@ import { DEFAULT_REVIEWER, resolveReviewerConfig, buildReviewerEffortNote, build* 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 -23% on `review` (258,260 →- * 198,997 chars), -27% on `pr`, and -28% on `depfree`. (slashdo's- * orchestration wrapper is never pruned — it dispatches even a single-entry- * reviewer list — which is ~37KB of the theoretical ceiling.)- * 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.+ * File-tool hosts receive slashdo's deferred bundle: an entrypoint and supporting+ * files read only at the relevant phase. API providers receive an eager body.+ * Oversized bodies without references still use the existing file pointer.** 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 —@@ -121,18 +110,23 @@ export async function applySlashdoInvocation(task, {? []: unreachableReviewerIncludes({ reviewers: resolvedReviewers, usernames: resolvedUsernames });- const body = await loadSlashdoFile(command, { stripFrontmatter: true, skipIncludes }).catch(() => null);+ const options = { stripFrontmatter: true, skipIncludes };+ const bundle = hasFileTools ? await loadSlashdoBundle(command, options) : null;+ let body = hasFileTools ? bundle?.body : await loadSlashdoFile(command, options);if (!body) console.log(`⚠️ Slashdo command body unavailable, sending invocation only: ${command}`);+ const hasDeferredFiles = !!bundle && Object.keys(bundle.files).length > 0;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) => {+ // Even a tiny entrypoint needs a stable filesystem base for relative reads.+ // If staging fails, reload eagerly; inlining the deferred body would strand+ // its required references in the managed app's unrelated working directory.+ const bodyPath = (hasFileTools && (overBudget || hasDeferredFiles))+ ? await writeResolvedSlashdoBody(command, body, { files: bundle.files }).catch(async (err) => {console.warn(`⚠️ Could not stage slashdo body for ${command}, inlining instead: ${err.message}`);+ body = await loadSlashdoFile(command, options);+ if (!body) throw new Error(`Slashdo fallback body unavailable: ${command}`);return null;}): null;