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: preload configurable data for scheduled agents
[._.]/ Adam Eivyd808f6f14ac3
diff --git a/client/src/components/apps/tabs/CustomTasksSection.jsx b/client/src/components/apps/tabs/CustomTasksSection.jsxindex a378599ede..519d9f9733 100644--- a/client/src/components/apps/tabs/CustomTasksSection.jsx+++ b/client/src/components/apps/tabs/CustomTasksSection.jsx@@ -8,6 +8,7 @@ import { parseCronToRecurrence, buildCronFromRecurrence } from '../../../utils/cimport AgentJobProviderFields from '../../cos/AgentJobProviderFields';import JobCard, { AUTONOMY_OPTIONS, PRIORITY_OPTIONS, ScheduleFields, TaskMetadataFields } from '../../cos/JobCard';import { filterRunnableProviders } from '../../../utils/providers';+import TaskDataInputs from '../../cos/TaskDataInputs';export function emptyForm() {return {@@ -24,6 +25,7 @@ export function emptyForm() {providerId: '',model: '',effort: '',+ dataInputs: [],taskMetadata: { useWorktree: true, openPR: true, simplify: true }};}@@ -43,6 +45,7 @@ export function formFromJob(job) {providerId: job.providerId || '',model: job.model || '',effort: job.effort || '',+ dataInputs: job.dataInputs || [],taskMetadata: { useWorktree: false, openPR: false, simplify: false, ...(job.taskMetadata || {}) }};}@@ -60,6 +63,7 @@ export function toPayload(form, appId) {providerId: form.providerId || null,model: form.model || null,effort: form.effort || null,+ dataInputs: form.dataInputs || [],taskMetadata: form.taskMetadata};if (form.scheduleMode === 'cron') {@@ -75,7 +79,7 @@ export function toPayload(form, appId) {return payload;}-function TaskForm({ form, setForm, onSave, onCancel, saveLabel, timezone, providers, activeProviderId }) {+function TaskForm({ form, setForm, onSave, onCancel, saveLabel, timezone, providers, activeProviderId, dataInputCatalog }) {const update = (key, val) => setForm(f => ({ ...f, [key]: val }));return (@@ -136,6 +140,12 @@ function TaskForm({ form, setForm, onSave, onCancel, saveLabel, timezone, providonChange={patch => setForm(f => ({ ...f, ...patch }))}/>+ <TaskDataInputs+ catalog={dataInputCatalog}+ value={form.dataInputs}+ onChange={dataInputs => update('dataInputs', dataInputs)}+ />+<TaskMetadataFields data={form} onChange={patch => setForm(f => ({ ...f, ...patch }))} /><div className="flex justify-end gap-2">@@ -159,6 +169,7 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, acconst [rawProviders, setRawProviders] = useState(providerCatalog || []);const [activeProviderId, setActiveProviderId] = useState(inheritedActiveProviderId);const [triggering, setTriggering] = useState(null);+ const [dataInputCatalog, setDataInputCatalog] = useState([]);const providers = useMemo(() => filterRunnableProviders(rawProviders, tasks.map(job => job.providerId)),@@ -169,6 +180,7 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, acconst data = await api.getCosJobs({ silent: true }).catch(() => null);const appTasks = (data?.jobs || []).filter(j => j.appId === appId);setTasks(appTasks);+ setDataInputCatalog(data?.dataInputCatalog || []);setLoading(false);}, [appId]);@@ -262,6 +274,7 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, actimezone={timezone}providers={providers}activeProviderId={activeProviderId}+ dataInputCatalog={dataInputCatalog}/>)}@@ -282,6 +295,7 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, acproviders={providers}activeProviderId={activeProviderId}timezone={timezone}+ dataInputCatalog={dataInputCatalog}onToggle={handleToggle}onTrigger={handleTrigger}onDelete={handleDelete}diff --git a/client/src/components/apps/tabs/CustomTasksSection.test.jsx b/client/src/components/apps/tabs/CustomTasksSection.test.jsxindex c07e043221..c925ba1388 100644--- a/client/src/components/apps/tabs/CustomTasksSection.test.jsx+++ b/client/src/components/apps/tabs/CustomTasksSection.test.jsx@@ -28,13 +28,20 @@ const task = {providerId: 'claude-code',model: 'claude-sonnet',effort: 'high',+ dataInputs: ['project-goals'],runCount: 0};describe('CustomTasksSection trigger outcomes', () => {beforeEach(() => {vi.clearAllMocks();- api.getCosJobs.mockResolvedValue({ jobs: [task] });+ api.getCosJobs.mockResolvedValue({+ jobs: [task],+ dataInputCatalog: [+ { id: 'project-goals', label: 'Project goals', description: 'Include GOALS.md.' },+ { id: 'open-issues', label: 'Open issues', description: 'Include open issues.' },+ ]+ });api.getProviders.mockResolvedValue({activeProvider: 'claude-code',providers: [{@@ -63,7 +70,8 @@ describe('CustomTasksSection trigger outcomes', () => {promptTemplate: 'Do the thing',providerId: 'claude-code',model: 'claude-sonnet',- effort: 'high'+ effort: 'high',+ dataInputs: ['project-goals']};expect(toPayload(form, 'app-1')).toEqual(expect.objectContaining({@@ -71,7 +79,8 @@ describe('CustomTasksSection trigger outcomes', () => {appId: 'app-1',providerId: 'claude-code',model: 'claude-sonnet',- effort: 'high'+ effort: 'high',+ dataInputs: ['project-goals']}));expect(toPayload({ ...form, providerId: '', model: '', effort: '' }, 'app-1')).toEqual(expect.objectContaining({ providerId: null, model: null, effort: null })@@ -97,6 +106,7 @@ describe('CustomTasksSection trigger outcomes', () => {fireEvent.change(screen.getByLabelText('Provider'), { target: { value: 'codex' } });fireEvent.change(screen.getByLabelText('Model'), { target: { value: 'gpt-5' } });fireEvent.change(screen.getByLabelText('Thinking effort'), { target: { value: 'high' } });+ fireEvent.click(screen.getByRole('button', { name: 'Open issues: off' }));fireEvent.click(screen.getByRole('button', { name: 'Create' }));await waitFor(() => expect(api.createCosJob).toHaveBeenCalledWith(expect.objectContaining({@@ -104,7 +114,8 @@ describe('CustomTasksSection trigger outcomes', () => {type: 'agent',providerId: 'codex',model: 'gpt-5',- effort: 'high'+ effort: 'high',+ dataInputs: ['open-issues']})));});diff --git a/client/src/components/cos/JobCard.jsx b/client/src/components/cos/JobCard.jsxindex 7f98be44cc..4bceb4d920 100644--- a/client/src/components/cos/JobCard.jsx+++ b/client/src/components/cos/JobCard.jsx@@ -10,6 +10,7 @@ import { AGENT_OPTIONS, agentOptionButtonClass } from './constants';import InlineConfirmRow from '../ui/InlineConfirmRow';import FormField from '../ui/FormField';import { useConfirmDelete } from '../../hooks/useConfirmDelete';+import TaskDataInputs from './TaskDataInputs';const SCHEDULE_MODE_OPTIONS = [{ value: 'interval', label: 'Interval' },@@ -67,6 +68,7 @@ export function normalizeJobPayload(formData) {payload.providerId = null;payload.model = null;payload.effort = null;+ payload.dataInputs = [];}// Empty app picker selection ('') → null so a PUT actively un-scopes the job// back to global (undefined would be dropped from JSON and updateJob would@@ -254,7 +256,8 @@ export default function JobCard({fixedAppId = null,fixedType = null,showTaskMetadata = false,- triggering = false+ triggering = false,+ dataInputCatalog = []}) {const [expanded, setExpanded] = useState(false);const [editing, setEditing] = useState(false);@@ -282,6 +285,7 @@ export default function JobCard({providerId: job.providerId || '',model: job.model || '',effort: job.effort || '',+ dataInputs: job.dataInputs || [],taskMetadata: showTaskMetadata? { useWorktree: false, openPR: false, simplify: false, ...(job.taskMetadata || {}) }: job.taskMetadata || {}@@ -483,6 +487,13 @@ export default function JobCard({onChange={patch => setEditData(d => ({ ...d, ...patch }))}/>)}+ {isAgentJobType(editData.type) && (+ <TaskDataInputs+ catalog={dataInputCatalog}+ value={editData.dataInputs}+ onChange={dataInputs => setEditData(d => ({ ...d, dataInputs }))}+ />+ )}{showTaskMetadata && isAgentJobType(editData.type) && <TaskMetadataFields data={editData} onChange={patch => setEditData(d => ({ ...d, ...patch }))} />}{editData.config && (<BriefingConfigdiff --git a/client/src/components/cos/TaskDataInputs.jsx b/client/src/components/cos/TaskDataInputs.jsxnew file mode 100644index 0000000000..ed0a06ccf7--- /dev/null+++ b/client/src/components/cos/TaskDataInputs.jsx@@ -0,0 +1,45 @@+import ToggleSwitch from '../ToggleSwitch';++/** Shared selector for deterministic context loaded before a scheduled agent starts. */+export default function TaskDataInputs({ catalog = [], value = [], onChange, disabled = false }) {+ if (!catalog.length) return null;+ const selected = new Set(value || []);++ const toggle = (id) => {+ const next = selected.has(id)+ ? (value || []).filter((entry) => entry !== id)+ : [...(value || []), id];+ onChange(next);+ };++ return (+ <div>+ <span className="text-sm text-gray-400 block mb-2">Preloaded data</span>+ <p className="text-xs text-gray-500 mb-2">+ PortOS reads selected sources before the agent starts and appends them to its prompt, avoiding repeated discovery tool calls.+ </p>+ <div className="space-y-1">+ {catalog.map(({ id, label, description }) => {+ const enabled = selected.has(id);+ return (+ <button+ key={id}+ type="button"+ disabled={disabled}+ aria-pressed={enabled}+ aria-label={`${label}: ${enabled ? 'on' : 'off'}`}+ onClick={() => toggle(id)}+ className={`w-full flex items-center justify-between gap-3 min-h-[44px] rounded px-2 -mx-2 text-left ${disabled ? 'opacity-60 cursor-not-allowed' : 'hover:bg-port-card/30 active:bg-port-card/50'}`}+ >+ <span className="min-w-0 flex-1">+ <span className="text-sm text-white block">{label}</span>+ <span className="text-xs text-gray-500 block">{description}</span>+ </span>+ <ToggleSwitch enabled={enabled} disabled={disabled} decorative />+ </button>+ );+ })}+ </div>+ </div>+ );+}diff --git a/client/src/components/cos/TaskDataInputs.test.jsx b/client/src/components/cos/TaskDataInputs.test.jsxnew file mode 100644index 0000000000..31fbe9cfd5--- /dev/null+++ b/client/src/components/cos/TaskDataInputs.test.jsx@@ -0,0 +1,27 @@+import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import TaskDataInputs from './TaskDataInputs';++const CATALOG = [+ { id: 'project-goals', label: 'Project goals', description: 'Include GOALS.md.' },+ { id: 'open-issues', label: 'Open issues', description: 'Include open issues.' },+];++describe('TaskDataInputs', () => {+ it('toggles ids while preserving catalog-independent selection order', () => {+ const onChange = vi.fn();+ render(<TaskDataInputs catalog={CATALOG} value={['project-goals']} onChange={onChange} />);+ expect(screen.getByRole('button', { name: 'Project goals: on' })).toHaveAttribute('aria-pressed', 'true');++ fireEvent.click(screen.getByRole('button', { name: 'Open issues: off' }));+ expect(onChange).toHaveBeenCalledWith(['project-goals', 'open-issues']);++ fireEvent.click(screen.getByRole('button', { name: 'Project goals: on' }));+ expect(onChange).toHaveBeenLastCalledWith([]);+ });++ it('renders nothing until the server catalog is available', () => {+ const { container } = render(<TaskDataInputs value={[]} onChange={() => {}} />);+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsxindex 7915a221f5..d9feaf8e3e 100644--- a/client/src/components/cos/tabs/JobsTab.jsx+++ b/client/src/components/cos/tabs/JobsTab.jsx@@ -17,6 +17,7 @@ import JobCard, {TRIGGER_ACTION_OPTIONS} from '../JobCard';import useUserTimezone from '../../../hooks/useUserTimezone.js';+import TaskDataInputs from '../TaskDataInputs';// Blank create-form state — shared by the initial useState and the post-create// reset so the two can't drift (a field added to one but not the other would@@ -40,6 +41,7 @@ const INITIAL_JOB = {providerId: '',model: '',effort: '',+ dataInputs: [],enabled: false};@@ -53,6 +55,7 @@ export default function JobsTab() {const [loading, setLoading] = useState(true);const [showCreate, setShowCreate] = useState(false);const [newJob, setNewJob] = useState(INITIAL_JOB);+ const [dataInputCatalog, setDataInputCatalog] = useState([]);const fetchJobs = useCallback(async () => {const data = await api.getCosJobs({ silent: true }).catch(err => {@@ -62,6 +65,7 @@ export default function JobsTab() {if (data) {setJobs(data.jobs || []);setStats(data.stats || null);+ setDataInputCatalog(data.dataInputCatalog || []);}setLoading(false);}, []);@@ -290,6 +294,13 @@ export default function JobsTab() {onChange={patch => setNewJob(j => ({ ...j, ...patch }))}/>)}+ {isAgentJobType(newJob.type) && (+ <TaskDataInputs+ catalog={dataInputCatalog}+ value={newJob.dataInputs}+ onChange={dataInputs => setNewJob(j => ({ ...j, dataInputs }))}+ />+ )}{newJob.type === 'shell' ? (<><textarea@@ -353,6 +364,7 @@ export default function JobsTab() {providers={providers}activeProviderId={activeProviderId}timezone={timezone}+ dataInputCatalog={dataInputCatalog}onToggle={handleToggle}onTrigger={handleTrigger}onDelete={handleDelete}diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex ffb777caff..15533b5e25 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -188,6 +188,7 @@ export default function ScheduleTab({ apps, providers, activeProviderId }) {onBulkToggleOverride={handleBulkToggleOverride}allTaskTypes={allTaskTypes}improvementDisabled={improvementDisabled}+ dataInputCatalog={schedule.dataInputCatalog || []}/></div></CodeReviewDefaultsProvider>diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsxindex aef7a959e9..47c1942c94 100644--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx@@ -17,6 +17,7 @@ import { effectiveModelFor } from '../../../../utils/providers';import EffortSelect from '../../EffortSelect';import PromptEditor from './PromptEditor';import RunTaskButton from './RunTaskButton';+import TaskDataInputs from '../../TaskDataInputs';import { INTERVAL_DESCRIPTIONS, toggleMetadataField, pipelineStages, IMPROVEMENT_DISABLED_TITLE, SAVING_TITLE, fileIssuesEffective, managedAgentOptionsFor, toggleFileIssuesMetadata } from './scheduleConstants';// Shown for the unpinned ('' → inherit) choice: the task type is global, so the@@ -39,7 +40,7 @@ const REVIEW_CONFIG_KEYS = ['reviewerApplies',];-export default function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset, category: _category, providers, activeProviderId, apps, updating, setUpdating, allTaskTypes, improvementDisabled }) {+export default function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset, category: _category, providers, activeProviderId, apps, updating, setUpdating, allTaskTypes, improvementDisabled, dataInputCatalog }) {const reviewDefaults = useCodeReviewDefaults();// Resolved model lists for the reviewer table's Model column (the picker itself// never fetches — see its `modelOptions` prop).@@ -504,6 +505,17 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTriactiveApps={activeApps}/>+ <TaskDataInputs+ catalog={dataInputCatalog}+ value={config.dataInputs || []}+ disabled={updating}+ onChange={async (dataInputs) => {+ setUpdating(true);+ await onUpdate(taskType, { dataInputs });+ setUpdating(false);+ }}+ />+{config.fileIssuesCapable && (<buttontype="button"diff --git a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsxindex f0f1e34bb0..b827ef78ac 100644--- a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx+++ b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx@@ -35,6 +35,7 @@ export default function TaskConfigDrawer({onBulkToggleOverride,allTaskTypes,improvementDisabled,+ dataInputCatalog,}) {const [updating, setUpdating] = useState(false);@@ -96,6 +97,7 @@ export default function TaskConfigDrawer({setUpdating={setUpdating}allTaskTypes={allTaskTypes}improvementDisabled={improvementDisabled}+ dataInputCatalog={dataInputCatalog}/>)}diff --git a/server/lib/README.md b/server/lib/README.mdindex 8a4c28340f..72f503d95b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -26,6 +26,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `appDeployFlags.js` | Shared allowlist of flags PortOS may forward to a managed app's `deploy.sh`, consumed by socket validation and deployment orchestration without reversing the lib/services dependency. || `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, result + approximate-token bounds, source-freshness status, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. || `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parseIndexParam`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |+| `taskDataInputCatalog.js` | Pure catalog and persisted ids for deterministic context sources that scheduled agent tasks can preload before dispatch. || `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). || `generationModes.js` | Shared immutable image/video render-backend alphabets (`IMAGE_GEN_MODE[S]`, `QUEUEABLE_IMAGE_MODES`, `VIDEO_GEN_MODE[S]`, and cloud subsets), kept below both validation and generation services so schemas never import orchestration modules. || `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. |diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 150b0ff02d..a1df2f11ab 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -18,6 +18,9 @@ import { isValidSlashdoCommand } from './slashdoInvocation.js';import { PR_COMPLETION_VALUES } from './prDisposition.js';import { AGENT_RUN_EVENT_KINDS, RUN_EVENT_READ_LIMITS } from './agentRunEvents.js';import { recurrenceRuleSchema } from './recurrenceValidation.js';+import { TASK_DATA_INPUT_DEFINITIONS, TASK_DATA_INPUT_IDS } from './taskDataInputCatalog.js';++export { TASK_DATA_INPUT_DEFINITIONS, TASK_DATA_INPUT_IDS } from './taskDataInputCatalog.js';// =============================================================================// COS TASK SCHEMAS@@ -1427,6 +1430,15 @@ export const createLoopSchema = z.object({// COS JOB SCHEMAS// =============================================================================+// Deterministic context sources that can be preloaded before a scheduled agent+// starts. The ids are persisted on both built-in schedule entries and custom+// agent jobs; taskDataInputs.js owns the I/O behind each id. Keep this catalog+// descriptive and side-effect-free so APIs can expose it directly to every+// configuration surface without duplicating labels or capabilities in clients.+export const taskDataInputsSchema = z.array(z.enum(TASK_DATA_INPUT_IDS))+ .max(TASK_DATA_INPUT_IDS.length)+ .transform((ids) => [...new Set(ids)]);+export const createCosJobSchema = z.object({name: z.string().min(1),description: z.string().optional(),@@ -1447,6 +1459,10 @@ export const createCosJobSchema = z.object({priority: z.string().optional(),autonomyLevel: z.enum(['standby', 'assistant', 'manager', 'yolo']).optional(),promptTemplate: z.string().optional(),+ // Deterministic repository/tracker context appended before the agent starts.+ // An empty array actively clears every selection on update; absent preserves+ // the stored selection.+ dataInputs: taskDataInputsSchema.optional(),command: z.string().optional(),triggerAction: z.preprocess(v => v === '' ? undefined : v, z.string().optional()),// Optional AI provider + model override for agent jobs. Empty string from thediff --git a/server/lib/cosValidation.test.js b/server/lib/cosValidation.test.jsindex 81526f6b69..7a997a9a73 100644--- a/server/lib/cosValidation.test.js+++ b/server/lib/cosValidation.test.js@@ -110,6 +110,21 @@ describe('cosValidation autonomous-job effort field', () => {});});+describe('cosValidation autonomous-job data inputs', () => {+ it('accepts registered ids, de-duplicates them, and preserves an explicit clear', () => {+ expect(createCosJobSchema.parse({+ name: 'j',+ dataInputs: ['project-goals', 'open-issues', 'project-goals'],+ }).dataInputs).toEqual(['project-goals', 'open-issues']);+ expect(updateCosJobSchema.parse({ dataInputs: [] }).dataInputs).toEqual([]);+ expect(updateCosJobSchema.parse({}).dataInputs).toBeUndefined();+ });++ it('rejects unknown input ids', () => {+ expect(createCosJobSchema.safeParse({ name: 'j', dataInputs: ['unknown-source'] }).success).toBe(false);+ });+});+describe('cosValidation job taskMetadata.worktreeChangesExpected (#3102)', () => {it('accepts the flag and preserves an explicit false (schema parity with the sanitizer)', () => {// Zod strips undeclared keys, so an unlisted flag would be silently droppeddiff --git a/server/lib/index.js b/server/lib/index.jsindex 29c1a86ca9..b1dad1f43a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -92,6 +92,7 @@ export * from './styleGuide.js';export * from './storyBuilderIntegrity.js';export * from './storyBuilderSteps.js';export * from './streamLines.js';+export * from './taskDataInputCatalog.js';// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for// back-compat — namespace it so the canonical scenePrompt export wins flat.export * as storyBible from './storyBible.js';diff --git a/server/lib/taskDataInputCatalog.js b/server/lib/taskDataInputCatalog.jsnew file mode 100644index 0000000000..a2c66ff1be--- /dev/null+++ b/server/lib/taskDataInputCatalog.js@@ -0,0 +1,14 @@+/** Pure catalog for deterministic context sources available to scheduled agents. */+export const TASK_DATA_INPUT_DEFINITIONS = Object.freeze([+ Object.freeze({ id: 'product-requirements', label: 'Product requirements', description: 'Find and include PRD.md files from the target repository.', requiresApp: true }),+ Object.freeze({ id: 'project-goals', label: 'Project goals', description: 'Find and include GOALS.md files from the target repository.', requiresApp: true }),+ Object.freeze({ id: 'open-issues', label: 'Open issues', description: 'Include the target repository\'s current open forge issues.', requiresApp: true }),+ Object.freeze({ id: 'open-pull-requests', label: 'Open pull requests', description: 'Include the target repository\'s current open pull or merge requests.', requiresApp: true }),+ Object.freeze({ id: 'closed-unmerged-pull-requests', label: 'Closed unmerged pull requests', description: 'Include recently closed pull or merge requests that were not merged.', requiresApp: true }),+]);++export const TASK_DATA_INPUT_IDS = Object.freeze(TASK_DATA_INPUT_DEFINITIONS.map(({ id }) => id));++export function getTaskDataInputCatalog() {+ return TASK_DATA_INPUT_DEFINITIONS.map((definition) => ({ ...definition }));+}diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.jsindex 55162e5137..abee650968 100644--- a/server/routes/cosJobRoutes.js+++ b/server/routes/cosJobRoutes.js@@ -11,6 +11,7 @@ import { parseCronToNextRun, isValidRecurrence } from '../services/eventScheduleimport { getUserTimezone } from '../services/userTimezone.js';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';import { createCosJobSchema, updateCosJobSchema } from '../lib/validation.js';+import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';const router = Router();@@ -54,7 +55,7 @@ router.get('/jobs', asyncHandler(async (req, res) => {...(j.cronSchedule ? { nextRunAt: Number.isFinite(nextRun) ? new Date(nextRun).toISOString() : null } : {})};});- res.json({ jobs: jobsWithGates, stats, registeredGates: getRegisteredGates() });+ res.json({ jobs: jobsWithGates, stats, registeredGates: getRegisteredGates(), dataInputCatalog: getTaskDataInputCatalog() });}));// GET /api/cos/jobs/due - Get jobs that are due to run@@ -109,7 +110,7 @@ router.get('/jobs/:id', asyncHandler(async (req, res) => {router.post('/jobs', asyncHandler(async (req, res) => {const parsedJob = createCosJobSchema.safeParse(req.body);if (!parsedJob.success) failValidation(parsedJob);- const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, appId, taskMetadata, providerId, model, effort } = parsedJob.data;+ const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule, enabled, priority, autonomyLevel, promptTemplate, dataInputs, command, triggerAction, appId, taskMetadata, providerId, model, effort } = parsedJob.data;if (type === 'shell' && !command?.trim()) {throw new ServerError('command is required for shell jobs', { status: 400, code: 'VALIDATION_ERROR' });@@ -126,7 +127,7 @@ router.post('/jobs', asyncHandler(async (req, res) => {const job = await autonomousJobs.createJob({name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule,- enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, appId, taskMetadata, providerId, model, effort+ enabled, priority, autonomyLevel, promptTemplate, dataInputs, command, triggerAction, appId, taskMetadata, providerId, model, effort});res.json({ success: true, job });}));@@ -136,14 +137,14 @@ router.put('/jobs/:id', asyncHandler(async (req, res) => {const parsedJobUpdate = updateCosJobSchema.safeParse(req.body);if (!parsedJobUpdate.success) failValidation(parsedJobUpdate);const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule,- enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort } = parsedJobUpdate.data;+ enabled, priority, autonomyLevel, promptTemplate, dataInputs, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort } = parsedJobUpdate.data;if (cronExpression) {validateCronExpression(cronExpression);}if (cronSchedule) validateRecurrenceRule(cronSchedule);const job = await autonomousJobs.updateJob(req.params.id, {name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule,- enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort+ enabled, priority, autonomyLevel, promptTemplate, dataInputs, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort});if (!job) {throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.jsindex 37c962464f..0da5d9544e 100644--- a/server/routes/cosJobRoutes.test.js+++ b/server/routes/cosJobRoutes.test.js@@ -77,6 +77,7 @@ describe('CoS Job Routes', () => {expect(response.body.jobs).toHaveLength(1);expect(response.body.jobs[0].hasGate).toBe(false);expect(response.body.stats).toHaveProperty('total');+ expect(response.body.dataInputCatalog.map(({ id }) => id)).toContain('project-goals');});it('projects the next run for rich recurrence jobs', async () => {@@ -313,6 +314,28 @@ describe('CoS Job Routes', () => {);});+ it('should accept registered data inputs and forward them to createJob', async () => {+ autonomousJobs.createJob.mockResolvedValue({ id: 'j1' });++ const response = await request(app)+ .post('/api/cos/jobs')+ .send({ name: 'Context Task', type: 'agent', promptTemplate: 'test', dataInputs: ['project-goals', 'open-issues'] });++ expect(response.status).toBe(200);+ expect(autonomousJobs.createJob).toHaveBeenCalledWith(+ expect.objectContaining({ dataInputs: ['project-goals', 'open-issues'] })+ );+ });++ it('should reject unknown data input ids', async () => {+ const response = await request(app)+ .post('/api/cos/jobs')+ .send({ name: 'Bad Context Task', type: 'agent', promptTemplate: 'test', dataInputs: ['unknown'] });++ expect(response.status).toBe(400);+ expect(autonomousJobs.createJob).not.toHaveBeenCalled();+ });+it('should reject an effort value outside EFFORT_LEVELS', async () => {const response = await request(app).post('/api/cos/jobs')diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.jsindex 69b10c97fe..c4081a96c8 100644--- a/server/routes/cosScheduleRoutes.js+++ b/server/routes/cosScheduleRoutes.js@@ -6,7 +6,7 @@ import { Router } from 'express';import { z } from 'zod';import * as taskSchedule from '../services/taskSchedule.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { sanitizeTaskMetadata, validateRequest, parsePagination } from '../lib/validation.js';+import { sanitizeTaskMetadata, taskDataInputsSchema, validateRequest, parsePagination } from '../lib/validation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';const templateTaskSchema = z.object({@@ -20,7 +20,7 @@ const templateTaskSchema = z.object({const router = Router();-const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'effort', 'prompt', 'taskMetadata', 'runAfter',+const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'effort', 'prompt', 'dataInputs', 'taskMetadata', 'runAfter',// Perpetual (drain-until-done) recheck cadence: after a perpetual task drains// its backlog and parks, it re-probes its work-detector on this cadence.// `recheckCron` (5-field) takes precedence over `recheckIntervalMs`.@@ -67,6 +67,13 @@ function pickScheduleSettings(body) {}settings.taskMetadata = sanitized;}+ if (settings.dataInputs !== undefined) {+ const parsed = taskDataInputsSchema.safeParse(settings.dataInputs);+ if (!parsed.success) {+ throw new ServerError('dataInputs must contain only registered task data input ids', { status: 400, code: 'VALIDATION_ERROR' });+ }+ settings.dataInputs = parsed.data;+ }if (settings.effort !== undefined && settings.effort !== null && !EFFORT_LEVELS.includes(settings.effort)) {throw new ServerError(`effort must be one of ${EFFORT_LEVELS.join(', ')} or null`, { status: 400, code: 'VALIDATION_ERROR' });}diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.jsindex d0b28926f8..5b8e89b8c8 100644--- a/server/routes/cosScheduleRoutes.test.js+++ b/server/routes/cosScheduleRoutes.test.js@@ -22,6 +22,14 @@ vi.mock('../services/taskSchedule.js', () => ({vi.mock('../lib/validation.js', () => ({sanitizeTaskMetadata: vi.fn((meta) => meta),+ taskDataInputsSchema: {+ safeParse: (ids) => {+ const allowed = new Set(['product-requirements', 'project-goals', 'open-issues', 'open-pull-requests', 'closed-unmerged-pull-requests']);+ return Array.isArray(ids) && ids.every((id) => allowed.has(id))+ ? { success: true, data: [...new Set(ids)] }+ : { success: false };+ }+ },validateRequest: vi.fn((schema, data) => {const result = schema.safeParse(data);if (!result.success) {@@ -147,6 +155,27 @@ describe('CoS Schedule Routes', () => {runAfter: null}));});++ it('validates and forwards registered data input ids', async () => {+ taskSchedule.updateTaskInterval.mockResolvedValue({ type: 'weekly' });+ const response = await request(app)+ .put('/api/cos/schedule/task/plan-feature')+ .send({ dataInputs: ['project-goals', 'open-issues', 'project-goals'] });++ expect(response.status).toBe(200);+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('plan-feature', expect.objectContaining({+ dataInputs: ['project-goals', 'open-issues']+ }));+ });++ it('rejects unknown data input ids', async () => {+ const response = await request(app)+ .put('/api/cos/schedule/task/plan-feature')+ .send({ dataInputs: ['not-registered'] });++ expect(response.status).toBe(400);+ expect(taskSchedule.updateTaskInterval).not.toHaveBeenCalled();+ });});describe('GET /api/cos/schedule/due', () => {diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.jsindex 17f16b3076..e9150286e2 100644--- a/server/services/autonomousJobs.test.js+++ b/server/services/autonomousJobs.test.js@@ -823,6 +823,18 @@ describe('autonomousJobs', () => {})expect(job.effort).toBe('xhigh')})++ it('stores configured data input ids and defaults to an empty selection', async () => {+ const configured = await createJob({+ name: 'Context Job',+ promptTemplate: 'do it',+ dataInputs: ['project-goals', 'open-issues']+ })+ expect(configured.dataInputs).toEqual(['project-goals', 'open-issues'])++ const plain = await createJob({ name: 'Plain Job', promptTemplate: 'do it' })+ expect(plain.dataInputs).toEqual([])+ })})describe('updateJob', () => {diff --git a/server/services/autonomousJobs/crud.js b/server/services/autonomousJobs/crud.jsindex e3890f4626..eaf0283103 100644--- a/server/services/autonomousJobs/crud.js+++ b/server/services/autonomousJobs/crud.js@@ -99,6 +99,9 @@ async function createJob(jobData) {priority: jobData.priority || 'MEDIUM',autonomyLevel: jobData.autonomyLevel || 'manager',promptTemplate: jobData.promptTemplate || '',+ // Selected deterministic context sources resolved immediately before the+ // agent task is generated. Empty is a real configured selection.+ dataInputs: Array.isArray(jobData.dataInputs) ? jobData.dataInputs : [],// Optional per-job AI provider + model override. Null = use the active// provider / its default model (historical behavior). generateTaskFromJob// forwards these into the task metadata the agent runner resolves.@@ -151,7 +154,7 @@ async function updateJob(jobId, updates) {const updatableFields = ['name', 'description', 'category', 'type', 'interval', 'intervalMs',- 'scheduledTime', 'cronExpression', 'cronSchedule', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate',+ 'scheduledTime', 'cronExpression', 'cronSchedule', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate', 'dataInputs','command', 'triggerAction', 'config', 'appId', 'taskMetadata', 'providerId', 'model', 'effort']diff --git a/server/services/autonomousJobs/skillTemplates.js b/server/services/autonomousJobs/skillTemplates.jsindex 744979b7a1..865d4834b6 100644--- a/server/services/autonomousJobs/skillTemplates.js+++ b/server/services/autonomousJobs/skillTemplates.js@@ -8,8 +8,10 @@import { writeFile } from 'fs/promises'import { join } from 'path'-import { ensureDir, tryReadFile } from '../../lib/fileUtils.js'+import { ensureDir, PATHS, tryReadFile } from '../../lib/fileUtils.js'import { JOBS_SKILLS_DIR, JOB_SKILL_MAP } from './constants.js'+import { getAppById } from '../apps.js'+import { appendTaskDataInputs, resolveTaskDataInputs } from '../taskDataInputs.js'/*** Load a job skill template from disk@@ -142,7 +144,15 @@ async function getJobEffectivePrompt(job) {* @returns {Promise<Object>} Task data suitable for cos.addTask()*/async function generateTaskFromJob(job) {- const description = await getJobEffectivePrompt(job)+ const prompt = await getJobEffectivePrompt(job)+ const selectedInputs = Array.isArray(job.dataInputs) ? job.dataInputs : []+ const app = selectedInputs.length > 0+ ? (job.appId ? await getAppById(job.appId) : { id: null, name: 'PortOS', repoPath: PATHS.root })+ : null+ const inputs = selectedInputs.length > 0+ ? await resolveTaskDataInputs(selectedInputs, { app })+ : []+ const description = appendTaskDataInputs(prompt, inputs)const meta = job.taskMetadata || {}return {id: `${job.id}-${Date.now().toString(36)}`,diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex d88fc3e963..16b54d0bbc 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -64,6 +64,7 @@ import {buildTargetWorkItemBlock,normalizeWorkItemRef,} from './cosTaskPrompts.js';+import { appendTaskDataInputs, resolveTaskDataInputs } from './taskDataInputs.js';export {buildClaimOverrideContextBlock,@@ -3092,7 +3093,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stconst planConstraintBlock = buildPlanConstraintBlock(metadata.planId);const modeInstructions = isAuditTaskType(taskType) ? modeContractFor(fileIssues) : '';- const description = await buildImprovementTaskDescription({+ const baseDescription = await buildImprovementTaskDescription({promptTemplate: applyAuditModeWrapper(promptTemplate, modeInstructions),app, promptTaskType, metadata,blocks: {@@ -3108,6 +3109,8 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stplanConstraint: planConstraintBlock}});+ const taskDataInputs = await resolveTaskDataInputs(interval.dataInputs, { app });+ const description = appendTaskDataInputs(baseDescription, taskDataInputs);applyAppWorktreeDefault(metadata, app);// File-issues posture wins over app worktree/PR defaults — the deliverablediff --git a/server/services/taskDataInputs.js b/server/services/taskDataInputs.jsnew file mode 100644index 0000000000..9c9d344416--- /dev/null+++ b/server/services/taskDataInputs.js@@ -0,0 +1,218 @@+/**+ * Scheduled-task data inputs.+ *+ * Resolves reusable, deterministic repository/tracker context before an agent+ * starts. Schedules and custom jobs persist only catalog ids; this module owns+ * the I/O and the single prompt rendering contract for every consumer.+ */++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';++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 SEARCH_MAX_DEPTH = 4;+const SKIP_DIRECTORIES = new Set([+ '.git', '.idea', '.next', '.turbo', '.venv', '.vscode',+ 'build', 'coverage', 'dist', 'node_modules', 'vendor', 'data'+]);++async function findNamedFiles(root, filename, {+ readDir = readdir,+ readFile = tryReadFile,+ maxDepth = SEARCH_MAX_DEPTH,+ maxFiles = MAX_DOCUMENT_FILES,+} = {}) {+ if (!root) return [];+ const matches = [];+ const target = filename.toLowerCase();++ async function walk(directory, depth) {+ if (matches.length >= maxFiles || depth > maxDepth) return;+ const entries = await readDir(directory, { withFileTypes: true }).catch(() => null);+ if (!entries) return;++ // Files first and alphabetical traversal make root documents win while the+ // bounded fallback remains deterministic across platforms.+ const ordered = [...entries].sort((a, b) => {+ if (a.isFile() !== b.isFile()) return a.isFile() ? -1 : 1;+ return a.name.localeCompare(b.name);+ });+ for (const entry of ordered) {+ if (matches.length >= maxFiles) return;+ 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) });+ }+ } else if (entry.isDirectory() && !SKIP_DIRECTORIES.has(entry.name)) {+ await walk(path, depth + 1);+ }+ }+ }++ await walk(root, 0);+ return matches;+}++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);+}++function normalizeLabels(labels) {+ if (!Array.isArray(labels)) return [];+ return labels.map((label) => typeof label === 'string' ? label : label?.name).filter(Boolean);+}++export function renderForgeItems(items, { emptyMessage }) {+ if (!items.length) return emptyMessage;+ const shown = items.slice(0, MAX_LIST_ITEMS);+ const lines = shown.map((item) => {+ const number = item.number ?? item.iid;+ const ref = number != null ? `#${number} ` : '';+ const author = item.author?.login || item.author?.username || item.author?.name || item.authorLogin;+ const labels = normalizeLabels(item.labels);+ const details = [+ item.isDraft === true || item.draft === true ? 'draft' : null,+ author ? `author: ${author}` : null,+ labels.length ? `labels: ${labels.join(', ')}` : null,+ item.headRefName || item.source_branch ? `head: ${item.headRefName || item.source_branch}` : null,+ ].filter(Boolean).join('; ');+ 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);+}++export async function listForgeOpenIssues({ cli, cwd, env, exec = runCli } = {}) {+ if (!cwd || (cli !== 'gh' && cli !== 'glab')) return { ok: false, issues: [] };+ const args = cli === 'glab'+ ? withGlabJson(['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: [] };+ const parsed = safeJSONParse(result.stdout, null, { logError: false });+ if (!Array.isArray(parsed)) return result.stdout.trim() ? { ok: false, issues: [] } : { ok: true, issues: [] };+ return {+ ok: true,+ issues: parsed+ .filter((item) => !item.state || ['open', 'opened'].includes(String(item.state).toLowerCase()))+ .map((item) => ({+ number: item.number ?? item.iid,+ title: item.title || '',+ state: 'open',+ url: item.url || item.web_url || null,+ labels: normalizeLabels(item.labels),+ })),+ };+}++export async function listForgePullRequests({ cli, cwd, env, state = 'open', exec = runCli } = {}) {+ 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'])+ : [+ 'pr', 'list', '--state', closed ? 'closed' : 'open',+ ...(closed ? ['--search', 'is:unmerged'] : []),+ '--limit', closed ? '20' : '100',+ '--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: [] };+ const parsed = safeJSONParse(result.stdout, null, { logError: false });+ if (!Array.isArray(parsed)) return result.stdout.trim() ? { ok: false, items: [] } : { ok: true, 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+ ? parsed.filter((item) => !item.merged_at && String(item.state || '').toLowerCase() !== 'merged')+ : parsed;+ return { ok: true, items };+}++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) {+ if (!app?.repoPath) return null;+ const forge = await resolveForge(app.repoPath);+ return forge?.cli === 'gh' || forge?.cli === 'glab' ? forge : null;+}++const INPUT_LOADERS = {+ 'product-requirements': async ({ app, deps }) => renderRepositoryDocuments(+ 'PRD.md', await deps.findFiles(app?.repoPath, 'PRD.md')+ ),+ 'project-goals': async ({ app, deps }) => renderRepositoryDocuments(+ 'GOALS.md', await deps.findFiles(app?.repoPath, 'GOALS.md')+ ),+ 'open-issues': async ({ app, deps, forge }) => {+ if (!forge) return unavailableMessage('Open issues', 'repository forge is unavailable');+ const result = await deps.listIssues({ cli: forge.cli, cwd: app.repoPath, env: forge.env });+ return result.ok+ ? renderForgeItems(result.issues, { emptyMessage: 'No open issues.' })+ : unavailableMessage('Open issues');+ },+ 'open-pull-requests': async ({ app, deps, forge }) => {+ if (!forge) return unavailableMessage('Open pull requests', 'repository forge is unavailable');+ const result = await deps.listPullRequests({ cli: forge.cli, cwd: app.repoPath, env: forge.env, state: 'open' });+ return result.ok+ ? renderForgeItems(result.items, { emptyMessage: 'No open pull requests.' })+ : unavailableMessage('Open pull requests');+ },+ 'closed-unmerged-pull-requests': async ({ app, deps, forge }) => {+ if (!forge) return unavailableMessage('Closed unmerged pull requests', 'repository forge is unavailable');+ const result = await deps.listPullRequests({ cli: forge.cli, cwd: app.repoPath, env: forge.env, state: 'closed-unmerged' });+ return result.ok+ ? renderForgeItems(result.items, { emptyMessage: 'No recently closed unmerged pull requests.' })+ : unavailableMessage('Closed unmerged pull requests');+ },+};++/** Resolve selected input ids into prompt-ready sections without throwing. */+export async function resolveTaskDataInputs(inputIds, { app, dependencies = {} } = {}) {+ const selected = Array.isArray(inputIds) ? [...new Set(inputIds)] : [];+ if (!selected.length) return [];+ const definitions = new Map(TASK_DATA_INPUT_DEFINITIONS.map((definition) => [definition.id, definition]));+ const deps = {+ findFiles: findNamedFiles,+ resolveForge: resolveForgeForRepo,+ listIssues: listForgeOpenIssues,+ listPullRequests: listForgePullRequests,+ ...dependencies,+ };+ const needsForge = selected.some((id) => id.includes('issues') || id.includes('pull-requests'));+ const forge = needsForge+ ? await resolveForgeContext(app, deps.resolveForge).catch(() => null)+ : null;++ const sections = await Promise.all(selected.map(async (id) => {+ const definition = definitions.get(id);+ const loader = INPUT_LOADERS[id];+ if (!definition || !loader) return null;+ const content = await loader({ app, deps, forge }).catch(() => unavailableMessage(definition.label));+ return { id, label: definition.label, content };+ }));+ return sections.filter(Boolean);+}++export function appendTaskDataInputs(prompt, sections) {+ if (!Array.isArray(sections) || sections.length === 0) return prompt;+ 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}`;+}diff --git a/server/services/taskDataInputs.test.js b/server/services/taskDataInputs.test.jsnew file mode 100644index 0000000000..29e2170e00--- /dev/null+++ b/server/services/taskDataInputs.test.js@@ -0,0 +1,96 @@+import { describe, expect, it, vi } from 'vitest';+import {+ appendTaskDataInputs,+ listForgePullRequests,+ renderForgeItems,+ resolveTaskDataInputs,+} from './taskDataInputs.js';+import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';++const APP = { id: 'app-1', name: 'Example App', repoPath: '/repo' };++describe('taskDataInputs', () => {+ it('exposes a stable reusable catalog', () => {+ expect(getTaskDataInputCatalog().map(({ id }) => id)).toEqual([+ 'product-requirements',+ 'project-goals',+ 'open-issues',+ 'open-pull-requests',+ 'closed-unmerged-pull-requests',+ ]);+ });++ 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 findFiles = vi.fn(async (_root, filename) => [{ path: filename, content: `${filename} body` }]);+ const listIssues = vi.fn().mockResolvedValue({+ ok: true,+ issues: [{ number: 4, title: 'Open work', state: 'open', labels: ['plan'] }],+ });+ const listPullRequests = vi.fn().mockResolvedValue({+ ok: true,+ items: [{ number: 8, title: 'Current change', author: { login: 'alice' } }],+ });++ const sections = await resolveTaskDataInputs([+ 'project-goals', 'open-issues', 'open-pull-requests', 'project-goals'+ ], { app: APP, dependencies: { resolveForge, 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' }));+ });++ it('preserves failed versus legitimately empty tracker reads', async () => {+ const common = {+ app: APP,+ dependencies: {+ resolveForge: vi.fn().mockResolvedValue({ cli: 'gh', env: {} }),+ listIssues: vi.fn().mockResolvedValue({ ok: false, issues: [] }),+ },+ };+ const failed = await resolveTaskDataInputs(['open-issues'], common);+ expect(failed[0].content).toContain('could not be preloaded');+ expect(failed[0].content).toContain('Do not interpret this as an empty source');++ common.dependencies.listIssues.mockResolvedValue({ ok: true, issues: [] });+ const empty = await resolveTaskDataInputs(['open-issues'], common);+ expect(empty[0].content).toBe('No open issues.');+ });++ 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.' },+ ]);+ expect(prompt).toContain('Do the task.');+ expect(prompt).toContain('## Preloaded task data');+ expect(prompt).toContain('do not spend tools or tokens fetching the same data again');+ expect(prompt).toContain('### Project goals');+ });++ it('renders forge metadata without serializing label objects', () => {+ const rendered = renderForgeItems([{+ number: 2,+ title: 'Example',+ labels: [{ name: 'plan' }],+ author: { username: 'alice' },+ source_branch: 'feature/example',+ }], { emptyMessage: 'None.' });+ expect(rendered).toContain('labels: plan');+ expect(rendered).toContain('author: alice');+ expect(rendered).not.toContain('[object Object]');+ });++ it('lists GitHub closed-unmerged pull requests with explicit search semantics', async () => {+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: '[]', stderr: '' });+ await expect(listForgePullRequests({+ cli: 'gh', cwd: '/repo', state: 'closed-unmerged', exec+ })).resolves.toEqual({ ok: true, items: [] });+ expect(exec).toHaveBeenCalledWith('gh', expect.arrayContaining([+ '--state', 'closed', '--search', 'is:unmerged'+ ]), expect.objectContaining({ cwd: '/repo' }));+ });+});diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.jsindex 3a60aa94cd..7ca72701c8 100644--- a/server/services/taskPromptDefaults.test.js+++ b/server/services/taskPromptDefaults.test.js@@ -150,11 +150,14 @@ describe('taskPromptDefaults integrity snapshot', () => {expect(v9).not.toBe(current);});- // plan-feature v2: product intent is specific-first (PRD → GOALS → repository- // docs) and no longer depends on the retired roadmap/rejection-ledger files.- it('plan-feature v2 uses the PRD/docs fallback hierarchy and preserves v1', () => {+ // 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', () => {const current = DEFAULT_TASK_PROMPTS['plan-feature'];- expect(PROMPT_VERSIONS['plan-feature']).toBe(2);+ expect(PROMPT_VERSIONS['plan-feature']).toBe(3);+ expect(current).toContain('Preloaded task data');+ expect(current).toContain('do NOT list them again');+ expect(current).toContain('Closed unmerged pull requests');expect(current).toContain('PRD.md');expect(current).toContain('GOALS.md');expect(current).toContain('README.md');@@ -163,6 +166,11 @@ describe('taskPromptDefaults integrity snapshot', () => {expect(current).not.toContain('REJECTED.md');expect(current).not.toContain('ALSO read PLAN.md');+ 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');+ expect(v2).not.toBe(current);+const v1 = PREVIOUS_DEFAULT_PROMPTS['plan-feature'].find((prompt) => prompt.includes('ALSO read PLAN.md'));expect(v1).toBeDefined();expect(v1).toContain('REJECTED.md');diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex 74d0982ab0..98499daf12 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": "b20980c8eda2256060d09d4bca397244",+ "plan-feature": "a707866783fd0d8c1037489f23ff66de","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": 2,+ "plan-feature": 3,"security": 2,"code-quality": 2,"test-coverage": 2,@@ -232,6 +232,7 @@"ca7324a0f2251a66b46ea534940c9da8"],"plan-feature": [+ "b20980c8eda2256060d09d4bca397244","3df6f0a46f2a524af1dc4f83dfdf0647"],"stash-cleanup": [diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.jsindex d5d03e8dad..88cdfa55d5 100644--- a/server/services/taskPromptDefaults/previousDefaults.js+++ b/server/services/taskPromptDefaults/previousDefaults.js@@ -10965,6 +10965,108 @@ Default branch: {defaultBranch}were added, updated, or removed and the sources you verified them against.`,],'plan-feature': [+ // 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++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.** Follow the "Inventory" step under+ "Where to record the plan" above for this app's tracker — 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 or recently shipped work is NOT a candidate.++2. **Build a product brief from the repository's documentation.** Use the most+ specific available source of intent, and make a best effort rather than+ assuming a missing document means the app has no direction:++ - If \`PRD.md\` exists, read it first. Treat its requirements, acceptance+ criteria, success metrics, constraints, and non-goals as the primary+ evaluation for what the feature should accomplish.+ - If \`GOALS.md\` exists, read 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.+ - Check the repo's recently closed-unmerged PRs (\`gh pr list --state closed+ --search "is:unmerged" --limit 20\`, or the forge's equivalent) — a feature+ whose PR the user closed WITHOUT merging was rejected; treat those ideas as+ rejected too.+ - 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.`,// v1 default prompt — initial release; superseded by the PRD/docs-first// research hierarchy in v2.`[Improvement: {appName}] Feature Planning — brainstorm one feature and file its plandiff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 0fd1ef276c..2fe0690bf7 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -619,20 +619,28 @@ Repository: {repoPath}## What to do-1. **Inventory so you don't duplicate.** Follow the "Inventory" step under- "Where to record the plan" above for this app's tracker — 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 or recently shipped work is NOT a candidate.--2. **Build a product brief from the repository's documentation.** Use the most- specific available source of intent, and make a best effort rather than- assuming a missing document means the app has no direction:-- - If \`PRD.md\` exists, read it first. Treat its requirements, acceptance+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, acceptancecriteria, success metrics, constraints, and non-goals as the primaryevaluation for what the feature should accomplish.- - If \`GOALS.md\` exists, read it for strategic context and to supplement+ - If the Project goals section contains a \`GOALS.md\`, use it for strategic context and to supplementthe PRD. If there is no PRD, use GOALS.md as the primary statement ofdesired direction.- If neither exists, start with the root \`README.md\`, \`docs/README.md\`@@ -648,10 +656,9 @@ Repository: {repoPath}constraints, not as a substitute for product intent. When documentationis sparse, validate the inferred need against the current source, tests,and recent history and name the evidence in the plan.- - Check the repo's recently closed-unmerged PRs (\`gh pr list --state closed- --search "is:unmerged" --limit 20\`, or the forge's equivalent) — a feature- whose PR the user closed WITHOUT merging was rejected; treat those ideas as- rejected too.+ - 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 namesreal files rather than imagined ones.diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex 3e7ae7dab1..77b6a9deec 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': 2, // 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; removes obsolete roadmap/rejection-ledger research dependencies while retaining the resolved work-tracker filing flow. v1: net-new planning-only sibling of feature-ideas.+ '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.// Basic self-improvement tasks — versioned so installs created before the// Jan→Feb 2026 genericization (which still have the app-name-hardcoded "PortOS"diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 90f37aaea6..4d07485fdb 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -46,6 +46,7 @@ import {enforceManagedAgentOptions} from './taskScheduleRegistry.js';import { loadSchedule, saveSchedule } from './taskScheduleStore.js';+import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';import {clearFailureLedgerFields,clearTaskTypeFailurePark,@@ -1160,7 +1161,8 @@ export async function getScheduleStatus() {tasks: {},templates: schedule.templates,onDemandRequests: schedule.onDemandRequests || [],- learningAdjustmentsActive: 0+ learningAdjustmentsActive: 0,+ dataInputCatalog: getTaskDataInputCatalog()};// Fetch active apps once for per-app override aggregationdiff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex 53a3d7da2a..9b7710edd0 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -1372,6 +1372,13 @@ describe('taskSchedule', () => {expect(cfg.enabled).toBe(false)// Refresh the configured work tracker before filing a new proposal.expect(cfg.runAfter).toEqual(['do-replan'])+ expect(cfg.dataInputs).toEqual([+ 'product-requirements',+ 'project-goals',+ 'open-issues',+ 'open-pull-requests',+ 'closed-unmerged-pull-requests',+ ])expect(cfg.taskMetadata.useWorktree).toBe(false)expect(cfg.taskMetadata.openPR).toBe(false)// Writable: a file-based tracker path commits checklist items.@@ -1403,7 +1410,7 @@ describe('taskSchedule', () => {expect(prompt).toContain('docs/README.md')expect(prompt).not.toContain('PLAN.md')expect(prompt).not.toContain('REJECTED.md')- expect(prompt).toContain('closed-unmerged')+ expect(prompt).toContain('Closed unmerged pull requests')// Never implements — the plan IS the deliverable.expect(prompt).toContain('no branches, no PRs')expect(prompt).toContain('Acceptance criteria')diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.jsindex 7a22f76463..4bbfce1bf2 100644--- a/server/services/taskScheduleRegistry.js+++ b/server/services/taskScheduleRegistry.js@@ -342,7 +342,7 @@ export const DEFAULT_TASK_INTERVALS = {// enabled run doesn't flood the tracker with plans — one filed plan per run.// runAfter do-replan so proposals are checked against the freshest available// work tracker before a new feature plan is filed.- 'plan-feature': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['do-replan'], taskMetadata: { useWorktree: false, openPR: false, readOnly: false } },+ 'plan-feature': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, dataInputs: ['product-requirements', 'project-goals', 'open-issues', 'open-pull-requests', 'closed-unmerged-pull-requests'], runAfter: ['do-replan'], taskMetadata: { useWorktree: false, openPR: false, readOnly: false } },// layered-intelligence is a programmatic-I/O task (agent-backed, hooked). Daily// by default; per-app scheduling (enabled/interval/provider/model) is set in the// Intelligence tab and stored on the app's taskTypeOverrides['layered-intelligence'].