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

fix: harden scheduled task data preloads

[._.]/ Adam Eivy3d3485d45c80
diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.js
index abee650968..35d7ea98f7 100644
--- a/server/routes/cosJobRoutes.js
+++ b/server/routes/cosJobRoutes.js
@@ -207,6 +207,7 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {
provider: task.metadata?.provider,
model: task.metadata?.model,
effort: task.metadata?.effort,
+ prompt: task.metadata?.prompt,
// Preserve the markers consumed by the job:spawned listener so Run now
// records the execution and re-registers the saved schedule.
autonomousJob: task.metadata?.autonomousJob,
diff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.js
index 0da5d9544e..bea07bf693 100644
--- a/server/routes/cosJobRoutes.test.js
+++ b/server/routes/cosJobRoutes.test.js
@@ -503,7 +503,8 @@ describe('CoS Job Routes', () => {
simplify: false,
provider: 'anthropic',
model: 'claude-opus-4-8',
- effort: 'high'
+ effort: 'high',
+ prompt: 'Review\n\n## Preloaded task data\nSnapshot'
}
});
cos.addTask.mockResolvedValue({ id: 'task-2' });
@@ -521,6 +522,7 @@ describe('CoS Job Routes', () => {
provider: 'anthropic',
model: 'claude-opus-4-8',
effort: 'high',
+ prompt: 'Review\n\n## Preloaded task data\nSnapshot',
autonomousJob: true,
jobId: 'j1'
}),
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index e9150286e2..f81cf1ef68 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -194,6 +194,16 @@ describe('autonomousJobs', () => {
})
expect(task.id).toContain(job.id)
expect(task.description).toBeTruthy()
+ expect(task.metadata.prompt).toBe('Do the test thing')
+ })
+
+ it('stores a multiline generated body in metadata.prompt and keeps the row summary one-line', async () => {
+ const task = await generateTaskFromJob({
+ ...mockJobsData.jobs[0],
+ promptTemplate: 'Review the app\n\n## Context\nUse the configured inputs.',
+ })
+ expect(task.description).toBe('Review the app')
+ expect(task.metadata.prompt).toBe('Review the app\n\n## Context\nUse the configured inputs.')
})
it('autoApprove true when autonomyLevel is yolo', async () => {
diff --git a/server/services/autonomousJobs/skillTemplates.js b/server/services/autonomousJobs/skillTemplates.js
index 865d4834b6..5e0f0fef53 100644
--- a/server/services/autonomousJobs/skillTemplates.js
+++ b/server/services/autonomousJobs/skillTemplates.js
@@ -152,7 +152,8 @@ async function generateTaskFromJob(job) {
const inputs = selectedInputs.length > 0
? await resolveTaskDataInputs(selectedInputs, { app })
: []
- const description = appendTaskDataInputs(prompt, inputs)
+ const taskPrompt = appendTaskDataInputs(prompt, inputs)
+ const description = taskPrompt.split('\n').map(line => line.trim()).find(Boolean) || job.name
const meta = job.taskMetadata || {}
return {
id: `${job.id}-${Date.now().toString(36)}`,
@@ -164,6 +165,7 @@ async function generateTaskFromJob(job) {
jobName: job.name,
jobCategory: job.category,
autonomyLevel: job.autonomyLevel,
+ prompt: taskPrompt,
// App-scoped jobs carry the target app id so prepareAgentWorkspace resolves
// the agent's workspace to the app's repoPath. Absent = runs in PortOS root.
...(job.appId != null ? { app: job.appId } : {}),
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 16b54d0bbc..95da1de1e9 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -23,6 +23,7 @@ import { readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, resolveClaimReviewerConfig, reviewerConfigMetadata, SWARM_COUNT_MIN, ISSUE_AUTHOR_FILTERS } from '../lib/validation.js';
+import { PATHS } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';
import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunning } from './cosState.js';
@@ -1851,6 +1852,11 @@ export async function generateSelfImprovementTaskForType(taskType, state) {
+ buildLocalReviewerInstructions(reviewers.reviewers, reviewers.reviewerModels, reviewers.reviewerEfforts);
}
+ const taskDataInputs = await resolveTaskDataInputs(interval.dataInputs, {
+ app: { id: null, name: 'PortOS', repoPath: PATHS.root }
+ });
+ description = appendTaskDataInputs(description, taskDataInputs);
+
const task = {
id: `self-improve-${taskType}-${Date.now().toString(36)}`,
status: 'pending',
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 9a09b6a278..fbc5bff4cb 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -233,6 +233,13 @@ describe('isConfiguredApprovalRequired', () => {
expect(GEN_SRC.slice(appStart, appStart + 11000)).toContain('stampApprovalReason(metadata, approval)');
});
+ it('the PortOS self-improvement lane resolves and appends configured data inputs', () => {
+ const selfStart = GEN_SRC.indexOf('export async function generateSelfImprovementTaskForType');
+ const selfBody = GEN_SRC.slice(selfStart, selfStart + 9000);
+ expect(selfBody).toContain('resolveTaskDataInputs(interval.dataInputs');
+ expect(selfBody).toContain('appendTaskDataInputs(description, taskDataInputs)');
+ });
+
it('resolveConfidenceApproval consults the toggle before safety-kind and confidence', () => {
const start = GEN_SRC.indexOf('async function resolveConfidenceApproval');
expect(start).toBeGreaterThan(-1);
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 3333ef37b6..dcbda6e9ad 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -570,6 +570,21 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
// inference. See `server/lib/cosTaskPrompt.js` for the full contract.
const splitMetadata = splitTaskPromptFields(newTask.metadata);
if (splitMetadata !== newTask.metadata) newTask = { ...newTask, metadata: splitMetadata };
+ // Markdown task rows are one-line records. Preserve every generated prompt
+ // in the newline-safe metadata field before persistence, including raw
+ // on-demand tasks that bypass the queue generator's normalization pass.
+ if (typeof newTask.description === 'string' && newTask.description.includes('\n')) {
+ newTask = {
+ ...newTask,
+ description: firstLine(newTask.description),
+ metadata: {
+ ...(newTask.metadata || {}),
+ prompt: typeof newTask.metadata?.prompt === 'string'
+ ? newTask.metadata.prompt
+ : newTask.description,
+ },
+ };
+ }
// Add task to top or bottom based on position parameter
if (taskData.position === 'top') {
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index c223d93868..c9fe91deda 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -385,6 +385,38 @@ describe('cosTaskStore.addTask', () => {
expect(reloaded.metadata.context).toBeUndefined();
});
+ it('moves a raw multiline description into metadata.prompt before markdown persistence', async () => {
+ const fullPrompt = 'Scheduled review\n\n## Preloaded task data\nCurrent snapshot.';
+ const created = await addTask({
+ id: 'sys-scheduled-prompt',
+ status: 'pending',
+ priority: 'MEDIUM',
+ priorityValue: 2,
+ description: fullPrompt,
+ metadata: { autonomousJob: true, jobId: 'job-example' },
+ section: 'pending',
+ }, 'internal', { raw: true });
+ expect(created.description).toBe('Scheduled review');
+ expect(created.metadata.prompt).toBe(fullPrompt);
+ const reloaded = await getTaskById('sys-scheduled-prompt');
+ expect(reloaded.description).toBe('Scheduled review');
+ expect(reloaded.metadata.prompt).toBe(fullPrompt);
+ });
+
+ it('preserves an explicitly empty prompt while normalizing a multiline raw description', async () => {
+ const created = await addTask({
+ id: 'sys-cleared-scheduled-prompt',
+ status: 'pending',
+ priority: 'MEDIUM',
+ priorityValue: 2,
+ description: 'Scheduled review\n\nFallback body',
+ metadata: { prompt: '' },
+ section: 'pending',
+ }, 'internal', { raw: true });
+ expect(created.description).toBe('Scheduled review');
+ expect(created.metadata).toHaveProperty('prompt', '');
+ });
+
it('leaves a one-line human note on metadata.context', async () => {
const created = await addTask({ description: 'job', id: 'task-note', context: 'Manually triggered job: nightly' }, 'user');
expect(created.metadata.context).toBe('Manually triggered job: nightly');
@@ -871,11 +903,11 @@ describe('cosTaskStore.addTask', () => {
expect(task.metadata.worktreeChangesExpected).toBeUndefined();
});
- it('raw=true stores the pre-built object verbatim', async () => {
- const raw = { id: 'sys-raw', description: 'raw\nmultiline', status: 'pending', metadata: { context: 'ctx' } };
+ it('raw=true stores a pre-built one-line object verbatim', async () => {
+ const raw = { id: 'sys-raw', description: 'raw task', status: 'pending', metadata: { context: 'ctx' } };
const task = await addTask(raw, 'internal', { raw: true });
expect(task).toBe(raw);
- expect(task.description).toBe('raw\nmultiline');
+ expect(task.description).toBe('raw task');
});
it('position:top unshifts the task to the front', async () => {
diff --git a/server/services/taskDataInputs.js b/server/services/taskDataInputs.js
index 9c9d344416..7f051e0804 100644
--- a/server/services/taskDataInputs.js
+++ b/server/services/taskDataInputs.js
@@ -10,16 +10,20 @@ import { readdir } from 'fs/promises';
import { join, relative } from 'path';
import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { TASK_DATA_INPUT_DEFINITIONS } from '../lib/taskDataInputCatalog.js';
-import { withGlabJson } from '../lib/glabArgs.js';
-import { resolveForgeForRepo } from './git.js';
-import { runCli } from './layeredIntelligence/runCli.js';
+import { githubApiHost, resolveAppWorkTracker } from '../lib/workTracker.js';
+import { resolveForgeTokenEnv } from './git.js';
+import { execGh } from './github.js';
+import { execGlabJson } from './gitlab.js';
const MAX_DOCUMENT_FILES = 3;
const MAX_DOCUMENT_CHARS = 8_000;
const MAX_LIST_ITEMS = 50;
const MAX_INPUT_CHARS = 12_000;
const MAX_TOTAL_CHARS = 40_000;
+const FORGE_TIMEOUT_MS = 30_000;
+const TOKEN_TIMEOUT_MS = 10_000;
const SEARCH_MAX_DEPTH = 4;
+const TRUNCATION_NOTICE = '\n\n[Preload truncated. Read this source directly if the omitted detail is needed.]';
const SKIP_DIRECTORIES = new Set([
'.git', '.idea', '.next', '.turbo', '.venv', '.vscode',
'build', 'coverage', 'dist', 'node_modules', 'vendor', 'data'
@@ -51,9 +55,11 @@ async function findNamedFiles(root, filename, {
const path = join(directory, entry.name);
if (entry.isFile() && entry.name.toLowerCase() === target) {
const content = await readFile(path);
- if (typeof content === 'string') {
- matches.push({ path: relative(root, path) || entry.name, content: content.slice(0, MAX_DOCUMENT_CHARS) });
- }
+ matches.push({
+ path: relative(root, path) || entry.name,
+ content: typeof content === 'string' ? content : null,
+ unreadable: typeof content !== 'string',
+ });
} else if (entry.isDirectory() && !SKIP_DIRECTORIES.has(entry.name)) {
await walk(path, depth + 1);
}
@@ -64,9 +70,21 @@ async function findNamedFiles(root, filename, {
return matches;
}
+function truncateWithNotice(value, maxChars) {
+ if (value.length <= maxChars) return value;
+ const keep = Math.max(0, maxChars - TRUNCATION_NOTICE.length);
+ return `${value.slice(0, keep)}${TRUNCATION_NOTICE}`;
+}
+
export function renderRepositoryDocuments(filename, documents) {
if (!documents.length) return `No ${filename} file was found within the repository search boundary.`;
- return documents.map(({ path, content }) => `#### ${path}\n\n${content}`).join('\n\n').slice(0, MAX_INPUT_CHARS);
+ const rendered = documents.map(({ path, content, unreadable }) => {
+ const body = unreadable
+ ? 'This file was found but could not be preloaded (source read failed). Read it directly before relying on this section.'
+ : truncateWithNotice(content, MAX_DOCUMENT_CHARS);
+ return `#### ${path}\n\n${body}`;
+ }).join('\n\n');
+ return truncateWithNotice(rendered, MAX_INPUT_CHARS);
}
function normalizeLabels(labels) {
@@ -91,19 +109,31 @@ export function renderForgeItems(items, { emptyMessage }) {
const url = item.url || item.web_url;
return `- ${ref}${String(item.title || '').trim()}${details ? ` (${details})` : ''}${url ? ` — ${url}` : ''}`;
});
- if (items.length > shown.length) lines.push(`- ${items.length - shown.length} additional item(s) omitted.`);
- return lines.join('\n').slice(0, MAX_INPUT_CHARS);
+ if (items.length > shown.length) lines.push(`- ${items.length - shown.length} additional item(s) omitted; query the forge if they are needed.`);
+ return truncateWithNotice(lines.join('\n'), MAX_INPUT_CHARS);
}
-export async function listForgeOpenIssues({ cli, cwd, env, exec = runCli } = {}) {
+async function runForgeCli(cli, args, { cwd, env } = {}) {
+ if (cli === 'gh') {
+ const stdout = await execGh(args, FORGE_TIMEOUT_MS, { cwd, env }).catch(() => null);
+ return stdout === null ? { code: -1, stdout: '' } : { code: 0, stdout };
+ }
+ if (cli === 'glab') {
+ const { rows } = await execGlabJson(args, cwd, FORGE_TIMEOUT_MS);
+ return rows === null ? { code: -1, stdout: '' } : { code: 0, stdout: JSON.stringify(rows) };
+ }
+ return { code: -1, stdout: '' };
+}
+
+export async function listForgeOpenIssues({ cli, cwd, env, exec = runForgeCli } = {}) {
if (!cwd || (cli !== 'gh' && cli !== 'glab')) return { ok: false, issues: [] };
const args = cli === 'glab'
- ? withGlabJson(['issue', 'list', '-P', '100'])
+ ? ['issue', 'list', '-P', '100']
: ['issue', 'list', '--state', 'open', '--limit', '100', '--json', 'number,title,state,url,labels'];
const result = await exec(cli, args, { cwd, env });
- if (result.code !== 0) return { ok: false, issues: [] };
+ if (result.code !== 0 || !result.stdout.trim()) return { ok: false, issues: [] };
const parsed = safeJSONParse(result.stdout, null, { logError: false });
- if (!Array.isArray(parsed)) return result.stdout.trim() ? { ok: false, issues: [] } : { ok: true, issues: [] };
+ if (!Array.isArray(parsed)) return { ok: false, issues: [] };
return {
ok: true,
issues: parsed
@@ -118,11 +148,11 @@ export async function listForgeOpenIssues({ cli, cwd, env, exec = runCli } = {})
};
}
-export async function listForgePullRequests({ cli, cwd, env, state = 'open', exec = runCli } = {}) {
+export async function listForgePullRequests({ cli, cwd, env, state = 'open', exec = runForgeCli } = {}) {
if (!cwd || (cli !== 'gh' && cli !== 'glab')) return { ok: false, items: [] };
const closed = state === 'closed-unmerged';
const args = cli === 'glab'
- ? withGlabJson(['mr', 'list', closed ? '--closed' : '--opened', '-P', closed ? '20' : '100'])
+ ? ['mr', 'list', closed ? '--closed' : '--opened', '-P', closed ? '20' : '100']
: [
'pr', 'list', '--state', closed ? 'closed' : 'open',
...(closed ? ['--search', 'is:unmerged'] : []),
@@ -130,9 +160,9 @@ export async function listForgePullRequests({ cli, cwd, env, state = 'open', exe
'--json', 'number,title,author,url,isDraft,headRefName,baseRefName,labels,closedAt'
];
const result = await exec(cli, args, { cwd, env });
- if (result.code !== 0) return { ok: false, items: [] };
+ if (result.code !== 0 || !result.stdout.trim()) return { ok: false, items: [] };
const parsed = safeJSONParse(result.stdout, null, { logError: false });
- if (!Array.isArray(parsed)) return result.stdout.trim() ? { ok: false, items: [] } : { ok: true, items: [] };
+ if (!Array.isArray(parsed)) return { ok: false, items: [] };
// GitLab's --closed excludes merged MRs on current glab versions. Keep the
// explicit filter as a compatibility guard if a version returns both.
const items = closed
@@ -145,10 +175,23 @@ function unavailableMessage(label, reason = 'source read failed') {
return `${label} could not be preloaded (${reason}). Do not interpret this as an empty source.`;
}
-async function resolveForgeContext(app, resolveForge) {
+async function resolveForgeContext(app, deps) {
if (!app?.repoPath) return null;
- const forge = await resolveForge(app.repoPath);
- return forge?.cli === 'gh' || forge?.cli === 'glab' ? forge : null;
+ const tracker = await deps.resolveTracker(app);
+ if (tracker?.forge !== 'gh' && tracker?.forge !== 'glab') return null;
+
+ const env = { ...deps.environment };
+ if (tracker.forge === 'gh') {
+ // A github.com token must never be forwarded to an arbitrary GHES host.
+ // Enterprise hosts use gh's host-scoped credential store instead.
+ if (githubApiHost(tracker.host) === 'github.com') {
+ Object.assign(env, await deps.resolveTokenEnv(app.repoPath, { timeoutMs: TOKEN_TIMEOUT_MS }));
+ } else {
+ delete env.GH_TOKEN;
+ delete env.GITHUB_TOKEN;
+ }
+ }
+ return { cli: tracker.forge, env, host: tracker.host };
}
const INPUT_LOADERS = {
@@ -188,14 +231,16 @@ export async function resolveTaskDataInputs(inputIds, { app, dependencies = {} }
const definitions = new Map(TASK_DATA_INPUT_DEFINITIONS.map((definition) => [definition.id, definition]));
const deps = {
findFiles: findNamedFiles,
- resolveForge: resolveForgeForRepo,
+ resolveTracker: resolveAppWorkTracker,
+ resolveTokenEnv: resolveForgeTokenEnv,
listIssues: listForgeOpenIssues,
listPullRequests: listForgePullRequests,
+ environment: process.env,
...dependencies,
};
const needsForge = selected.some((id) => id.includes('issues') || id.includes('pull-requests'));
const forge = needsForge
- ? await resolveForgeContext(app, deps.resolveForge).catch(() => null)
+ ? await resolveForgeContext(app, deps).catch(() => null)
: null;
const sections = await Promise.all(selected.map(async (id) => {
@@ -210,9 +255,11 @@ export async function resolveTaskDataInputs(inputIds, { app, dependencies = {} }
export function appendTaskDataInputs(prompt, sections) {
if (!Array.isArray(sections) || sections.length === 0) return prompt;
+ const headingChars = sections.reduce((total, { label }) => total + `### ${label}\n\n`.length, 0);
+ const separatorChars = Math.max(0, sections.length - 1) * 2;
+ const perSectionChars = Math.max(256, Math.floor((MAX_TOTAL_CHARS - headingChars - separatorChars) / sections.length));
const rendered = sections
- .map(({ label, content }) => `### ${label}\n\n${content}`)
- .join('\n\n')
- .slice(0, MAX_TOTAL_CHARS);
- return `${prompt}\n\n---\n\n## Preloaded task data\n\nPortOS collected these configured inputs immediately before this task was queued. Treat them as the current snapshot; do not spend tools or tokens fetching the same data again unless a section says it could not be preloaded or the task requires deeper detail.\n\n${rendered}`;
+ .map(({ label, content }) => `### ${label}\n\n${truncateWithNotice(content, perSectionChars)}`)
+ .join('\n\n');
+ return `${prompt}\n\n---\n\n## Preloaded task data\n\nPortOS collected these configured inputs immediately before this task was queued. Treat them as the current snapshot; do not spend tools or tokens fetching the same data again unless a section says it could not be preloaded, was truncated, or the task requires deeper detail.\n\n${rendered}`;
}
diff --git a/server/services/taskDataInputs.test.js b/server/services/taskDataInputs.test.js
index 29e2170e00..b4fdd2548e 100644
--- a/server/services/taskDataInputs.test.js
+++ b/server/services/taskDataInputs.test.js
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import {
appendTaskDataInputs,
+ listForgeOpenIssues,
listForgePullRequests,
renderForgeItems,
resolveTaskDataInputs,
@@ -21,7 +22,8 @@ describe('taskDataInputs', () => {
});
it('resolves selected sources in configured order and reuses one forge resolution', async () => {
- const resolveForge = vi.fn().mockResolvedValue({ cli: 'gh', env: { GH_TOKEN: 'test-token' } });
+ const resolveTracker = vi.fn().mockResolvedValue({ forge: 'gh', host: 'github.com' });
+ const resolveTokenEnv = vi.fn().mockResolvedValue({ GH_TOKEN: 'test-token' });
const findFiles = vi.fn(async (_root, filename) => [{ path: filename, content: `${filename} body` }]);
const listIssues = vi.fn().mockResolvedValue({
ok: true,
@@ -34,21 +36,25 @@ describe('taskDataInputs', () => {
const sections = await resolveTaskDataInputs([
'project-goals', 'open-issues', 'open-pull-requests', 'project-goals'
- ], { app: APP, dependencies: { resolveForge, findFiles, listIssues, listPullRequests } });
+ ], { app: APP, dependencies: { resolveTracker, resolveTokenEnv, findFiles, listIssues, listPullRequests } });
expect(sections.map(({ id }) => id)).toEqual(['project-goals', 'open-issues', 'open-pull-requests']);
expect(sections[0].content).toContain('GOALS.md body');
expect(sections[1].content).toContain('#4 Open work');
expect(sections[2].content).toContain('#8 Current change');
- expect(resolveForge).toHaveBeenCalledTimes(1);
- expect(listIssues).toHaveBeenCalledWith(expect.objectContaining({ cli: 'gh', cwd: '/repo' }));
+ expect(resolveTracker).toHaveBeenCalledTimes(1);
+ expect(resolveTokenEnv).toHaveBeenCalledTimes(1);
+ expect(listIssues).toHaveBeenCalledWith(expect.objectContaining({
+ cli: 'gh', cwd: '/repo', env: expect.objectContaining({ GH_TOKEN: 'test-token' })
+ }));
});
it('preserves failed versus legitimately empty tracker reads', async () => {
const common = {
app: APP,
dependencies: {
- resolveForge: vi.fn().mockResolvedValue({ cli: 'gh', env: {} }),
+ resolveTracker: vi.fn().mockResolvedValue({ forge: 'gh', host: 'github.com' }),
+ resolveTokenEnv: vi.fn().mockResolvedValue({}),
listIssues: vi.fn().mockResolvedValue({ ok: false, issues: [] }),
},
};
@@ -61,6 +67,51 @@ describe('taskDataInputs', () => {
expect(empty[0].content).toBe('No open issues.');
});
+ it('reports a discovered document that could not be read', async () => {
+ const sections = await resolveTaskDataInputs(['project-goals'], {
+ app: APP,
+ dependencies: {
+ findFiles: vi.fn().mockResolvedValue([
+ { path: 'GOALS.md', content: null, unreadable: true },
+ ]),
+ },
+ });
+ expect(sections[0].content).toContain('GOALS.md');
+ expect(sections[0].content).toContain('could not be preloaded');
+ expect(sections[0].content).toContain('Read it directly');
+ });
+
+ it('respects the resolved app tracker and never forwards ambient GitHub tokens to GHES', async () => {
+ const listIssues = vi.fn().mockResolvedValue({ ok: true, issues: [] });
+ const resolveTokenEnv = vi.fn();
+ await resolveTaskDataInputs(['open-issues'], {
+ app: { ...APP, workTracker: 'github' },
+ dependencies: {
+ resolveTracker: vi.fn().mockResolvedValue({ forge: 'gh', host: 'github.example.com' }),
+ resolveTokenEnv,
+ listIssues,
+ environment: { GH_TOKEN: 'ambient', GITHUB_TOKEN: 'ambient-again', PATH: '/bin' },
+ },
+ });
+ expect(resolveTokenEnv).not.toHaveBeenCalled();
+ expect(listIssues).toHaveBeenCalledWith(expect.objectContaining({
+ cli: 'gh',
+ env: { PATH: '/bin' },
+ }));
+ });
+
+ it('uses an explicitly resolved GitLab tracker even on an ambiguous host', async () => {
+ const listIssues = vi.fn().mockResolvedValue({ ok: true, issues: [] });
+ await resolveTaskDataInputs(['open-issues'], {
+ app: { ...APP, workTracker: 'gitlab' },
+ dependencies: {
+ resolveTracker: vi.fn().mockResolvedValue({ forge: 'glab', host: 'scm.example.com' }),
+ listIssues,
+ },
+ });
+ expect(listIssues).toHaveBeenCalledWith(expect.objectContaining({ cli: 'glab' }));
+ });
+
it('appends one bounded prompt section with a no-refetch instruction', () => {
const prompt = appendTaskDataInputs('Do the task.', [
{ id: 'project-goals', label: 'Project goals', content: 'Ship useful work.' },
@@ -71,6 +122,18 @@ describe('taskDataInputs', () => {
expect(prompt).toContain('### Project goals');
});
+ it('keeps every selected heading and marks each bounded truncation', () => {
+ const prompt = appendTaskDataInputs('Do the task.', Array.from({ length: 5 }, (_, index) => ({
+ id: `input-${index}`,
+ label: `Input ${index}`,
+ content: 'x'.repeat(20_000),
+ })));
+ for (let index = 0; index < 5; index += 1) {
+ expect(prompt).toContain(`### Input ${index}`);
+ }
+ expect(prompt).toContain('[Preload truncated.');
+ });
+
it('renders forge metadata without serializing label objects', () => {
const rendered = renderForgeItems([{
number: 2,
@@ -93,4 +156,12 @@ describe('taskDataInputs', () => {
'--state', 'closed', '--search', 'is:unmerged'
]), expect.objectContaining({ cwd: '/repo' }));
});
+
+ it('does not treat blank forge output as a legitimately empty list', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: ' ', stderr: '' });
+ await expect(listForgeOpenIssues({ cli: 'gh', cwd: '/repo', exec }))
+ .resolves.toEqual({ ok: false, issues: [] });
+ await expect(listForgePullRequests({ cli: 'gh', cwd: '/repo', exec }))
+ .resolves.toEqual({ ok: false, items: [] });
+ });
});
diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.js
index 7ca72701c8..17cb9ccbab 100644
--- a/server/services/taskPromptDefaults.test.js
+++ b/server/services/taskPromptDefaults.test.js
@@ -150,13 +150,14 @@ describe('taskPromptDefaults integrity snapshot', () => {
expect(v9).not.toBe(current);
});
- // plan-feature v3: reusable scheduled-task inputs replace redundant agent
- // discovery calls while the v2 product-intent hierarchy remains intact.
- it('plan-feature v3 consumes preloaded task data and preserves v2 and v1', () => {
+ // plan-feature v4: bounded preloads now name their direct-read recovery path
+ // while v3 through v1 remain recognizable for cross-install upgrades.
+ it('plan-feature v4 permits recovery from bounded preloads and preserves prior defaults', () => {
const current = DEFAULT_TASK_PROMPTS['plan-feature'];
- expect(PROMPT_VERSIONS['plan-feature']).toBe(3);
+ expect(PROMPT_VERSIONS['plan-feature']).toBe(4);
expect(current).toContain('Preloaded task data');
expect(current).toContain('do NOT list them again');
+ expect(current).toContain('marked unavailable, unreadable, or');
expect(current).toContain('Closed unmerged pull requests');
expect(current).toContain('PRD.md');
expect(current).toContain('GOALS.md');
@@ -166,6 +167,11 @@ describe('taskPromptDefaults integrity snapshot', () => {
expect(current).not.toContain('REJECTED.md');
expect(current).not.toContain('ALSO read PLAN.md');
+ const v3 = PREVIOUS_DEFAULT_PROMPTS['plan-feature'].find((prompt) => prompt.includes('Preloaded task data'));
+ expect(v3).toBeDefined();
+ expect(v3).not.toContain('marked unavailable, unreadable, or');
+ expect(v3).not.toBe(current);
+
const v2 = PREVIOUS_DEFAULT_PROMPTS['plan-feature'].find((prompt) => prompt.includes('specific available source of intent'));
expect(v2).toBeDefined();
expect(v2).not.toContain('Preloaded task data');
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index 98499daf12..85e898a5d4 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -14,7 +14,7 @@
"data-safety": "86b07f51abdbcbe7016f840b5bb0cd9b",
"simplify": "2a048214d1dd3b75bee9ae1a38fa1589",
"feature-ideas": "d3282f16da29efe2d53595b3b34778bc",
- "plan-feature": "a707866783fd0d8c1037489f23ff66de",
+ "plan-feature": "9fbc2a2ded8f4533d1f0f6b9cb780b34",
"plan-task": "b85fe92999aa4ee4a8910320457c4242",
"claim-issue": "9bf278ab141120625cd6faf854622f91",
"claim-issue-gitlab": "745672581d766edff0ec585dd5b1ef5d",
@@ -54,7 +54,7 @@
"branch-reconcile": 3,
"issue-reconcile": 4,
"refresh-local-llm-catalog": 4,
- "plan-feature": 3,
+ "plan-feature": 4,
"security": 2,
"code-quality": 2,
"test-coverage": 2,
@@ -232,6 +232,7 @@
"ca7324a0f2251a66b46ea534940c9da8"
],
"plan-feature": [
+ "a707866783fd0d8c1037489f23ff66de",
"b20980c8eda2256060d09d4bca397244",
"3df6f0a46f2a524af1dc4f83dfdf0647"
],
diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.js
index 88cdfa55d5..cf9ff65070 100644
--- a/server/services/taskPromptDefaults/previousDefaults.js
+++ b/server/services/taskPromptDefaults/previousDefaults.js
@@ -10965,6 +10965,115 @@ Default branch: {defaultBranch}
were added, updated, or removed and the sources you verified them against.`,
],
'plan-feature': [
+ // v3 default prompt — scheduled inputs are preloaded, but truncated and
+ // unreadable sections did not yet tell the agent to read the source.
+ `[Improvement: {appName}] Feature Planning — brainstorm one feature and file its plan
+
+You are the planning-only sibling of the \`feature-ideas\` task. Your job is to
+research {appName}, pick ONE feature worth building, and file a decision-complete
+plan for it into the app's task tracker. You do NOT implement anything.
+
+**Read-only on source.** You do NOT edit application code, and you do NOT create
+branches or PRs. Your deliverable is ONE tracker item (described under "Where to
+record the plan" below) carrying a plan another agent — or a human — can pick up
+and execute cold. The plan is the product.
+
+Repository: {repoPath}
+
+## Where to record the plan
+
+{trackerInstructions}
+
+## What to do
+
+1. **Inventory so you don't duplicate.** Start with the **Preloaded task data**
+ appended below. Its Open issues and Open pull requests sections are current
+ snapshots collected immediately before dispatch, so do NOT list them again.
+ Follow the "Inventory" step under "Where to record the plan" only when the
+ corresponding preloaded section says it could not be collected or you need
+ a full issue body. Collect every existing \`[plan-feature-…]\` slug, then skim
+ the last 50 \`git log\` entries plus recent \`.changelog/\` files: an idea
+ that is already an open tracker item, in an open PR, or recently shipped work
+ is NOT a candidate.
+
+2. **Build a product brief from the preloaded repository documents.** PortOS
+ searched the repository for PRD.md and GOALS.md immediately before dispatch
+ and appended their contents below. Use the most specific available source of
+ intent, and do NOT search for or re-read those files when their section has
+ content. Make a best effort rather than assuming a missing document means the
+ app has no direction:
+
+ - If the Product requirements section contains a \`PRD.md\`, use it first.
+ Treat its requirements, acceptance
+ criteria, success metrics, constraints, and non-goals as the primary
+ evaluation for what the feature should accomplish.
+ - If the Project goals section contains a \`GOALS.md\`, use it for strategic context and to supplement
+ the PRD. If there is no PRD, use GOALS.md as the primary statement of
+ desired direction.
+ - If neither exists, start with the root \`README.md\`, \`docs/README.md\`
+ (if present), relevant guides, architecture notes, ADRs, design documents,
+ and other product documentation in the repository. In all cases, inspect
+ the relevant documentation for feature-specific context and fill gaps
+ from it. Extract stated users, problems, workflows, constraints, and
+ success signals rather than inventing a product direction.
+ - If PRD.md and GOALS.md conflict, follow the PRD's concrete requirements
+ and success criteria; use GOALS.md as strategic context and call out any
+ material tension in the filed plan.
+ - Read the repository's \`AGENTS.md\` or \`CLAUDE.md\` files as implementation
+ constraints, not as a substitute for product intent. When documentation
+ is sparse, validate the inferred need against the current source, tests,
+ and recent history and name the evidence in the plan.
+ - Use the preloaded Closed unmerged pull requests section — a feature whose
+ PR the user closed WITHOUT merging was rejected; treat those ideas as
+ rejected too. Query the forge only if that section says it was unavailable.
+ - Review the codebase structure and relevant source files so the plan names
+ real files rather than imagined ones.
+
+3. **Identify ONE small, high-impact feature** that:
+
+ - Aligns with PRD.md requirements and success criteria when available;
+ otherwise aligns with GOALS.md or the repository documentation gathered
+ in step 2
+ - Is NOT already shipped, planned, or filed (per step 1)
+ - Does NOT duplicate existing functionality or repeat a closed-unmerged
+ automation PR
+ - Saves user time, improves UX, or makes the app more useful
+ - Is self-contained and completable in one session by the agent that claims it
+
+4. **Write the decision-complete plan.** Every design choice is DECIDED, not
+ raised as a question — make the call and state it. The filed item must carry:
+
+ - **A slug-tagged title.** Lowercase kebab-case starting with
+ \`plan-feature-\`, naming the feature (e.g.
+ \`plan-feature-export-universe-to-markdown\`); ≤80 chars total; unique
+ against every existing \`[plan-feature-…]\` slug (re-check before recording).
+ - **Motivation** — which documented requirement, success criterion, goal, or
+ evidenced user need this serves, 1–2 sentences.
+ - **Approach** — the design you have decided on: the behavior to build, the
+ existing patterns in {appName} it follows, and the concrete files/components
+ it would touch (describe them; do NOT write the code).
+ - **\`Scope: small | medium | large\`** — an honest estimate for one session.
+ - **Acceptance criteria** — checkboxes another agent can verify cold, without
+ asking anyone anything.
+ - **Non-goals** — what this feature deliberately does NOT cover, so the
+ implementing agent doesn't expand scope.
+
+5. **Redact before you publish.** The filed item is world-readable the moment it
+ lands. Never paste a secret, credential, token, hostname, IP address, or
+ absolute path containing a username into the title or body.
+
+6. **Record exactly ONE plan item** using the "Record" mechanics under "Where
+ to record the plan" above. If the feature hinges on a genuine product
+ judgment the user owns (not a design detail you can decide), file it anyway
+ as a **Maybe — needs human call** item with the \`**Decision needed:**\` line
+ the tracker instructions describe — do not skip filing.
+
+7. **Finalize** per the "Finalize" step under "Where to record the plan" above.
+ No source edits, no branches, no PRs.
+
+8. Your final assistant message must be a 2–3 sentence summary of: the feature
+ you planned, where you filed it (item slug / issue number), and the one
+ design call you made that a reviewer is most likely to question.`,
// v2 default prompt — PRD/docs-first research hierarchy; superseded by
// v3's programmatically preloaded scheduled-task data inputs.
`[Improvement: {appName}] Feature Planning — brainstorm one feature and file its plan
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 2fe0690bf7..cf07437734 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -633,8 +633,9 @@ Repository: {repoPath}
searched the repository for PRD.md and GOALS.md immediately before dispatch
and appended their contents below. Use the most specific available source of
intent, and do NOT search for or re-read those files when their section has
- content. Make a best effort rather than assuming a missing document means the
- app has no direction:
+ complete content. If a section is marked unavailable, unreadable, or
+ truncated, read the named source directly before relying on it. Make a best
+ effort rather than assuming a missing document means the app has no direction:
- If the Product requirements section contains a \`PRD.md\`, use it first.
Treat its requirements, acceptance
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index 77b6a9deec..a34cd48bc5 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -23,7 +23,7 @@ export const PROMPT_VERSIONS = {
'branch-reconcile': 3, // v3: SUPERSEDED is a first-class outcome — a branch whose problem the default branch already solved a different way is reported and left untouched, never merged (merging it undoes shipped work). A resolvable conflict is explicitly NOT evidence the work is still wanted, and every branch is rebased + test-verified before it reaches a PR. v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.
'issue-reconcile': 4, // v4: follow-up recipes apply independent slashdo dispatch hints and contributor labels (`good first issue`/`help wanted`, Jira hyphenated equivalents) instead of only `plan`. v3: adds a JIRA arm — status-based zombies (a ticket left In Review with remaining scope + no live claim; JIRA has no `in-progress` label) detected via the PortOS JIRA API and healed through ticket transitions + `POST tickets`, routed in via the app's resolved workTracker ('jira') rather than the git host. v2: forge-aware — the scan + coordinator now cover GitLab (`glab` issues + MRs) as well as GitHub, resolved from the app's origin host; every heal command is shown as gh/glab and the injected header names the forge. v1: per-app coordinator that heals ZOMBIE issues (open + in-progress but their PR merged with no live claim) after the deterministic gh/git scan. Applies the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the claim so the queue re-picks it.
'refresh-local-llm-catalog': 4, // v4: follows the current no-per-branch-changelog contract and relies on a release-note-quality commit subject. v3: catalog maintenance now preserves the primary-lane + cross-lane recommendation taxonomy and reserves featured treatment for a deliberate first choice. v2: PortOS-only task, so it names the retired fragment command directly. v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)
- 'plan-feature': 3, // v3: consumes programmatically preloaded PRD/GOALS/open-issue/open-PR/closed-unmerged-PR snapshots and explicitly avoids re-fetching them. v2: PRD.md is the primary product/evaluation source, GOALS.md supplements or falls back, and repository documentation is the best-effort fallback when neither exists. v1: net-new planning-only sibling of feature-ideas.
+ 'plan-feature': 4, // v4: truncated/unreadable preloads explicitly allow a direct source read. v3: consumes programmatically preloaded PRD/GOALS/open-issue/open-PR/closed-unmerged-PR snapshots and explicitly avoids re-fetching them. v2: PRD.md is the primary product/evaluation source, GOALS.md supplements or falls back, and repository documentation is the best-effort fallback when neither exists. v1: net-new planning-only sibling of feature-ideas.
// Basic self-improvement tasks — versioned so installs created before the
// Jan→Feb 2026 genericization (which still have the app-name-hardcoded "PortOS"