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

prompt: match a re-indented issue-filing embed and reuse the rendered context block

[._.]/ Adam Eivy18795cab2881
diff --git a/scripts/measure-agent-prompt.js b/scripts/measure-agent-prompt.js
index e90161025b..f4870ead73 100644
--- a/scripts/measure-agent-prompt.js
+++ b/scripts/measure-agent-prompt.js
@@ -10,7 +10,7 @@
* 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
+ * --out also write <prefix>.user.md (and .system.md when split)
*
* Runs against the shipped defaults with placeholder app/reviewer values and
* NO database (NODE_ENV=test + MEMORY_BACKEND=file are forced), so the numbers
@@ -25,15 +25,12 @@ 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 [taskType = 'claim-issue', providerType = 'tui'] = args.filter((_, i) => i !== outIndex && i !== outIndex + 1);
-const [{ getTaskPrompt }, { buildImprovementTaskDescription }, { buildAgentPrompt }] = await Promise.all([
- import('../server/services/taskPromptService.js'),
- import('../server/services/cosTaskPreStepBlocks.js'),
- import('../server/services/agentPromptBuilder.js'),
-]);
+const { getTaskPrompt } = await import('../server/services/taskPromptService.js');
+const { buildImprovementTaskDescription } = await import('../server/services/cosTaskPreStepBlocks.js');
+const { buildAgentPrompt } = await import('../server/services/agentPromptBuilder.js');
+const { estimateTokens } = await import('../server/lib/contextBudget.js');
const app = { id: 'example-app', name: 'Example App', repoPath: process.env.REPO || '/repo/example' };
const template = await getTaskPrompt(taskType, { claimFlow: true });
@@ -41,12 +38,10 @@ 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,
+ promptTemplate: template, app, promptTaskType: taskType, metadata,
+ // Every pre-step block renders empty, whatever placeholders the generator grows.
+ blocks: new Proxy({}, { get: () => '' }),
});
const task = { id: 'task-measure', description, metadata, taskType: 'internal' };
const isApi = providerType === 'api';
@@ -58,22 +53,23 @@ const result = await buildAgentPrompt(task, {}, app.repoPath, null, undefined, {
agentId: 'agent-measure',
split: !isApi,
});
-const userPrompt = typeof result === 'string' ? result : result.userPrompt;
-const systemPrompt = typeof result === 'string' ? '' : (result.systemPrompt || '');
+const { userPrompt, systemPrompt = '' } = typeof result === 'string' ? { userPrompt: result } : result;
-// ~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)`);
+ console.log(`--- ${label} (${text.length}B, ~${estimateTokens(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`);
+console.log(`${taskType} via ${providerType}: template=${template.length}B description=${description.length}B total≈${estimateTokens(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`);
+ const written = [`${outPrefix}.user.md`];
+ if (systemPrompt) {
+ writeFileSync(`${outPrefix}.system.md`, systemPrompt);
+ written.push(`${outPrefix}.system.md`);
+ }
+ console.log(`📝 Wrote ${written.join(' and ')}`);
}
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index d19f157918..4d37e8865c 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -129,14 +129,6 @@ function resolveSentinelPath(worktreeInfo, workspaceDir, agentId) {
const PREVIOUS_STAGE_OUTPUT_INLINE_CAP = 12_000;
-/**
- * The task body as the agent reads it — description plus prompt/context block —
- * so a contract section can skip text the task already carries verbatim.
- */
-function renderedTaskText(task) {
- return [task.description, taskContextBlock(task)].filter(Boolean).join('\n');
-}
-
function pipelineContextLines(pipelineCtx) {
if (!pipelineCtx || (!pipelineCtx.previousStageAgentId && !pipelineCtx.previousStageOutput)) return [];
@@ -415,14 +407,6 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// CD plan already receives creative-tool specs via `getToolSpecs()` in its
// own prompt, not this section.
const skipDevContext = isCreativeDirectorTask;
- // Issue filing and planner attribution. Skipped for Creative Director runs
- // alongside the rest of the dev context — a scene evaluation files no issue.
- // The forge is left at the default here rather than probed: this path is
- // API-provider-only, and the two CLIs' `label create` idioms differ only in
- // flag spelling, which the guidance spells out for whichever the agent has.
- const issueFilingSection = skipDevContext
- ? ''
- : buildIssueFilingSection({ providerId, model: providerModel, taskText: renderedTaskText(task) });
// Architect doctrine for an orchestrated run (#5992). '' for every direct-mode
// task, which is the default, so this is inert unless a profile is configured.
const orchestrationSection = buildOrchestrationDoctrineSection(task);
@@ -653,6 +637,14 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
// custom template that wants to address it directly.
const briefingSourceTask = taskVisibleToPipelineReviewer(task);
const contextBlock = taskContextBlock(briefingSourceTask);
+ // Issue filing and planner attribution. Skipped for Creative Director runs
+ // alongside the rest of the dev context — a scene evaluation files no issue.
+ // The forge is left at the default here rather than probed: this path is
+ // API-provider-only, and the two CLIs' `label create` idioms differ only in
+ // flag spelling, which the guidance spells out for whichever the agent has.
+ const issueFilingSection = skipDevContext
+ ? ''
+ : buildIssueFilingSection({ providerId, model: providerModel, taskBody: [task.description, contextBlock] });
const uiAuditRuntimeSection = isUiAuditTask(task) ? UI_AUDIT_RUNTIME_RULE : '';
const briefingTask = contextBlock === (briefingSourceTask.metadata?.[TASK_CONTEXT_KEY] ?? null)
? briefingSourceTask
@@ -1106,7 +1098,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// Unconditional filing rules, with planner attribution when resolvable:
// whether a run ends up filing an issue is not knowable from its metadata,
// and a model cannot name itself.
- const lightFilingSection = buildIssueFilingSection({ providerId, model: providerModel, forgeCli: resolvedForgeCli, taskText: renderedTaskText(task) });
+ const lightFilingSection = buildIssueFilingSection({ providerId, model: providerModel, forgeCli: resolvedForgeCli, taskBody: [task.description, context] });
if (lightFilingSection) contractSections.push(lightFilingSection);
// --- Orchestrated execution ---------------------------------------------
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 159b0ec7a6..f67744b18b 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -4278,33 +4278,38 @@ describe('planner attribution', () => {
});
// The shipped claim-issue / issue-reconcile prompts open with the same
- // contract. Rendering it again as a contract section made every such run
- // read ~3KB twice; the attribution still has to come from PortOS because the
- // task body cannot name the model it was dispatched with.
- it('emits only the planner attribution when the task body already carries the contract verbatim', () => {
- const task = makeTask({
- description: `[Claim Issue] Ship the next issue\n\n${MANDATORY_DISPATCH_HINT_GUIDANCE}\n\n## Phase 1`,
- metadata: { openPR: false },
- });
- const prompt = buildLightContextPrompt(task, '/repo', null, isTruthyMeta,
- { providerId: 'claude-code-tui', providerCommand: 'claude', providerModel: 'claude-opus-5' });
- expect(prompt.split(MANDATORY_DISPATCH_HINT_GUIDANCE).length - 1).toBe(1);
- expect(prompt).not.toContain('## Issue Filing Labels');
- expect(prompt).toMatch(/## Planner Attribution/);
- expect(prompt).toMatch(/--label planner:opus-5/);
- });
-
- it('dedupes the contract on the api path too', async () => {
- const task = makeTask({
- description: `[Claim Issue] Ship the next issue\n\n${MANDATORY_DISPATCH_HINT_GUIDANCE}\n\n## Phase 1`,
- metadata: { openPR: false },
- });
- const prompt = await buildAgentPrompt(task, {}, '/repo', null, isTruthyMeta,
- { providerType: 'api', providerId: 'lmstudio', providerModel: 'claude-opus-5' });
- const text = typeof prompt === 'string' ? prompt : prompt.userPrompt;
- expect(text.split(MANDATORY_DISPATCH_HINT_GUIDANCE).length - 1).toBe(1);
+ // contract, and the tracker-filing prompts carry it re-indented. Rendering it
+ // again as a contract section made every such run read ~3KB twice; the
+ // attribution still has to come from PortOS because the task body cannot
+ // name the model it was dispatched with.
+ const embedsContract = (guidance) => makeTask({
+ description: `[Claim Issue] Ship the next issue\n\n${guidance}\n\n## Phase 1`,
+ metadata: { openPR: false },
+ });
+ const expectDeduped = (text) => {
expect(text).not.toContain('## Issue Filing Labels');
expect(text).toMatch(/--label planner:opus-5/);
+ };
+
+ it.each([
+ ['light', (task) => buildLightContextPrompt(task, '/repo', null, isTruthyMeta,
+ { providerId: 'claude-code-tui', providerCommand: 'claude', providerModel: 'claude-opus-5' })],
+ ['api', async (task) => {
+ const prompt = await buildAgentPrompt(task, {}, '/repo', null, isTruthyMeta,
+ { providerType: 'api', providerId: 'lmstudio', providerModel: 'claude-opus-5' });
+ return typeof prompt === 'string' ? prompt : prompt.userPrompt;
+ }],
+ ])('%s path emits only the planner attribution when the task body already carries the contract', async (_label, render) => {
+ const text = await render(embedsContract(MANDATORY_DISPATCH_HINT_GUIDANCE));
+ expect(text.split(MANDATORY_DISPATCH_HINT_GUIDANCE).length - 1).toBe(1);
+ expectDeduped(text);
+ });
+
+ it('recognizes the contract when a template re-indented it', () => {
+ const indented = MANDATORY_DISPATCH_HINT_GUIDANCE.split('\n').join('\n ');
+ const text = buildLightContextPrompt(embedsContract(indented), '/repo', null, isTruthyMeta,
+ { providerId: 'claude-code-tui', providerCommand: 'claude', providerModel: 'claude-opus-5' });
+ expectDeduped(text);
});
it('keeps the full contract for a task that paraphrased it', () => {
diff --git a/server/services/promptSections/plannerAttribution.js b/server/services/promptSections/plannerAttribution.js
index 88879279b6..60e96ca581 100644
--- a/server/services/promptSections/plannerAttribution.js
+++ b/server/services/promptSections/plannerAttribution.js
@@ -35,23 +35,25 @@ export function buildPlannerAttributionSection({ providerId = null, model = null
return `## Planner Attribution\n\n${guidance}`;
}
+const collapseWhitespace = (text) => String(text || '').replace(/\s+/g, ' ');
+const EMBEDDED_CONTRACT = collapseWhitespace(MANDATORY_DISPATCH_HINT_GUIDANCE);
+
/**
* Runtime contract reaches stored/custom tasks and follow-ups, even without a
- * planner identity.
- *
- * `taskText` is the task body the agent is about to read (description plus
- * context). The shipped claim-issue / issue-reconcile prompts embed the very
- * same contract at their top, so a run built from one of them would otherwise
- * read the ~3KB block twice — once in the task, once here. When the body
- * already carries it verbatim, only the planner attribution (which the task
- * cannot know about itself) is emitted; a customized prompt that dropped or
- * paraphrased the contract still gets the full section.
+ * planner identity. Skipped when the task body already carries the contract
+ * (the shipped claim-issue / issue-reconcile prompts embed it at the top, and
+ * the tracker-filing prompts carry it re-indented inside their tracker block);
+ * the attribution is always emitted because the task cannot name its own model.
+ * Templates keep their embed so the prompt editor shows a complete prompt — the
+ * runtime section defers to it rather than the other way round. Whitespace is
+ * collapsed on both sides so an indented copy still matches; a paraphrase
+ * does not.
*
* @param {object} [options]
- * @param {string} [options.taskText] - rendered task body to dedupe against
+ * @param {string[]} [options.taskBody] - rendered task parts (description, context)
*/
-export function buildIssueFilingSection({ taskText = '', ...options } = {}) {
+export function buildIssueFilingSection({ taskBody = [], ...options } = {}) {
const attribution = buildPlannerAttributionSection(options);
- if (taskText.includes(MANDATORY_DISPATCH_HINT_GUIDANCE)) return attribution;
+ if (taskBody.some((part) => collapseWhitespace(part).includes(EMBEDDED_CONTRACT))) return attribution;
return `## Issue Filing Labels\n\n${MANDATORY_DISPATCH_HINT_GUIDANCE}${attribution ? `\n\n${attribution}` : ''}`;
}