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
fix: make the four new audit types actually schedulable, and harden migration 305
[._.]/ Adam Eivy37db4816ca74
diff --git a/scripts/migrations/305-refresh-quota-burn-audit-contract.js b/scripts/migrations/305-refresh-quota-burn-audit-contract.jsindex 99753ac415..8a8d507297 100644--- a/scripts/migrations/305-refresh-quota-burn-audit-contract.js+++ b/scripts/migrations/305-refresh-quota-burn-audit-contract.js@@ -18,12 +18,22 @@* carried, which is how a user's own procedure is recognized and left alone.*/-import { readFile, writeFile } from 'fs/promises';+import { readFile } from 'fs/promises';import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileCore.js';import { upgradeStoredAuditPrompt } from '../../server/lib/quotaBurnPresets.js';const QUOTA_BURN_PATH = join('data', 'cos', 'quota-burn.json');+/**+ * Absent → `null` (nothing to migrate). Unparseable → THROW.+ *+ * Swallowing a parse error would return the same `null` as "this install has no+ * burn plan", the migration would report 0 updates, and the runner would record+ * 305 as applied — so once the user repaired their JSON, the refresh that is the+ * whole point of this migration would never run again. Failing loudly on a+ * corrupt file is the only outcome that stays recoverable.+ */async function readJson(path) {const raw = await readFile(path, 'utf-8').catch((err) => {if (err.code === 'ENOENT') return null;@@ -32,8 +42,8 @@ async function readJson(path) {if (raw == null) return null;try {return JSON.parse(raw);- } catch {- return null;+ } catch (err) {+ throw new Error(`${QUOTA_BURN_PATH} is not valid JSON (${err.message}) — repair it and re-run migrations`);}}@@ -61,7 +71,12 @@ export default {}}- if (updated) await writeFile(fullPath, `${JSON.stringify(config, null, 2)}\n`);+ // atomicWrite (temp file + rename), not writeFile: a truncating rewrite+ // interrupted mid-flight leaves a half-written quota-burn.json, and the+ // repaired-JSON path above would then never re-run because the runner has+ // already recorded 305 as applied. The trailing newline matches what the+ // store itself writes, so this never shows as a spurious diff.+ if (updated) await atomicWrite(fullPath, `${JSON.stringify(config, null, 2)}\n`);if (skipped) console.log(`✋ ${QUOTA_BURN_PATH}: left ${skipped} custom or already-current prompt(s) untouched`);return { updated, skipped };},diff --git a/scripts/migrations/305-refresh-quota-burn-audit-contract.test.js b/scripts/migrations/305-refresh-quota-burn-audit-contract.test.jsindex ad605b3ca4..0267141001 100644--- a/scripts/migrations/305-refresh-quota-burn-audit-contract.test.js+++ b/scripts/migrations/305-refresh-quota-burn-audit-contract.test.js@@ -22,10 +22,13 @@ const mission = currentPrompt.slice(0, currentPrompt.indexOf(AUDIT_CONTRACT_HEADconst staleContract = `${AUDIT_CONTRACT_HEADING}1. **Pick a bounded slice and say so first.** Audit one area.-2. **File each finding.** \`gh issue create --title "..." --body-file "$BODY"\`.+2. **Read the actual code.** Cite \`file.js:LINE\`.+3. **File each surviving finding as its own issue.**+ \`gh issue create --title "..." --body-file "$BODY"\`.Suggested labels: \`ux\`, \`plan\`. Run \`gh label list\` first.-3. **Change no code.** The deliverable is the filed issues.-4. **Report at the end**: the slice you audited and each issue number.+4. **Cap yourself at 5 issues.**+5. **Change no code.** The deliverable is the filed issues.+6. **Report at the end**: the slice you audited and each issue number.`;const stalePrompt = `${mission}${staleContract}`;@@ -82,4 +85,20 @@ describe('migration 305 — refresh quota-burn audit contract', () => {it('returns cleanly when the install has no quota-burn config', async () => {await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0 });});++ it('throws on a corrupt config instead of reporting zero updates', async () => {+ // Reporting `{ updated: 0 }` here would be indistinguishable from "this+ // install has no burn plan", the runner would record 305 as applied, and+ // the refresh would never run again once the user repaired the file.+ writeFileSync(configPath, '{ "families": { oops');+ await expect(migration.up({ rootDir })).rejects.toThrow(/not valid JSON/);+ });++ it('leaves the file byte-identical when it upgrades nothing', async () => {+ const custom = `# my own audit\n\n${AUDIT_CONTRACT_HEADING}\n\nJust report in chat.\n`;+ writeJson(configPath, config(custom));+ const before = readFileSync(configPath, 'utf8');+ await migration.up({ rootDir });+ expect(readFileSync(configPath, 'utf8')).toBe(before);+ });});diff --git a/server/lib/quotaBurnPresets.js b/server/lib/quotaBurnPresets.jsindex 5b6be6114f..98e8a135fa 100644--- a/server/lib/quotaBurnPresets.js+++ b/server/lib/quotaBurnPresets.js@@ -662,6 +662,52 @@ const SHIPPED_CONTRACT_ANCHORS = Object.freeze(['Report at the end',]);+/**+ * Every bolded heading any shipped contract revision has used — step titles and+ * the body-shape sub-labels.+ *+ * The anchors above prove a stored contract still contains the shipped skeleton;+ * they cannot tell whether the user ADDED to it. A user who kept all four+ * anchors and appended their own `**Also check X.**` step would pass the anchor+ * gate and have that step silently deleted by the refresh. So the rule is a+ * SUBSET test: every bold heading in the stored contract must be one this+ * project shipped. An unrecognized heading means the text is no longer purely+ * ours, and the prompt is left exactly as it is.+ *+ * The list must stay a superset of every historical render, not just the+ * current one — a title dropped from here turns into a refusal to upgrade the+ * jobs still carrying it. Refusing is the safe direction (the user keeps their+ * text and re-picks the preset), which is why the check is written this way+ * round rather than as a blocklist.+ */+const SHIPPED_CONTRACT_HEADINGS = Object.freeze(new Set([+ // Step titles, current revision.+ 'Pick a bounded slice and say so first.',+ 'Research each candidate before you judge it.',+ 'Prove the trigger.',+ 'Decide the fix before you file it.',+ 'De-duplicate before filing.',+ 'File each surviving finding as its own issue.',+ 'Bodies must be decision-complete',+ 'Cap yourself at 5 issues, and aim for two or three.',+ 'Redact before you publish.',+ 'Change no code.',+ 'Report at the end',+ // Step titles retired by earlier revisions but still sitting in stored jobs.+ 'Read the actual code.',+ 'Cap yourself at 5 issues.',+ // Body-shape sub-labels.+ 'Problem',+ 'Trigger',+ 'Impact',+ 'Fix',+ 'Acceptance criteria',+]));++/** The `**…**` headings in one rendered contract half, in document order. */+const contractHeadings = (contract) =>+ Array.from(contract.matchAll(/\*\*(.+?)\*\*/g), (match) => match[1]);+/*** The current render for a stored audit prompt that is still a shipped preset,* or `null` to leave the stored text exactly as it is.@@ -670,9 +716,12 @@ const SHIPPED_CONTRACT_ANCHORS = Object.freeze([* rather than on the whole string. A job seeded N contract revisions ago matches* no reconstructed prior render byte-for-byte (that is why migration 294 skipped* every real job as "user-edited"), but its mission half is unchanged, because- * revisions land in the contract. Requiring the stored contract to still carry- * `SHIPPED_CONTRACT_ANCHORS` keeps the looser rule from overwriting a user who- * kept a preset's mission and wrote their own procedure under it.+ * revisions land in the contract. Two gates keep that looser rule from eating a+ * user's own text: `SHIPPED_CONTRACT_ANCHORS` proves the shipped skeleton is+ * still there (they did not replace the procedure), and+ * `SHIPPED_CONTRACT_HEADINGS` proves nothing was ADDED to it (no step of their+ * own that a wholesale replacement would delete). Either gate failing means+ * leave it alone.** Returns `null` when the prompt is already current, so a caller can count real* upgrades without diffing.@@ -683,6 +732,7 @@ export function upgradeStoredAuditPrompt(stored) {const storedMission = stored.slice(0, index);const storedContract = stored.slice(index);if (!SHIPPED_CONTRACT_ANCHORS.every((anchor) => storedContract.includes(anchor))) return null;+ if (!contractHeadings(storedContract).every((heading) => SHIPPED_CONTRACT_HEADINGS.has(heading))) return null;for (const preset of QUOTA_BURN_PROMPT_PRESETS) {const current = preset.params.prompt;diff --git a/server/lib/quotaBurnPresets.test.js b/server/lib/quotaBurnPresets.test.jsindex 45154e3734..82d8f94a5a 100644--- a/server/lib/quotaBurnPresets.test.js+++ b/server/lib/quotaBurnPresets.test.js@@ -166,6 +166,33 @@ describe('upgradeStoredAuditPrompt', () => {expect(upgradeStoredAuditPrompt(`${mission}${AUDIT_CONTRACT_HEADING}\n\nJust report findings in chat.\n`)).toBeNull();});+ it('returns null when the user ADDED a step to an otherwise-shipped contract', () => {+ // The anchor gate alone passes here — every shipped sentence is still+ // present — so without the heading subset check the refresh would replace+ // the whole contract and silently delete the user's own step.+ const withExtraStep = current.replace(+ '9. **Redact before you publish.**',+ '9. **Always check the billing module first.** It is our riskiest area.\n10. **Redact before you publish.**'+ );+ expect(withExtraStep).not.toBe(current);+ expect(upgradeStoredAuditPrompt(withExtraStep)).toBeNull();+ });++ it('still upgrades a stale contract whose headings are all ones we shipped', () => {+ // Guards the subset check from the opposite failure: a retired step title+ // dropped from the known set turns into a silent refusal to upgrade every+ // job still carrying it, which is the bug migration 294 already had.+ const retiredTitles = `${mission}${AUDIT_CONTRACT_HEADING}+1. **Pick a bounded slice and say so first.** Audit one area.+2. **Read the actual code.** Cite file:line.+3. \`gh issue create --title "..."\` with **Problem**, **Impact**, **Fix**, and **Acceptance criteria**.+4. **Cap yourself at 5 issues.**+5. **Change no code.**+6. **Report at the end**: each issue number.+`;+ expect(upgradeStoredAuditPrompt(retiredTitles)).toBe(current);+ });+it('returns null for a prompt that is not a preset render at all', () => {expect(upgradeStoredAuditPrompt('Refactor the billing module and open a PR.')).toBeNull();expect(upgradeStoredAuditPrompt(undefined)).toBeNull();diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex fc4c14651d..0938239258 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -13,6 +13,10 @@"ux": "e03d03fc7c16faa5b5db93be2896b9ad","data-safety": "86b07f51abdbcbe7016f840b5bb0cd9b","simplify": "2a048214d1dd3b75bee9ae1a38fa1589",+ "api-contract": "cf02b10a5993baf473e0d320771f26b6",+ "react-lifecycle": "14b3816d1bcc10f0d7d6357e55cc5e69",+ "observability": "fdb4d77df5891cfb653a5da2553ecf8a",+ "copy": "6a0959e898d37fb4d4d7445dfc8008c9","feature-ideas": "d3282f16da29efe2d53595b3b34778bc","plan-feature": "87f71a894757f89354da4e2119e07118","plan-task": "b85fe92999aa4ee4a8910320457c4242",@@ -67,6 +71,10 @@"ux": 1,"data-safety": 1,"simplify": 1,+ "api-contract": 1,+ "react-lifecycle": 1,+ "observability": 1,+ "copy": 1,"stash-cleanup": 2,"repo-sync": 1,"release-check": 11diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 24cecdc4e6..ad4e9a49b4 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -527,6 +527,117 @@ Cross-version and cross-install compatibility code is NOT dead code, even whenthis install no longer hits it. Read the project's rules on migrations andversion gates before proposing any such removal.`,+ 'api-contract': `[Improvement: {appName}] API and route-contract audit++Audit {appName}'s API endpoints and route handlers for contract drift,+validation gaps, and error traps.++Repository: {repoPath}++{modeInstructions}++Trace client callers through to server routes and schemas, hunting for:++- **Unvalidated inputs** — endpoints reading \`req.body\`/\`query\`/\`params\`+ directly with no validation schema, letting malformed types into domain logic.+- **Client/server drift** — a client service sending a field no route reads, a+ route requiring one the caller omits, or a caller awaiting a key the response+ never carries.+- **Status and envelope errors** — a 200 carrying \`{ error }\`, a raw 500 for+ bad client input, or a bare string where the app's \`{ error: message }\`+ envelope is expected.+- **Async traps** — a route handler not wrapped in \`asyncHandler\`, where a+ rejected promise hangs the request socket instead of reaching the error+ middleware.+- **Loose schemas** — unbounded strings (no \`.max()\`), arbitrary keys (no+ \`.strict()\`), or an enum accepting values downstream code cannot handle.+- **Method mismatch** — a mutation behind \`GET\`, or a non-idempotent \`PUT\`.++For each finding, name the caller AND the route with \`file.js:LINE\`, the shape+that gets through, and the concrete failure it produces.`,++ 'react-lifecycle': `[Improvement: {appName}] React lifecycle and state audit++Audit {appName}'s React components, hooks, and state lifecycles for leaks,+stale closures, and render races.++Repository: {repoPath}++{modeInstructions}++Hunt specifically for:++- **Missing effect teardowns** — \`window\`/\`document\` listeners, timers,+ sockets, or observers created in \`useEffect\` with no cleanup on unmount.+- **Stale closures** — a callback or timer capturing state/props with no ref or+ dependency keeping it current, so it acts on data that has already moved on.+- **Unmounted state updates** — an async resolution setting state after unmount,+ or an earlier request's response overwriting a newer one's.+- **Derived-state anti-patterns** — a prop mirrored into local state and synced+ by an effect, which flashes the stale value before correcting itself.+- **Render-time side effects** — mutating a ref or firing work during render+ rather than in an effect or a handler.+- **Broken dependencies** — a missing dependency causing a stale read, or an+ inline object/array literal retriggering the effect every render.++Give the interaction sequence that triggers each defect, not just the code+shape: which action, in what order, leaving what on screen.`,++ 'observability': `[Improvement: {appName}] Logging and observability audit++Audit how {appName} logs events, reports runtime failures, and surfaces+diagnostics.++Repository: {repoPath}++{modeInstructions}++Hunt specifically for:++- **Silent failure swallowing** — a \`catch\` that discards the error with no+ log and no telemetry, so the failure is invisible in production.+- **Log noise** — a polling loop, socket frame handler, or hot render path+ emitting a line every tick, burying the errors that matter.+- **Missing error context** — an error logged with only \`err.message\`, with no+ task id, record id, route, or stack to reproduce from.+- **Wrong level** — a fatal runtime error logged through the equivalent of+ \`console.log\` instead of the project's error path.+- **Uninstrumented workflows** — a multi-step background pipeline or agent+ transition with no progress logging, so a stuck job looks identical to a slow+ one.++For each finding, name the catch block or uninstrumented step and state the+operational blind spot it creates: what breaks, and how long before anyone+notices.`,++ 'copy': `[Improvement: {appName}] Copy and text-clarity audit++Audit {appName}'s user-facing copy — labels, tooltips, dialogs, empty states,+and error messages — for clarity, accuracy, and consistency.++Repository: {repoPath}++{modeInstructions}++Hunt specifically for:++- **Internal jargon** — a variable name, database key, or protocol detail+ surfacing in a label where a domain term belongs.+- **Ambiguous action labels** — a generic "OK"/"Submit" on a destructive action+ instead of the actual verb ("Delete", "Discard"), or a "Cancel" that is+ ambiguous about which thing it cancels.+- **Dead-end error text** — "Failed" or "Invalid request" with no statement of+ what was wrong or what the user can do about it.+- **Broken pluralization** — "1 items", "found 1 results", "0 files deleted".+- **Inconsistent terminology** — the same entity or action named one way in the+ nav, another in a dialog, a third in a toast.+- **Clipped labels** — text in a fixed-width container that truncates the word+ carrying the meaning.++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.`,+'feature-ideas': `[Improvement: {appName}] Implement Next Planned FeatureYour goal is to implement the next planned item from PLAN.md, or brainstorm a new feature if no plan exists.diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex 39ffca138e..8d62f524dd 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -42,6 +42,10 @@ export const PROMPT_VERSIONS = {'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.'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.+ 'api-contract': 1, // v1: API/route-contract audit (validation gaps, client/server drift, status envelopes, asyncHandler). Net-new type (no PREVIOUS_DEFAULT_PROMPTS entry needed). Mode injected at dispatch.+ '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.'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 PREVIOUS_DEFAULT_PROMPTS entry 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 PREVIOUS_DEFAULT_PROMPTS entry needed).'release-check': 11, // 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/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.jsindex 4bbfce1bf2..34a8290061 100644--- a/server/services/taskScheduleRegistry.js+++ b/server/services/taskScheduleRegistry.js@@ -39,6 +39,21 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [// copy-paste drift — distinct from `code-quality` (which is the broader DRY /// long-function / TODO pass). Defaults to file-issues.'simplify',+ // Quota-burn `api-contract-audit` counterpart. Route validation, client/server+ // drift, status envelopes, and missing `asyncHandler`. Defaults to file-issues.+ 'api-contract',+ // Quota-burn `react-lifecycle-audit` counterpart. Effect teardowns, stale+ // closures, and post-unmount state — distinct from `ui-bugs` (console errors)+ // and `accessibility`. Defaults to file-issues.+ 'react-lifecycle',+ // Quota-burn `observability-audit` counterpart. Silent catches, log noise, and+ // errors logged without the context needed to reproduce them. Files under the+ // `code-quality` label. Defaults to file-issues.+ 'observability',+ // Quota-burn `copy-audit` counterpart. User-facing wording only — jargon,+ // 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',// 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@@ -328,6 +343,10 @@ export const DEFAULT_TASK_INTERVALS = {// file-issues so an unattended enable doesn't land code. Off by default.'data-safety': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },'simplify': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },+ 'api-contract': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },+ 'react-lifecycle': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },+ 'observability': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },+ 'copy': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },// pr-watcher polls for newly-opened PRs, so it runs on a short custom// interval rather than the loose rotation/daily cadence. 30 min keeps the// gh polling cheap while still reacting to a PR within one cycle. Default@@ -480,6 +499,10 @@ export const TASK_TYPE_DESCRIPTIONS = {'ux': 'UX/design audit — file issues (default) or implement fixes','data-safety': 'Data/upgrade-safety audit — file issues (default) or implement fixes','simplify': 'Dead-code/duplication audit — file issues (default) or implement removals',+ 'api-contract': 'API/route-contract audit — file issues (default) or implement fixes',+ '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','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','plan-feature': "Brainstorm one feature and file its decision-complete plan to the app's work tracker (no code)",