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(cos): split agent prompt into light vs full context by provider type
[._.]/ Adam Eivy97786b4a00b0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 76b4729aed..6f5439993b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1049,6 +1049,24 @@## Changed+- **CoS agent prompts: light vs full context split.** Codex / Claude Code /+ Gemini agents (`provider.type` ∈ {`tui`, `cli`}) now receive a minimal+ runtime-built prompt — just task description, attached context, screenshot+ paths, worktree/JIRA/pipeline coordinates, and the completion-workflow+ contract. Memory dumps, CLAUDE.md re-paste, digital twin, tools summary,+ `.planning/` snippets, auto-matched skill templates, and compaction+ warnings are deliberately omitted because those agents already have+ filesystem tools and native CLAUDE.md loading. API providers (LM Studio,+ raw OpenAI/Anthropic) keep the existing full-context prompt. Also drops+ the obsolete "# Chief of Staff Agent Briefing" header and "You are an+ autonomous agent…" role-play preamble from the shipped template. An+ example end-to-end TUI prompt now lands at ~1.7 KB instead of multiple KB+ of kitchen-sink context. New `buildLightContextPrompt()` in+ `server/services/agentPromptBuilder.js` is unit-tested with 16 cases+ covering routing + section assembly. Existing installs auto-migrate the+ shipped template via `data/migrations/009-simplify-cos-agent-briefing.js`+ if untouched; customized templates get a skip-with-warning.+- **DRY: consolidate duplicate `isStr`/`trimTo` helpers.** Six server modules(`server/services/pipeline/issues.js`, `server/services/sharing/exporter.js`,`server/services/sharing/manifest.js`, `server/services/sharing/importer.js`,diff --git a/data.sample/prompts/stages/cos-agent-briefing.md b/data.sample/prompts/stages/cos-agent-briefing.mdindex 450b5c8cfd..5c00f8daf5 100644--- a/data.sample/prompts/stages/cos-agent-briefing.md+++ b/data.sample/prompts/stages/cos-agent-briefing.md@@ -1,8 +1,3 @@-# Chief of Staff Agent Briefing--You are an autonomous agent working on behalf of the Chief of Staff system in PortOS.-Your job is to complete the assigned task independently and efficiently.-## Task Assignment**Task ID**: {{task.id}}diff --git a/data/migrations/009-simplify-cos-agent-briefing.js b/data/migrations/009-simplify-cos-agent-briefing.jsnew file mode 100644index 0000000000..5dc726e272--- /dev/null+++ b/data/migrations/009-simplify-cos-agent-briefing.js@@ -0,0 +1,79 @@+/**+ * Strip the obsolete preamble from the CoS agent prompt template:+ * - The "# Chief of Staff Agent Briefing" header+ * - The "You are an autonomous agent…" role-play framing+ * Both were chrome on top of the real instructions. The template only+ * serves API providers now (TUI and CLI agents get a runtime-built light+ * prompt from buildLightContextPrompt), so this cleanup is API-facing only.+ *+ * Strategy — "unmodified-only" update: if the installed file matches any+ * historical shipped hash, replace it with the current data.sample copy.+ * Diverged (customized) files are left alone with a warning.+ *+ * Idempotent — re-runs that find the current sample hash on disk are no-ops.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { createHash } from 'crypto';++const md5 = (str) => {+ const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');+ return createHash('md5').update(normalized).digest('hex');+};++const FILENAME = 'cos-agent-briefing.md';++// Every shipped version of cos-agent-briefing.md prior to this migration.+// If the installed file matches any of these, the user hasn't customized it+// and we can safely replace it with the current sample.+const OLD_SHIPPED_HASHES = [+ '699d053875472df455258724a0162bd5', // e827e066 — abort standardization on dirty worktree+ '181b26838e526427173e4dccfc884d01', // d086bdfc — remove git stash + enforce /do:push+ '3e1ca7f7b14b799f89a193c568003624', // f4589187 — don't update PortOS changelog+ 'af73fd50d6f29d561772474c12346e53', // 3b4ced6a — task-type skill templates+ '9bcd3a0167dd4aed7cfff7f404494dfb', // cf41dd61 — context compaction+ 'd761133753da290a0c02eca1c87709e4', // 9b4c4ba6 — initial CoS landing+];++// Hash of the version this migration copies in (data.sample current).+const NEW_SHIPPED_HASH = 'dccb392a43cbd3dac900fee12c31619a';++export default {+ async up({ rootDir }) {+ const dataPath = join(rootDir, 'data', 'prompts', 'stages', FILENAME);+ const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', FILENAME);++ const existing = await readFile(dataPath, 'utf-8').catch((err) => {+ if (err.code !== 'ENOENT') throw err;+ return null;+ });++ if (existing === null) {+ console.log(`📄 ${FILENAME}: not present in data/, will be created by setup-data.js`);+ return;+ }++ const existingMd5 = md5(existing);++ if (existingMd5 === NEW_SHIPPED_HASH) {+ console.log(`📝 ${FILENAME}: already up to date`);+ return;+ }++ if (!OLD_SHIPPED_HASHES.includes(existingMd5)) {+ console.warn(+ `⚠️ ${FILENAME} has been customized — skipping auto-update.\n` ++ ` To drop the obsolete header and role-play preamble manually, diff:\n` ++ ` data.sample/prompts/stages/${FILENAME}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${FILENAME}`,+ );+ return;+ }++ const sampleContent = await readFile(samplePath, 'utf-8');+ await writeFile(dataPath, sampleContent);+ console.log(`✅ updated CoS agent prompt template: ${FILENAME}`);+ },+};diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex 90473dc6f9..39a351ac31 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -144,6 +144,17 @@ const SHIPPED_PROMPT_OLD_MD5 = {'pipeline-extract-scenes.md': '59fa5ee305ce53d91eb15224d8b546d3',// INT/EXT + time-of-day additions to the places extractor (migration 007).'writers-room-places.md': '7f1f80eb63d67a21161994cde115045e',+ // CoS agent prompt: drop obsolete "# Chief of Staff Agent Briefing" header+ // and "You are an autonomous agent…" preamble (migration 009). Every+ // historical shipped hash is auto-updatable to the new sample.+ 'cos-agent-briefing.md': [+ '699d053875472df455258724a0162bd5',+ '181b26838e526427173e4dccfc884d01',+ '3e1ca7f7b14b799f89a193c568003624',+ 'af73fd50d6f29d561772474c12346e53',+ '9bcd3a0167dd4aed7cfff7f404494dfb',+ 'd761133753da290a0c02eca1c87709e4',+ ],};const SHIPPED_PROMPT_NEW_MD5 = {'pipeline-idea-expansion.md': '1ee44cf95851ff8debf18729ebcd40b4',@@ -157,6 +168,7 @@ const SHIPPED_PROMPT_NEW_MD5 = {'pipeline-arc-resolve.md': 'a8677bbe1eb38f871fb152a5b0fec7c6','pipeline-extract-scenes.md': 'c51fb208568d0d903eb43b437478b0ba','writers-room-places.md': '24a33628cc94d80fa5ca60831d973daf',+ 'cos-agent-briefing.md': 'dccb392a43cbd3dac900fee12c31619a',};const SHIPPED_PROMPT_FILES = Object.keys(SHIPPED_PROMPT_OLD_MD5);diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 794f14f366..6a49788ee3 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -433,10 +433,11 @@ export async function spawnAgentForTask(task) {const isTui = provider.type === 'tui';- // Build the agent prompt (includes worktree and JIRA context if applicable).- // TUI providers (Claude Code, etc.) read CLAUDE.md natively at session boot,- // so don't paste it into the prompt — saves tokens and avoids duplication.- const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, { skipClaudeMd: isTui, tui: isTui });+ // Build the agent prompt. `provider.type` drives the light-vs-full split+ // inside buildAgentPrompt — see its doc comment.+ const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, {+ providerType: provider.type+ });// Create agent directoryconst agentDir = join(AGENTS_DIR, agentId);diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex dbbeb6d104..0236e96de9 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -145,23 +145,46 @@ ${hints.map(h => `- ${h}`).join('\n')}}/**- * Build the full agent prompt.+ * Provider types that get the **light** prompt: agentic CLIs with native+ * filesystem tools and CLAUDE.md loading (Claude Code, Codex, Gemini —+ * whether running interactively as `tui` or one-shot as `cli`). Everything+ * else (`api`: LM Studio, raw OpenAI/Anthropic) needs the full pasted-in+ * context because it has no native filesystem access.+ */+const LIGHT_CONTEXT_PROVIDER_TYPES = new Set(['tui', 'cli']);++/**+ * Build the agent prompt.+ *+ * Two context modes, selected by `options.providerType`:+ *+ * - **Light** (`tui` / `cli`): minimal prompt — task description, attached+ * context, screenshot paths, worktree/jira/pipeline coordinates, and the+ * completion-workflow contract. Memory, CLAUDE.md, digital twin, tools+ * summary, planning context, skill templates, and compaction warnings are+ * deliberately omitted because the agent can fetch them itself.+ * - **Full** (`api`): kitchen-sink prompt with memory + CLAUDE.md + digital+ * twin + tools + skills + planning + git hygiene. The leading+ * "# Chief of Staff Agent Briefing" header is dropped from both modes.+ ** @param {Object} task - Task object* @param {Object} config - CoS configuration* @param {string} workspaceDir - Working directory (may be a worktree)* @param {Object|null} worktreeInfo - Worktree details if using a worktree* @param {Function} isTruthyMetaFn - isTruthyMeta function (passed to avoid circular dep)+ * @param {Object} options+ * @param {string} [options.providerType='api'] - `'tui' | 'cli' | 'api'`*/export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null, isTruthyMetaFn = (v) => v === true || v === 'true', options = {}) {- // TUI agents run inside an interactive Claude Code shell that already reads- // CLAUDE.md natively at session start — re-pasting it into the prompt just- // wastes tokens and duplicates context. TUI agents also own their- // commit/push/PR workflow directly via slashdo commands (Claude Code TUI- // has /simplify, /do:pr, etc. available), so the worktree/simplify- // sections that assume system-side post-exit cleanup are replaced with a- // single TUI workflow block.- const skipClaudeMd = options.skipClaudeMd === true;- const isTui = options.tui === true;+ const providerType = options.providerType || 'api';+ const isTui = providerType === 'tui';++ if (LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) {+ return buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui });+ }++ // Full path: API providers don't read CLAUDE.md natively, so always include it.+ const skipClaudeMd = false;// Fetch independent context sections in parallelconst [memorySection, claudeMdSection, digitalTwinSection] = await Promise.all([getMemorySection(task, { maxTokens: config.memory?.maxContextTokens || 2000 })@@ -392,14 +415,11 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch}// Fallback to built-in template- return `# Chief of Staff Agent Briefing--${claudeMdSection || ''}+ return `${claudeMdSection || ''}${memorySection || ''}## Task Assignment-You are an autonomous agent working on behalf of the Chief of Staff.### Task Details- **ID**: ${task.id}@@ -454,6 +474,210 @@ ${task.metadata?.app ? `You are working in the target app directory: \`${workspaBegin working on the task now.`;}+/**+ * Build the **light-context** prompt for agents that have native filesystem+ * tools and CLAUDE.md loading (Claude Code, Codex, Gemini — `tui` or `cli`).+ *+ * The agent already has direct access to the project, so we don't paste in:+ * memory dumps, CLAUDE.md contents, digital twin, tools summary,+ * `.planning/` snippets, auto-matched skill templates, or compaction+ * warnings. We just hand it the task, any user-attached context/screenshots,+ * and the PortOS-specific contract bits it can't infer (worktree branch,+ * JIRA ticket, pipeline predecessors, completion-sentinel protocol,+ * review-loop follow-up procedure).+ *+ * Falls back gracefully when worktree/jira/pipeline metadata is absent — only+ * the present sections render.+ */+export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true } = {}) {+ const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);+ const willReviewLoop = isTruthyMetaFn(task.metadata?.reviewLoop);+ const simplifyEnabled = isTruthyMetaFn(task.metadata?.simplify);+ const isReadOnly = isTruthyMetaFn(task.metadata?.readOnly);+ const isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);+ const isWorktreeOnExistingBranch = worktreeInfo?.existingBranch === true;++ const sections = [];++ // --- Task block --------------------------------------------------------+ const taskLines = [+ '## Task',+ `- **ID**: ${task.id}`,+ `- **Priority**: ${task.priority}`,+ `- **Description**: ${task.description}`+ ];+ if (task.metadata?.app) taskLines.push(`- **Target App**: ${task.metadata.app}`);+ taskLines.push(`- **Working Directory**: \`${workspaceDir}\``);+ sections.push(taskLines.join('\n'));++ const context = task.metadata?.context;+ if (context) {+ sections.push(context.includes('\n')+ ? `### Context\n\n${context.trimEnd()}`+ : `### Context\n${context}`);+ }++ if (Array.isArray(task.metadata?.screenshots) && task.metadata.screenshots.length > 0) {+ sections.push(+ '### Screenshots\nUse your filesystem tools to inspect each path:\n' ++ task.metadata.screenshots.map(s => `- \`${s}\``).join('\n')+ );+ }++ // --- Worktree ----------------------------------------------------------+ if (worktreeInfo) {+ sections.push([+ '## Git Worktree',+ `- **Branch**: \`${worktreeInfo.branchName}\`${isWorktreeOnExistingBranch ? ' *(pre-existing PR branch)*' : ''}`,+ `- **Path**: \`${worktreeInfo.worktreePath}\``,+ worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\`` : null,+ '',+ worktreeCommitGuidance({ isTui, isWorktreeOnExistingBranch, willOpenPR }),+ 'Do NOT manually switch branches or modify the worktree configuration.'+ ].filter(Boolean).join('\n'));+ }++ // --- Pipeline ----------------------------------------------------------+ const pipelineCtx = task.metadata?.pipeline;+ if (pipelineCtx?.previousStageAgentId) {+ const prevOutput = join(AGENTS_DIR, pipelineCtx.previousStageAgentId, 'output.txt');+ sections.push([+ '## Pipeline Context',+ `Stage ${pipelineCtx.currentStage + 1} of ${pipelineCtx.stages.length}: "${pipelineCtx.stages[pipelineCtx.currentStage]?.name}"`,+ `Previous stage: "${pipelineCtx.stages[pipelineCtx.currentStage - 1]?.name}"`,+ '',+ `Read the previous stage's output from: \`${prevOutput}\``,+ 'If it produced a JSON results block, parse it to determine which items to process.'+ ].join('\n'));+ }++ // --- JIRA --------------------------------------------------------------+ if (task.metadata?.jiraTicketId) {+ sections.push([+ '## JIRA',+ `- **Ticket**: ${task.metadata.jiraTicketId} (${task.metadata.jiraTicketUrl})`,+ task.metadata.jiraBranch ? `- **Branch**: \`${task.metadata.jiraBranch}\` — commit here; do NOT switch branches.` : null,+ `Include the ticket ID in commit messages, e.g. \`${task.metadata.jiraTicketId}: description\`.`+ ].filter(Boolean).join('\n'));+ }++ // --- Completion / review-loop ------------------------------------------+ if (isReadOnly) {+ sections.push('## Read-Only Task\nDo NOT commit, push, or modify any files. Read data and report findings only.');+ } else if (isReviewLoopFollowUp) {+ const prUrl = task.metadata?.reviewLoopPRUrl || '';+ const prBranch = task.metadata?.reviewLoopPRBranch || '';+ const prNumber = task.metadata?.reviewLoopPRNumber ?? '';+ const prOwner = task.metadata?.reviewLoopPROwner ?? '';+ const prRepo = task.metadata?.reviewLoopPRRepo ?? '';+ const sourceTaskId = task.metadata?.sourceTaskId || 'unknown';+ sections.push([+ '## Review-Loop Follow-up (PRIMARY OBJECTIVE)',+ `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. The system has requested an initial Copilot review. Drive the review-and-fix loop to completion and merge.`,+ '',+ '**Loop UNTIL zero unresolved Copilot comments OR 10 iterations:**',+ '1. Wait for the latest Copilot review (poll 5–15s, max 5 min per round).',+ '2. If unresolved threads: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, resolve threads.',+ '3. Re-request a Copilot review.',+ '4. Repeat.',+ '5. When clean, merge with:',+ ' ```bash',+ ` gh pr merge "${prUrl}" --squash --auto --delete-branch`,+ ' ```',+ prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --auto --delete-branch\`.)` : null,+ '6. Exit — do NOT run `/do:push` or open a new PR.',+ '',+ '**Hard stop:** if not converged after 10 rounds, post a PR comment summarising blockers and exit.',+ '**Repeated comments:** if a round only re-raises feedback you intentionally rejected (with a reply explaining why), treat as clean and merge.'+ ].filter(Boolean).join('\n'));+ } else if (isTui) {+ sections.push(buildTuiCompletionSection({+ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`+ }));+ } else {+ sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR }));+ }++ sections.push('Begin working on the task now.');+ return sections.join('\n\n') + '\n';+}++/**+ * Worktree commit-guidance helper for the light prompt. Picks the right+ * single-sentence instruction based on whether the agent will run its own+ * push workflow (TUI), reuse an existing PR branch (review fixes), or hand+ * off to PortOS's post-exit push.+ */+function worktreeCommitGuidance({ isTui, isWorktreeOnExistingBranch, willOpenPR }) {+ if (isTui) return 'Commit your changes to this branch — see **Completion Workflow** below.';+ if (isWorktreeOnExistingBranch) {+ return 'Commit and **push** any review-fix commits to this branch (the PR points at it). Use `git pull --rebase` before pushing if needed.';+ }+ if (willOpenPR) {+ return 'Commit your changes here. The system will push and open a PR after you exit — do NOT push or open a PR yourself.';+ }+ return 'Commit your changes here. Your branch will be merged back automatically when the task completes.';+}++/**+ * TUI completion-workflow block. The TUI owns its own commit → push → PR+ * pipeline via slashdo commands and signals "done" with a sentinel file.+ */+function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath }) {+ const cmd = willOpenPR ? '/do:pr' : '/do:push';+ const verb = willOpenPR ? 'PR' : 'push';+ const cmdEffect = willOpenPR+ ? ', pushes, and opens a PR against the default branch. Write the PR title and body yourself; do NOT let any tool auto-generate from terminal output'+ : ' and pushes the branch';+ const reviewSuffix = willOpenPR && willReviewLoop+ ? ' After the PR is open, request a Copilot review (e.g. via `gh`).' : '';+ const simplifyStep = simplifyEnabled+ ? '1. `/simplify` — review the changed code for reuse/quality/efficiency and fix any findings.'+ : '1. (simplify disabled — skip)';+ const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';++ return [+ '## Completion Workflow',+ `You own the entire commit → push → ${verb} sequence. PortOS will NOT push or open a PR for you. When the task is complete, run these in order without further user input:`,+ '',+ simplifyStep,+ `2. \`${cmd}\` — commits${cmdEffect}.${reviewSuffix}`,+ '3. Write the completion sentinel as a SHORT markdown report (~5–15 lines):',+ '',+ ' ```bash',+ ` cat > "${sentinelPath}" <<'EOF'`,+ ' ## Summary',+ ' <one-sentence statement of what was accomplished>',+ '',+ ' ## Changes',+ ' - <key file or area>: <what changed and why>',+ '',+ sentinelTail,+ ' EOF',+ ' ```',+ '',+ ' PortOS polls for this file every 2 seconds; without it the agent sits idle until the 3-minute fallback fires.',+ '4. Run `/quit` to exit cleanly.'+ ].join('\n');+}++/**+ * CLI (non-TUI) completion block. CLI agents (codex exec / claude -p /+ * gemini one-shot) don't have slashdo commands available — they commit and+ * PortOS handles the push/PR after exit.+ */+function buildCliCompletionSection({ worktreeInfo, willOpenPR }) {+ let body;+ if (worktreeInfo && willOpenPR) {+ body = 'Commit your changes (stage specific files, `feat:`/`fix:` prefix, no Co-Authored-By). Do NOT push — PortOS will push and open the PR after you exit.';+ } else if (worktreeInfo) {+ body = 'Commit your changes to this branch. PortOS will merge it back when the task completes.';+ } else {+ body = 'Commit and push your changes (`git pull --rebase && git push`, conventional commit prefix, no `git add -A`).';+ }+ return `## Completion\n${body}`;+}+/*** Get workspace path for an app.*/diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsnew file mode 100644index 0000000000..54bb6ad2a8--- /dev/null+++ b/server/services/agentPromptBuilder.test.js@@ -0,0 +1,213 @@+/**+ * Tests for the light-vs-full context split in buildAgentPrompt.+ *+ * The split is by `provider.type`:+ * - `tui` / `cli` → light prompt (Claude Code, Codex, Gemini — agentic+ * CLIs with native filesystem tools and CLAUDE.md loading)+ * - `api` → full prompt (LM Studio, raw OpenAI/Anthropic — no+ * native filesystem access, so we paste in memory/CLAUDE.md/etc.)+ *+ * The light path is the focus here because it's the new code. The full+ * path is exercised by a single negative assertion that confirms the+ * obsolete "# Chief of Staff Agent Briefing" header and "You are an+ * autonomous agent…" preamble are gone from BOTH paths.+ */++import { describe, it, expect } from 'vitest';+import { buildLightContextPrompt, buildAgentPrompt } from './agentPromptBuilder.js';+import { isTruthyMeta } from './agentState.js';++function makeTask(overrides = {}) {+ return {+ id: 'task-test-1',+ priority: 'HIGH',+ description: 'Add a button to the dashboard',+ metadata: {},+ ...overrides,+ };+}++describe('buildLightContextPrompt', () => {+ describe('what it omits', () => {+ it('does NOT include the obsolete "# Chief of Staff Agent Briefing" header', () => {+ const prompt = buildLightContextPrompt(makeTask(), '/repo', null, isTruthyMeta);+ expect(prompt).not.toMatch(/Chief of Staff Agent Briefing/);+ });++ it('does NOT inject the "You are an autonomous agent" role-play framing', () => {+ const prompt = buildLightContextPrompt(makeTask(), '/repo', null, isTruthyMeta);+ expect(prompt).not.toMatch(/You are an autonomous agent/);+ });++ it('does NOT paste memory, CLAUDE.md, digital-twin, tools-summary, planning, or skill blocks', () => {+ // Light path is synchronous and reads NONE of these — proving it by+ // checking the rendered output has no section headings for them.+ const prompt = buildLightContextPrompt(makeTask({+ metadata: { context: 'extra detail', app: 'comics' }+ }), '/repo', null, isTruthyMeta);+ expect(prompt).not.toMatch(/## CLAUDE\.md Instructions/);+ expect(prompt).not.toMatch(/## Relevant Memory/);+ expect(prompt).not.toMatch(/## Digital Twin/);+ expect(prompt).not.toMatch(/## Onboard Tools/);+ expect(prompt).not.toMatch(/## Project Planning Context/);+ expect(prompt).not.toMatch(/## Task-Type Skill Guidelines/);+ expect(prompt).not.toMatch(/## Context Compaction Required/);+ // No generic "Instructions / Guidelines / Git Hygiene" boilerplate either.+ expect(prompt).not.toMatch(/^## Guidelines$/m);+ expect(prompt).not.toMatch(/^## Git Hygiene/m);+ });+ });++ describe('what it includes', () => {+ it('includes task id/priority/description and working directory', () => {+ const prompt = buildLightContextPrompt(makeTask(), '/workspaces/foo', null, isTruthyMeta);+ expect(prompt).toMatch(/task-test-1/);+ expect(prompt).toMatch(/HIGH/);+ expect(prompt).toMatch(/Add a button to the dashboard/);+ expect(prompt).toMatch(/\/workspaces\/foo/);+ });++ it('renders attached context (multiline and single-line)', () => {+ const single = buildLightContextPrompt(+ makeTask({ metadata: { context: 'one-liner' } }), '/r', null, isTruthyMeta);+ expect(single).toMatch(/### Context\none-liner/);++ const multi = buildLightContextPrompt(+ makeTask({ metadata: { context: 'line one\nline two' } }), '/r', null, isTruthyMeta);+ expect(multi).toMatch(/### Context\n\nline one\nline two/);+ });++ it('lists screenshot file paths so the agent can read them via its own tools', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { screenshots: ['/tmp/a.png', '/tmp/b.png'] } }),+ '/r', null, isTruthyMeta);+ expect(prompt).toMatch(/### Screenshots/);+ expect(prompt).toMatch(/`\/tmp\/a\.png`/);+ expect(prompt).toMatch(/`\/tmp\/b\.png`/);+ });++ it('renders the worktree block with branch + path when worktreeInfo is present', () => {+ const wt = {+ branchName: 'cos/test-1',+ worktreePath: '/tmp/wt',+ baseBranch: 'origin/main',+ };+ const prompt = buildLightContextPrompt(makeTask(), '/r', wt, isTruthyMeta);+ expect(prompt).toMatch(/## Git Worktree/);+ expect(prompt).toMatch(/`cos\/test-1`/);+ expect(prompt).toMatch(/`\/tmp\/wt`/);+ expect(prompt).toMatch(/`origin\/main`/);+ });++ it('renders the JIRA block when a ticket id is set', () => {+ const prompt = buildLightContextPrompt(makeTask({+ metadata: {+ jiraTicketId: 'PROJ-123',+ jiraTicketUrl: 'https://j/PROJ-123',+ jiraBranch: 'jira/proj-123',+ }+ }), '/r', null, isTruthyMeta);+ expect(prompt).toMatch(/## JIRA/);+ expect(prompt).toMatch(/PROJ-123/);+ expect(prompt).toMatch(/`jira\/proj-123`/);+ });++ it('renders the Completion Workflow with /do:pr for TUI + openPR', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { simplify: true, openPR: true } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta,+ { isTui: true });+ expect(prompt).toMatch(/## Completion Workflow/);+ expect(prompt).toMatch(/`\/simplify`/);+ expect(prompt).toMatch(/`\/do:pr`/);+ expect(prompt).toMatch(/\.agent-done/);+ expect(prompt).toMatch(/\/quit/);+ });++ it('renders the Completion Workflow with /do:push when openPR is false', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { simplify: true, openPR: false } }),+ '/r', null, isTruthyMeta, { isTui: true });+ expect(prompt).toMatch(/`\/do:push`/);+ expect(prompt).not.toMatch(/`\/do:pr`/);+ });++ it('emits a non-TUI "Completion" block (no slashdo) for CLI agents', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta,+ { isTui: false });+ expect(prompt).toMatch(/^## Completion$/m);+ expect(prompt).not.toMatch(/`\/do:pr`/);+ expect(prompt).not.toMatch(/`\/quit`/);+ expect(prompt).toMatch(/PortOS will push and open the PR/);+ });++ it('suppresses the completion block and warns when readOnly is set', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { readOnly: true } }),+ '/r', null, isTruthyMeta, { isTui: true });+ expect(prompt).toMatch(/Read-Only Task/);+ expect(prompt).not.toMatch(/## Completion Workflow/);+ });++ it('renders the review-loop follow-up block when reviewLoopFollowUp is set', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: {+ reviewLoopFollowUp: true,+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',+ reviewLoopPRBranch: 'b',+ reviewLoopPRNumber: 9,+ reviewLoopPROwner: 'o',+ reviewLoopPRRepo: 'r',+ sourceTaskId: 'task-src-1',+ }}),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta);+ expect(prompt).toMatch(/## Review-Loop Follow-up/);+ expect(prompt).toMatch(/task-src-1/);+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9"/);+ expect(prompt).not.toMatch(/## Completion Workflow/);+ });++ it('renders the pipeline block when previousStageAgentId is present', () => {+ const prompt = buildLightContextPrompt(makeTask({+ metadata: { pipeline: {+ previousStageAgentId: 'agent-prev-1',+ currentStage: 1,+ stages: [{ name: 'idea' }, { name: 'prose' }, { name: 'comic' }],+ }}+ }), '/r', null, isTruthyMeta);+ expect(prompt).toMatch(/## Pipeline Context/);+ expect(prompt).toMatch(/Stage 2 of 3: "prose"/);+ expect(prompt).toMatch(/Previous stage: "idea"/);+ expect(prompt).toMatch(/agent-prev-1\/output\.txt/);+ });+ });+});++describe('buildAgentPrompt — provider type routing', () => {+ it('routes TUI provider through the light path (no roleplay preamble)', async () => {+ const prompt = await buildAgentPrompt(+ makeTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'tui', tui: true, skipClaudeMd: true });+ expect(prompt).not.toMatch(/Chief of Staff Agent Briefing/);+ expect(prompt).not.toMatch(/You are an autonomous agent/);+ expect(prompt).toMatch(/^## Task$/m);+ });++ it('routes CLI provider through the light path too', async () => {+ const prompt = await buildAgentPrompt(+ makeTask(), {}, '/r', null, isTruthyMeta,+ { providerType: 'cli', tui: false });+ expect(prompt).not.toMatch(/Chief of Staff Agent Briefing/);+ expect(prompt).not.toMatch(/You are an autonomous agent/);+ // Light + non-TUI uses the plain "## Completion" block.+ expect(prompt).toMatch(/^## Completion$/m);+ });+});