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
enforce audit file-issues vs implement mode from one catalog posture through task generation (#6380)
[._.]/ Adam Eivy3bb9a626aa91
diff --git a/server/lib/README.md b/server/lib/README.mdindex b86eabb088..dbab766c2c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -66,7 +66,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. || `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request: `normalizeQuotaBurnProvenance` (family + burn-step id required, plus the limiting-window reset and the provider/model/effort overrides) and `quotaBurnTaskMetadata`, the single spread both on-demand engines apply so a reference-dispatched burn stamps the same `quotaBurnFamily` / `quotaBurnLimitingResetAt` keys the retired direct executor did. Import-light on purpose — `taskScheduleConstants.js` declares the origin string and must not drag the quota-burn config graph. || `quotaBurnPresets.js` | `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`. |-| `auditCatalog.js` | Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. `isFileIssuesMode`, `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. |+| `auditCatalog.js` | Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. `isFileIssuesMode`, `isExplicitFileIssuesRequest`, `FILE_ISSUES_DELIVERY_SETTINGS` (the one delivery posture every file-issues lane stamps), `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. || `quotaBurnTaskRef.js` | The quota-burn STEP model: a discriminated scheduled-task reference (`builtin` task type + validated target app, or `custom` app-job id whose own scope is authoritative) plus the per-invocation `overrides` bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). `normalizeQuotaBurnTaskRef` / `normalizeQuotaBurnOverrides` / `normalizeQuotaBurnParams`, the `QUOTA_BURN_UNAVAILABLE` reason codes, `resolveQuotaBurnStepAvailability` (catalog passed IN, so this stays pure) / `applyQuotaBurnAvailability`, and `quotaBurnStepIsDispatchable`. || `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). || `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. |diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.jsindex 332f2ba754..cdd20db5e4 100644--- a/server/lib/auditCatalog.js+++ b/server/lib/auditCatalog.js@@ -354,11 +354,28 @@ export function auditDoWorkRequiresWorktree(taskType) {return AUDIT_DEFINITIONS[taskType]?.doWorkRequiresWorktree === true;}+/**+ * The dispatch's own `fileIssues` answer, or `null` when it did not give one.+ *+ * Three-valued on purpose: absent is NOT "off". The catalog default only+ * applies to the absent case, and an explicit `false` on a type that defaults+ * to filing has to survive as a real "implement" choice. Accepts the+ * `'true'`/`'false'` string forms for parity with other metadata gates that+ * round-trip through TASKS.md as text.+ *+ * @param {Record<string, unknown>} [metadata] - Task metadata object+ * @returns {boolean|null} The explicit choice, or null when the key is absent+ */+function explicitFileIssues(metadata) {+ const raw = metadata?.fileIssues;+ if (raw === true || raw === 'true') return true;+ if (raw === false || raw === 'false') return false;+ return null;+}+/*** Effective file-issues mode for a dispatch. An explicit `fileIssues` boolean* on the merged task metadata wins; otherwise the catalog default applies.- * Accepts the `'true'`/`'false'` string forms for parity with other metadata- * gates that round-trip through TASKS.md as text.** @param {string} taskType - Task type identifier* @param {Record<string, unknown>} [metadata] - Task metadata object@@ -366,12 +383,58 @@ export function auditDoWorkRequiresWorktree(taskType) {*/export function isFileIssuesMode(taskType, metadata) {if (!isAuditTaskType(taskType)) return false;- const raw = metadata?.fileIssues;- if (raw === true || raw === 'true') return true;- if (raw === false || raw === 'false') return false;- return defaultFileIssuesFor(taskType);+ return explicitFileIssues(metadata) ?? defaultFileIssuesFor(taskType);}+/**+ * Whether a dispatch EXPLICITLY asked for file-issues delivery — the lane for+ * work that has no catalog default to fall back on.+ *+ * A custom app job is user-authored: nothing in this catalog knows what it+ * audits, so there is no default to consult and opting in is the only way a+ * custom agent task can carry the posture. Deliberately separate from+ * `isFileIssuesMode`, which stays gated on the catalog so a non-audit built-in+ * (`claim-issue`, `user-action-review`) cannot acquire the audit posture from a+ * `fileIssues` key it uses to mean something else.+ *+ * @param {Record<string, unknown>} [metadata] - Task metadata object+ * @returns {boolean} True only when the dispatch itself asked to file issues+ */+export function isExplicitFileIssuesRequest(metadata) {+ return explicitFileIssues(metadata) === true;+}++/**+ * The task-metadata posture a file-issues dispatch runs with, in ONE place.+ *+ * These flags are what actually enforce the mode: the banner is text a+ * model may argue with, but `noCodeOutput` is what routes the prompt through+ * `buildActionOutputCompletionSection` — stripping every commit/push/PR/+ * auto-merge instruction — and what makes `declaresNoCommitCriterion` stop+ * scoring a diff-free run as a failure (`services/taskTypeHooks.js`), so an+ * issues-only run can neither be told to ship code nor be failed and retried+ * for not shipping any. `useWorktree: false` keeps `openPR: false` from+ * meaning the AUTO-MERGE posture, and `simplify: false` drops a step that+ * presupposes a diff.+ *+ * `fileIssues` rides along so the persisted task states the mode it ran in+ * rather than leaving readers to re-derive it from a catalog default that may+ * have changed since.+ *+ * Every lane stamps THIS object — the scheduled audit generator and the custom+ * agent job generator — so the two cannot drift into separate postures.+ * `worktreeChangesExpected` is deliberately NOT here: the PLAN.md tracker files+ * by committing checklist items, so its file-issues run legitimately leaves a+ * dirty tree, and that flag is derived per dispatch from the resolved tracker.+ */+export const FILE_ISSUES_DELIVERY_SETTINGS = Object.freeze({+ fileIssues: true,+ noCodeOutput: true,+ useWorktree: false,+ openPR: false,+ simplify: false,+});+/*** Retrieve filing preset configuration for an audit task type.*diff --git a/server/lib/auditCatalog.test.js b/server/lib/auditCatalog.test.jsindex e6a6785819..6f39054c81 100644--- a/server/lib/auditCatalog.test.js+++ b/server/lib/auditCatalog.test.js@@ -9,6 +9,8 @@ import {defaultFileIssuesFor,auditDoWorkRequiresWorktree,isFileIssuesMode,+ isExplicitFileIssuesRequest,+ FILE_ISSUES_DELIVERY_SETTINGS,getAuditFilingPreset,modeContractFor,applyAuditModeWrapper,@@ -33,6 +35,28 @@ describe('AUDIT_DEFINITIONS', () => {}});+ // The REVERSE of the mapping above. The forward direction stops a new burn+ // preset landing without a scheduled counterpart; this one stops a `quotaBurnId`+ // that names a preset which was renamed or deleted. Once the presets are+ // compatibility-only inputs to the migration, a dangling id here is invisible+ // — nothing dereferences it at runtime — so only a test can catch it.+ it('every non-null quotaBurnId names a preset that exists', () => {+ const presetIds = new Set(QUOTA_BURN_PROMPT_PRESETS.map((preset) => preset.id));+ const referenced = Object.entries(AUDIT_DEFINITIONS)+ .filter(([, def]) => def.quotaBurnId != null);+ // Guards the guard: an accidental `quotaBurnId: null` sweep would make the+ // loop below vacuous while still passing.+ expect(referenced.length).toBeGreaterThan(0);+ for (const [taskType, def] of referenced) {+ expect(presetIds.has(def.quotaBurnId), `${taskType} → unknown preset "${def.quotaBurnId}"`).toBe(true);+ }+ });++ it('never points two audit types at the same burn preset', () => {+ const ids = Object.values(AUDIT_DEFINITIONS).map((def) => def.quotaBurnId).filter(Boolean);+ expect(new Set(ids).size).toBe(ids.length);+ });+it('defaults new audit types to file-issues and existing do-work types to implement', () => {expect(defaultFileIssuesFor('ux')).toBe(true);expect(defaultFileIssuesFor('data-safety')).toBe(true);@@ -68,6 +92,66 @@ describe('isFileIssuesMode', () => {expect(isFileIssuesMode('security', {})).toBe(false);expect(isFileIssuesMode('data-safety', null)).toBe(true);});++ // The override a migrated issues-only burn step writes: an explicit `true`+ // has to beat a shipped scheduled default of `false`, or migrating an+ // issues-only burn preset onto `security` would silently convert it into+ // code-writing work.+ it('an explicit true beats a shipped false default', () => {+ expect(defaultFileIssuesFor('security')).toBe(false);+ expect(isFileIssuesMode('security', { fileIssues: true })).toBe(true);+ expect(isFileIssuesMode('performance', { fileIssues: 'true' })).toBe(true);+ });+});++describe('isExplicitFileIssuesRequest', () => {+ it('is true only when the dispatch itself asked — absent is not off, and not on', () => {+ expect(isExplicitFileIssuesRequest({ fileIssues: true })).toBe(true);+ expect(isExplicitFileIssuesRequest({ fileIssues: 'true' })).toBe(true);+ expect(isExplicitFileIssuesRequest({ fileIssues: false })).toBe(false);+ expect(isExplicitFileIssuesRequest({})).toBe(false);+ expect(isExplicitFileIssuesRequest(null)).toBe(false);+ });++ // The custom-agent-job lane reads it without a task type, so it must not be+ // gated on the catalog the way isFileIssuesMode is.+ it('is type-agnostic — a custom job has no catalog entry to default from', () => {+ expect(isAuditTaskType('my-custom-job')).toBe(false);+ expect(isFileIssuesMode('my-custom-job', { fileIssues: true })).toBe(false);+ expect(isExplicitFileIssuesRequest({ fileIssues: true })).toBe(true);+ });+});++describe('FILE_ISSUES_DELIVERY_SETTINGS', () => {+ it('is the whole posture, frozen — every flag that could ship code is off', () => {+ expect(FILE_ISSUES_DELIVERY_SETTINGS).toEqual({+ fileIssues: true,+ noCodeOutput: true,+ useWorktree: false,+ openPR: false,+ simplify: false,+ });+ expect(Object.isFrozen(FILE_ISSUES_DELIVERY_SETTINGS)).toBe(true);+ });++ // `worktreeChangesExpected` is derived per dispatch from the RESOLVED tracker:+ // a PLAN.md tracker files by committing checklist items, so its file-issues+ // run legitimately leaves a dirty tree. Baking `false` in here would score+ // every one of those successful runs as a missed deliverable (#3102).+ it('does not pin worktreeChangesExpected — the resolved tracker owns it', () => {+ expect(FILE_ISSUES_DELIVERY_SETTINGS).not.toHaveProperty('worktreeChangesExpected');+ });++ // The legacy burn presets are the OTHER definition of this posture (their+ // `AUDIT_PARAMS`, copied into a job at pick time). They stay compatibility-only+ // inputs to the migration, so they are not deduped into this constant — but+ // they must not disagree with it while both exist.+ it('agrees with the legacy quota-burn audit presets', () => {+ const { fileIssues: _fileIssues, ...runShape } = FILE_ISSUES_DELIVERY_SETTINGS;+ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {+ expect(preset.params, preset.id).toMatchObject(runShape);+ }+ });});describe('mode contracts + wrapper', () => {diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 18f18dd26b..33910f5829 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -466,6 +466,14 @@ export const createCosJobSchema = z.object({// PortOS-owned audits may succeed after proving the branch is empty; the// finalizer still requires the forge/no-commit proof before honoring this.noChangeSuccess: z.boolean().optional(),+ // Opt a custom AGENT job into file-issues delivery. A custom job is+ // user-authored, so unlike a built-in audit type it has no catalog default+ // — the explicit flag IS the opt-in, and `generateTaskFromJob` turns it+ // into the shared posture from lib/auditCatalog.js+ // (`FILE_ISSUES_DELIVERY_SETTINGS`), overriding the code-shipping+ // useWorktree/openPR/simplify keys above. Zod strips unknown keys, so+ // without this row the flag never survives a job create/update.+ fileIssues: z.boolean().optional(),}).optional(),});diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 86d0ac1779..ad7ff7105c 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -205,7 +205,18 @@ describe('deferred imports stay deferred (#6156)', () => {// `avatarStyles.js` in from the client tree). Each is one extra NODE on a path// that already existed — a flatter graph, not a new eager edge into a heavy// subtree. Fits inside the allowance above.-const MAX_STATIC_INSTANTIATIONS = 91400;+//+// #6380 measures 91,710 — the ~1.5k allowance restored at #6377 is spent, so+// re-measure and restore it rather than inching. The +371 is ONE new suite,+// `services/cosTaskGenerator.auditMode.test.js`, and its cost IS its point: it+// generates a real audit task through `cosTaskGenerator.js` (274) and renders+// the final agent prompt from it through `agentPromptBuilder.js` (+94+// marginal), because the file-issues mode is enforced across exactly that seam+// and neither half alone can prove an issues-only run cannot acquire+// commit/push/PR instructions. No new eager edge into a heavy subtree: the+// production change adds only `lib/auditCatalog.js` (a zero-import leaf) to+// `autonomousJobs/skillTemplates.js`, worth 2.+const MAX_STATIC_INSTANTIATIONS = 93200;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);const serverTestFiles = (dir = SERVER_DIR, out = []) => {diff --git a/server/services/autonomousJobs/skillTemplates.js b/server/services/autonomousJobs/skillTemplates.jsindex 8e9c1accae..c57197d4fc 100644--- a/server/services/autonomousJobs/skillTemplates.js+++ b/server/services/autonomousJobs/skillTemplates.js@@ -11,6 +11,7 @@ import { ensureDir, PATHS, tryReadFile, writeFileGuarded } from '../../lib/fileUimport { JOBS_SKILLS_DIR, JOB_SKILL_MAP } from './constants.js'import { getAppById } from '../apps.js'import { appendTaskDataInputs, resolveTaskDataInputs } from '../taskDataInputs.js'+import { FILE_ISSUES_DELIVERY_SETTINGS, isExplicitFileIssuesRequest } from '../../lib/auditCatalog.js'/*** Load a job skill template from disk@@ -186,7 +187,15 @@ async function generateTaskFromJob(job) {// Reasoning-effort override — agentLifecycle reads metadata.effort and the// spawn builders emit `--effort`/`-c model_reasoning_effort=` (no-op for// non-effort providers). Absent = provider default.- ...(job.effort ? { effort: job.effort } : {})+ ...(job.effort ? { effort: job.effort } : {}),+ // File-issues delivery, from the SAME catalog object a scheduled audit+ // stamps (`lib/auditCatalog.js`) rather than a second definition of the+ // mode. A custom job is user-authored, so there is no catalog default to+ // consult — it is opt-in, and the opt-in is the explicit `fileIssues`+ // flag on the job's own taskMetadata. Stamped LAST so it wins over the+ // useWorktree/openPR/simplify forwards above: those describe a+ // code-shipping run, which is exactly what this mode is not.+ ...(isExplicitFileIssuesRequest(meta) ? FILE_ISSUES_DELIVERY_SETTINGS : {})},taskType: 'internal',autoApprove: job.autonomyLevel === 'yolo'diff --git a/server/services/cos.js b/server/services/cos.jsindex 042316a847..0cf349050e 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -1063,7 +1063,13 @@ async function spawnDequeuePriority0OnDemand(ctx) {skipPreconditions: true,deferPerpetualDispatch: true,targetPullRequest: request.targetPullRequest ?? null,- providerOverride: request.providerOverride ?? null+ providerOverride: request.providerOverride ?? null,+ // Mirrors the sibling engine in cosTaskGenerator.js#spawnPriority0OnDemand+ // — either may drain any given request, so a quota-burn step's run+ // parameters have to reach the generator from both or the mode a+ // migrated issues-only step pinned depends on which engine got there+ // first.+ runOverrides: request.burn?.overrides?.params ?? null});if (task) {await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.jsnew file mode 100644index 0000000000..be655773cb--- /dev/null+++ b/server/services/cosTaskGenerator.auditMode.test.js@@ -0,0 +1,368 @@+/**+ * The generated-task/prompt BOUNDARY for the file-issues vs implement audit mode (#6380).+ *+ * Every other test of this contract stops at `isFileIssuesMode` or at the task+ * metadata. Neither proves the thing that actually matters: that an issues-only+ * run cannot ACQUIRE code-shipping instructions. The mode is enforced two hops+ * apart — the generator stamps `FILE_ISSUES_DELIVERY_SETTINGS`, and the prompt+ * builder reads `noCodeOutput` off that stamp to pick a completion contract — so+ * a change on either side can quietly re-arm `/do:push` on an audit that was+ * only ever supposed to file issues.+ *+ * This suite closes both hops: it GENERATES the real task for every audit type+ * in the catalog and RENDERS the final agent prompt from it, then asserts that+ * no commit/push/PR/auto-merge directive survives — and that the same pipeline+ * in implement mode still emits the ordinary code-delivery workflow, so the+ * assertions cannot pass by rendering nothing.+ *+ * Isolated file for the same reason `cosTaskGenerator.referenceWatch.test.js`+ * is: the mocked leaf graph (taskSchedule / taskPromptService / appActivity)+ * must not leak into the shared cosTaskGenerator suite.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++// A stand-in for a shipped audit template. Deliberately WITHOUT+// `{modeInstructions}`: that is the customized-stored-prompt shape, where the+// banner has to be PREPENDED or flipping the mode would be a silent no-op on+// any install whose user edited the prompt.+const AUDIT_TEMPLATE = [+ '# Audit {appName}',+ '',+ 'Repository: {repoPath}',+ '',+ 'Fix what you find and commit it.',+ '',+ '## Where to record findings',+ '',+ '{trackerInstructions}',+].join('\n');++// The other shape: a template that still carries the token, so the generator+// substitutes rather than prepends.+const AUDIT_TEMPLATE_WITH_TOKEN = [+ '# Audit {appName}',+ '',+ '{modeInstructions}',+ '',+ '{trackerInstructions}',+].join('\n');++const promptTemplate = vi.hoisted(() => ({ body: null }));++vi.mock('./taskPromptService.js', () => ({+ getTaskPrompt: vi.fn(async () => promptTemplate.body),+ getStagePrompt: vi.fn(async () => promptTemplate.body),+}));++vi.mock('./taskSchedule.js', () => ({+ INTERVAL_TYPES: { PERPETUAL: 'perpetual', WEEKLY: 'weekly' },+ getTaskInterval: vi.fn(async () => ({ type: 'weekly', taskMetadata: {} })),+ stripManagedAgentOptionsFromOverride: vi.fn((_type, meta) => meta),+ recordExecution: vi.fn(async () => {}),+ parkPerpetual: vi.fn(async () => {}),+ getPerpetualDrainState: vi.fn(async () => ({ signature: null, dispatchCount: 0 })),+ recordPerpetualDispatch: vi.fn(async () => 1),+}));++vi.mock('./appActivity.js', async (importActual) => ({+ ...(await importActual()),+ updateAppActivity: vi.fn(async () => {}),+}));++vi.mock('./apps.js', async (importActual) => ({+ ...(await importActual()),+ getAppTaskTypeOverrides: vi.fn(async () => ({})),+}));++vi.mock('./codeReview.js', async (importActual) => ({+ ...(await importActual()),+ getCodeReviewDefaults: vi.fn(async () => ({ reviewers: ['codex'], usernames: [], optionalReviewers: [] })),+}));++vi.mock('./taskLearning.js', async (importActual) => ({+ ...(await importActual()),+ getTaskTypeConfidence: vi.fn(async () => ({ autoApprove: true, tier: 'high', reason: 'test' })),+}));++// Keeps the real tracker resolver but stops it shelling out `git remote get-url`+// against the fixture repoPath.+vi.mock('../lib/gitRemote.js', async (importActual) => ({+ ...(await importActual()),+ readOriginRemoteUrl: vi.fn(async () => null),+}));++import { generateManagedAppImprovementTaskForType } from './cosTaskGenerator.js';+import { generateTaskFromJob } from './autonomousJobs/skillTemplates.js';+import { buildLightContextPrompt } from './agentPromptBuilder.js';+import { declaresNoCommitCriterion } from './taskTypeHooks.js';+import { isTruthyMeta } from './agentState.js';+import {+ AUDIT_TASK_TYPES,+ FILE_ISSUES_DELIVERY_SETTINGS,+ defaultFileIssuesFor,+ isFileIssuesMode,+} from '../lib/auditCatalog.js';+import { isProgrammaticScheduledTaskType, PROGRAMMATIC_SCHEDULED_TASK_TYPES } from '../lib/taskTargetScope.js';++const AUDIT_TYPES = [...AUDIT_TASK_TYPES];+const WORKSPACE = '/tmp/example-repo';++const makeApp = (overrides = {}) => ({+ id: 'app-1',+ name: 'Example App',+ repoPath: WORKSPACE,+ workTracker: 'github',+ referenceRepos: [],+ ...overrides,+});++const STATE = { config: { confidenceAutoApproval: { enabled: false }, idleReviewPriority: 'MEDIUM' } };++/** The ordinary scheduled lane. */+const generate = (taskType, options = {}) =>+ generateManagedAppImprovementTaskForType(taskType, makeApp(), STATE, options);++/**+ * The FINAL text an agent sees: the rendered mission plus the operating+ * contract the prompt builder derives from the task's settings. `tui`/`cli`+ * providers are the ones a scheduled audit actually runs on, and they all take+ * this path — a mode enforced only in the api-path builder would be no+ * enforcement at all.+ */+const renderPrompt = (task) =>+ `${task.description}\n\n${buildLightContextPrompt(task, WORKSPACE, null, isTruthyMeta, { isTui: true })}`;++/**+ * Affirmative code-delivery directives. Matched as numbered workflow STEPS and+ * section headers rather than bare substrings on purpose: the no-code+ * completion section names `/do:push`, `git commit` and "open a pull request"+ * inside its own PROHIBITION, and a naive `toContain` would fire on the very+ * text that enforces the mode.+ */+const CODE_DELIVERY_DIRECTIVES = [+ ['completion-workflow header', /^## Completion Workflow$/m],+ ['run-these-in-order preamble', /When the task is complete, run these in order:/],+ ['/do:push step', /^\s*\d+\.\s+`\/do:push/m],+ ['/do:pr step', /^\s*\d+\.\s+`\/do:pr/m],+ ['/simplify step', /^\s*\d+\.\s+`\/simplify`/m],+ ['git commit step', /^\s*\d+\..*`git commit/m],+ ['git push step', /^\s*\d+\..*`git push/m],+ ['PR merge step', /`gh pr merge|`glab mr merge/],+ ['auto-merge handoff', /merged back to the source branch/],+ ['open-a-PR handoff', /the system will push your branch and open a pull request/],+];++const expectNoCodeDelivery = (prompt, label) => {+ for (const [name, pattern] of CODE_DELIVERY_DIRECTIVES) {+ expect(pattern.test(prompt), `${label}: emitted a ${name}`).toBe(false);+ }+};++describe('issues-only audit dispatch never acquires code-shipping instructions (#6380)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ promptTemplate.body = AUDIT_TEMPLATE;+ });++ it.each(AUDIT_TYPES)('%s — file-issues mode renders no commit/push/PR/auto-merge directive', async (taskType) => {+ const { getTaskInterval } = await import('./taskSchedule.js');+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues: true } });++ const task = await generate(taskType);+ expect(task, taskType).not.toBeNull();+ expect(task.metadata).toMatchObject(FILE_ISSUES_DELIVERY_SETTINGS);++ const prompt = renderPrompt(task);+ expectNoCodeDelivery(prompt, taskType);+ // Positive control: the file-issues contract IS what rendered, so the+ // negatives above are not passing on an empty or truncated prompt.+ expect(prompt).toContain('Mode: file issues, change nothing');+ expect(prompt).toContain('## Completion (No Code Output)');+ expect(prompt).not.toContain('{modeInstructions}');+ expect(prompt).not.toContain('{trackerInstructions}');+ });++ it.each(AUDIT_TYPES)('%s — a diff-free run is not a failure, so nothing retries it', async (taskType) => {+ const { getTaskInterval } = await import('./taskSchedule.js');+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues: true } });++ const task = await generate(taskType);+ // The mechanism, not a phrasing: `declaresNoCommitCriterion` is the gate+ // agentFinalization consults before scoring a clean tree as a miss (and+ // before the failure ledger can park or retry the type).+ expect(declaresNoCommitCriterion(task), taskType).toBe(true);+ });++ it.each(AUDIT_TYPES)('%s — implement mode keeps the normal code-delivery settings', async (taskType) => {+ const { getTaskInterval } = await import('./taskSchedule.js');+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues: false, simplify: true } });++ const task = await generate(taskType);+ expect(task, taskType).not.toBeNull();+ expect(task.metadata.fileIssues).toBe(false);+ expect(task.metadata.noCodeOutput).toBeUndefined();+ expect(task.metadata.simplify).toBe(true);+ expect(declaresNoCommitCriterion(task), taskType).toBe(false);++ const prompt = renderPrompt(task);+ expect(prompt).toContain('Mode: implement the highest-value fix');+ expect(prompt).toMatch(/^## Completion Workflow$/m);+ expect(prompt).toMatch(/^\s*\d+\.\s+`\/do:push/m);+ });++ it('substitutes the banner into a template that still carries {modeInstructions}', async () => {+ promptTemplate.body = AUDIT_TEMPLATE_WITH_TOKEN;+ const { getTaskInterval } = await import('./taskSchedule.js');+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues: true } });++ const prompt = renderPrompt(await generate('security'));+ expect(prompt).toContain('Mode: file issues, change nothing');+ expect(prompt).not.toContain('{modeInstructions}');+ expectNoCodeDelivery(prompt, 'security/{modeInstructions}');+ });+});++/**+ * A custom app job is the OTHER agent lane a quota burn may invoke. It has no+ * catalog entry, so file-issues delivery is opt-in — but when it opts in it+ * must land the SAME posture, from the same object, or "issues only" would mean+ * two different things depending on which lane ran.+ */+describe('eligible custom agent task honors the same file-issues contract', () => {+ const job = (taskMetadata) => ({+ id: 'job-1',+ name: 'Example audit job',+ category: 'audit',+ priority: 'MEDIUM',+ autonomyLevel: 'yolo',+ promptTemplate: 'Audit the example slice and file what you find.',+ appId: 'app-1',+ taskMetadata,+ });++ it('stamps the shared delivery posture and renders no code-delivery directive', async () => {+ const generated = await generateTaskFromJob(job({ fileIssues: true, useWorktree: true, openPR: true, simplify: true }));+ expect(generated.metadata).toMatchObject(FILE_ISSUES_DELIVERY_SETTINGS);+ // The opt-in OVERRIDES the job's own code-shipping toggles rather than+ // landing beside them — a task that both files issues and opens a PR is the+ // contradiction this contract exists to make unrepresentable.+ expect(generated.metadata.useWorktree).toBe(false);+ expect(generated.metadata.openPR).toBe(false);+ expect(generated.metadata.simplify).toBe(false);++ const task = { ...generated, description: generated.metadata.prompt };+ expect(declaresNoCommitCriterion(task)).toBe(true);+ expectNoCodeDelivery(renderPrompt(task), 'custom agent job');+ });++ it('leaves a job that did not opt in on its normal code-delivery policy', async () => {+ const generated = await generateTaskFromJob(job({ useWorktree: true, openPR: true, simplify: true }));+ expect(generated.metadata.fileIssues).toBeUndefined();+ expect(generated.metadata.noCodeOutput).toBeUndefined();+ expect(generated.metadata.useWorktree).toBe(true);+ expect(generated.metadata.openPR).toBe(true);+ });+});++/**+ * The mode is a property of the TASK, not of who invoked it. All three lanes+ * reach the same generator; a burn additionally carries per-invocation run+ * parameters, which is the only legitimate difference between them.+ */+describe('mode is honored identically from schedule, manual run, and quota burn', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ promptTemplate.body = AUDIT_TEMPLATE;+ });++ it.each([+ ['ordinary schedule', {}],+ ['manual run / on-demand', { skipPreconditions: true, deferPerpetualDispatch: true, targetPullRequest: null, runOverrides: null }],+ ['quota burn (no param override)', { skipPreconditions: true, deferPerpetualDispatch: true, targetPullRequest: null, runOverrides: {} }],+ ])('%s renders the same file-issues prompt and settings', async (_lane, options) => {+ const { getTaskInterval } = await import('./taskSchedule.js');+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues: true } });++ const task = await generate('ux', options);+ expect(task.metadata).toMatchObject(FILE_ISSUES_DELIVERY_SETTINGS);+ expectNoCodeDelivery(renderPrompt(task), _lane);+ });++ it("a burn step's explicit true beats a shipped scheduled default of false", async () => {+ const { getTaskInterval } = await import('./taskSchedule.js');+ // `security` ships defaulting to IMPLEMENT, and this schedule says nothing —+ // exactly the install a migrated issues-only burn step lands on.+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: {} });+ expect(defaultFileIssuesFor('security')).toBe(false);++ const withoutOverride = await generate('security', { skipPreconditions: true });+ expect(withoutOverride.metadata.noCodeOutput).toBeUndefined();++ const burned = await generate('security', { skipPreconditions: true, runOverrides: { fileIssues: true } });+ expect(burned.metadata).toMatchObject(FILE_ISSUES_DELIVERY_SETTINGS);+ expectNoCodeDelivery(renderPrompt(burned), 'burn override');+ });++ it("a burn step's explicit false beats a shipped scheduled default of true", async () => {+ const { getTaskInterval } = await import('./taskSchedule.js');+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: {} });+ expect(defaultFileIssuesFor('ux')).toBe(true);++ const task = await generate('ux', { skipPreconditions: true, runOverrides: { fileIssues: false } });+ expect(task.metadata.fileIssues).toBe(false);+ expect(task.metadata.noCodeOutput).toBeUndefined();+ expect(task.description).toContain('Mode: implement the highest-value fix');+ });++ it('run overrides pass the same allowlist a stored override does', async () => {+ const { getTaskInterval } = await import('./taskSchedule.js');+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues: true } });++ const task = await generate('ux', { skipPreconditions: true, runOverrides: { fileIssues: true, notARealFlag: true } });+ expect(task.metadata.fileIssues).toBe(true);+ expect(task.metadata.notARealFlag).toBeUndefined();+ });++ // Both on-demand engines may drain any given request (see+ // `onDemandRequestMetadata`), so a burn's run parameters have to be forwarded+ // from BOTH or the mode a migrated step pinned would depend on which engine+ // got there first. Asserted at the source because the two engines are a+ // deliberate mirror and only their agreement is the invariant.+ it('both on-demand engines forward the burn step run parameters', async () => {+ const { readFile } = await import('fs/promises');+ const { PATHS } = await import('../lib/fileUtils.js');+ for (const file of ['server/services/cosTaskGenerator.js', 'server/services/cos.js']) {+ const source = await readFile(`${PATHS.root}/${file}`, 'utf8');+ expect(source, file).toContain('runOverrides: request.burn?.overrides?.params ?? null');+ }+ });+});++/**+ * The programmatic scheduled handlers (description/image generation) do the work+ * themselves — there is no agent to instruct, so "file issues instead" is not a+ * mode they can honor. They must therefore expose no toggle to turn on.+ */+describe('programmatic scheduled handlers expose no issues-only toggle', () => {+ it('none of them is an audit type, so no mode banner or default reaches them', () => {+ expect(PROGRAMMATIC_SCHEDULED_TASK_TYPES.length).toBeGreaterThan(0);+ for (const taskType of PROGRAMMATIC_SCHEDULED_TASK_TYPES) {+ expect(AUDIT_TASK_TYPES.has(taskType), taskType).toBe(false);+ expect(defaultFileIssuesFor(taskType), taskType).toBe(false);+ // Even a hand-edited schedule cannot switch one on: the catalog gate in+ // `isFileIssuesMode` refuses a type it does not own.+ expect(isFileIssuesMode(taskType, { fileIssues: true }), taskType).toBe(false);+ // `getScheduleStatus` sets the UI's `fileIssuesCapable` flag for exactly+ // two shapes — an audit-catalog type (ruled out above) and the+ // `user-action-review` carve-out — so the toggle cannot render for these.+ expect(taskType).not.toBe('user-action-review');+ }+ });++ it('no programmatic handler is registered in the audit catalog', () => {+ for (const taskType of AUDIT_TYPES) {+ expect(isProgrammaticScheduledTaskType(taskType), taskType).toBe(false);+ }+ });+});diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 54d14862e5..4b8d03ca0a 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -58,6 +58,7 @@ import {auditDoWorkRequiresWorktree,modeContractFor,applyAuditModeWrapper,+ FILE_ISSUES_DELIVERY_SETTINGS,} from '../lib/auditCatalog.js';import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';import { ServerError } from '../lib/errorHandler.js';@@ -840,7 +841,16 @@ async function spawnPriority0OnDemand(ctx) {skipPreconditions: true,deferPerpetualDispatch: true,targetPullRequest: request.targetPullRequest ?? null,- providerOverride: request.providerOverride ?? null+ providerOverride: request.providerOverride ?? null,+ // A quota-burn step's per-invocation run parameters. They must reach+ // the PROMPT, so unlike the provider/model/effort pins they cannot+ // ride the post-generation `onDemandRequestMetadata` stamp below —+ // the generator overlays them before it picks the mode banner.+ // `normalizeQuotaBurnProvenance` (lib/quotaBurnOrigin.js) has to keep+ // `overrides.params` for a step to reach this; it drops them today,+ // so a burn currently runs the task's SAVED mode, which is correct+ // for every step until the migration starts pinning one.+ runOverrides: request.burn?.overrides?.params ?? null});if (task) {await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);@@ -2963,7 +2973,8 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stdeferPerpetualDispatch = false,targetPullRequest = null,// Per-request provider/model/effort pin — see applyProviderModelPins.- providerOverride = null+ providerOverride = null,+ runOverrides = null} = {}) {const { updateAppActivity } = await import('./appActivity.js');const taskSchedule = await import('./taskSchedule.js');@@ -2997,6 +3008,24 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stconst appOverride = appOverrides[taskType] || null;const metadata = buildImprovementTaskMetadata(taskType, app, interval, taskSchedule, appOverride);+ // Per-INVOCATION run parameters, layered on top of the schedule + per-app+ // metadata the task saved. A quota-burn step is the caller that needs them: a+ // step migrated from an issues-only burn preset pins `fileIssues: true`+ // explicitly, so it keeps filing even against an audit type whose shipped+ // scheduled default is `false` — migration must never silently turn an+ // issues-only burn into code-writing work.+ //+ // It has to land HERE, before the mode decision and the prompt render below.+ // The post-generation stamp both on-demand engines apply+ // (`onDemandRequestMetadata`) is far too late: by then the banner is chosen+ // and the description is built, so a `fileIssues` arriving there would flip+ // the flag while the agent still read a "fix and commit" prompt.+ //+ // Sanitized through the SAME allowlist the schedule and per-app overrides+ // pass, so an invocation can carry nothing a stored override could not.+ const sanitizedRunMeta = sanitizeTaskMetadata(runOverrides);+ if (sanitizedRunMeta) Object.assign(metadata, sanitizedRunMeta);+if (taskType === 'pr-reviewer') ensurePrReviewerPipeline(metadata);initializePipelineMetadata(metadata);const securityPreflight = await runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest, taskSchedule);@@ -3149,11 +3178,10 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// File-issues posture wins over app worktree/PR defaults — the deliverable// is tracker items, so a managed worktree or an implied PR is the wrong shape.if (fileIssues) {- metadata.fileIssues = true;- metadata.noCodeOutput = true;- metadata.useWorktree = false;- metadata.openPR = false;- metadata.simplify = false;+ // The catalog's one delivery posture, stamped rather than restated — the+ // custom-job lane (autonomousJobs/skillTemplates.js) applies this same+ // object, so the two cannot drift into different definitions of the mode.+ Object.assign(metadata, FILE_ISSUES_DELIVERY_SETTINGS);} else if (auditDoWorkRequiresWorktree(taskType)) {// Some structural audits are safe to remediate only in isolation. Enforce// this after schedule/app defaults so a stale file-issues toggle transitiondiff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex d97ad058cc..b9d44a6887 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -322,7 +322,12 @@ describe('isConfiguredApprovalRequired', () => {const selfStart = GEN_SRC.indexOf('export async function generateSelfImprovementTaskForType');const appStart = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');expect(GEN_SRC.slice(selfStart, appStart)).toContain('stampApprovalReason(metadata, approval)');- expect(GEN_SRC.slice(appStart, appStart + 12000)).toContain('stampApprovalReason(metadata, approval)');+ // Bounded by the function's own `return task;` rather than a character+ // count: a magic window makes this guard fire on any commit that adds a+ // comment above the stamp, which says nothing about whether the stamp is+ // still there.+ const appBody = GEN_SRC.slice(appStart, GEN_SRC.indexOf('\n return task;', appStart));+ expect(appBody).toContain('stampApprovalReason(metadata, approval)');});it('the PortOS self-improvement lane resolves and appends configured data inputs', () => {