Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

scripts: add measure-agent-prompt to rank a rendered agent prompt's sections by size

[._.]/ Adam Eivy467ffca8f6bf
diff --git a/docs/features/prompt-manager.md b/docs/features/prompt-manager.md
index 84c69c3775..a76ade8306 100644
--- a/docs/features/prompt-manager.md
+++ b/docs/features/prompt-manager.md
@@ -57,6 +57,25 @@ Templates use Mustache-like syntax:
- Live preview with test variables
- Insert variable references
+## Measuring what an agent actually reads
+
+A scheduled task's prompt is assembled in layers — the shipped default, the
+pre-step block substitutions, then the operating contract `buildAgentPrompt`
+adds (worktree, completion workflow, issue-filing labels) — and the layers are
+where duplication hides. Render one end to end and rank its sections by size:
+
+```bash
+npm run measure:agent-prompt -- claim-issue tui # light path: split user/system prompt
+npm run measure:agent-prompt -- claim-issue api # full path: instruction files, memory, tools
+npm run measure:agent-prompt -- plan-task cli --out /tmp/plan # also dump the rendered text
+```
+
+It uses placeholder app/reviewer values and no database, so the numbers are the
+prompt's own cost. Set `REPO=<checkout>` to point the api path's
+instruction-file walk at a real tree. On a Claude Code host the root
+`AGENTS.md` is loaded natively on top of this, so its size is part of every
+run's budget too.
+
## Related Features
- [Chief of Staff](./chief-of-staff.md) - Uses prompts for agent briefings
diff --git a/package.json b/package.json
index c5210d5808..204ece30c1 100644
--- a/package.json
+++ b/package.json
@@ -14,6 +14,7 @@
"dev": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && node scripts/dev-start.js",
"dev:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs",
"eval:agent-context": "node scripts/agent-context-eval.js",
+ "measure:agent-prompt": "node scripts/measure-agent-prompt.js",
"build": "npm run build --prefix client",
"start": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && node scripts/ensure-deps.js && npm run build && node scripts/setup-db.js && node scripts/setup-cert.js && (node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent || echo pm2 delete skipped) && node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs && node ./node_modules/pm2/bin/pm2 save",
"pm2:start": "node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs",
diff --git a/scripts/measure-agent-prompt.js b/scripts/measure-agent-prompt.js
new file mode 100644
index 0000000000..e90161025b
--- /dev/null
+++ b/scripts/measure-agent-prompt.js
@@ -0,0 +1,79 @@
+#!/usr/bin/env node
+/**
+ * Render a scheduled task type's agent prompt end-to-end — shipped prompt
+ * default → pre-step block substitution → `buildAgentPrompt` — and print the
+ * byte size of every `## ` section, so a context audit starts from numbers
+ * instead of guesses about which block is fat.
+ *
+ * node scripts/measure-agent-prompt.js [taskType] [providerType] [--out <prefix>]
+ *
+ * taskType a DEFAULT_TASK_PROMPTS key (default: claim-issue)
+ * providerType tui (light path, split system/user prompt), cli, or api
+ * (full path: instruction files, memory, tools; default: tui)
+ * --out also write <prefix>.user.md / <prefix>.system.md
+ *
+ * Runs against the shipped defaults with placeholder app/reviewer values and
+ * NO database (NODE_ENV=test + MEMORY_BACKEND=file are forced), so the numbers
+ * are the prompt's own cost, not this install's. Set REPO=<path> to point the
+ * api path's instruction-file walk at a real checkout.
+ */
+import { writeFileSync } from 'fs';
+
+process.env.NODE_ENV = 'test';
+process.env.MEMORY_BACKEND ||= 'file';
+
+const args = process.argv.slice(2);
+const outIndex = args.indexOf('--out');
+const outPrefix = outIndex === -1 ? null : args[outIndex + 1];
+const positional = outIndex === -1 ? args : args.filter((_, i) => i !== outIndex && i !== outIndex + 1);
+const taskType = positional[0] || 'claim-issue';
+const providerType = positional[1] || 'tui';
+
+const [{ getTaskPrompt }, { buildImprovementTaskDescription }, { buildAgentPrompt }] = await Promise.all([
+ import('../server/services/taskPromptService.js'),
+ import('../server/services/cosTaskPreStepBlocks.js'),
+ import('../server/services/agentPromptBuilder.js'),
+]);
+
+const app = { id: 'example-app', name: 'Example App', repoPath: process.env.REPO || '/repo/example' };
+const template = await getTaskPrompt(taskType, { claimFlow: true });
+const metadata = {
+ app: app.id, appName: app.name, repoPath: app.repoPath, analysisType: taskType,
+ autoGenerated: true, claimFlow: true, reviewers: ['antigravity', 'ollama'], useWorktree: false, openPR: false,
+};
+const emptyBlocks = Object.fromEntries([
+ 'referenceData', 'trackerInstructions', 'modeInstructions', 'prData', 'inFlightBranches',
+ 'zombieIssues', 'repoSyncReport', 'repoFullName', 'defaultBranch', 'planConstraint',
+].map((key) => [key, '']));
+const description = await buildImprovementTaskDescription({
+ promptTemplate: template, app, promptTaskType: taskType, metadata, blocks: emptyBlocks,
+});
+const task = { id: 'task-measure', description, metadata, taskType: 'internal' };
+const isApi = providerType === 'api';
+const result = await buildAgentPrompt(task, {}, app.repoPath, null, undefined, {
+ providerType,
+ providerId: isApi ? 'example-api' : 'claude-code',
+ providerCommand: isApi ? null : 'claude',
+ providerModel: 'example-model',
+ agentId: 'agent-measure',
+ split: !isApi,
+});
+const userPrompt = typeof result === 'string' ? result : result.userPrompt;
+const systemPrompt = typeof result === 'string' ? '' : (result.systemPrompt || '');
+
+// ~4 chars/token is close enough to rank sections; it is not a tokenizer.
+const tokens = (text) => Math.round(text.length / 4);
+const sections = (text) => text.split(/\n(?=## )/).map((s) => [s.split('\n')[0].slice(0, 72), s.length]);
+const printSections = (label, text) => {
+ console.log(`--- ${label} (${text.length}B, ~${tokens(text)} tok)`);
+ for (const [heading, size] of sections(text)) console.log(`${String(size).padStart(7)} ${heading}`);
+};
+
+console.log(`${taskType} via ${providerType}: template=${template.length}B description=${description.length}B total≈${tokens(userPrompt + systemPrompt)} tok`);
+printSections('user prompt', userPrompt);
+if (systemPrompt) printSections('system prompt', systemPrompt);
+if (outPrefix) {
+ writeFileSync(`${outPrefix}.user.md`, userPrompt);
+ writeFileSync(`${outPrefix}.system.md`, systemPrompt);
+ console.log(`📝 Wrote ${outPrefix}.user.md and ${outPrefix}.system.md`);
+}