Skip to content

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

feat(cos): schedule every do:better audit lens as its own self-improvement task

[._.]/ Adam Eivy69669f4a5455
diff --git a/docs/README.md b/docs/README.md
index 5d1b8719e3..937613f09b 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -40,7 +40,7 @@ Start with the [product surface map](./features/product-surfaces.md) for a compl
App management: [app-wizard](./features/app-wizard.md) · [autofixer](./features/autofixer.md) · [browser](./features/browser.md) · [error-handling](./features/error-handling.md) · [jira-sprint-manager](./features/jira-sprint-manager.md)
-Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [grok-box-local-mind](./features/grok-box-local-mind.md) · [fleet-llm-host](./features/fleet-llm-host.md) · [mtplx](./features/mtplx.md) · [slotstream](./features/slotstream.md) · [dflash2](./features/dflash2.md) ([DSpark vs DFlash 2](./research/2026-08-19-dspark-vs-dflash2.md)) · [qwen38-rtx3090](./features/qwen38-rtx3090.md) ([3090 bring-up](./research/2026-08-21-qwen38-rtx3090-vllm.md)) · [sglang-qwen38](./features/sglang-qwen38.md) ([SGLang Hopper/Blackwell evaluation](./research/2026-08-21-sglang-qwen38-27b.md)) · [prompt-manager](./features/prompt-manager.md)
+Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [self-improvement-audits](./features/self-improvement-audits.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [grok-box-local-mind](./features/grok-box-local-mind.md) · [fleet-llm-host](./features/fleet-llm-host.md) · [mtplx](./features/mtplx.md) · [slotstream](./features/slotstream.md) · [dflash2](./features/dflash2.md) ([DSpark vs DFlash 2](./research/2026-08-19-dspark-vs-dflash2.md)) · [qwen38-rtx3090](./features/qwen38-rtx3090.md) ([3090 bring-up](./research/2026-08-21-qwen38-rtx3090-vllm.md)) · [sglang-qwen38](./features/sglang-qwen38.md) ([SGLang Hopper/Blackwell evaluation](./research/2026-08-21-sglang-qwen38-27b.md)) · [prompt-manager](./features/prompt-manager.md)
- [Persistent Mind continuous play + local context](./features/persistent-mind-continuous-play.md) — explore/invent playbook and mind-adjustable `numCtx` clamps
Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system](./features/identity-system.md) · [soul-system](./features/soul-system.md) · [privacy-center](./features/privacy-center.md) · [post](./features/post.md) (insights design spike: [plans/2026-06-03](./plans/2026-06-03-cross-domain-insights-engine.md))
diff --git a/docs/features/self-improvement-audits.md b/docs/features/self-improvement-audits.md
new file mode 100644
index 0000000000..6dc2357449
--- /dev/null
+++ b/docs/features/self-improvement-audits.md
@@ -0,0 +1,103 @@
+# Self-improvement audits
+
+PortOS ships one scheduled task per category of software quality. Each is an
+**audit lane**: it reads a managed app (PortOS included), and either files
+decision-complete tracker items or implements a fix — a per-task toggle, not two
+different tasks.
+
+Configure them in **CoS → Schedule**. Every lane is on-demand and enabled by
+default, so a fresh install spends nothing until you press Run or pick a cadence
+(the AI Provider Usage Policy in `AGENTS.md`).
+
+Registry: `server/lib/auditCatalog.js` (what each lane is and how it files),
+`server/services/taskScheduleRegistry.js` (cadence and posture),
+`server/services/taskPromptDefaults/prompts.js` (the mission bodies).
+
+## The lanes
+
+`Mode` is the shipped default. `Isolated` marks lanes whose remediation must run
+in a managed worktree — a mechanical restructuring of hot code must never land in
+the operator's live checkout.
+
+| Task type | Owns | Files under | Mode | Isolated |
+|---|---|---|---|---|
+| `security` | Exposure real under the app's own threat model | `security` | implement | |
+| `code-quality` | Conventional maintainability defects | `code-quality` | implement | |
+| `test-coverage` | Untested behavior worth covering | `tests` | implement | |
+| `performance` | Provably wasted work on a hot path | `performance` | implement | |
+| `accessibility` | Keyboard, screen-reader, contrast, zoom barriers | `accessibility` | implement | |
+| `documentation` | Docs that are wrong, then docs that are missing | `documentation` | implement | |
+| `ui-bugs` | Things that are broken in the running interface | `bug` | implement | |
+| `mobile-responsive` | Small-screen and touch usability | `mobile` | implement | |
+| `error-handling` | Failure paths, timeouts, retries, degraded fallback | `resilience` | implement | |
+| `typing` | Type contracts at boundaries | `code-quality` | implement | |
+| `console-errors` | What the app actually emits while running | `bug` | implement | |
+| `ux` | Whether a user can get the job done | `ux` | file | |
+| `data-safety` | Migrations, schema parity, cross-version safety | `data-safety` | file | |
+| `simplify` | Dead code, duplication, YAGNI | `code-quality` | file | |
+| `module-hygiene` | Responsibility boundaries, reuse, discoverability | `code-quality` | file | yes |
+| `api-contract` | Route validation, client/server drift, envelopes | `api-contract` | file | |
+| `react-lifecycle` | Effect teardown, stale closures, render races | `react-lifecycle` | file | |
+| `observability` | Silent catches, log noise, missing error context | `code-quality` | file | |
+| `copy` | User-facing wording | `ux` | file | |
+| `better-complexity` | Counted branching per function | `code-quality` | file | yes |
+| `better-cognitive-load` | Reader cost no metric captures | `code-quality` | file | yes |
+| `better-structural-drift` | The same fact kept in two places | `code-quality` | file | yes |
+| `better-runtime-safety` | Latent defects not yet triggered | `bug` | file | |
+| `better-dependency-freedom` | Whether a dependency should exist at all | `dependencies` | file | yes |
+| `better-test-quality` | Existing tests that prove nothing | `tests` | file | |
+
+## Why the boundaries are explicit
+
+Twenty-five lanes only pay off if they do not file each other's findings. Every
+mission body names what it cedes and to whom, so two lanes cannot both claim one
+problem:
+
+- **Complexity is split three ways.** `better-complexity` owns *counted*
+ branching and must report the number. `better-cognitive-load` owns reader cost
+ that no metric captures — mixed abstraction levels, flag arguments, names that
+ lie. `module-hygiene` owns responsibility boundaries and treats a complexity
+ score only as a candidate signal, never as a finding.
+- **Duplication is split two ways.** `simplify` owns copy-paste and dead code.
+ `better-structural-drift` owns a derived artifact or hand-synced registry acting
+ as a second source of truth, which is a different fix (derive it, or add the
+ parity check).
+- **Defects are split four ways.** `better-runtime-safety` reads source for
+ latent defects; `console-errors` collects what actually errors at runtime;
+ `error-handling` owns the failure path once something goes wrong; and
+ `react-lifecycle` owns component effects.
+- **Tests are split two ways.** `test-coverage` owns the gaps;
+ `better-test-quality` owns the tests that already exist.
+
+## The `better-` prefix and slashdo parity
+
+The `better-` lanes mirror an audit lens from the bundled slashdo `/do:better`
+command (`lib/slashdo/lib/better-audit.md`). That command fans every lens out to
+sub-agents inside a single run; these task types expose the same lenses
+individually, so each can be scheduled, pinned to its own provider and model, and
+toggled between filing and fixing on its own.
+
+The prefix marks a **parity obligation**: when one of these missions improves,
+the improvement is a candidate to push upstream to slashdo rather than to let the
+two definitions drift. `DO_BETTER_LENS_COVERAGE` in `server/lib/auditCatalog.js`
+records which lane owns each lens, and `auditCatalog.test.js` reads the bundled
+submodule and fails when a lens declared upstream has no lane here — so a
+category added to slashdo cannot silently become unschedulable in PortOS.
+
+The prefix is spelled with a hyphen rather than `better:` because a task type is
+interpolated into the CoS task id, which becomes a git branch name
+(`cos/<taskId>/<agentId>`) and a worktree directory. Git refs reject a colon,
+Windows paths reject a colon, and the `TASKS.md` id pattern accepts only word
+characters and hyphens.
+
+## Filing and mode
+
+`fileIssues` decides the deliverable, and the banner injected at
+`{modeInstructions}` is what enforces it — overriding any instruction in the
+body. In file-issues mode the dispatch also stamps `noCodeOutput`, so a run that
+produces no diff is not scored as a failure.
+
+Findings go to whichever tracker the app resolves to — a `PLAN.md` checklist
+item, a GitHub or GitLab issue, or a JIRA ticket — via `{trackerInstructions}`.
+Each lane carries a slug prefix so repeat runs deduplicate against their own
+history instead of re-filing.
diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.js
index cdd20db5e4..0cfd258ef3 100644
--- a/server/lib/auditCatalog.js
+++ b/server/lib/auditCatalog.js
@@ -319,6 +319,98 @@ export const AUDIT_DEFINITIONS = Object.freeze({
noun: 'copy finding(s)',
}),
},
+ // The six types below give every `do:better` audit lens a scheduled
+ // counterpart (DO_BETTER_LENS_COVERAGE, at the bottom of this file). They
+ // are refactor- or defect-hunting lanes carved out of the broader
+ // code-quality / module-hygiene / test-coverage bodies so each can be
+ // scheduled, pinned to a provider, and toggled between filing and fixing on
+ // its own. Every one files under an existing label rather than minting a
+ // near-duplicate category, and the refactor lanes require a managed
+ // worktree in do-work mode: a mechanical restructuring of a hot function or
+ // a dependency swap is exactly the edit that must never land in the user's
+ // live checkout.
+ 'better-complexity': {
+ quotaBurnId: null,
+ label: 'Cyclomatic complexity',
+ description: 'Complexity-reduction audit — configurable: file issues (default) or implement one refactor',
+ defaultFileIssues: true,
+ doWorkRequiresWorktree: true,
+ filing: filing({
+ slugPrefix: 'complexity-',
+ label: 'complexity-audit',
+ issueLabel: 'code-quality',
+ labelDescription: 'Proposed from a cyclomatic-complexity audit',
+ noun: 'complexity finding(s)',
+ }),
+ },
+ 'better-cognitive-load': {
+ quotaBurnId: null,
+ label: 'Cognitive load & readability',
+ description: 'Reader-cost audit — configurable: file issues (default) or implement one refactor',
+ defaultFileIssues: true,
+ doWorkRequiresWorktree: true,
+ filing: filing({
+ slugPrefix: 'cognitive-load-',
+ label: 'cognitive-load-audit',
+ issueLabel: 'code-quality',
+ labelDescription: 'Proposed from a cognitive-load/readability audit',
+ noun: 'cognitive-load finding(s)',
+ }),
+ },
+ 'better-structural-drift': {
+ quotaBurnId: null,
+ label: 'Structural drift & sources of truth',
+ description: 'Generated-artifact / hand-synced-registry drift audit — configurable: file issues (default) or implement one consolidation',
+ defaultFileIssues: true,
+ doWorkRequiresWorktree: true,
+ filing: filing({
+ slugPrefix: 'structural-drift-',
+ label: 'structural-drift-audit',
+ issueLabel: 'code-quality',
+ labelDescription: 'Proposed from a structural-drift audit',
+ noun: 'structural-drift finding(s)',
+ }),
+ },
+ 'better-runtime-safety': {
+ quotaBurnId: null,
+ label: 'Runtime safety & async correctness',
+ description: 'Latent-defect audit — configurable: file issues (default) or implement fixes',
+ defaultFileIssues: true,
+ filing: filing({
+ slugPrefix: 'runtime-safety-',
+ label: 'runtime-safety-audit',
+ issueLabel: 'bug',
+ labelDescription: 'Proposed from a runtime-safety audit',
+ noun: 'runtime-safety finding(s)',
+ }),
+ },
+ 'better-dependency-freedom': {
+ quotaBurnId: null,
+ label: 'Dependency freedom',
+ description: 'Dependency-necessity audit — configurable: file issues (default) or implement one removal',
+ defaultFileIssues: true,
+ doWorkRequiresWorktree: true,
+ filing: filing({
+ slugPrefix: 'depfree-',
+ label: 'dependency-freedom-audit',
+ issueLabel: 'dependencies',
+ labelDescription: 'Proposed from a dependency-freedom audit',
+ noun: 'dependency finding(s)',
+ }),
+ },
+ 'better-test-quality': {
+ quotaBurnId: null,
+ label: 'Test quality',
+ description: 'Vacuous/weak/redundant-test audit — configurable: file issues (default) or implement one cleanup',
+ defaultFileIssues: true,
+ filing: filing({
+ slugPrefix: 'test-quality-',
+ label: 'test-quality-audit',
+ issueLabel: 'tests',
+ labelDescription: 'Proposed from a test-quality audit',
+ noun: 'test-quality finding(s)',
+ }),
+ },
});
export const AUDIT_TASK_TYPES = new Set(Object.keys(AUDIT_DEFINITIONS));
@@ -470,3 +562,31 @@ export function applyAuditModeWrapper(promptTemplate, modeInstructions) {
if (prompt.includes('{modeInstructions}')) return prompt;
return `${modeInstructions}\n\n---\n\n${prompt}`;
}
+
+/**
+ * Which scheduled audit types cover each `do:better` audit lens
+ * (lib/slashdo/lib/better-audit.md, the `For \`<lens>\`:` list). The slashdo
+ * command fans the same lenses out to sub-agents in one run; PortOS exposes
+ * each as its own schedulable, provider-pinnable task so a managed app can run
+ * every category of self-improvement on its own cadence. Keys are the lens
+ * slugs slashdo uses; values are the AUDIT_DEFINITIONS types that own that
+ * lens's findings — the first entry is the primary owner.
+ *
+ * auditCatalog.test.js checks this map two ways: every listed type is a real
+ * audit type, and (when the submodule is checked out) every lens slashdo
+ * declares has an entry here — so a lens added upstream cannot silently go
+ * unscheduled.
+ */
+export const DO_BETTER_LENS_COVERAGE = Object.freeze({
+ security: ['security'],
+ 'code-quality': ['code-quality', 'observability'],
+ dry: ['simplify'],
+ architecture: ['module-hygiene', 'api-contract'],
+ 'bugs-perf': ['better-runtime-safety', 'performance', 'error-handling', 'observability'],
+ 'stack-specific': ['react-lifecycle', 'accessibility', 'data-safety', 'security'],
+ deps: ['better-dependency-freedom', 'security'],
+ tests: ['test-coverage', 'better-test-quality'],
+ ux: ['ux', 'mobile-responsive', 'copy'],
+ structural: ['module-hygiene', 'better-structural-drift', 'simplify'],
+ 'cognitive-load': ['better-cognitive-load', 'better-complexity'],
+});
diff --git a/server/lib/auditCatalog.test.js b/server/lib/auditCatalog.test.js
index 6f39054c81..fdd8202b64 100644
--- a/server/lib/auditCatalog.test.js
+++ b/server/lib/auditCatalog.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import { QUOTA_BURN_PROMPT_PRESETS } from './quotaBurnPresets.js';
+import { requireSlashdoSubmoduleInCi } from './testHelper.js';
import {
AUDIT_DEFINITIONS,
AUDIT_TASK_TYPES,
@@ -14,6 +15,7 @@ import {
getAuditFilingPreset,
modeContractFor,
applyAuditModeWrapper,
+ DO_BETTER_LENS_COVERAGE,
} from './auditCatalog.js';
describe('AUDIT_DEFINITIONS', () => {
@@ -199,3 +201,44 @@ describe('getAuditFilingPreset', () => {
expect(AUDIT_TASK_TYPES).toEqual(new Set(Object.keys(AUDIT_DEFINITIONS)));
});
});
+
+// The `better-*` audit types exist to give each slashdo `do:better` audit lens
+// a schedulable counterpart. The coverage map is the contract between the two,
+// and it only means anything if both halves are checked: that every type it
+// names is real, and that every lens upstream declares is actually named.
+describe('DO_BETTER_LENS_COVERAGE', () => {
+ it('names only registered audit types, primary owner first', () => {
+ for (const [lens, owners] of Object.entries(DO_BETTER_LENS_COVERAGE)) {
+ expect(Array.isArray(owners) && owners.length, lens).toBeTruthy();
+ for (const owner of owners) {
+ expect(AUDIT_TASK_TYPES.has(owner), `${lens} -> ${owner}`).toBe(true);
+ }
+ expect(new Set(owners).size, `${lens} lists a duplicate owner`).toBe(owners.length);
+ }
+ });
+
+ it('gives every better-prefixed audit type a lens to be in parity with', () => {
+ const covered = new Set(Object.values(DO_BETTER_LENS_COVERAGE).flat());
+ const orphaned = [...AUDIT_TASK_TYPES]
+ .filter((type) => type.startsWith('better-') && !covered.has(type));
+ expect(orphaned).toEqual([]);
+ });
+
+ // Reads the bundled submodule when it is initialized. A lens added upstream
+ // with no entry here is a category of app quality that silently became
+ // unschedulable — exactly the gap these task types were added to close.
+ it('covers every lens the bundled do:better command declares', async () => {
+ const { existsSync, readFileSync } = await import('fs');
+ const auditRef = new URL('../../lib/slashdo/lib/better-audit.md', import.meta.url);
+ if (!existsSync(auditRef)) {
+ requireSlashdoSubmoduleInCi(false);
+ return;
+ }
+ const body = readFileSync(auditRef, 'utf8');
+ // Each lens is introduced as: For `<slug>`:
+ const declared = [...body.matchAll(/^For `([a-z-]+)`:/gm)].map(([, slug]) => slug);
+ expect(declared.length).toBeGreaterThan(5);
+ const missing = declared.filter((lens) => !DO_BETTER_LENS_COVERAGE[lens]);
+ expect(missing).toEqual([]);
+ });
+});
diff --git a/server/lib/workTracker.trackerInstructions.test.js b/server/lib/workTracker.trackerInstructions.test.js
index d1f174b56a..85234c246e 100644
--- a/server/lib/workTracker.trackerInstructions.test.js
+++ b/server/lib/workTracker.trackerInstructions.test.js
@@ -144,19 +144,60 @@ describe('formatTrackerInstructions — ux preset (#3273)', () => {
});
// The SHIPPED prompt (not the generator's mocked stand-in) must fully expand:
- // the tracker block is injected FIRST precisely because it carries {appName}/
- // {repoPath} of its own, and a token that survives reaches the agent literally.
+ // a token that survives reaches the agent literally. The substitution order
+ // below MIRRORS buildImprovementTaskDescription and is load-bearing — the
+ // file-issues mode contract carries a {trackerInstructions} of its own, and
+ // the injected tracker block carries {appName}/{repoPath} of its own. Run in
+ // any other order and a real dispatch ships a literal placeholder.
it('leaves no unexpanded {token} in the shipped ux prompt on any tracker', async () => {
const { DEFAULT_TASK_PROMPTS } = await import('../services/taskPromptDefaults.js');
+ const { modeContractFor } = await import('./auditCatalog.js');
const template = DEFAULT_TASK_PROMPTS['ux'];
expect(template).toContain('{trackerInstructions}');
+ expect(template).toContain('{modeInstructions}');
for (const tracker of ['plan', 'github', 'gitlab', 'jira']) {
- const rendered = template
- .replace(/\{trackerInstructions\}/g, () => formatTrackerInstructions(tracker, ux))
- .replace(/\{appName\}/g, () => 'Example App')
- .replace(/\{repoPath\}/g, () => '/tmp/example-repo');
- expect(rendered.match(/\{[a-zA-Z][a-zA-Z0-9_]*\}/g)).toBeNull();
+ for (const fileIssues of [true, false]) {
+ const rendered = template
+ .replace(/\{modeInstructions\}/g, () => modeContractFor(fileIssues))
+ .replace(/\{trackerInstructions\}/g, () => formatTrackerInstructions(tracker, ux))
+ .replace(/\{appName\}/g, () => 'Example App')
+ .replace(/\{repoPath\}/g, () => '/tmp/example-repo');
+ expect(rendered.match(/\{[a-zA-Z][a-zA-Z0-9_]*\}/g), `${tracker} fileIssues=${fileIssues}`).toBeNull();
+ }
+ }
+ });
+
+ // The same contract for EVERY audit lane, not just ux. Each one is dispatched
+ // through the identical chain, so one prompt that introduces a placeholder the
+ // generator does not substitute ships that literal text to the agent — and the
+ // failure is invisible until someone reads a run's transcript. Cheap to assert
+ // across the whole catalog, and it covers each new lane on the day it is added.
+ it('leaves no unexpanded {token} in ANY shipped audit prompt, in either mode', async () => {
+ const { DEFAULT_TASK_PROMPTS } = await import('../services/taskPromptDefaults.js');
+ const { AUDIT_TASK_TYPES, modeContractFor, getAuditFilingPreset } = await import('./auditCatalog.js');
+
+ expect(AUDIT_TASK_TYPES.size).toBeGreaterThan(1);
+ for (const taskType of AUDIT_TASK_TYPES) {
+ const template = DEFAULT_TASK_PROMPTS[taskType];
+ expect(template, taskType).toBeTruthy();
+ for (const tracker of ['plan', 'github', 'gitlab', 'jira']) {
+ for (const fileIssues of [true, false]) {
+ // Do-work mode resolves {trackerInstructions} to empty, exactly as
+ // resolveTrackerFilingBlock does when an audit is not filing.
+ const rendered = template
+ .replace(/\{modeInstructions\}/g, () => modeContractFor(fileIssues))
+ .replace(/\{trackerInstructions\}/g, () => (
+ fileIssues ? formatTrackerInstructions(tracker, getAuditFilingPreset(taskType)) : ''
+ ))
+ .replace(/\{appName\}/g, () => 'Example App')
+ .replace(/\{repoPath\}/g, () => '/tmp/example-repo');
+ expect(
+ rendered.match(/\{[a-zA-Z][a-zA-Z0-9_]*\}/g),
+ `${taskType} on ${tracker} fileIssues=${fileIssues}`,
+ ).toBeNull();
+ }
+ }
}
});
});
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 03b64f218a..840e712d03 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -176,6 +176,44 @@ describe('composable skill template routing', () => {
},
);
+ // A registered audit type is authoritative about what it is, so it must never
+ // fall through to the description keyword matcher. That matcher cannot read
+ // an audit correctly: the security template claims the bare word "audit",
+ // which every audit prompt says about itself in its opening line, so eleven of
+ // nineteen audit types were being handed OWASP scoping guidance the operator
+ // never chose — copy, typing, api-contract, ux and the rest. Ordinary
+ // vocabulary misroutes the others just as easily: an audit that mentions
+ // duplication while explicitly ceding it to a sibling drew the dead-code
+ // template. The correct answer for an audit type with no template of its own
+ // is NO lifecycle template, not a guess.
+ it('never keyword-guesses a lifecycle template for a registered audit type', async () => {
+ const { AUDIT_TASK_TYPES } = await import('../lib/auditCatalog.js');
+ const SKILLED = { security: 'security-audit', 'mobile-responsive': 'mobile-responsive', documentation: 'documentation', 'data-safety': 'data-safety', simplify: 'simplify', 'module-hygiene': 'module-hygiene' };
+
+ for (const taskType of AUDIT_TASK_TYPES) {
+ // The real dispatched body, which is what the matcher actually sees.
+ const description = DEFAULT_TASK_PROMPTS[taskType]
+ .replaceAll('{appName}', 'Example App')
+ .replaceAll('{repoPath}', '/workspace/example-app')
+ .replace('{modeInstructions}', '## Mode: file issues, change nothing');
+ const routed = detectSkillTemplates(makeTask({ description, metadata: { analysisType: taskType } }));
+ expect(routed, taskType).toEqual(SKILLED[taskType] ? [SKILLED[taskType]] : []);
+ }
+ });
+
+ it('still keyword-matches a free-text task, which is what the fallback is for', () => {
+ // No task type — an operator-written task keeps the keyword routing.
+ expect(detectSkillTemplates(makeTask({
+ description: 'Fix the broken avatar upload crash',
+ }))).toEqual(['bug-fix']);
+ // An unregistered type falls through to keywords rather than resolving to
+ // no template, so a custom job is unaffected by the audit-type gate.
+ expect(detectSkillTemplates(makeTask({
+ description: 'Refactor the export pipeline',
+ metadata: { analysisType: 'custom-app-job' },
+ }))).toEqual(['refactor']);
+ });
+
it('joins templates in routing order and tolerates an unavailable domain guide', async () => {
const loadTemplate = vi.fn(async (name) => ({
'security-audit': 'Security lifecycle guidance',
diff --git a/server/services/promptSections/instructions.js b/server/services/promptSections/instructions.js
index daafeeaebd..cb1a186493 100644
--- a/server/services/promptSections/instructions.js
+++ b/server/services/promptSections/instructions.js
@@ -7,6 +7,7 @@ import { readdir } from 'fs/promises';
import { homedir } from 'os';
import { PATHS, tryReadFile } from '../../lib/fileUtils.js';
import { AGENT_INSTRUCTIONS_FILENAME, CLAUDE_BRIDGE_FILENAME } from '../../lib/agentInstructionsFile.js';
+import { isAuditTaskType } from '../../lib/auditCatalog.js';
const SKILLS_DIR = join(PATHS.root, 'data/prompts/skills');
@@ -59,6 +60,24 @@ const TASK_TYPE_SKILL_ALIASES = Object.freeze({
security: 'security-audit',
});
+/**
+ * A registered audit type carries its whole method in its own prompt body and
+ * is therefore AUTHORITATIVE about what it is — so when it has no template of
+ * its own, the answer is "no lifecycle template", not "guess from the words".
+ *
+ * The keyword fallback below exists for free-text user tasks, and it cannot
+ * read an audit correctly: the `security-audit` matcher claims the bare word
+ * `audit`, which every audit prompt says about itself in its first line. That
+ * silently spliced OWASP scoping guidance into the copy, typing, api-contract,
+ * react-lifecycle, observability, ux, accessibility, ui-bugs, console-errors,
+ * error-handling and test-coverage audits — eleven of nineteen at the time this
+ * gate was added. Ordinary vocabulary misroutes the rest just as easily: an
+ * audit that mentions "duplication" while ceding it to a sibling drew the
+ * dead-code template, and one that mentions the module-hygiene work drew that
+ * one. Every case reads as a template the operator never chose.
+ */
+const NO_LIFECYCLE_SKILL = Symbol('no-lifecycle-skill');
+
const skillForTaskType = (task) => {
const taskTypes = [
task?.metadata?.analysisType,
@@ -72,6 +91,7 @@ const skillForTaskType = (task) => {
return TASK_TYPE_SKILL_ALIASES[normalized];
}
if (SKILL_NAMES.has(normalized)) return normalized;
+ if (isAuditTaskType(normalized)) return NO_LIFECYCLE_SKILL;
}
return null;
};
@@ -98,6 +118,7 @@ const DOMAIN_SKILL_MATCHERS = [
*/
export function detectSkillTemplate(task) {
const taskTypeSkill = skillForTaskType(task);
+ if (taskTypeSkill === NO_LIFECYCLE_SKILL) return null;
if (taskTypeSkill) return taskTypeSkill;
const desc = (task?.description || '').toLowerCase();
diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.js
index 7fef4ec40f..f949847277 100644
--- a/server/services/taskPromptDefaults.test.js
+++ b/server/services/taskPromptDefaults.test.js
@@ -68,14 +68,58 @@ describe('taskPromptDefaults integrity snapshot', () => {
expect(current).not.toMatch(/localhost|:\d{4}/);
});
- it('code-quality v3 inventories structural drift', () => {
+ // The structural-drift hunts moved OUT of code-quality in v4 and into the
+ // `better-structural-drift` lane, which owns them alone. Both halves are
+ // asserted so the split cannot silently collapse back into one prompt or,
+ // worse, leave the hunts in neither.
+ it('code-quality v4 keeps conventional defects and cedes drift to its sibling lanes', () => {
const current = DEFAULT_TASK_PROMPTS['code-quality'];
- expect(PROMPT_VERSIONS['code-quality']).toBe(3);
+ expect(PROMPT_VERSIONS['code-quality']).toBe(4);
+ // Still its own: the conventional maintainability defects.
+ expect(current).toContain('Brittle conditionals');
+ expect(current).toContain('Unexplained magic values');
+ expect(current).toContain('Dead and unreachable code');
+ expect(current).toContain('Convention violations');
+ // Ceded, by name, so a run does not file another lane's finding.
+ expect(current).toContain('structural-drift work');
+ expect(current).toContain('cognitive-load work');
+ expect(current).toContain('module-hygiene work');
+ // The drift hunts themselves are gone from this body.
+ expect(current).not.toContain('Derived artifacts committed as a second source of truth');
+ expect(current).not.toContain('regeneration-only churn');
+ });
+
+ it('better-structural-drift owns the hunts code-quality gave up', () => {
+ const current = DEFAULT_TASK_PROMPTS['better-structural-drift'];
+
+ expect(PROMPT_VERSIONS['better-structural-drift']).toBe(1);
expect(current).toContain('Derived artifacts committed as a second source of truth');
- expect(current).toContain('volatile line/column/offset');
- expect(current).toContain('regeneration-only churn');
+ // Case-insensitive: the phrase carries the concept whether it heads the
+ // evidence recipe or appears in prose, and pinning the casing would break
+ // on an edit that changes neither.
+ expect(current.toLowerCase()).toContain('regeneration-only churn');
expect(current).toContain('Incidental-layout coupling');
+ // Position-keyed records are the specific failure that makes a committed
+ // manifest conflict on every rebase; it must survive the move.
+ expect(current).toContain('Position-keyed records');
+ expect(current).toContain('line number, column, byte offset');
+ });
+
+ // Each `better-*` lane mirrors one slashdo do:better audit lens. The bodies
+ // are what make them worth scheduling separately, so each is pinned to the
+ // discipline that distinguishes it from its neighbors — a counted metric, a
+ // proof obligation, or an explicit hand-off — rather than to prose.
+ it.each([
+ ['better-complexity', ['1 + the number of independent decision points', 'Length is not complexity', 'Name the transformation', 'Behavior preservation is the contract']],
+ ['better-cognitive-load', ['reader cost', 'Flag arguments', 'Action at a distance', 'are not your findings']],
+ ['better-runtime-safety', ['Sentinel confusion', 'a failure scenario, not a code shape', 'Not yours']],
+ ['better-dependency-freedom', ['Acceptable', 'Suspect', 'Removable', 'Respect documented decisions', 'file no version bumps here']],
+ ['better-test-quality', ['Vacuous', 'mutation probe', 'Deletion is a valid outcome', 'Missing coverage is separate work']],
+ ])('%s states the discipline that makes it its own lane', (key, markers) => {
+ const current = DEFAULT_TASK_PROMPTS[key];
+ expect(PROMPT_VERSIONS[key]).toBe(1);
+ for (const marker of markers) expect(current, key).toContain(marker);
});
it('claim workflows avoid Copilot and require verified remote merge state before cleanup', () => {
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index 20d3b344e6..62216036bb 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -1,31 +1,37 @@
{
"DEFAULT_TASK_PROMPTS": {
- "accessibility": "372916803f32b82da38a5b2130a54baf",
+ "accessibility": "76cfcab471c1a555767b71b8b9932ae0",
"api-contract": "cf02b10a5993baf473e0d320771f26b6",
+ "better-cognitive-load": "a1fe22f6ef936131456c55a6b0623204",
+ "better-complexity": "c92b99080d0453d70bb26a412fb48ce9",
+ "better-dependency-freedom": "8a79c8be829f926bbc7720ee29818d53",
+ "better-runtime-safety": "4259ab85dd3eaf8efb16a250187bd857",
+ "better-structural-drift": "941389a1f1c8983eef4f87af1241fbf9",
+ "better-test-quality": "ab53a477cd194a5c4fbda09d901a3775",
"branch-cleanup": "8fdeb4acc2749816a47ca318b6602721",
"branch-reconcile": "44281269863b3133696fdebe9b558256",
"claim-issue": "5600fde65e31874bd96c3ad83ce72a92",
"claim-issue-gitlab": "bb83608738b6517f3f05df116994a6fd",
"claim-issue-jira": "b14a5dde5519fda59c2ba1ae7a3d8989",
- "code-quality": "c34792a374dd9868e6381557da582dc1",
+ "code-quality": "6762542233cdffb86d4e2244945bf52b",
"code-reviewer-implement": "2e10cac7c1e1cd021d06bfddb5c1eaf2",
"code-reviewer-review": "27ded42013f28e7d327d8f1cc624aac1",
- "console-errors": "2b6ed595287f0742bed9ecba6788afe6",
+ "console-errors": "eec33a9293f9393019917a6632dd964e",
"copy": "6a0959e898d37fb4d4d7445dfc8008c9",
"data-safety": "86b07f51abdbcbe7016f840b5bb0cd9b",
"dependency-updates": "1d59f04bea630a85a3085829db8599e7",
"do-replan": "35660eb7b43e4259a6a9253ed288a1db",
- "documentation": "246be4932c277fa0ec0ab365beb3baad",
- "error-handling": "9afba2e99b90a8d5771c75e7f0615d96",
+ "documentation": "a30e3bfba8cd13369ccaf806a3534a79",
+ "error-handling": "137b371f38398042c0a2c7e2279c92ce",
"feature-ideas": "804f62f1dadadbfa8a0bcd4aff16b2e8",
"issue-reconcile": "53e068c533e989ae31025fdfd4a3ecf9",
"jira-sprint-manager": "3e63c8a3bdf0d5a05a30faaa2dc07980",
"jira-status-report": "9d374a9d8ccb92c5c8fd0aa9899e79a5",
- "mobile-responsive": "16d8e7f63a673a2de48994c0ac08ef3d",
+ "mobile-responsive": "eb7f6b307bccd15199c74d7aff5c21c3",
"model-comparison-refresh": "dc1702b07c7fb8be6165feb776d5acb6",
"module-hygiene": "3b7671cd44f719d4b2116b96a279e6d0",
"observability": "fdb4d77df5891cfb653a5da2553ecf8a",
- "performance": "672bd3958b12afb0f382bcebb6dc3b33",
+ "performance": "d7e3a80f42903fbf90be0efc9b559c0b",
"plan-feature": "87f71a894757f89354da4e2119e07118",
"plan-task": "b85fe92999aa4ee4a8910320457c4242",
"plan-task-claim": "910802d67f3b5a785f068f4d90178543",
@@ -39,41 +45,47 @@
"refresh-local-llm-catalog": "9741ca6a8419fcdea2743e3b64781a8b",
"release-check": "5a82eec9f86ad05185ed77a42dbfd9d4",
"repo-sync": "0a648d35d43b023b758226b9c709c8ea",
- "security": "8e58c1305a391ac765b0b13ab9615eb3",
+ "security": "c5e35a12eeb06e6afe4617f4428fa1ab",
"simplify": "2a048214d1dd3b75bee9ae1a38fa1589",
"stash-cleanup": "1c12bac5aac6bb27008c40981e7db08c",
- "test-coverage": "0d8359170529da12cd63356610b2e220",
- "typing": "1f2758ce0bb62d789a21aec241549531",
- "ui-bugs": "def9ad96bd74ab397233f234d79a1974",
+ "test-coverage": "36beffc0c2959be5d818ded54b3fe298",
+ "typing": "bd7cb874b2784395280b116369c7e7ac",
+ "ui-bugs": "073bea13a94b0266c53b5f55bb2344b9",
"user-action-review": "1a083430e43f60cdd586cfffbdebc583",
- "ux": "e03d03fc7c16faa5b5db93be2896b9ad"
+ "ux": "ac11f692eae40ffe8ddeaeaccbcf75e9"
},
"PROMPT_VERSIONS": {
- "accessibility": 2,
+ "accessibility": 3,
"api-contract": 1,
+ "better-cognitive-load": 1,
+ "better-complexity": 1,
+ "better-dependency-freedom": 1,
+ "better-runtime-safety": 1,
+ "better-structural-drift": 1,
+ "better-test-quality": 1,
"branch-reconcile": 5,
"claim-issue": 25,
"claim-issue-gitlab": 22,
"claim-issue-jira": 16,
- "code-quality": 3,
+ "code-quality": 4,
"code-reviewer-a": 1,
"code-reviewer-b": 1,
- "console-errors": 2,
+ "console-errors": 3,
"copy": 1,
"data-safety": 1,
"dependency-updates": 4,
"do-replan": 2,
- "documentation": 6,
- "error-handling": 2,
+ "documentation": 7,
+ "error-handling": 3,
"feature-ideas": 11,
"issue-reconcile": 5,
"jira-sprint-manager": 1,
"jira-status-report": 1,
- "mobile-responsive": 2,
+ "mobile-responsive": 3,
"model-comparison-refresh": 1,
"module-hygiene": 1,
"observability": 1,
- "performance": 2,
+ "performance": 3,
"plan-feature": 5,
"plan-task": 18,
"pr-reviewer": 5,
@@ -83,20 +95,21 @@
"refresh-local-llm-catalog": 4,
"release-check": 13,
"repo-sync": 1,
- "security": 2,
+ "security": 3,
"simplify": 1,
"stash-cleanup": 2,
- "test-coverage": 2,
- "typing": 2,
- "ui-bugs": 2,
+ "test-coverage": 3,
+ "typing": 3,
+ "ui-bugs": 3,
"user-action-review": 2,
- "ux": 1
+ "ux": 2
},
"REFERENCE_WATCH_AUDITED_VERSION": 3,
"PREVIOUS_DEFAULT_PROMPTS": {
"accessibility": [
"ce7377d0ac57cbf0526074cfb95e3803",
- "b07cfe1e367411036ef1d4cc4b6e9d2e"
+ "b07cfe1e367411036ef1d4cc4b6e9d2e",
+ "372916803f32b82da38a5b2130a54baf"
],
"branch-reconcile": [
"7ef2b5f7d8f05937d4912b26ad45f42e",
@@ -172,11 +185,13 @@
],
"code-quality": [
"62752723eba7a39aa94e010911923cc8",
- "b1cce8f89218844746746ceb576553c1"
+ "b1cce8f89218844746746ceb576553c1",
+ "c34792a374dd9868e6381557da582dc1"
],
"console-errors": [
"23b1a2e33cb414f27d4002b51d315e83",
- "3e3f690729ead5e312927ae4bce330c0"
+ "3e3f690729ead5e312927ae4bce330c0",
+ "2b6ed595287f0742bed9ecba6788afe6"
],
"dependency-updates": [
"020d66b93698341c556eca1eee851bee",
@@ -193,10 +208,12 @@
"658395fa391df5a0fefaaebdf8dbedb7",
"751186658f5d9a9dbccdd6830946f3d8",
"74aa8433896647e7815f9d6d9e4a56c8",
- "b375f95ae2274f03d06ba5ceff5705d8"
+ "b375f95ae2274f03d06ba5ceff5705d8",
+ "246be4932c277fa0ec0ab365beb3baad"
],
"error-handling": [
- "26225ac04f2f35feb61151b2e6474465"
+ "26225ac04f2f35feb61151b2e6474465",
+ "9afba2e99b90a8d5771c75e7f0615d96"
],
"feature-ideas": [
"abc098e3acf4eb6b9d1211680ec0440f",
@@ -217,11 +234,13 @@
"a30f5d76b980bc9016f576047c9d5bb1"
],
"mobile-responsive": [
- "636bdc17fa39ed2f2e27623284c8e04c"
+ "636bdc17fa39ed2f2e27623284c8e04c",
+ "16d8e7f63a673a2de48994c0ac08ef3d"
],
"performance": [
"c8224243c15f6897ee04be25d172f021",
- "4fea5eb3585bdc150980934b289016bc"
+ "4fea5eb3585bdc150980934b289016bc",
+ "672bd3958b12afb0f382bcebb6dc3b33"
],
"plan-feature": [
"9fbc2a2ded8f4533d1f0f6b9cb780b34",
@@ -280,23 +299,30 @@
],
"security": [
"b199739b21a8c45ed3778b2339ebf55f",
- "d0f54c1fbe62d067b1a23ee0a9f3528c"
+ "d0f54c1fbe62d067b1a23ee0a9f3528c",
+ "8e58c1305a391ac765b0b13ab9615eb3"
],
"stash-cleanup": [
"f9de8b10937919ceb6656fbdb70179c4"
],
"test-coverage": [
"ec70fb2b8e193b6a98bec2fbf337b190",
- "c2b0f0dee5bc881239684e706ea88324"
+ "c2b0f0dee5bc881239684e706ea88324",
+ "0d8359170529da12cd63356610b2e220"
],
"typing": [
- "d8fd1423cf2a523b528ed7d2d7a2bb55"
+ "d8fd1423cf2a523b528ed7d2d7a2bb55",
+ "1f2758ce0bb62d789a21aec241549531"
],
"ui-bugs": [
- "01d2a7e034713195f33071f2c71a3c99"
+ "01d2a7e034713195f33071f2c71a3c99",
+ "def9ad96bd74ab397233f234d79a1974"
],
"user-action-review": [
"945a716d446d26a03e2805d28bd1ae16"
+ ],
+ "ux": [
+ "e03d03fc7c16faa5b5db93be2896b9ad"
]
}
}
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 9cfa83e6c5..dd55ff4e44 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -93,156 +93,300 @@ Every metric requires an HTTPS source URL, actual retrieval timestamp and method
Validate the complete candidate import using modelComparisonImportSchema via the documented validation command, then import with POST /api/providers/comparison/import. Reuse stable observation IDs for the same identity; create a new ID for a changed benchmark version/configuration. Partial research must preserve existing unrelated observations and newer evidence. On missing/unavailable sources, leave old metrics untouched. GET the catalog again and verify the imported observations before reporting success. Report refreshed count, remaining gaps and unavailable sources. Do not claim complete coverage or verified truth merely because schema validation passed.`,
'security': `[Improvement: {appName}] Security Audit
-Analyze the {appName} codebase for security vulnerabilities:
+Audit {appName} for security defects that are real under its actual threat
+model.
Repository: {repoPath}
-1. Review routes/controllers for:
- - Command injection in exec/spawn calls
- - Path traversal in file operations
- - Missing input validation
- - XSS vulnerabilities
- - SQL/NoSQL injection
-
-2. Review services for:
- - Unsafe eval() or Function()
- - Hardcoded credentials
- - Insecure dependencies
-
-3. Review client code for:
- - XSS vulnerabilities
- - Sensitive data in localStorage
- - CSRF protection
+{modeInstructions}
-4. Check authentication and authorization where applicable
+**Read the project's documented security model first and treat it as binding.**
+If it declares something a non-issue for this deployment — an omitted control, a
+documented default, an accepted risk — do not file it. A window spent re-filing
+an explicitly closed concern is worse than a window spent idle.
+
+## Hunt for
+
+- **Secrets in the wrong place** — credentials, tokens, or keys that could reach
+ a commit, a log line, a bundled client asset, a shared artifact, or an
+ outbound request that had no business carrying them.
+- **Injection** — user-controlled input reaching a shell, a query, a path join,
+ a dynamic import, or a template without validation; an allowlist a crafted
+ value can walk out of.
+- **Path traversal** — a filesystem path built from input that can escape its
+ intended root, including through symlinks and encoded separators.
+- **Missing authorization** — an endpoint or action that checks who you are but
+ not whether you may do this, or checks neither.
+- **Unvalidated trust boundaries that are actually crossed** — data arriving
+ from another machine, a third-party API, or a model response, used without
+ validation where a malformed or hostile value would do damage.
+- **Destructive operations with too little scoping** — a delete, overwrite, or
+ reset whose target is computed rather than constrained, especially where a
+ test or development path could aim it at real data.
+- **Client-side exposure** — untrusted content rendered as markup, sensitive
+ values placed in browser storage, secrets shipped in the client bundle.
+- **Dependency exposure** — a known-vulnerable package on a path that actually
+ processes untrusted input, not a transitive development-only advisory.
+
+## The bar
+
+Every finding needs a plausible attacker or accident story ending in real harm:
+who supplies the input, how it reaches the sink, and what they get. "Best
+practice says otherwise" is not one, and neither is a control whose absence the
+project's threat model already accounts for.
+
+Cite \`file:LINE\` for both the sink and the entry point that reaches it. Redact
+before you publish: never paste a real secret, token, hostname, address, or
+personal record into a finding — describe its shape and location instead.`,
+
+ 'code-quality': `[Improvement: {appName}] Code Quality Review
+
+Audit {appName} for maintainability defects that create real operational or
+engineering cost.
-Fix any vulnerabilities found and commit with security advisory notes.`,
+Repository: {repoPath}
- 'code-quality': `[Improvement: {appName}] Code Quality and Structural Drift Review
+{modeInstructions}
-Audit {appName} for maintainability failures that create real operational or
-engineering cost.
+Start with a cheap repository-wide inventory of candidates, then choose one
+bounded, coherent slice and trace it deeply.
+
+## Hunt for
+
+- **Brittle conditionals and hardcoded paths** — logic that works for the cases
+ it was written against and silently misbehaves just outside them: an
+ environment or platform assumption baked into a branch, a narrow
+ implementation that passes a specific case without being correct in general.
+- **Unexplained magic values** — a number, timeout, limit, or string literal
+ carrying meaning nothing states, especially one repeated across files.
+- **Test-shaped hacks in production code** — a branch that exists only to make a
+ test pass, an environment check gating real behavior, a stub left reachable.
+- **Dead and unreachable code** — unused imports and variables, a branch whose
+ condition can no longer occur, an option nothing sets.
+- **Convention violations** — code contradicting the conventions the repository
+ documents for itself. Read the project's own instruction files first and treat
+ them as binding, including the non-issues they explicitly declare.
+- **Stale TODOs and comments that lie** — a comment describing behavior the code
+ no longer has, or a TODO whose work already shipped.
+- **Missing boundary error handling** — a call across a process, network, or
+ filesystem boundary whose failure mode is simply unhandled.
+
+## Owned by sibling audits — do not file here
+
+Filing the same problem twice is noise. Name an overlap if it is the cause of
+what you found, then leave it to its owner:
+
+- Generated artifacts as a second source of truth, hand-synchronized registries,
+ and incidental-layout coupling belong to the structural-drift work.
+- Counted branching complexity and reader-cost problems (mixed abstraction
+ levels, flag arguments, misleading names) belong to the complexity and
+ cognitive-load work.
+- Responsibility boundaries, module topology, and reuse discoverability belong
+ to the module-hygiene work.
+- Pure dead-code removal and copy-paste consolidation belong to the
+ simplification work.
+- Latent runtime defects belong to the runtime-safety work; logging gaps to the
+ observability work.
+
+## The evidence bar
+
+Read the producer, its callers, its tests, and recent history before judging
+anything. Keep only findings with a named transformation and a proven
+consequence: a reachable runtime or data failure, a CI or release failure, or
+recurring manual churn demonstrated by the repository's own history. Delete
+subjective style preferences and any finding whose consequence you cannot show.
+Do not propose a rewrite because you would have written it differently.
+
+Cite \`file:LINE\` for every finding.`,
+
+ 'test-coverage': `[Improvement: {appName}] Test Coverage
+
+Find the untested behavior in {appName} whose silent failure would actually
+cost something, and cover it at the right level.
Repository: {repoPath}
{modeInstructions}
-Start with a cheap repository-wide inventory of candidates, then choose one
-bounded, coherent slice and trace it deeply. Hunt specifically for:
+## Prioritize by consequence, not by percentage
-1. **Derived artifacts committed as a second source of truth** — generated
- catalogs, manifests, snapshots, indexes, or caches that copy facts already
- available from source. Pay special attention to volatile line/column/offset,
- timestamp, absolute-path, or ordering metadata that changes when behavior
- does not. Check history for regeneration-only churn and determine whether the
- value can instead be derived at build time, startup, or first use and cached.
-2. **Manually synchronized registries** — the same routes, events, commands,
- schemas, feature flags, or capabilities listed in multiple places, with a
- drift test merely telling a human to copy one representation into another.
- Prefer one semantic registry consumed by every projection. When a second
- registry would only duplicate hundreds of real declarations, derive the
- projection from those declarations and cache it; use source scans as CI
- guards for protocols whose call sites already consume a canonical registry.
-3. **Incidental-layout coupling** — tests, manifests, or runtime behavior tied to
- source line numbers, array positions, object insertion order, filenames, or
- other coordinates that are not part of the product contract.
-4. **Architecture and ownership leaks** — one concern split across unrelated
- layers, helpers that reverse dependency direction, ad-hoc conditionals bolted
- onto a generic flow, or wrappers that add indirection without policy.
-5. **Conventional code-quality defects** — duplicated logic, functions that mix
- unrelated concerns, dead code, unused imports, stale TODOs, missing boundary
- error handling, noisy debug logging, and unexplained magic values.
-
-For every candidate, read the producer, all consumers, its tests, and recent
-history before judging it. A checked-in generated artifact can be legitimate
-when distribution lacks the source, derivation is expensive or nondeterministic,
-or reproducible releases require frozen bytes. Do not file or implement a
-subjective rewrite. Keep only findings with a named transformation and proven
-impact: runtime/data failure, CI or release failure, or recurring manual churn.`,
-
- 'test-coverage': `[Improvement: {appName}] Improve Test Coverage
-
-Analyze and improve test coverage for {appName}:
+Coverage percentage is a diagnostic, not a goal. Rank gaps by what breaking them
+costs: data loss or corruption, money or quota spend, a security or privacy
+guarantee, a destructive action, an upgrade or migration path, then everything
+else. A gap in code that changes often is worth more than a gap in code that
+never changes — the repository's history tells you which is which.
-Repository: {repoPath}
+## Test at the highest practical boundary
-1. Check existing tests and identify untested critical paths
-2. Look for:
- - API routes without tests
- - Services with complex logic
- - Error handling paths
- - Edge cases
+Prefer a test at a real public surface — an HTTP route, a service workflow, a
+persisted-store adapter, a rendered user interaction, a CLI invocation — over a
+test of an internal helper. A boundary test should cover the success path plus
+the materially different failure and compatibility paths. Do not enumerate every
+internal branch just because the branch exists, and do not add a unit test for a
+deterministic helper already exercised through a stable caller.
-3. Add tests following existing patterns in the project
-4. Ensure tests:
- - Use appropriate mocks
- - Test edge cases
- - Follow naming conventions
+Focused unit tests are still right for behavior a higher-level test cannot pin
+cheaply or precisely: parsers and algorithms with a real input matrix; security,
+privacy, and destructive-action guards; migrations and cross-version
+compatibility; serialization and schema boundaries; retry, timeout, and
+lifecycle state machines. Test real timeout behavior once, with injected or fake
+time, never with production sleeps.
-5. Run tests to verify all pass
-6. Commit test additions with clear message describing coverage`,
+## Before adding a test, name the regression it uniquely catches
- 'performance': `[Improvement: {appName}] Performance Analysis
+If you cannot name a specific way the code could break that this test and no
+existing test would catch, do not write it. When you add one, verify it is not
+vacuous: mutate the code it covers so it is wrong, confirm the test fails, then
+revert the mutation. A test that passes against broken code is worse than no
+test.
-Analyze {appName} for performance issues:
+Follow the project's existing test conventions — its runner, file placement,
+naming, and mocking patterns — rather than importing a style from elsewhere.
-Repository: {repoPath}
+## Not yours
+
+Existing tests that are vacuous, weak, or redundant belong to the test-quality
+work. You own the gaps; leave the audit of what is already written to its owner
+unless a gap is hidden BY a vacuous test, in which case say so explicitly.
+
+For each finding, name the uncovered behavior with \`file:LINE\`, the failure it
+would allow, the boundary you would test it at, and why that boundary.`,
-1. Review components/views for:
- - Unnecessary re-renders
- - Missing memoization
- - Large files that should be split
+ 'performance': `[Improvement: {appName}] Performance Analysis
-2. Review backend for:
- - N+1 query patterns
- - Missing caching opportunities
- - Inefficient file operations
- - Slow API endpoints
+Find where {appName} does provably more work than it needs to, on a path that is
+actually hot.
-3. Review build/bundle for:
- - Missing code splitting
- - Large dependencies that could be optimized
+Repository: {repoPath}
-4. Check for:
- - Memory leaks
- - Unnecessary broadcasts/events
+{modeInstructions}
-Optimize and commit improvements.`,
+## Measure or reason concretely — never guess
+
+A performance finding needs a quantity: how often the path runs, over how much
+data, and what the cost grows with. "This could be slow" is not a finding.
+Prefer evidence in this order: a measurement you took, a complexity argument
+over a data size you can state, or a pattern whose cost is unambiguous at the
+scale the code actually sees. Say which one you have.
+
+## Hunt for
+
+- **Work repeated per item that could be done once** — a query, read, parse,
+ compile, or allocation inside a loop whose result does not vary.
+- **N+1 access patterns** — a related record, file, or request fetched inside a
+ loop over a parent collection.
+- **Superlinear algorithms on unbounded input** — nested scans over the same
+ collection, repeated linear lookups where a map would answer in one step.
+- **Unbounded result sets** — a query, listing, or fetch with no limit over data
+ that grows with usage, especially one rendered or held entirely in memory.
+- **Missing indexes** — a filter or sort on a column that has none, on a table
+ that grows.
+- **Redundant re-computation in a render or hot callback** — work repeated on
+ every frame, keystroke, or event that depends only on stable inputs.
+- **Payload and startup weight** — a large module pulled into a path that needs
+ one constant from it, an asset far larger than its rendered size, work done at
+ import time that only one rare path needs.
+- **Cache misuse** — a cache that never invalidates, one that never hits because
+ its key varies, or an unbounded one that is really a leak.
+
+## Do not trade correctness or clarity for a gain you cannot measure
+
+Reject micro-optimizations with no measured effect, and any change that makes
+behavior harder to reason about for a speedup you cannot state. If a slow path
+is slow because it is doing something necessary, say so and move on.
+
+For each finding, give \`file:LINE\`, the quantity (frequency times size), the
+growth term, the proposed change, and the expected effect. In implement mode,
+state how you verified the improvement.`,
'accessibility': `[Improvement: {appName}] Accessibility Audit
-Audit {appName} for accessibility issues:
+Audit {appName} for barriers that stop someone using it with a keyboard, a
+screen reader, magnification, or reduced color perception.
Repository: {repoPath}
-If the app has a web UI:
-1. Navigate to the app's UI
-2. Check for:
- - Missing ARIA labels
- - Missing alt text on images
- - Insufficient color contrast
- - Keyboard navigation issues
- - Focus indicators
- - Semantic HTML usage
+{modeInstructions}
-3. Fix accessibility issues in components
-4. Add appropriate aria-* attributes
-5. Test and commit changes`,
+If the project has no user interface, say so and exit cleanly.
+
+## Hunt for
+
+- **Keyboard traps and unreachable controls** — an interactive element that
+ cannot be reached or activated by keyboard, a custom control with no key
+ handling, a dialog that does not trap and restore focus.
+- **Missing focus indication** — a focus style removed and never replaced, so
+ keyboard users cannot tell where they are.
+- **Unlabeled controls** — an icon-only button, an input with no associated
+ label, a form control whose only label is placeholder text.
+- **Images and media without text alternatives** — a meaningful image with no
+ description, or a decorative one announced as content.
+- **Semantics faked with generic elements** — a clickable element that is not a
+ button or link, a heading order that skips levels, a list that is not marked
+ up as one, a table without headers.
+- **Dynamic changes nobody is told about** — an async result, validation error,
+ or toast that appears with no live region, so a screen-reader user never
+ learns it happened.
+- **Color as the only signal** — state conveyed by color alone, or text and
+ interactive elements below the contrast floor.
+- **Motion and zoom** — animation that ignores a reduced-motion preference,
+ layout that breaks or clips at 200% zoom.
+
+## The bar
+
+Name who is blocked and how far they get: which control, using what input
+method, and what happens instead of the intended outcome. Test with the keyboard
+before claiming a keyboard defect, and inspect the rendered accessibility tree
+rather than guessing from source when the running interface is reachable. If it
+is not reachable, audit source only, and say that is what you did.
+
+Prefer the native element over a custom control with added attributes — a
+correct element needs no announcement patch. Cite \`file:LINE\` for each finding
+and give the concrete fix.`,
'console-errors': `[Improvement: {appName}] Console Error Investigation
-Find and fix console errors in {appName}:
+Find the errors and warnings {appName} actually emits while running, and fix
+their causes.
Repository: {repoPath}
-1. If the app has a UI, check browser console for errors
-2. Check server logs for errors
-3. For each error:
- - Identify the source file and line
- - Understand the root cause
- - Implement a fix
+{modeInstructions}
-4. Test fixes and commit changes`,
+## Collect before diagnosing
+
+Exercise the application and collect what it really emits: browser console
+errors and warnings across the main views, server logs during startup and
+ordinary use, failed network requests, and unhandled promise rejections. If the
+running application is not reachable, say so and audit source only rather than
+inventing findings from imagination.
+
+## Then, for each distinct message
+
+- Identify the source with \`file:LINE\` and the action that triggers it.
+- Find the root cause rather than the line that reported it — the stack frame
+ that threw is often not the mistake.
+- Judge whether it is a real defect or expected noise. A warning from a
+ dependency you cannot control, or a deliberate diagnostic, is not a defect;
+ say so and move on rather than silencing it.
+- Group duplicates: one cause emitting fifty lines is one finding, not fifty.
+
+## Never fix an error by hiding it
+
+Suppressing a warning, wrapping a throw in an empty catch, or removing the log
+line is not a fix — it converts a visible failure into an invisible one. If the
+message is genuinely expected, the fix is to stop producing the condition, or to
+document why it is expected where the next person will see it.
+
+## Not yours
+
+A missing log, a swallowed error, or log noise as a design problem belongs to
+the observability work. Component effect and lifecycle defects belong to the
+React lifecycle work. Fix what actually errors; name overlaps and leave them.
+
+For each finding: the message, the trigger, the root cause with \`file:LINE\`, and
+the fix. In implement mode, re-run the same exercise and confirm the message is
+gone.`,
'dependency-updates': `[Improvement: {appName}] Dependency Updates
@@ -366,61 +510,154 @@ repo (a globally-configured \`gh\` will silently target an unrelated GitHub repo
IMPORTANT: Only update one major version bump at a time.`,
- 'documentation': `[Improvement: {appName}] Update Documentation
+ 'documentation': `[Improvement: {appName}] Documentation Review
-Review and improve {appName} documentation:
+Find where {appName}'s documentation is wrong, missing, or has drifted from the
+code — and fix the gaps that actually mislead someone.
Repository: {repoPath}
-1. Check README.md:
- - Installation instructions current?
- - Quick start guide clear?
- - Feature overview complete?
+{modeInstructions}
-2. Review inline documentation:
- - Add JSDoc to exported functions
- - Document complex algorithms
- - Explain non-obvious code
+## Prioritize by who gets hurt
+
+Rank gaps by the cost of the mistake they cause: a broken install or setup
+instruction, a documented command or flag that no longer exists, a stated
+contract the code does not honor, an undocumented breaking change, then merely
+absent detail. Documentation that is *wrong* outranks documentation that is
+*missing* — a reader who follows a false instruction loses more than a reader
+who finds nothing.
+
+## Hunt for
+
+- **Instructions that no longer work** — a setup step, command, path, port, or
+ environment variable that has changed or gone away. Verify against the code
+ rather than trusting the prose.
+- **Documented behavior the code contradicts** — a described default, response
+ shape, option, or guarantee that no longer matches.
+- **Undocumented contracts a reader must know** — a required environment value,
+ a destructive side effect, an ordering requirement, an upgrade step.
+- **Stale references** — links to moved or deleted files, examples using retired
+ APIs, screenshots of interfaces that no longer exist.
+- **Missing "why" on non-obvious decisions** — a constraint, workaround, or
+ deliberate trade-off that reads as arbitrary and invites someone to "fix" it.
+- **Comments that lie** — an inline comment describing behavior the function no
+ longer has.
+
+## Respect the project's own conventions
+
+Read the repository's instruction files first, and follow the documentation
+structure, index, and changelog convention they already document rather than
+introducing a different one.
+
+The changelog is where this goes wrong most often, so check before you write:
+some repos collect a per-branch fragment per change precisely so parallel agents
+do not conflict on one shared file, and others derive their notes from commit
+history at release time and want no per-change file at all. Appending to a
+shared unreleased section is the fallback for a repo that documents no
+convention — never the default instruction. If the project states that a file is
+retired, honor that.
+
+## Do not pad
+
+Do not add documentation for its own sake: a comment restating the code, a
+docstring on an obvious helper, or a README section nobody asked for is
+maintenance debt with no reader. Write for someone trying to do something
+specific.
+
+For each finding, cite the documentation location and the code that contradicts
+it with \`file:LINE\`.`,
-3. Check for docs/ folder:
- - Are all features documented?
- - Is information current?
- - Add missing guides if needed
+ 'ui-bugs': `[Improvement: {appName}] UI Bug Analysis
-4. Update PLAN.md if present:
- - Remove completed milestones from PLAN.md outright. Do NOT archive to a \`DONE.md\` — that file is retired; \`git log\` and \`.changelog/\` (or per-app equivalent) are the audit trail.
- - If the repo maintains a changelog, log what shipped there **following the convention the repo documents** — check its \`AGENTS.md\` (or \`CLAUDE.md\`) and changelog README first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the project's existing prose style only when no convention is documented.
- - Keep PLAN.md focused on next actions and future work
+Walk {appName}'s running interface and find things that are actually broken.
-Commit documentation improvements.`,
+Repository: {repoPath}
- 'ui-bugs': `[Improvement: {appName}] UI Bug Analysis
+{modeInstructions}
+
+## Exercise the interface
+
+Discover the running application's URL from the project's own configuration,
+README, or dev-server output. Visit each main view and, for every one: read the
+rendered structure, check the console for errors, watch for failed network
+requests, and interact with the primary controls rather than only looking at the
+page.
-Use Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages) to analyze the app UI:
+If the interface is not reachable, exit cleanly and say so. Do not file
+speculative findings from source alone.
-1. Navigate to the app's UI
-2. Check each main route
-3. For each route:
- - Take a browser_snapshot to see the page structure
- - Check browser_console_messages for JavaScript errors
- - Look for broken UI elements, missing data, failed requests
-4. Fix any bugs found in the components or API routes
-5. Run tests and commit changes`,
+## Hunt for
- 'mobile-responsive': `[Improvement: {appName}] Mobile Responsiveness Analysis
+- **Controls that do nothing** — a button, link, or form whose action fails
+ silently or never fires.
+- **Data that never arrives** — a view stuck in loading, a panel showing an
+ empty state while its request succeeded, a value rendered as undefined, null,
+ NaN, or a raw identifier.
+- **Failed requests** — a call returning an error the interface does not
+ surface, or one firing repeatedly in a loop.
+- **Broken rendering** — overlapping or clipped elements, a component that
+ crashes its subtree, an image or icon that fails to load.
+- **State that does not update** — a mutation that succeeds on the server but
+ leaves the view stale until reload, or a list that loses its selection.
+- **Navigation defects** — a route that 404s, a deep link that lands somewhere
+ else, a back navigation that loses state it should keep.
-Use Playwright MCP to test the app at different viewport sizes:
+## Not yours
-1. browser_resize to mobile (375x812), then navigate to the app UI
-2. Take browser_snapshot and analyze for:
- - Text overflow or truncation
- - Buttons too small to tap (< 44px)
- - Horizontal scrolling issues
- - Elements overlapping
- - Navigation usability
-3. Repeat at tablet (768x1024) and desktop (1440x900)
-4. Fix CSS responsive classes as needed
-5. Test fixes and commit changes`,
+Viewport and layout breakage at small sizes belongs to the mobile and responsive
+work; keyboard, contrast, and screen-reader barriers to the accessibility work;
+design and flow judgments to the UX work; wording to the copy work. This audit
+owns things that are broken, not things that could be better.
+
+For each finding: the view, the exact steps to reproduce, what happens, what
+should happen, and the \`file:LINE\` of the cause once you have traced it.`,
+
+ 'mobile-responsive': `[Improvement: {appName}] Mobile and Responsive Audit
+
+Check that {appName} is usable on a small screen and a touch device, not merely
+that it renders.
+
+Repository: {repoPath}
+
+{modeInstructions}
+
+## Exercise real viewports
+
+Discover the running application's URL from the project's own configuration,
+README, or dev-server output, then walk each main view at a small phone width, a
+tablet width, and a desktop width. Compare: a defect is usually something that
+works at one size and fails at another. If the interface is not reachable, exit
+cleanly and say so.
+
+## Hunt for
+
+- **Horizontal overflow** — a fixed width, an unwrapped row, a wide table, or a
+ long unbroken string forcing the page to scroll sideways.
+- **Touch targets too small or too close** — a control under roughly 44 by 44
+ points, or crowded against its neighbors so the wrong one is hit.
+- **Hover-only interactions** — a menu, tooltip, or control reachable only by
+ hovering, with no touch equivalent.
+- **Content clipped or truncated** — text cut off where wrapping was expected,
+ especially variable-length or user-supplied content.
+- **Viewport-height assumptions** — a full-height layout that breaks when mobile
+ browser chrome covers part of the viewport.
+- **The primary action pushed off-screen** — the one thing a user came to the
+ view to do, requiring a scroll to find on a phone.
+- **Breakpoint gaps** — a component styled for some sizes but not the project's
+ full breakpoint scale, or a one-off media query that does not match it.
+- **Oversized assets** — an image shipped far larger than its rendered size, or
+ without responsive sources.
+
+## The bar
+
+Name the viewport width, the view, and what a user cannot do there. A layout
+that merely looks different at a smaller size is not a finding; one that hides,
+clips, or blocks an action is. Use the project's existing responsive
+conventions — its breakpoint scale and utility classes — rather than adding
+one-off values.
+
+Cite \`file:LINE\` for the rule or component responsible.`,
'ux': `[Improvement: {appName}] UX / Design Audit
@@ -428,14 +665,17 @@ You are reviewing {appName}'s running UI as a UX reviewer, not as an engineer
fixing bugs. The question you are answering for every screen is **"can a user
actually get their job done here, and does the design help or fight them?"**
-**Read-only on source.** You do NOT edit application code, CSS, or components,
-and you do NOT create branches or PRs. Your deliverable is one item per finding
-in {appName}'s task tracker (described under "Where to record findings" below),
-so a human — or a later \`/claim\`-style task runner — decides what actually gets
-built. Design judgment is proposed, never auto-merged.
-
Repository: {repoPath}
+{modeInstructions}
+
+Design judgment is normally proposed rather than merged: this audit defaults to
+filing one tracker item per finding so a human — or a later claim-style task
+runner — decides what actually gets built. The mode banner above is what
+decides; when it puts you in implement mode, the sections below that describe
+recording a finding instead describe the change you make, and you still walk the
+interface the same way and hold to the same checklist.
+
## Where to record findings
{trackerInstructions}
@@ -516,8 +756,9 @@ keyboard-inaccessible icon") — and file it as the UX finding, not as the a11y
succeeds, not every aesthetic preference. A handful of well-argued items
beats twenty nitpicks.
-6. **Finalize** per the "Finalize" step under "Where to record findings" above.
- No source edits, no branches, no PRs.
+6. **Finalize** per the "Finalize" step under "Where to record findings" above,
+ and per the mode banner — which is what decides whether this run ends in
+ tracker items or in a change.
7. Your final assistant message must be a 2–3 sentence summary of: how many
routes you audited, how many findings you filed (and their slugs), and which
@@ -809,6 +1050,419 @@ Quote the exact current string with \`file.jsx:LINE\`, and give the proposed
replacement plus a one-line rationale. A finding with no proposed wording is
not actionable.`,
+ 'better-complexity': `[Improvement: {appName}] Cyclomatic complexity audit
+
+Reduce the branching complexity of {appName}'s hottest functions. Complexity is
+what makes a function expensive to change safely: every independent path is a
+case the next person must hold in their head and a case the tests must cover.
+
+Repository: {repoPath}
+
+{modeInstructions}
+
+## Measure, do not estimate
+
+Cyclomatic complexity is 1 + the number of independent decision points in a
+function body. Count, in the function itself and not in the functions it calls:
+
+- \`if\` and \`else if\` (a bare \`else\` adds nothing — it has no test of its own)
+- each \`case\` that can be reached independently
+- each loop (\`for\`, \`while\`, \`do\`, and comprehension forms)
+- each \`catch\` / \`except\` clause
+- each short-circuit or conditional operator guarding a distinct outcome
+ (\`&&\`, \`||\`, \`??\`, the ternary)
+
+Report the number you counted for every candidate. A finding that says
+"complex" without a count is not a finding.
+
+**Length is not complexity.** A 200-line function with three branches is a
+different problem, and belongs to the repository's module-hygiene work. A
+30-line function with 22 paths is squarely yours.
+
+## Rank by cost, not by score
+
+The worst-scoring function in the repository is not automatically worth
+changing. Rank candidates by complexity, by how often the function actually
+changes, and by how many callers depend on it:
+
+\`\`\`bash
+git log --since='90 days ago' --name-only --format='' | sort | uniq -c | sort -rn | head -40
+\`\`\`
+
+A high-complexity function in a file nothing has touched in a year is stable by
+revealed preference — record that you found it and move on. A high-complexity
+function inside the top churn files is where defects are actively being
+introduced.
+
+## Reject these — high branching is correct here
+
+- **Dispatch tables and exhaustive switches over a closed set.** A \`switch\` with
+ 30 cases mapping a known enum to a known result is a lookup written in control
+ flow; splitting it hides the totality the reader wants.
+- **Parsers, tokenizers, and format decoders** whose branches mirror a real
+ input grammar.
+- **Generated, vendored, and migration sources**, and historical compatibility
+ ladders whose branches each pin a released behavior.
+- **Validation chains** whose branches are one independent rule apiece.
+- **A function whose branches are already named** — a flat sequence of guard
+ clauses reads linearly no matter what the metric says.
+
+## Name the transformation
+
+Every finding must name which of these it applies, and to what:
+
+- **Guard clauses / early return** — invert a nested condition so the
+ exceptional path exits and the happy path un-indents.
+- **Extract a named predicate** — replace a multi-clause boolean with one
+ function whose name states the rule.
+- **Lookup table or dispatch map** — replace an \`if\`/\`else if\` ladder or a
+ value-mapping \`switch\` with data.
+- **Extract a cohesive step** — pull a self-contained block into a named
+ function, but only when the block has a real name that is not "part 2".
+- **Collapse duplicated branches** — two arms differing by one value become one
+ arm parameterized by that value.
+- **Replace a state-flag ladder** with an explicit state map or table.
+
+"Split this up" is not a transformation. "Extract the retry-budget decision into
+\`shouldRetry(attempt, err)\`, collapsing 6 paths to 2" is.
+
+## Behavior preservation is the contract
+
+A complexity reduction that changes behavior is a bug, not an improvement. For
+every finding, state what pins the behavior today: the existing tests covering
+the function, or — when the paths are untested — the test that must be written
+FIRST, at the highest practical public boundary rather than against the
+extracted helper. Report the before and after path counts.
+
+Give each finding exact \`file:LINE\` evidence, the counted complexity, the churn
+and caller evidence that made it worth changing, the named transformation, and
+what proves behavior is unchanged.`,
+
+ 'better-cognitive-load': `[Improvement: {appName}] Cognitive load and readability audit
+
+Find the code in {appName} that is hardest to understand, and say precisely what
+a reader must hold in their head to change one line of it safely.
+
+Repository: {repoPath}
+
+{modeInstructions}
+
+This audit is about **reader cost**, which no metric captures. Sibling work owns
+the measurable shapes: counted branching, function length, nesting depth, file
+size, and responsibility boundaries are not your findings. Start from the files
+a newcomer reads first — entry points, primary route or command handlers, the
+modules with the most importers — and from whatever the repository's history
+shows is changed most often.
+
+## Hunt for
+
+- **Mixed abstraction levels in one function** — high-level orchestration
+ interleaved with raw query text, byte manipulation, or DOM detail, so the
+ reader switches altitude mid-paragraph.
+- **Flag arguments** — a boolean or enum parameter that makes one function do
+ two unrelated jobs, so every call site is a puzzle and the body is a fork.
+- **Names that lie or say nothing** — \`data\`, \`tmp2\`, \`handle\`, \`doStuff\`;
+ abbreviations that need tribal knowledge; a name describing the implementation
+ where the caller needs the intent.
+- **Negated booleans** — \`notDisabled\`, \`hideNothing\`, \`skipUnlessMissing\` —
+ anything forcing double-negative reasoning at a call site.
+- **Comments that compensate for the code** — a paragraph explaining what a
+ rename or an extraction would have made self-evident, and commented-out code
+ left behind as documentation.
+- **Action at a distance** — module-level mutable state, implicit ordering
+ requirements between calls ("you must call init first"), and side effects
+ hidden behind names that read as pure.
+- **Defensive soup** — chains of optional access and \`|| fallback\` that obscure
+ which values are actually possible, and casts papering over a contract nobody
+ wrote down.
+- **A contract you cannot state in one sentence** — if you cannot say what a
+ function guarantees without reading its body twice, that is the finding.
+
+## Do not file
+
+- Formatting, quote style, import order, line length, or anything a formatter or
+ linter owns.
+- A rename of a public export without a backward-compatible re-export path.
+- Personal preference between two equally readable spellings.
+- A restructuring whose only argument is that you would have written it
+ differently.
+
+## Every finding names the cost it removes
+
+State the transformation (extract, invert, rename, table-ize, early-return,
+make-the-state-explicit) **and** the specific reader cost it deletes: what the
+next person currently has to know, look up, or keep in their head, and will not
+have to after the change. A finding calling code "confusing" or "hard to follow"
+without naming what specifically must be held in mind is not actionable — drop
+it.
+
+Quote the code with \`file:LINE\`, give the proposed shape, and keep behavior
+identical. This audit never changes what the code does.`,
+
+ 'better-structural-drift': `[Improvement: {appName}] Structural drift and sources of truth
+
+Find where {appName} keeps the same fact in two places, so the two can disagree
+— and where one of them has silently drifted already.
+
+Repository: {repoPath}
+
+{modeInstructions}
+
+## Hunt for
+
+1. **Derived artifacts committed as a second source of truth** — generated
+ catalogs, manifests, snapshots, indexes, or caches copying facts already
+ available from source. Ask first whether the artifact needs to exist at all:
+ a derivation that is deterministic, cheap, and reads only inputs every
+ install already ships belongs in memory, derived on first use and cached for
+ the process.
+2. **Position-keyed records** — any committed artifact addressing what it
+ describes by line number, column, byte offset, array index, or insertion
+ order. These are rewritten by edits that change nothing, so their drift tests
+ fire on innocent commits, parallel branches regenerate them differently, and
+ rebases conflict on them. Records must be keyed by the declaring file plus
+ the semantic identity of what it declares.
+3. **Manually synchronized registries and mirrors** — the same routes, events,
+ commands, schemas, feature flags, constants, or capabilities declared in more
+ than one place, held together by a comment ("keep in sync with…", "mirrors…",
+ "must match…") or by a drift test whose only remedy is for a human to copy
+ one side onto the other.
+4. **Incidental-layout coupling** — tests, fixtures, or runtime behavior
+ depending on source line numbers, array positions, object key insertion
+ order, or filenames that are not part of the product contract.
+
+## Prove the drift, do not assert it
+
+A duplicate that has never diverged and is cheap to keep aligned may be correct.
+Evidence that turns a suspicion into a finding:
+
+\`\`\`bash
+# Regeneration-only churn: commits that touched ONLY the artifact
+git log --oneline -- <artifact> | wc -l
+# One-sided history is the drift proof: a fix that landed in one copy, not both
+git log -S'<symbol>' --oneline -- <fileA>
+git log -S'<symbol>' --oneline -- <fileB>
+\`\`\`
+
+A symbol present in one copy's history and absent from the other's means a fix
+reached one side only. Identical same-commit history across both means recurring
+manual churn — weaker, but still a cost you can count. Then diff the present-day
+bodies and say whether they have already drifted.
+
+## Legitimate second copies — do not file these
+
+- Distribution genuinely lacks the source at the point of use.
+- Derivation is expensive, nondeterministic, or needs inputs an install lacks.
+- Reproducible releases require frozen bytes.
+- A cross-runtime mirror the project's layering rules forbid collapsing (a
+ browser bundle that must not import a server-only module), where a parity test
+ already guards it mechanically.
+- Vendored or third-party trees maintained upstream.
+
+When a copy is legitimate, the finding may still be that the parity check is
+missing: a hand-synced pair with NO mechanical guard is a defect even when the
+duplication itself is justified.
+
+## For each finding
+
+Name the producer, every consumer, the evidence above, and the decided
+resolution — derive at first use, re-export from the declaring module, generate
+with a content-addressed key, or add the mechanical parity check. Say what
+remains behind and what compatibility obligation it carries.`,
+
+ 'better-runtime-safety': `[Improvement: {appName}] Runtime safety and async correctness
+
+Read {appName}'s source for latent defects — the ones already in the code that
+simply have not been triggered yet.
+
+Repository: {repoPath}
+
+{modeInstructions}
+
+## Hunt for
+
+- **Missing \`await\` and floating promises** — an async call whose result nobody
+ waits for, so its failure is invisible and its effect lands after the caller
+ moved on. Check whether SOMEONE awaits the returned promise before calling it
+ a bug.
+- **Rejections with no owner outside the request lifecycle** — timers,
+ intervals, event listeners, socket handlers, child-process callbacks, and
+ queue workers. Nothing holds the promise these return, so a rejection escapes
+ unhandled and can take the whole process down.
+- **Unguarded access** — a property read, index, or destructure on a value a
+ real code path can deliver as null, undefined, or empty.
+- **Sentinel confusion** — code letting *absent*, *failed to load*, and
+ *legitimately empty* collapse into one value. Truthiness on a length, or a
+ bare \`||\` fallback, conflates "nothing there" with "we never looked" — so a
+ cleared value silently reverts, or a cached empty result is re-fetched forever.
+- **Shared-state races** — read-modify-write pairs on the same record or file
+ from two paths that can interleave, check-then-act sequences whose condition
+ can change before the act, and handlers mutating module-level state
+ concurrently.
+- **Resource leaks** — caches and maps that only grow, listeners and
+ subscriptions never removed, streams, connections, or handles never closed on
+ the error path.
+- **Unbounded reads** — a query, directory walk, or fetch with no limit over a
+ set that grows with usage.
+- **Wrong operator or off-by-one** — a boundary comparison, slice bound, or loop
+ condition provably off by one for a stated input.
+- **Process-killing calls in reusable code** — exiting the process from a module
+ a library or test can import.
+
+## Not yours — name the overlap and move on
+
+Performance shapes (N+1 queries, quadratic loops, missing indexes) belong to the
+performance work; retries, timeouts, fallbacks, and health checks to the
+error-handling work; swallowed errors and missing log context to the
+observability work; component effect teardown and stale closures to the React
+lifecycle work. Mentioning an overlap is fine; filing it twice is noise.
+
+## The bar: a failure scenario, not a code shape
+
+Every finding must state concrete inputs or state, the sequence reaching the
+defect, and the observable outcome — a crash, a wrong value, a lost write, a
+leak growing without bound. Read the callers and at least 30 surrounding lines
+before flagging: a guard may live one frame up, and framework idioms routinely
+handle what looks unhandled. If you cannot construct the scenario, you do not
+have a finding.
+
+Cite \`file:LINE\` for the defect AND for the caller that reaches it.`,
+
+ 'better-dependency-freedom': `[Improvement: {appName}] Dependency freedom audit
+
+Every third-party package in {appName} is code you did not write, running with
+your privileges, updated on someone else's schedule. Find the ones not earning
+that.
+
+Repository: {repoPath}
+
+{modeInstructions}
+
+This audit asks whether a dependency should exist at all. Keeping the
+dependencies you do have current is separate work — file no version bumps here.
+
+## Inventory and classify
+
+Read the project's manifest(s) and classify every direct dependency:
+
+- **Acceptable** — large, widely audited, doing real work you would never
+ reimplement: frameworks, runtimes, database drivers, build toolchains,
+ rendering and math libraries. Skip these; do not spend the run relitigating
+ them.
+- **Suspect** — a smaller library where the project appears to use one or two
+ functions, a wrapper over capabilities the platform now provides, or a
+ single-purpose utility.
+- **Removable** — the used functionality is small enough to own outright, the
+ package wraps an API that is now native, it is unmaintained, or it is a
+ micro-package whose whole body is a few lines.
+
+## Prove usage before proposing removal
+
+For each suspect or removable package:
+
+\`\`\`bash
+grep -rn "<package-name>" --include='*.*' . | grep -v node_modules
+\`\`\`
+
+List every symbol imported, count the call sites and files, and check for
+dynamic or string-keyed usage a plain grep misses — config files, plugin
+registries, build tooling, CI. Then size the replacement honestly: Trivial
+(under ~20 lines), Moderate (~20–100), Complex (~100–300), or Infeasible. Check
+maintenance status: last release, open advisories, and whether it still supports
+the runtime versions the project targets.
+
+**A platform capability that has replaced a package is the strongest case** — a
+built-in UUID generator, structured cloning, array flattening, promise-based
+file APIs, a built-in HTTP client, native date formatting. Name the exact
+replacement API and the minimum runtime version it needs, and confirm the
+project actually targets that floor.
+
+## Respect documented decisions
+
+If the repository's own instructions declare a dependency deliberate, or declare
+a class of dependency finding a non-issue, that is binding — do not re-file it.
+An audit that argues with the project's stated policy wastes the window.
+
+## Report
+
+Per finding: the package, its tier, the symbols used, call-site and file counts,
+replacement complexity and the concrete replacement, maintenance and advisory
+status, and the risk the removal carries. Severity follows real exposure —
+unmaintained with a known advisory on a reachable path is the top of the list; a
+suspect package with a complex replacement is the bottom.
+
+In implement mode, remove exactly ONE package per run, and cover its replacement
+with a test exercising the behavior the package used to provide.`,
+
+ 'better-test-quality': `[Improvement: {appName}] Test quality audit
+
+Audit {appName}'s existing tests for ones that cannot fail, prove nothing, or
+duplicate a stronger test. Missing coverage is separate work — you own the tests
+that already exist.
+
+Repository: {repoPath}
+
+{modeInstructions}
+
+A suite's value is the regressions it catches, not its size. A vacuous test is
+worse than no test: it costs CI time on every run and reports safety that is not
+there.
+
+## Hunt for
+
+**Vacuous — the test passes no matter what the code does:**
+
+- Assertions against a mocked return value, so the test proves the mock works.
+- A test that mocks the very module it is testing.
+- A test re-implementing the logic under test instead of importing it, so it
+ agrees with itself while the real code regresses.
+- Assertions that cannot fail: a literal compared to itself, a type check on an
+ object literal, a bare truthiness check on an always-truthy value.
+- A named test with no meaningful assertion, or with its assertions commented
+ out.
+
+**Weak — the test passes for the wrong reason:**
+
+- Assertions on implementation details: internal state, private helpers, call
+ counts, or a call order the contract does not promise.
+- A test that would still pass if the function returned null, undefined, or an
+ empty collection.
+- An integration test mocked so heavily it only exercises glue.
+- Only the happy path, where the error and boundary paths carry the risk.
+- Cases sharing mutable state, so they pass only in one order.
+- A guard or safety test that never probes the bypass — it asserts the guard
+ allows the good case but never proves it blocks the bad one.
+
+**Redundant — the test is real but earns nothing:**
+
+- It duplicates an assertion a higher-level test already makes.
+- Table-driven permutations that all prove the same single outcome.
+- A unit test on a deterministic helper already exercised through a stable
+ caller, where the helper and every caller would have to change together
+ anyway.
+
+## Prove it before you file it
+
+The rigorous check is a **mutation probe**: change the code under test so it is
+wrong — invert a condition, return a constant, delete a guard — and run the
+test. If it still passes, you have proof, and the finding must quote what you
+changed and what still passed. Revert the mutation before moving on; never
+commit one. For a redundant test, name the stronger test that survives it.
+
+For each finding, also name the regression the test was presumably meant to
+catch, and whether that regression is still caught after your proposed change.
+
+## Deletion is a valid outcome
+
+Removing a vacuous or redundant test is an improvement, and the resulting drop
+in test count or line coverage is not a regression — say so plainly in the
+finding so a reviewer does not read the deletion as lost safety. When a weak
+test guards behavior that genuinely matters, strengthen it at the highest
+practical public boundary instead of deleting it.
+
+Cite the test file and case name with \`file:LINE\`, the source it claims to
+cover, and the probe result.`,
+
'feature-ideas': `[Improvement: {appName}] Implement Next Planned Feature
Your goal is to implement the next planned item from PLAN.md, or brainstorm a new feature if no plan exists.
@@ -2054,56 +2708,94 @@ Categorize into:
- Items rejected (with reasons)
- Items already done`,
- 'error-handling': `[Improvement: {appName}] Improve Error Handling
+ 'error-handling': `[Improvement: {appName}] Failure-path Audit
-Enhance error handling in {appName}:
+Audit what {appName} does when things go wrong: whether failures are handled,
+recoverable, and comprehensible to whoever hits them.
Repository: {repoPath}
-1. Review code for:
- - Missing try-catch blocks where needed
- - Silent failures (empty catch blocks)
- - Errors that should be logged
- - User-facing error messages
-
-2. Add error handling for:
- - Network requests
- - File operations
- - Database queries
- - External API calls
-
-3. Ensure errors are:
- - Logged appropriately
- - Have clear messages
- - Include relevant context
- - Don't expose sensitive data
-
-4. Test error paths and commit improvements`,
-
- 'typing': `[Improvement: {appName}] TypeScript Type Improvements
+{modeInstructions}
-Improve TypeScript types in {appName}:
+## Hunt for
+
+- **Failures with no handler at a real boundary** — a network call, filesystem
+ operation, database query, subprocess, or external API whose failure has no
+ path other than propagating as an unhandled error.
+- **Missing timeouts** — an outbound call that can hang indefinitely, holding a
+ connection, a worker, or a user's request open with it.
+- **Retries without a ceiling** — a retry loop with no maximum, no backoff, or
+ no jitter, which converts a downstream blip into a self-inflicted flood.
+- **No fallback for a degraded dependency** — a feature that fails completely
+ when an optional or slow dependency is unavailable, where partial service was
+ possible.
+- **Errors that reach the user as noise** — a raw stack trace, an internal
+ identifier, or "Something went wrong" with no statement of what failed or what
+ to do next. An error message a user cannot act on is a defect.
+- **Sensitive detail in an error path** — a message, log line, or response that
+ leaks a secret, credential, internal path, or personal record while reporting
+ a failure.
+- **Cleanup that only runs on success** — a handle, lock, temporary file, or
+ in-flight marker released on the happy path but leaked when the operation
+ throws.
+- **Partial writes with no recovery** — a multi-step mutation that can fail
+ halfway, leaving a record or file in a state no code path expects.
+
+## Not yours
+
+A swallowed error with no log, log noise, and missing diagnostic context belong
+to the observability work. Latent defects that are simply bugs — a missing
+await, an unguarded null — belong to the runtime-safety work. Name an overlap
+where it is the cause, but leave the filing to its owner.
+
+## The bar
+
+Read the caller and the surrounding frames before flagging: the handling may
+live one level up, and the framework may already route what looks unhandled. For
+each finding, state the failure that reaches this code, what happens today, and
+what should happen instead — with \`file:LINE\`.`,
+
+ 'typing': `[Improvement: {appName}] Type Safety Audit
+
+Improve the type contracts in {appName} where weak typing is actually hiding a
+defect or blocking a correct change.
Repository: {repoPath}
-1. Review TypeScript files for:
- - 'any' types that should be specific
- - Missing type annotations
- - Type assertions that could be avoided
- - Missing interfaces/types for objects
-
-2. Add types for:
- - Function parameters and returns
- - Component props
- - API responses
- - Configuration objects
-
-3. Ensure:
- - Types are properly exported
- - No implicit any
- - Types are reusable
+{modeInstructions}
-4. Run type checking and commit improvements`,
+If the project does not use a typed language or a type checker, say so and exit
+cleanly rather than proposing that it adopt one.
+
+## Hunt for
+
+- **Escape hatches at a real boundary** — an untyped or \`any\`-typed value
+ crossing a public API, a route handler, a persisted record, or a module
+ boundary, so nothing downstream is checked.
+- **Assertions that paper over an unknown shape** — a cast asserting what the
+ code hopes is true, where a validated parse would prove it.
+- **Unvalidated external data typed as if it were trusted** — a network
+ response, file, environment value, or model output declared as a concrete type
+ without a runtime check that it matches.
+- **Optionality that does not match reality** — a field marked optional that
+ every path requires, or required where a real path omits it, forcing defensive
+ access everywhere.
+- **Types that disagree with their runtime validator** — a declared shape and
+ its schema that can accept different values, so one of them is lying.
+- **Structural duplicates** — the same shape declared independently in several
+ places, free to drift.
+
+## The bar
+
+A type change must remove a real class of mistake, not merely add annotation.
+Prefer narrowing at the boundary where untrusted data enters, so everything
+inside can rely on it. Do not propose a mechanical annotation sweep, and do not
+weaken a check to make an error disappear — if the type is inconvenient because
+the value really can be absent, the fix is the missing branch, not the cast.
+
+For each finding, give \`file:LINE\`, the value whose shape is unproven, the
+mistake the current typing permits, and the narrowing you propose. In implement
+mode, run the project's type check and tests before committing.`,
'release-check': `[Improvement: {appName}] Release Check
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index 22e63f3d9d..2bced5038b 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -33,19 +33,19 @@ export const PROMPT_VERSIONS = {
// default persisted, sometimes mis-flagged promptCustomized) auto-upgrade to the
// current {appName} body. See the retired-hash history in
// integrity.snapshot.json + the self-heal in taskScheduleStore.js readSchedule().
- 'security': 2, // v2: generic {appName} body (older default hardcoded "PortOS"/"server/routes" paths)
- 'code-quality': 3, // v3: inventory structural drift, duplicate sources of truth, volatile generated artifacts, and incidental-layout coupling before conventional maintainability checks. v2: generic {appName} body (older default hardcoded "PortOS")
- 'test-coverage': 2, // v2: generic {appName} body (older default hardcoded "PortOS")
- 'performance': 2, // v2: generic {appName} body (older default hardcoded "PortOS")
- 'accessibility': 2, // v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)
- 'console-errors': 2, // v2: unified `[Improvement: {appName}]` body (pre-unification defaults shipped separate self- and app-improvement bodies)
- 'error-handling': 2, // v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)
- 'typing': 2, // v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)
+ 'security': 3, // v3: carries {modeInstructions} (the pre-v3 body had no placeholder, so its own "fix and commit" steps fought a file-issues dispatch) and defers to the project's documented threat model, requiring an attacker-or-accident story per finding instead of a generic OWASP checklist walk. Previously v2: generic {appName} body (older default hardcoded "PortOS"/"server/routes" paths)
+ 'code-quality': 4, // v4: hands generated-artifact/hand-synced-registry/layout-coupling drift to the better-structural-drift lane and counted branching + reader cost to better-complexity / better-cognitive-load, keeping conventional maintainability defects — the split the sibling do:better lenses made possible. Previously v3: inventory structural drift, duplicate sources of truth, volatile generated artifacts, and incidental-layout coupling before conventional maintainability checks. v2: generic {appName} body (older default hardcoded "PortOS")
+ 'test-coverage': 3, // v3: carries {modeInstructions}, ranks gaps by consequence rather than percentage, tests at the highest practical public boundary, requires naming the regression a new test uniquely catches, and hands existing-test quality to better-test-quality. Previously v2: generic {appName} body (older default hardcoded "PortOS")
+ 'performance': 3, // v3: carries {modeInstructions} and requires a quantity (frequency x size, or a stated growth term) per finding — the pre-v3 body invited unmeasured micro-optimization. Previously v2: generic {appName} body (older default hardcoded "PortOS")
+ 'accessibility': 3, // v3: carries {modeInstructions}, names who is blocked and how far they get, and prefers a native element over a custom control with patched attributes. Previously v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)
+ 'console-errors': 3, // v3: carries {modeInstructions}, collects real emitted output before diagnosing, groups duplicates by cause, and forbids "fixing" an error by suppressing it. Previously v2: unified `[Improvement: {appName}]` body (pre-unification defaults shipped separate self- and app-improvement bodies)
+ 'error-handling': 3, // v3: carries {modeInstructions} and covers resilience (timeouts, retry ceilings, degraded-dependency fallback, cleanup on the error path, actionable user-facing text) while handing swallowed errors and log context to observability. Previously v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)
+ 'typing': 3, // v3: carries {modeInstructions}, exits cleanly on an untyped project, and targets boundary escape hatches and validator/type disagreement instead of a mechanical annotation sweep. Previously v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)
'dependency-updates': 4, // v4: the Phase 1 GitLab MR listing gains `--output json` — without it glab answers with the human table, which carries the head branch but NOT the author, while the classification right below it reads both. The same bump drops `--state` from the MR-list recipes — that flag does not exist (MR state is selected by presence flags `--merged`/`--closed`/`--all`, and OPEN is the default), so `--state opened` exited 1 with `Unknown flag: --state` and Phase 1 skipped its bot-PR triage entirely on GitLab repos. v3: Phase 1 triages open Dependabot/Renovate PRs first (evidence → MERGE / FIX-THEN-MERGE / CLOSE / LEAVE, including conflict + CI-failure repair on the bot branch) before Phase 2 updates anything the bots didn't cover — an agent that bumped packages itself was duplicating and conflicting with open bot PRs. v2: generic {appName} body (older default hardcoded "PortOS")
- 'documentation': 6, // v6: the changelog step names `AGENTS.md` (or `CLAUDE.md`) as the file carrying the repo's documented convention — #4852 made AGENTS.md the canonical cross-vendor agent-instructions filename, and a managed app that adopted it would otherwise be told to read a file it no longer has. v5: the changelog step defers to the convention the repo documents (some repos collect per-branch fragments in a directory so parallel agents don't conflict) instead of prescribing an append to `.changelog/NEXT.md`. v4: generic {appName} body (v1 hardcoded "PortOS"; v2/v3 retired DONE.md wording)
- 'ui-bugs': 2, // v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)
- 'mobile-responsive': 2, // v2: generic {appName} app-UI body (older default hardcoded "PortOS" + http://localhost:5555)
- 'ux': 1, // v1: walk the running UI with Playwright MCP against a 7-item named UX checklist and file ONE tracker item per finding via {trackerInstructions} — read-only on source, no branches/PRs. Mode (file-issues vs implement) is injected at dispatch via {modeInstructions} / applyAuditModeWrapper — no prompt bump required.
+ 'documentation': 7, // v7: carries {modeInstructions} and ranks wrong documentation above missing documentation, verifying instructions against the code rather than trusting the prose. Previously v6: the changelog step names `AGENTS.md` (or `CLAUDE.md`) as the file carrying the repo's documented convention — #4852 made AGENTS.md the canonical cross-vendor agent-instructions filename, and a managed app that adopted it would otherwise be told to read a file it no longer has. v5: the changelog step defers to the convention the repo documents (some repos collect per-branch fragments in a directory so parallel agents don't conflict) instead of prescribing an append to `.changelog/NEXT.md`. v4: generic {appName} body (v1 hardcoded "PortOS"; v2/v3 retired DONE.md wording)
+ 'ui-bugs': 3, // v3: carries {modeInstructions}, exits cleanly when the interface is unreachable instead of filing from imagination, and cedes layout/a11y/UX/copy to their owners. Previously v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)
+ 'mobile-responsive': 3, // v3: carries {modeInstructions} and requires the viewport width plus what a user cannot do there, rather than flagging any layout that merely looks different. Previously v2: generic {appName} app-UI body (older default hardcoded "PortOS" + http://localhost:5555)
+ 'ux': 2, // v2: replaces the hardcoded "Read-only on source / no branches, no PRs" paragraph with {modeInstructions} — the audit is registered as file-issues-capable, so a do-work dispatch previously got a mode banner that its own body contradicted in two places. Previously v1: walk the running UI with Playwright MCP against a 7-item named UX checklist and file ONE tracker item per finding via {trackerInstructions} — read-only on source, no branches/PRs. Mode (file-issues vs implement) is injected at dispatch via {modeInstructions} / applyAuditModeWrapper — no prompt bump required.
'data-safety': 1, // v1: data/upgrade-safety audit (migrations, schema parity, version gates). Mode injected at dispatch.
'simplify': 1, // v1: dead-code/duplication audit. Mode injected at dispatch.
'module-hygiene': 1, // v1: evidence-led complexity, responsibility, reuse, and reusable-surface discoverability audit. Mode injected at dispatch.
@@ -53,6 +53,21 @@ export const PROMPT_VERSIONS = {
'react-lifecycle': 1, // v1: React lifecycle/state audit (effect teardowns, stale closures, unmounted setState, derived state). Net-new type. Mode injected at dispatch.
'observability': 1, // v1: logging/observability audit (silent catches, log noise, missing error context, uninstrumented pipelines). Net-new type. Mode injected at dispatch.
'copy': 1, // v1: copy/text-clarity audit (jargon, ambiguous action verbs, dead-end errors, pluralization). Net-new type. Mode injected at dispatch.
+
+ // The `better-*` lanes: one scheduled task per slashdo `do:better` audit
+ // lens, so every category of app quality can be scheduled, provider-pinned,
+ // and toggled between filing and fixing on its own instead of being reachable
+ // only by fanning eight sub-agents out of one command run. The prefix marks
+ // the parity obligation — these bodies mirror an upstream lens
+ // (DO_BETTER_LENS_COVERAGE in lib/auditCatalog.js), so an improvement here is
+ // a candidate to push upstream rather than to diverge silently. Net-new types
+ // (no retired-hash history needed). Mode injected at dispatch.
+ 'better-complexity': 1, // v1: counted branching per function, ranked by churn/fan-in, with a named transformation and a behavior-preservation contract.
+ 'better-cognitive-load': 1, // v1: reader cost (mixed abstraction, flag arguments, lying names, action at a distance) — explicitly NOT the size/nesting thresholds its siblings own.
+ 'better-structural-drift': 1, // v1: derived artifacts as a second source of truth, position-keyed records, hand-synced registries, incidental-layout coupling — carved out of code-quality v3.
+ 'better-runtime-safety': 1, // v1: latent defects (floating promises, unowned rejections, unguarded access, sentinel confusion, races, leaks) requiring a concrete failure scenario.
+ 'better-dependency-freedom': 1, // v1: dependency NECESSITY (the do:depfree lens) — classify, prove usage, size the replacement. Distinct from dependency-updates, which bumps what stays.
+ 'better-test-quality': 1, // v1: vacuous/weak/redundant existing tests, proven with a mutation probe. Distinct from test-coverage, which owns the gaps.
'stash-cleanup': 2, // v2: the STALE/ABANDONED heuristic names `AGENTS.md` (or `CLAUDE.md`) as the policy file to check before assuming a stash contradicts current architecture (#4852). v1: triage git stash list — supersession check against main, drop superseded/stale entries, leave real unlanded work in place. Net-new type (no retired-hash history needed).
'repo-sync': 1, // v1: verify + finish the deterministic install-wide origin-sync sweep (services/repoSync.js) — resolve mid-flight merges/rebases, decide what to do with uncommitted work, land or report unpushed branches, triage the stashes it could not prove redundant. Net-new type (no retired-hash history needed).
'release-check': 13, // v13: a failing test suite or red CI is work the run must FIX (reproduce, classify regression vs. bad test vs. environmental blocker, fix the root cause, verify, commit, resume) instead of a reason to halt the release — a pre-existing failure on main stopped v12 short with the release untouched; skipping/deleting/loosening a test to force green is explicitly not a fix, and the loop is bounded (3 attempts per failure, 10 fix commits per run). v12: code review is advisory and only CI gates release progress; v11: delegate release mechanics to bundled slashdo release and pin PortOS-configured reviewers. v10: the release-documentation search names the `AGENTS.md` (or `CLAUDE.md`) context instead of CLAUDE.md alone (#4852). v9: Step 1 reconciles missing GitHub Releases against git release tags (publishing any missing tag with .changelog/vX.Y.Z.md as body and --latest=false when a newer version exists) BEFORE evaluating if enough unreleased work has accumulated; v8: database-backed release tests are provisioned and run using the repo's documented isolated test database before the release PR gate; v7: Step 1 also reads the UNCOLLECTED changelog fragments (the fragment dir, plus whatever preview command that repo documents — release-check is a generic {appName} prompt, so it never names a PortOS script to run) and counts substantive entries across the assembled notes — reading only the staged `.changelog/NEXT.md` under-counts a release whose entries are still per-branch fragments, so a ready release reported as "not enough work". v6: generic {appName} body (older defaults hardcoded "PortOS")
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index eb24165c2a..460efb92ce 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -182,6 +182,7 @@ import { RETIRED_CONSOLE_ERRORS_PROMPT } from './taskPromptDefaults/retiredPromp
// — the posture guard below iterates it so the two can't drift apart.
import { NON_COMMITTING_COORDINATOR_TASK_TYPES } from './taskTypeHooks.js'
import { enforceManagedAgentOptions } from './taskScheduleRegistry.js'
+import { modeContractFor, auditDoWorkRequiresWorktree } from '../lib/auditCatalog.js'
import { loadState } from './cosState.js'
@@ -1808,13 +1809,21 @@ describe('taskSchedule', () => {
expect(cfg.taskMetadata.readOnly).toBe(false)
})
- it('ships a prompt that files findings to the tracker and never edits source', async () => {
+ it('ships a prompt that files findings to the tracker and honors the injected mode', async () => {
const prompt = await getTaskPrompt('ux')
// The tracker block is injected at dispatch, so the token must survive here.
expect(prompt).toContain('{trackerInstructions}')
expect(prompt).toContain('[ux-…]')
- // Read-only on source; the issues ARE the deliverable.
- expect(prompt).toContain('do NOT create branches or PRs')
+ // Read-only-on-source is carried by the injected mode banner, not restated
+ // in the body. ux is a file-issues-CAPABLE audit that merely DEFAULTS to
+ // filing, so a body that hardcoded "no branches, no PRs" contradicted the
+ // do-work banner the catalog prepends when the user flips the toggle.
+ // Pin the seam instead of the sentence, and assert the contract it
+ // resolves to actually forbids the edits.
+ expect(prompt).toContain('{modeInstructions}')
+ expect(prompt).not.toMatch(/do NOT (edit|create branches)/)
+ expect(modeContractFor(true)).toContain('deliverable is tracker items, not code')
+ expect(modeContractFor(true)).toContain('open a PR, create a branch')
// Named checklist, not vibes.
expect(prompt).toContain('above the fold')
expect(prompt).toContain('1440x900')
@@ -1904,6 +1913,49 @@ describe('taskSchedule', () => {
])
})
+ // One scheduled lane per slashdo do:better audit lens. They ship file-issues
+ // by default because an unattended scheduled run must not land a refactor,
+ // and the four that restructure code require worktree isolation the moment
+ // the user flips them to implement — a mechanical rewrite of a hot function,
+ // a consolidation of two sources of truth, or a dependency swap is exactly
+ // the edit that must never happen in the operator's live checkout.
+ const BETTER_LANES = [
+ 'better-complexity',
+ 'better-cognitive-load',
+ 'better-structural-drift',
+ 'better-runtime-safety',
+ 'better-dependency-freedom',
+ 'better-test-quality',
+ ]
+
+ it.each(BETTER_LANES)('registers %s as an enabled on-demand file-issues audit', (taskType) => {
+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain(taskType)
+ expect(TASK_TYPE_DESCRIPTIONS[taskType]).toBeTruthy()
+ expect(DEFAULT_TASK_PROMPTS[taskType]).toBeTruthy()
+ const cfg = DEFAULT_TASK_INTERVALS[taskType]
+ expect(cfg.type).toBe(INTERVAL_TYPES.ON_DEMAND)
+ expect(cfg.enabled).toBe(true)
+ expect(cfg.taskMetadata.fileIssues).toBe(true)
+ expect(cfg.taskMetadata.useWorktree).toBe(false)
+ expect(cfg.taskMetadata.openPR).toBe(false)
+ // Dedup against work already filed or in flight, without spending the
+ // agent's own forge calls — the shape module-hygiene established.
+ expect(cfg.dataInputs).toEqual(['open-issues', 'open-pull-requests'])
+ // The file-issues posture is enforced at dispatch, so the user can still
+ // flip the toggle and implement.
+ expect(MANAGED_AGENT_OPTIONS[taskType]).toBeUndefined()
+ })
+
+ it('requires worktree isolation for the lanes whose remediation restructures code', () => {
+ const isolated = BETTER_LANES.filter((t) => auditDoWorkRequiresWorktree(t))
+ expect(isolated).toEqual([
+ 'better-complexity',
+ 'better-cognitive-load',
+ 'better-structural-drift',
+ 'better-dependency-freedom',
+ ])
+ })
+
it('surfaces fileIssuesCapable on audit types in getScheduleStatus', async () => {
mockSchedule()
const status = await getScheduleStatus()
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
index d0904c3a60..961a39bec2 100644
--- a/server/services/taskScheduleRegistry.js
+++ b/server/services/taskScheduleRegistry.js
@@ -57,9 +57,10 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// Quota-burn `data-safety-audit` counterpart. Migrations, schema parity, and
// cross-version compatibility. Defaults to file-issues (safer for unattended).
'data-safety',
- // Quota-burn `simplify-audit` counterpart. Dead code, unused exports, and
- // copy-paste drift — distinct from `code-quality` (which is the broader DRY /
- // long-function / TODO pass). Defaults to file-issues.
+ // Quota-burn `simplify-audit` counterpart. Dead code, unused exports,
+ // copy-paste drift, and YAGNI (speculative abstractions) — distinct from
+ // `code-quality` (conventional defects: magic values, brittle conditionals,
+ // convention violations). Defaults to file-issues.
'simplify',
// Structural-maintainability audit. Treats complexity thresholds as candidate
// signals, then proves responsibility, reuse, or discoverability impact before
@@ -80,6 +81,37 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// ambiguous action verbs, dead-end error text. Files under the `ux` label;
// narrower than the `ux` audit, which walks the running UI. File-issues.
'copy',
+ // The six lanes below complete the scheduled counterparts of the slashdo
+ // `do:better` audit lenses (DO_BETTER_LENS_COVERAGE in lib/auditCatalog.js),
+ // so every category of app quality can be scheduled on its own cadence
+ // instead of fanning eight sub-agents out of one command run.
+ // Measured branching per function — ranks the hottest high-complexity
+ // functions by churn and reduces them with a named transformation. The
+ // structural cousin of `module-hygiene` (which owns responsibility and
+ // ownership, and only uses complexity as a candidate signal). Remediation
+ // is a mechanical refactor of hot code, so do-work is worktree-isolated.
+ 'better-complexity',
+ // Reader cost no metric catches: mixed abstraction levels, flag arguments,
+ // misleading names, action at a distance. Sibling of `better-complexity`.
+ 'better-cognitive-load',
+ // Carved out of `code-quality` v3: derived artifacts kept as a second
+ // source of truth, hand-synchronized registries, incidental-layout
+ // coupling. Files under `code-quality`; do-work is worktree-isolated.
+ 'better-structural-drift',
+ // Latent defects found by reading source: missing awaits, unhandled
+ // rejections, unguarded null access, resource leaks, races, unbounded
+ // reads. Distinct from `console-errors` (observed at runtime),
+ // `error-handling` (failure paths + resilience) and `react-lifecycle`
+ // (component effects). Files under `bug`.
+ 'better-runtime-safety',
+ // Third-party dependency NECESSITY (the `do:depfree` lens) — replace
+ // micro-packages and native-API wrappers with in-repo code. Distinct from
+ // `dependency-updates`, which bumps what stays. Worktree-isolated do-work.
+ 'better-dependency-freedom',
+ // Tests that prove nothing: assert on mocks, can never fail, re-implement
+ // the code under test, or duplicate a stronger boundary test. Distinct from
+ // `test-coverage`, which owns the GAPS. Files under `tests`.
+ 'better-test-quality',
// Audits `git stash list` for {appName} and drops entries already superseded
// by (or a subset of) current `main`/HEAD, or that are stale/abandoned scratch
// work — without discarding real unlanded work. On-demand only (no cadence
@@ -462,6 +494,16 @@ export const DEFAULT_TASK_INTERVALS = {
'react-lifecycle': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
'observability': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
'copy': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
+ // The do:better-lens lanes. All file-issues by default (an unattended run
+ // must not land a refactor) and on-demand until the user picks a cadence.
+ // Open issues + PRs are preloaded so the agent dedups against in-flight
+ // work without spending its own forge calls, the way module-hygiene does.
+ 'better-complexity': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
+ 'better-cognitive-load': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
+ 'better-structural-drift': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
+ 'better-runtime-safety': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
+ 'better-dependency-freedom': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
+ 'better-test-quality': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
// Trusted remediation is separate from external intake. Legacy author
// filter settings cannot widen this lane into untrusted contributor PRs.
'pr-watcher': { type: INTERVAL_TYPES.ON_DEMAND, intervalMs: 1800000, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { prAuthorFilter: 'trusted', readOnly: false } },
@@ -657,6 +699,12 @@ export const TASK_TYPE_DESCRIPTIONS = {
'react-lifecycle': 'React lifecycle/state audit — file issues (default) or implement fixes',
'observability': 'Logging/observability audit — file issues (default) or implement fixes',
'copy': 'Copy/text-clarity audit — file issues (default) or implement rewrites',
+ 'better-complexity': 'Cyclomatic complexity — measure branching per function, reduce the hottest offenders; file issues (default) or implement one refactor',
+ 'better-cognitive-load': 'Cognitive load — mixed abstraction levels, flag arguments, misleading names, action at a distance; file issues (default) or implement one refactor',
+ 'better-structural-drift': 'Structural drift — generated artifacts as a second source of truth, hand-synced registries, layout coupling; file issues (default) or implement one consolidation',
+ 'better-runtime-safety': 'Runtime safety — missing awaits, unhandled rejections, unguarded nulls, leaks, races; file issues (default) or implement fixes',
+ 'better-dependency-freedom': 'Dependency freedom — replace micro-packages and native-API wrappers with in-repo code; file issues (default) or implement one removal',
+ 'better-test-quality': 'Test quality — vacuous, weak, or redundant tests; file issues (default) or implement one cleanup',
'model-comparison-refresh': 'Research sourced model quality, effort, price, latency and quota evidence for Models Comparison',
'stash-cleanup': 'Triage git stash list — drop entries superseded by or stale relative to main, leave real unlanded work in place',
'repo-sync': 'Sync every managed app with origin — back on the default branch, pushed and pulled, merged branches/worktrees and redundant stashes cleared',
diff --git a/server/services/workflow.js b/server/services/workflow.js
index 06000dfcb2..8179d4dcb0 100644
--- a/server/services/workflow.js
+++ b/server/services/workflow.js
@@ -83,7 +83,13 @@ export const WORKFLOW_STAGES = [
'api-contract',
'react-lifecycle',
'observability',
- 'copy'
+ 'copy',
+ 'better-complexity',
+ 'better-cognitive-load',
+ 'better-structural-drift',
+ 'better-runtime-safety',
+ 'better-dependency-freedom',
+ 'better-test-quality'
],
jobIds: ['job-wiki-maintenance', 'job-refresh-local-llm-catalog', 'job-refresh-cli-provider-catalogs']
},