Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Keep code comments focused and audit excess in cognitive-load tasks (#11594)
[._.]/54a174f8089c
diff --git a/AGENTS.md b/AGENTS.mdindex 187dcc9297..0c58b8b3b5 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -199,6 +199,17 @@ When CoS agents or AI tools work on managed apps outside PortOS, all research, pThis complements the Security Model (the deployed product) — this section governs what agents may *write down* while working against real data.+## Code comments++Write comments for coding agents maintaining the code: concise context that cannot+be inferred from names and control flow. Keep the why, invariants, non-obvious+constraints, safety rationale, external contracts, and justified workarounds.+Remove redundant narration, stale explanations, commented-out code, and verbose+walkthroughs; prefer clear code when it can express the same information. Preserve+licenses, tool directives, meaningful type/JSDoc metadata, public API documentation,+and needed rationale. Do not use comment counts or length quotas as quality goals.+This policy governs code comments, not user-facing guides or product copy.+## Code Conventions- **Error handling** — in Express request handlers, let errors bubble to centralized middleware instead of wrapping each handler in try/catch. Client code uses the shared error/save boundaries in `client/src/AGENTS.md`. **Process-boundary exception:** PTY/child-process/`setTimeout`/`setInterval` callbacks and any code running *outside* the Express request lifecycle, where an uncaught throw crashes the Node process. At those boundaries, wrap hook invocation in try/catch and log via the emoji-prefixed `console.error` style. Async event handlers that mutate shared module-level state (e.g. the TUI spawner's `handleData`) must also be serialized — chain them onto a per-session/per-actor `Promise.resolve()` queue rather than firing concurrently.diff --git a/autofixer/server.js b/autofixer/server.jsindex 618bcfd675..53460737b3 100644--- a/autofixer/server.js+++ b/autofixer/server.js@@ -75,7 +75,6 @@ async function loadSettings() {return readJsonSafe(SETTINGS_FILE, {});}-// Get all monitored process names from registered appsasync function getMonitoredProcesses() {const apps = await loadApps();const processes = new Set();@@ -157,7 +156,6 @@ async function saveSession(sessionId, prompt, output, metadata, patch) {await saveIndex(index);}-// Get error logs for a processasync function getProcessLogs(processName) {const { stdout: errLogs } = await execPm2(['logs', processName, '--lines', '100', '--nostream', '--err']).catch(() => {throw new Error(`PM2 stderr logs unavailable for ${processName.replace(/[\r\n]/g, ' ').slice(0, 120)} — skipping repair`);diff --git a/autofixer/shared.js b/autofixer/shared.jsindex 85777f5f2e..27a9fdaa92 100644--- a/autofixer/shared.js+++ b/autofixer/shared.js@@ -68,7 +68,6 @@ export const APPS_FILE = join(DATA_DIR, 'apps.json');export const AUTOFIXER_DIR = join(DATA_DIR, 'autofixer');export const INDEX_FILE = join(AUTOFIXER_DIR, 'index.json');-// Load apps from PortOSexport async function loadApps() {try {const parsed = JSON.parse(await readFile(APPS_FILE, 'utf8'));diff --git a/autofixer/ui.js b/autofixer/ui.jsindex 7ad76f61bb..362375385b 100644--- a/autofixer/ui.js+++ b/autofixer/ui.js@@ -22,7 +22,6 @@ const UI_HTML = await readFile(UI_TEMPLATE_FILE, 'utf8');const stagedFixes = createStagedFixStore({ root: AUTOFIXER_DIR, loadApps, execPm2 });-// Load autofixer historyasync function loadHistory() {const data = await readFile(INDEX_FILE, 'utf8').catch(() => '[]');return stagedFixes.decorateHistory(JSON.parse(data));diff --git a/browser/server.js b/browser/server.jsindex 28259b5557..c55b12de6a 100644--- a/browser/server.js+++ b/browser/server.js@@ -44,10 +44,7 @@ function getMacAppBundle(config, chromePath) {async function loadConfig() {const raw = await readFile(CONFIG_FILE, 'utf-8').catch(() => null);if (!raw) return {};- // Guard against a partially-written / corrupt config (now user-editable via- // the Browser settings UI). An unguarded JSON.parse here throws on boot —- // loadConfig is awaited from launchBrowser()→main() with no catch, so a bad- // file would crash the PM2 child into a restart-loop. Fall back to defaults.+ // Corrupt user-editable config must not put the browser child in a restart loop.try {return JSON.parse(raw);} catch (err) {@@ -58,25 +55,9 @@ async function loadConfig() {const checkCdp = () => probeCdpVersion(`http://${CDP_HOST}:${CDP_PORT}/json/version`);-// Chrome's download directory is set through the profile's own `Preferences`-// file, NOT through CDP's `Browser.setDownloadBehavior`.-//-// `Browser.setDownloadBehavior` looks like the obvious lever, but setting it-// swaps Chrome's `ChromeDownloadManagerDelegate` for the automation-only-// `DevToolsDownloadManagerDelegate`. That delegate routes the bytes to the-// requested path — downloads land correctly and the download UI lists them —-// but it leaves `OpenDownload()` / `ShowDownloadInShell()` as no-ops. The-// result: every shell handoff from the download UI ("Show in Finder", "Open-// file", clicking a row in chrome://downloads or the download bubble) silently-// does nothing, with no error anywhere. Verified against Chrome 151 by-// A/B-ing two otherwise identical browsers: without the CDP call the reveal-// selects the file in Finder, with it nothing happens at the OS level.-//-// Writing `download.default_directory` into the profile keeps the native-// delegate, so downloads land in the configured directory AND the UI stays-// clickable. The pref is not one of Chrome's MAC-protected prefs, so writing-// it directly is safe. It must be written while Chrome is NOT running —-// Chrome rewrites Preferences from memory on exit.+// CDP Browser.setDownloadBehavior replaces Chrome's native download delegate,+// making Open/Show in Finder no-ops (verified on Chrome 151). Set the unprotected+// profile prefs instead, before Chrome starts: it overwrites them on exit.async function applyDownloadDirPreference(profileDir, downloadDir) {const prefsPath = join(profileDir, 'Default', 'Preferences');const raw = await tryReadJson(prefsPath);diff --git a/client/src/components/DecisionLogWidget.jsx b/client/src/components/DecisionLogWidget.jsxindex 0e9b2ad337..7f490ece59 100644--- a/client/src/components/DecisionLogWidget.jsx+++ b/client/src/components/DecisionLogWidget.jsx@@ -93,7 +93,6 @@ const DecisionLogWidget = memo(function DecisionLogWidget() {const { last24Hours, impactfulDecisions, transparencyScore } = summary;- // Get icon and color for decision typeconst getDecisionStyle = (type) => {switch (type) {case 'task_skipped':diff --git a/client/src/components/UpcomingTasksWidget.jsx b/client/src/components/UpcomingTasksWidget.jsxindex a6223d43a6..dc927300a0 100644--- a/client/src/components/UpcomingTasksWidget.jsx+++ b/client/src/components/UpcomingTasksWidget.jsx@@ -56,7 +56,6 @@ const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {return null;}- // Separate ready tasks from scheduled onesconst currentTasks = upcoming.map(task => ({...task,eligibleInFormatted: Number.isFinite(task.eligibleAt) ? timeUntil(task.eligibleAt) : task.eligibleInFormatted,@@ -65,7 +64,6 @@ const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {const readyTasks = currentTasks.filter(t => t.status === 'ready');const scheduledTasks = currentTasks.filter(t => t.status === 'scheduled');- // Get interval type labelconst getIntervalLabel = (intervalType) => {const labels = {'on-demand': 'On Demand',@@ -74,7 +72,6 @@ const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {return labels[intervalType] || intervalType;};- // Get icon for task based on typeconst getTaskIcon = (taskType) => {const icons = {'security': '🔒',diff --git a/client/src/components/digital-twin/PersonalityMap.jsx b/client/src/components/digital-twin/PersonalityMap.jsxindex fc7f7e4f57..1e47b88c88 100644--- a/client/src/components/digital-twin/PersonalityMap.jsx+++ b/client/src/components/digital-twin/PersonalityMap.jsx@@ -59,7 +59,6 @@ export default function PersonalityMap({ traits, confidence, providers, onAnalyzconst bigFive = traits?.bigFive;const hasTraits = bigFive && Object.keys(bigFive).length > 0;- // Get dimension confidence from confidence objectconst getDimensionConfidence = (trait) => {const dimensionMap = {O: 'openness',diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex 7860822b59..72572a629a 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -315,7 +315,6 @@ export function usePostSession() {const newResults = [...drillResults, result];setDrillResults(newResults);- // Check if there are more drillsif (currentDrillIndex + 1 < drills.length) {setState(STATES.BETWEEN_DRILLS);} else {@@ -382,7 +381,6 @@ export function usePostSession() {return;}- // Check if drill is completeif (currentQuestionIndex + 1 >= (currentDrill.questions?.length ?? 0)) {finishDrillRef.current(newAnswers);} else {diff --git a/client/src/utils/coalesce.js b/client/src/utils/coalesce.jsindex d7ddbb808a..a606786984 100644--- a/client/src/utils/coalesce.js+++ b/client/src/utils/coalesce.js@@ -1,12 +1,6 @@-// Collapse a burst of rapid calls into a single trailing invocation on a short tick.-// OpenWorld subscribes to many socket events (CoS agent spawn/complete, AI status, task-// changes, …); when several fire at once — e.g. a wave of agents spawning — a handler that-// triggers a full refetch per event would fan out N identical refreshes. Wrapping that-// handler in `coalesce` runs it once on the trailing edge instead.-//-// Trailing-edge by design: the LAST call's effect always runs, so state still converges to-// the freshest value — only the redundant intermediate calls are dropped. Call `.cancel()`-// on teardown so a pending flush can't fire after unmount.+// Coalesce event bursts into one trailing call with the latest arguments, so+// refreshes converge without duplicate requests. Call .cancel() on teardown+// to prevent a pending flush after unmount.export function coalesce(fn, waitMs = 100) {let timer = null;let lastArgs = [];diff --git a/scripts/jira-create-ticket.js b/scripts/jira-create-ticket.jsindex f59b6efbab..d7fac11d23 100755--- a/scripts/jira-create-ticket.js+++ b/scripts/jira-create-ticket.js@@ -28,10 +28,8 @@ import fs from 'fs/promises';const __dirname = dirname(fileURLToPath(import.meta.url));const rootDir = join(__dirname, '..');-// Import services directlyconst jiraService = await import(join(rootDir, 'server/services/jira.js'));-// Parse CLI argsfunction parseArgs() {const args = process.argv.slice(2);const parsed = { sprint: true, points: 1 };diff --git a/scripts/jira-update-ticket.js b/scripts/jira-update-ticket.jsindex 18e276ccbf..76f788db71 100644--- a/scripts/jira-update-ticket.js+++ b/scripts/jira-update-ticket.js@@ -33,10 +33,8 @@ import fs from 'fs/promises';const __dirname = dirname(fileURLToPath(import.meta.url));const rootDir = join(__dirname, '..');-// Import services directlyconst jiraService = await import(join(rootDir, 'server/services/jira.js'));-// Parse CLI argsfunction parseArgs() {const args = process.argv.slice(2);const parsed = {};diff --git a/scripts/setup-db.js b/scripts/setup-db.jsindex 4ca00c383e..c73601cf78 100644--- a/scripts/setup-db.js+++ b/scripts/setup-db.js@@ -72,7 +72,6 @@ function getMode() {return settings.mode;}-// Check if Docker is availablefunction hasDocker() {try {execFileSync('docker', ['--version'], { stdio: 'pipe' });@@ -82,7 +81,6 @@ function hasDocker() {}}-// Check if Docker daemon is runningfunction isDockerRunning() {try {execFileSync('docker', ['info'], { stdio: 'pipe' });@@ -92,7 +90,6 @@ function isDockerRunning() {}}-// Check if docker compose is available (v2 plugin)function hasCompose() {try {execFileSync('docker', ['compose', 'version'], { stdio: 'pipe' });diff --git a/scripts/setup-ghostty.js b/scripts/setup-ghostty.jsindex 998f3044e0..3162ff78c0 100644--- a/scripts/setup-ghostty.js+++ b/scripts/setup-ghostty.js@@ -10,7 +10,6 @@ const rootDir = join(__dirname, '..');const home = homedir();const isMac = platform() === 'darwin';-// Check if Ghostty is installedconst ghosttyInstalled = (() => {const paths = ['/Applications/Ghostty.app',diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.jsindex 69cf445a29..f3dd6cdec8 100644--- a/server/lib/auditCatalog.js+++ b/server/lib/auditCatalog.js@@ -413,7 +413,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({'better-cognitive-load': {quotaBurnId: null,label: 'Cognitive load & readability',- description: 'Reader-cost audit — configurable: file issues (default) or implement one refactor',+ description: 'Reader-cost and excessive code-comment audit — configurable: file issues (default) or implement one refactor',defaultFileIssues: true,doWorkRequiresWorktree: true,filing: filing({diff --git a/server/routes/apps/agents.js b/server/routes/apps/agents.jsindex 6e975044b4..4eefb76454 100644--- a/server/routes/apps/agents.js+++ b/server/routes/apps/agents.js@@ -18,7 +18,6 @@ router.get('/:id/agents', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;const { limit } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 500 });- // Get running agents filtered by this appconst runningAgents = await cos.getAgents().catch(() => []);const appRunning = runningAgents.filter(a =>a.metadata?.app === app.id || a.metadata?.taskApp === app.id@@ -38,7 +37,6 @@ router.get('/:id/agents', loadApp, asyncHandler(async (req, res) => {historyAgents.push(...appAgents);}- // Combine running + history, deduplicate by id, limitconst seenIds = new Set();const combined = [];for (const agent of [...appRunning, ...historyAgents]) {diff --git a/server/routes/apps/lifecycle.js b/server/routes/apps/lifecycle.jsindex e5a9eb4c11..6907f41498 100644--- a/server/routes/apps/lifecycle.js+++ b/server/routes/apps/lifecycle.js@@ -317,13 +317,10 @@ router.post('/:id/refresh-config', loadApp, asyncHandler(async (req, res) => {throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });}- // Parse ecosystem config from the app's repo pathconst { processes, pm2Home } = await parseEcosystemFromPath(app.repoPath);- // Update app with new process dataconst updates = {};- // Detect buildCommand from package.json if not already setif (!app.buildCommand) {const pkgPath = join(app.repoPath, 'package.json');const pkgContent = await tryReadFile(pkgPath);@@ -333,7 +330,6 @@ router.post('/:id/refresh-config', loadApp, asyncHandler(async (req, res) => {}}- // Update pm2Home if detected and different from currentif (pm2Home && pm2Home !== app.pm2Home) {updates.pm2Home = pm2Home;}diff --git a/server/routes/brainLinks.js b/server/routes/brainLinks.jsindex a8070b30f0..73baf1870e 100644--- a/server/routes/brainLinks.js+++ b/server/routes/brainLinks.js@@ -125,7 +125,6 @@ router.post('/links', asyncHandler(async (req, res) => {const { url, ...options } = validateRequest(linkInputSchema, req.body);if (deriveRepoLinkFields(url).isRepo && options.autoClone !== false) assertHostControl(req);- // Check if URL already existsconst existing = await brainService.getLinkByUrl(url);if (existing) {throw new ServerError('Link with this URL already exists', {diff --git a/server/routes/uploads.js b/server/routes/uploads.jsindex 183bb779af..3305e890fd 100644--- a/server/routes/uploads.js+++ b/server/routes/uploads.js@@ -113,7 +113,6 @@ router.get('/', asyncHandler(async (req, res) => {};}));- // Sort by creation date, newest firstuploads.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));res.json({diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 24581ec3e0..33a860b703 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -1,17 +1,4 @@-/**- * Tests for the light-vs-full context split in buildAgentPrompt.- *- * The split is by `provider.type`:- * - `tui` / `cli` → light prompt (Claude Code, Codex, Antigravity — agentic- * CLIs with native filesystem tools and agent-instruction loading)- * - `api` → full prompt (LM Studio, raw OpenAI/Anthropic — no- * native filesystem access, so we paste in memory/AGENTS.md/etc.)- *- * The light path is the focus here because it's the new code. The full- * path is exercised by a single negative assertion that confirms the- * obsolete "# Chief of Staff Agent Briefing" header and "You are an- * autonomous agent…" preamble are gone from BOTH paths.- */+// Exercise both native-file-tool and API prompt assembly paths.import { MANDATORY_DISPATCH_HINT_GUIDANCE } from '../lib/dispatchLabels.js';import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';@@ -21,15 +8,8 @@ import { tmpdir } from 'os';import { execFileSync, spawnSync } from 'child_process';import { PATHS } from '../lib/fileUtils.js';-// #3475 — The builder reads ~/.claude/CLAUDE.md off the real filesystem and splices-// it into the prompt, so without this every `not.toMatch` assertion below is decided-// by the contributor's personal global config: it false-fails when their file happens-// to contain the string, and false-passes on a machine that has no such file at all-// (CI), where the suppression being asserted is never actually exercised. Pointing-// homedir() at a path that cannot exist makes the global section deterministically-// empty. `homeStub` stays mutable so the one test that needs a REAL global CLAUDE.md-// (a fixture that deliberately contains the suppressed string) can swap it in and-// prove the suppression positively — see the #3475 describe block further down.+// Isolate personal instructions so contributor config cannot decide assertions.+// Tests of global-instruction loading override this with a fixture home (#3475).const homeStub = vi.hoisted(() => ({ dir: '/nonexistent-home-for-tests' }));vi.mock('os', async (importOriginal) => ({...(await importOriginal()),@@ -235,6 +215,26 @@ describe('composable skill template routing', () => {expect(loadTemplate).toHaveBeenNthCalledWith(2, 'threejs-visual');});+ it.each([true, false])('preserves comment maintenance in API/native prompts with fileIssues=%s', async (fileIssues) => {+ const { modeContractFor } = await import('../lib/auditCatalog.js');+ const mode = modeContractFor(fileIssues);+ const description = DEFAULT_TASK_PROMPTS['better-cognitive-load']+ .replaceAll('{appName}', 'Example App')+ .replaceAll('{repoPath}', '/workspace/example-app')+ .replace('{modeInstructions}', mode);+ const task = makeTask({ description, metadata: {+ analysisType: 'better-cognitive-load', noCodeOutput: fileIssues,+ } });+ for (const providerType of ['api', 'tui', 'cli']) {+ const prompt = await buildAgentPrompt(task, {}, '/workspace/example-app', null, { providerType });+ expect(prompt).toContain('Excessive code comments');+ expect(prompt).toContain('Preserve licenses, tool directives, meaningful type/JSDoc metadata');+ expect(prompt).toContain('review the diff for behavior preservation');+ expect(prompt).not.toContain('{modeInstructions}');+ expect(prompt).not.toMatch(/add (?:clear |helpful )?comments/i);+ }+ });+it('keeps the final module-hygiene mission generic across API and TUI/CLI paths', async () => {const description = DEFAULT_TASK_PROMPTS['module-hygiene'].replaceAll('{appName}', 'Example App')diff --git a/server/services/autonomousJobs/scheduler.js b/server/services/autonomousJobs/scheduler.jsindex 4b5de3663f..30a10b99d8 100644--- a/server/services/autonomousJobs/scheduler.js+++ b/server/services/autonomousJobs/scheduler.js@@ -87,7 +87,6 @@ async function getDueJobs() {if (lastRun >= targetUtc) continue}- // If job is weekdaysOnly, skip weekendsif (job.weekdaysOnly && !isWeekday(timezone)) continuedue.push({@@ -98,7 +97,6 @@ async function getDueJobs() {}}- // Sort by overdue time (most overdue first)due.sort((a, b) => b.overdueBy - a.overdueBy)return duediff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.jsindex 5d0288fe84..b1371b6116 100644--- a/server/services/cosTaskGenerator.auditMode.test.js+++ b/server/services/cosTaskGenerator.auditMode.test.js@@ -1,24 +1,5 @@-/**- * The generated-task/prompt BOUNDARY for the file-issues vs implement audit mode (#6380).- *- * Every other test of this contract stops at `isFileIssuesMode` or at the task- * metadata. Neither proves the thing that actually matters: that an issues-only- * run cannot ACQUIRE code-shipping instructions. The mode is enforced two hops- * apart — the generator stamps `FILE_ISSUES_DELIVERY_SETTINGS`, and the prompt- * builder reads `noCodeOutput` off that stamp to pick a completion contract — so- * a change on either side can quietly re-arm `/do:push` on an audit that was- * only ever supposed to file issues.- *- * This suite closes both hops: it GENERATES the real task for every audit type- * in the catalog and RENDERS the final agent prompt from it, then asserts that- * no commit/push/PR/auto-merge directive survives — and that the same pipeline- * in implement mode still emits the ordinary code-delivery workflow, so the- * assertions cannot pass by rendering nothing.- *- * Isolated file for the same reason `cosTaskGenerator.referenceWatch.test.js`- * is: the mocked leaf graph (taskSchedule / taskPromptService / appActivity)- * must not leak into the shared cosTaskGenerator suite.- */+// Generate real tasks and render final prompts: mode metadata alone cannot prove+// that issues-only audits stay free of shipping instructions (#6380).import { describe, it, expect, beforeEach, vi } from 'vitest';@@ -175,6 +156,30 @@ describe('issues-only audit dispatch never acquires code-shipping instructions (applicability.inapplicable = {};});+ it.each([true, false])('cognitive-load comment policy survives dispatch with fileIssues=%s', async (fileIssues) => {+ const { DEFAULT_TASK_PROMPTS } = await import('./taskPromptDefaults.js');+ const { getTaskInterval } = await import('./taskSchedule.js');+ promptTemplate.body = DEFAULT_TASK_PROMPTS['better-cognitive-load'];+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues } });++ const task = await generate('better-cognitive-load');+ const prompt = renderPrompt(task);+ expect(prompt).toContain('Excessive code comments');+ expect(prompt).toContain('safety rationale, external contracts, and justified workarounds');+ expect(prompt).toContain('Preserve licenses, tool directives, meaningful type/JSDoc metadata');+ expect(prompt).toContain('not a rewrite of user-facing documentation');+ expect(prompt).toContain('review the diff for behavior preservation');+ expect(prompt).not.toContain('{modeInstructions}');+ expect(prompt).not.toMatch(/add (?:clear |helpful )?comments/i);+ if (fileIssues) {+ expectNoCodeDelivery(prompt, 'better-cognitive-load');+ expect(prompt).toContain('Mode: file issues, change nothing');+ } else {+ expect(task.metadata.noCodeOutput).not.toBe(true);+ expect(prompt).toContain('## Completion Workflow');+ }+ });+it('bails out before generating an audit that cannot apply, advancing the cadence', async () => {applicability.inapplicable = { 'mobile-responsive': 'no user interface found in this repository' };const { recordExecution } = await import('./taskSchedule.js');diff --git a/server/services/dailyReview.js b/server/services/dailyReview.jsindex 19ef70e5d8..ec1d838805 100644--- a/server/services/dailyReview.js+++ b/server/services/dailyReview.js@@ -58,7 +58,6 @@ export async function getDailyReview(date, { limit = DAILY_REVIEW_PAGE_SIZE, off}return review;});- // Get all events for this date across all accountsconst startDate = `${date}T00:00:00`;const endDate = `${date}T23:59:59`;const [dayEvents, accounts, goalsData] = await Promise.all([@@ -73,7 +72,6 @@ export async function getDailyReview(date, { limit = DAILY_REVIEW_PAGE_SIZE, off}}- // Build goal and subcalendar maps for linking infoconst goalMap = {};for (const goal of goalsData.goals) {goalMap[goal.id] = goal;@@ -85,7 +83,6 @@ export async function getDailyReview(date, { limit = DAILY_REVIEW_PAGE_SIZE, off}}- // Enrich events with confirmation status and goal matchesconst pageEvents = dayEvents.slice(offset, offset + limit);const enrichedEvents = pageEvents.map(event => {const confirmation = existing.confirmations[eventKey(event)];@@ -104,7 +101,6 @@ export async function getDailyReview(date, { limit = DAILY_REVIEW_PAGE_SIZE, off};});- // Get progress entries for this dateconst progressEntries = [];for (const goal of goalsData.goals) {for (const entry of (goal.progressLog || [])) {diff --git a/server/services/digital-twin-meta.js b/server/services/digital-twin-meta.jsindex 56f4455aa9..a6bacfa541 100644--- a/server/services/digital-twin-meta.js+++ b/server/services/digital-twin-meta.js@@ -101,7 +101,6 @@ async function buildInitialMeta() {});}- // Sort by prioritymeta.documents.sort((a, b) => a.priority - b.priority);return meta;diff --git a/server/services/digital-twin-testing.js b/server/services/digital-twin-testing.jsindex 61c65fd9ab..4016456153 100644--- a/server/services/digital-twin-testing.js+++ b/server/services/digital-twin-testing.js@@ -20,7 +20,6 @@ export async function parseTestSuite() {const content = await readFile(testFile, 'utf-8');const tests = [];- // Parse test blocks using regexconst testPattern = /### Test (\d+): (.+?)\n\n\*\*Prompt\*\*\s*\n([\s\S]*?)\n\n\*\*Expected Behavior\*\*\s*\n([\s\S]*?)\n\n\*\*Failure Signals\*\*\s*\n([\s\S]*?)(?=\n---|\n### Test|\n## |$)/g;let match;@@ -52,7 +51,6 @@ export async function runTests(providerId, model, testIds = null, personaId = nuthrow new Error(`Provider ${providerId} not found or disabled`);}- // Filter tests if specific IDs providedconst testsToRun = testIds? tests.filter(t => testIds.includes(t.testId)): tests;diff --git a/server/services/messageTokenExtractor.js b/server/services/messageTokenExtractor.jsindex bfdd1fd126..c62f22b7f4 100644--- a/server/services/messageTokenExtractor.js+++ b/server/services/messageTokenExtractor.js@@ -166,13 +166,11 @@ export async function getToken(provider) {const config = PROVIDERS[provider];if (!config) return { error: 'unknown-provider', message: `Unknown provider: ${provider}`, provider };- // Return cached token if still validconst cached = tokenCache.get(provider);if (cached && isTokenValid(cached)) {return { token: cached.token, decoded: cached.decoded, fresh: false, provider };}- // Find the provider's tab in the browserconst pages = await getPages().catch(() => []);const page = pages.find(p => p.url?.includes(config.tabPattern));diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.jsindex c60d053c3f..4244bc4afd 100644--- a/server/services/taskPromptDefaults.test.js+++ b/server/services/taskPromptDefaults.test.js@@ -228,7 +228,7 @@ describe('taskPromptDefaults integrity snapshot', () => {['better-dev-environment', ['Measure, do not only read', 'before and after', 'Prefer a guard to a patch', 'Not yours']],])('%s states the discipline that makes it its own lane', (key, markers) => {const current = DEFAULT_TASK_PROMPTS[key];- const versions = { 'better-complexity': 2, 'better-runtime-safety': 3, 'better-test-quality': 2 };+ const versions = { 'better-cognitive-load': 2, 'better-complexity': 2, 'better-runtime-safety': 3, 'better-test-quality': 2 };expect(PROMPT_VERSIONS[key]).toBe(versions[key] ?? 1);for (const marker of markers) expect(current, key).toContain(marker);});diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex 089b8df0cd..4cec9489bd 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -3,7 +3,7 @@"accessibility": "46f628a44a919bb788de8761e86ca0e1","api-contract": "d52e00ec53eb5618df1a769efccc08f3","app-launch-video": "271c1e8bc301ba02b4a2207e0abf8573",- "better-cognitive-load": "a1fe22f6ef936131456c55a6b0623204",+ "better-cognitive-load": "882bbda803edcdef5a4308521050f8fd","better-complexity": "c99f67b43ff54a1c8cf0176c721d9c06","better-dependency-freedom": "8a79c8be829f926bbc7720ee29818d53","better-dev-environment": "62523b82066e70ff1c786da22ccf0372",@@ -68,7 +68,7 @@"accessibility": 5,"api-contract": 2,"app-launch-video": 8,- "better-cognitive-load": 1,+ "better-cognitive-load": 2,"better-complexity": 2,"better-dependency-freedom": 1,"better-dev-environment": 1,@@ -145,6 +145,9 @@"e355d37fb682c1f6c2ad4c031a7988a7","d9ce59c884841cdfcab7139d05778e74"],+ "better-cognitive-load": [+ "a1fe22f6ef936131456c55a6b0623204"+ ],"better-complexity": ["c92b99080d0453d70bb26a412fb48ce9"],diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 6c5726606f..21e94b2f1a 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -1472,9 +1472,18 @@ shows is changed most often.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.+- **Excessive code comments** — redundant narration, stale explanations,+ commented-out code, and verbose walkthroughs of obvious control flow. Read the+ surrounding code before deciding what to remove or shorten. Keep concise context+ that cannot be inferred from names and code paths: why, invariants, non-obvious+ constraints, safety rationale, external contracts, and justified workarounds.+ Preserve licenses, tool directives, meaningful type/JSDoc metadata, public API+ documentation, and needed rationale. Prefer clearer code when it can express+ the same information. Do not use comment counts or length quotas as targets.+ This is code-comment maintenance, not a rewrite of user-facing documentation.+ In file-issues mode, report concrete examples and the proposed cleanup without+ editing source; in implement mode, remove or tighten excessive comments and+ review the diff for behavior preservation.- **Action at a distance** — module-level mutable state, implicit orderingrequirements between calls ("you must call init first"), and side effectshidden behind names that read as pure.diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex 2090ccb295..ec1b469927 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -64,7 +64,7 @@ export const PROMPT_VERSIONS = {// than copied command mechanics. Net-new types (no retired-hash history// needed). Mode injected at dispatch.'better-complexity': 2, // v2: compare repository-wide worst offenders; low churn is not an exclusion. 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-cognitive-load': 2, // v2: audit and clean excessive code comments while preserving contracts and rationale. 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': 3, // v3: adds cross-module contract breaks in untyped code (missing members, missing named exports, dropped wrapper arguments) with a guard-test fix. Previous version: Framework-neutral UI lifecycle overlap. Previous version: 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.diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.jsindex 14685d1291..beafdd3e6d 100644--- a/server/services/taskScheduleRegistry.js+++ b/server/services/taskScheduleRegistry.js@@ -602,7 +602,7 @@ export const TASK_TYPE_DESCRIPTIONS = {'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-cognitive-load': 'Cognitive load — excessive code comments, 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',