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: bound Deep audit assignments without shrinking coverage (#10595)
[._.]/4ecc90ad2f09
diff --git a/docs/DEEP-AUDITS.md b/docs/DEEP-AUDITS.mdindex ba432000a1..a601356abe 100644--- a/docs/DEEP-AUDITS.md+++ b/docs/DEEP-AUDITS.md@@ -4,7 +4,7 @@ Deep is an audit depth, independent of **File issues** or **Audit and fix** deli## Run and resume-In an app's **Quality** tab, choose the categories, delivery policy, provider/model and **Audit depth → Deep**, then Run now. A launch performs one assigned pass, not the whole audit. A partial checkpoint stops the maintenance run. **Resume Deep audit** starts another invocation using the same coverage ledger. It may finish the current pass before moving to the next. Failed Deep tasks are parked rather than automatically retried. Completion keeps the task held until worktree cleanup finishes, then atomically parks it with any surviving branch/worktree pointer. Explicit resume waits for that handoff and reuses the persisted audit instructions. Recovery of an interrupted invocation also parks it for explicit resume instead of treating a commit or retry budget as permission to continue. Boot and reading status do not launch work.+In an app's **Quality** tab, choose the categories, delivery policy, provider/model and **Audit depth → Deep**, then Run now. A launch performs one server-assigned batch of one pass, not the whole audit. Batches contain at most 12 units and 96 distinct source paths; an indivisible larger unit is assigned alone and remains blocked if it cannot be substantively reviewed. Untouched units precede blocked units. The agent receives a compact assignment with pinned sources, prior evidence and relevant candidates; the full ledger remains available for targeted lookup. Batch limits never reduce the full coverage denominator. Delivery-only retries retain the full-scope challenge requirement and are not batched. A partial checkpoint stops the maintenance run. **Resume Deep audit** starts another invocation using the same coverage ledger. It may finish the current pass before moving to the next. Failed Deep tasks are parked rather than automatically retried. Completion keeps the task held until worktree cleanup finishes, then atomically parks it with any surviving branch/worktree pointer. Explicit resume waits for that handoff and reuses the persisted audit instructions. Recovery of an interrupted invocation also parks it for explicit resume instead of treating a commit or retry budget as permission to continue. Boot and reading status do not launch work.An app's **Automation** tab also exposes depth separately from delivery. An explicitly configured schedule can start a Deep audit; a partial task then parks and blocks further automatic dispatch for that app/category. Use Run Now to resume explicitly. Its app/category/delivery identity keeps the same ledger across those invocations. Custom agent jobs accept `taskMetadata.auditDepth: "deep"` and an optional `deepAuditId` for an explicitly selected checkpoint. A custom job without an audit category uses the code-quality coverage category. Different apps, categories and delivery modes cannot share a checkpoint.diff --git a/server/lib/deepAudit.js b/server/lib/deepAudit.jsindex 10f3a0168f..084456957e 100644--- a/server/lib/deepAudit.js+++ b/server/lib/deepAudit.js@@ -84,9 +84,28 @@ export function assignDeepAuditAttempt(ledger, agentId) {if (ledger.invalidReason || !ledger.units.length) throw new Error(ledger.invalidReason || 'Deep audit inventory is empty');const pass = DEEP_AUDIT_PASSES.find(name => ledger.units.some(unit => !unit.evidence[name] || unit.evidence[name].status === 'blocked'))|| (ledger.delivery === 'fix' ? 'post-fix' : 'challenge');- const units = ledger.units.filter(unit => !unit.evidence[pass] || unit.evidence[pass].status === 'blocked').map(unit => unit.id);- // A delivery-only retry still challenges the entire scope rather than accepting an empty proof.- const unitIds = units.length ? units : ledger.units.map(unit => unit.id);+ const remaining = ledger.units.filter(unit => !unit.evidence[pass] || unit.evidence[pass].status === 'blocked');+ const assignedCounts = new Map();+ for (const previous of Object.values(ledger.attempts)) {+ if (previous.pass !== pass) continue;+ for (const id of previous.unitIds) assignedCounts.set(id, (assignedCounts.get(id) || 0) + 1);+ }+ // Delivery-only retries still revisit scope; no empty assignment can certify delivery.+ const deliveryOnly = remaining.length === 0;+ const eligible = [...(deliveryOnly ? ledger.units : remaining)];+ // Untouched work first, then least-assigned retries: persistent blockers cannot starve peers.+ eligible.sort((a, b) => Number(Boolean(a.evidence[pass])) - Number(Boolean(b.evidence[pass]))+ || (assignedCounts.get(a.id) || 0) - (assignedCounts.get(b.id) || 0));+ const unitIds = [];+ const files = new Set();+ for (const unit of eligible) {+ const combined = new Set([...files, ...unit.files]);+ if (!deliveryOnly && unitIds.length && (unitIds.length >= 12 || combined.size > 96)) break;+ unitIds.push(unit.id);+ unit.files.forEach(path => files.add(path));+ }+ // An oversized indivisible unit is assigned alone and may remain explicitly blocked.+const prerequisiteHash = canonicalSnapshotChecksum(ledger.units.map(unit => ({ id: unit.id,evidence: Object.fromEntries(Object.entries(unit.evidence).filter(([key]) => key !== pass)) })));const attempt = { id: agentId, generation: ledger.generation, pass, unitIds, prerequisiteHash, scopeHash: ledger.scopeHash };@@ -153,15 +172,20 @@ export function mergeDeepAuditReport(ledger, agentId, raw, { deliverySuccess = funit.evidence[attempt.pass] = { ...result, agentId, prerequisiteHash: attempt.prerequisiteHash,...(attempt.pass === 'post-fix' ? { validationRevision } : {}), attestation: 'agent-reported, source-verified' };}+ const candidateUnits = new Set(attempt.unitIds);for (const addition of report.additionalUnits || []) {if (addition.files.some(path => !paths.has(path))) throw new Error('Additional coverage references unknown inventory');const id = canonicalSnapshotChecksum({ category: ledger.category, subsystem: addition.subsystem, scenario: addition.scenario });if (draft.units.some(unit => unit.id === id)) throw new Error('Additional unit duplicates existing scope');draft.units.push({ ...addition, id, category: ledger.category, evidence: {} });+ candidateUnits.add(id);}for (const candidate of report.candidates) {if (POLLUTING_KEYS.has(candidate.id)) throw new Error('Invalid candidate identity');- if (!draft.units.some(unit => unit.id === candidate.unitId)) throw new Error('Candidate references unknown coverage unit');+ if (!candidateUnits.has(candidate.unitId)) throw new Error('Candidate references unassigned coverage unit');+ if (draft.candidates[candidate.id] && draft.candidates[candidate.id].unitId !== candidate.unitId) {+ throw new Error('Candidate identity belongs to another coverage unit');+ }if (candidate.disposition === 'resolved' && (attempt.pass !== 'post-fix' || candidate.resolvedRevision !== validationRevision)) {throw new Error('Resolved findings require post-fix evidence at the tested revision');}@@ -185,10 +209,22 @@ export function refreshDeepAuditScope(ledger, scope) {return next;}-export function deepAuditInstructions({ ledger, attempt, ledgerPath, reportPath }) {+/** Agent-facing projection; the canonical ledger remains the authority for every receipt. */+export function deepAuditAssignment(ledger, attempt) {+ const byId = new Map(ledger.units.map(unit => [unit.id, unit]));+ const units = attempt.unitIds.map(id => byId.get(id));+ const paths = new Set(units.flatMap(unit => unit.files));+ return { version: ledger.version, id: ledger.id, category: ledger.category, delivery: ledger.delivery,+ scopeHash: ledger.scopeHash, generation: ledger.generation, attempt,+ scope: { ...ledger.scope, files: ledger.scope.files.filter(file => paths.has(file.path)) },+ units, candidates: Object.values(ledger.candidates).filter(candidate => attempt.unitIds.includes(candidate.unitId)),+ progress: deepAuditProgress(ledger), oversizedUnit: units.length === 1 && paths.size > 96 };+}++export function deepAuditInstructions({ ledger, attempt, ledgerPath, assignmentPath, reportPath }) {return `## Deep audit coverage contract v${DEEP_AUDIT_CONTRACT_VERSION} — highest-priority audit scopeThis overrides ALL bounded-slice, one-finding, five-findings, high-score and early-stop discovery instructions in saved/custom/legacy prompts and completion templates. Delivery mode stays ${ledger.delivery}. Small coherent remediation PRs remain required; do not expand a PR to contain the findings register.-Read the entire server-generated ledger at ${JSON.stringify(ledgerPath)}. Audit every assigned unit of pass ${attempt.pass}; follow all remaining units after finding a defect. The denominator is ${ledger.units.length} category/subsystem/scenario units, each requiring static, end-to-end trace, adversarial failure/concurrency/recovery and independent challenge evidence. Static scans alone never certify review. Inventory is a minimum: enroll discovered workflows, entry points and scenarios through additionalUnits before claiming completeness. Inaccessible evidence remains blocked.+Read the server-generated assignment at ${JSON.stringify(assignmentPath)}. The canonical full ledger at ${JSON.stringify(ledgerPath)} is available for targeted lookup; do not read or rescan all unrelated inventory/history on every invocation. Audit every assigned unit of pass ${attempt.pass}; continue the assigned batch after finding a defect. The server limits each batch to 12 units and 96 distinct source paths; an indivisible oversized unit is assigned alone and must remain blocked if it cannot be substantively reviewed. Delivery-only retries with all pass receipts already present retain the full-scope challenge requirement and are not batched. These limits bound work per invocation, never coverage. Stop with an honest partial checkpoint after the batch; remaining units require explicit resume. The denominator is ${ledger.units.length} category/subsystem/scenario units, each requiring static, end-to-end trace, adversarial failure/concurrency/recovery and independent challenge evidence. Static scans alone never certify review. Inventory is a minimum: enroll discovered workflows, entry points and scenarios through additionalUnits before claiming completeness. Inaccessible evidence remains blocked.Assignment: attemptId=${attempt.id}; scopeHash=${ledger.scopeHash}; prerequisiteHash=${attempt.prerequisiteHash}. Do not change the ledger or self-assign another pass. Independent challenge is a separate server-assigned invocation after prior passes. Discovery passes must not edit source; only the post-fix pass may implement one coherent fix, test/review/deliver it under the selected policy. Other confirmed findings stay in the register for later small PRs. File-issues mode may file findings after substantive review; filing limits never limit discovery or the register.During the run, atomically replace ${JSON.stringify(reportPath)} with a JSON checkpoint after each completed unit. This file is imported on exit, failure or interruption; never wait until context is exhausted. Time/context/budget exhaustion means PARTIAL with a stopReason and remaining units, not success. Resume requires another explicit launch; never create automatic retry loops or launch other audits.Report shape: {version:1,scopeHash,attemptId,prerequisiteHash,pass,units:[{id,status:"evidenced"|"blocked"|"inapplicable",reason,sources:[{path,blob}],evidence:{...}}],candidates:[{id,unitId,finding,disposition:"pending"|"confirmed"|"rejected"|"duplicate"|"deferred"|"resolved",resolution,resolvedRevision?}],additionalUnits?:[{subsystem,scenario,files,reason}],stopReason${attempt.pass === 'post-fix' ? ',validationRevision:"exact tested workspace HEAD"' : ''}}. Use resolved only in post-fix with resolvedRevision matching the tested HEAD and concrete fix/test evidence in resolution. Omit optional keys rather than spelling question marks in JSON. No extra keys. Include all checkpoints from this attempt in each atomic write. Copy identities and source blob hashes from the ledger. Static reports must account for EVERY file in their unit. Required evidence fields for ${attempt.pass}: ${EVIDENCE_FIELDS[attempt.pass].join(', ')}. Every field needs concrete observations, paths and outcomes, including when no findings survive. Inapplicability needs a scenario-specific reason and evidence in every pass, including independent confirmation; inaccessible evidence is BLOCKED, not inapplicable. Never invent commands, results or inspection evidence. These are agent attestations, not independent proof that tests ran.@@ -197,5 +233,5 @@ Checkpoint JSON schema (authoritative field types and limits):\`\`\`json${JSON.stringify(z.toJSONSchema(deepAuditReportSchema))}\`\`\`-Keep all candidates in the register, triage every one, including duplicates/rejections/deferred fixes. Delivery completion is distinct from discovery and does not mean all confirmed findings were remediated. Also preserve the ordinary QUALITY_AUDIT_JSON assessment and completion sentinel; neither a score nor process success can replace this checkpoint. Report missing evidence honestly.`;+Preserve the findings register; omitted candidates remain stored. Prefix new candidate IDs with this attemptId to avoid collisions with other batches; updates must reference assigned or newly enrolled units, and existing candidate IDs cannot move between units. Triage candidates relevant to this assignment, including duplicates/rejections/deferred fixes. Delivery completion is distinct from discovery and does not mean all confirmed findings were remediated. Also preserve the ordinary QUALITY_AUDIT_JSON assessment and completion sentinel; neither a score nor process success can replace this checkpoint. Report missing evidence honestly.`;}diff --git a/server/services/deepAudit.js b/server/services/deepAudit.jsindex 59713da450..e3dd5d4d8a 100644--- a/server/services/deepAudit.js+++ b/server/services/deepAudit.js@@ -6,7 +6,7 @@ import { atomicWrite, PATHS } from '../lib/fileUtils.js';import { tryReadFile } from '../lib/jsonIo.js';import { canonicalSnapshotChecksum } from '../lib/snapshotChecksum.js';import { normalizeAuditTaskType, isAuditTaskType } from '../lib/auditCatalog.js';-import { createDeepAuditLedger, assignDeepAuditAttempt, deepAuditProgress, deepAuditInstructions,+import { createDeepAuditLedger, assignDeepAuditAttempt, deepAuditProgress, deepAuditInstructions, deepAuditAssignment,mergeDeepAuditReport, refreshDeepAuditScope, DEEP_AUDIT_CONTRACT_VERSION } from '../lib/deepAudit.js';import { PROMPT_VERSIONS } from './taskPromptDefaults/versions.js';import { resolveTaskHookType } from './taskTypeHooks.js';@@ -21,7 +21,7 @@ function deepAuditId(task) {function deepAuditPaths(_workspacePath, agentId) {const prefix = `.portos-deep-${canonicalSnapshotChecksum(agentId).slice(0, 24)}`;const directory = join(PATHS.cos, 'deep-audit-checkpoints');- return { ledgerPath: join(directory, `${prefix}-ledger.json`), reportPath: join(directory, `${prefix}-report.json`) };+ return { ledgerPath: join(directory, `${prefix}-ledger.json`), assignmentPath: join(directory, `${prefix}-assignment.json`), reportPath: join(directory, `${prefix}-report.json`) };}async function inventoryDeepAudit(workspacePath, { promptHash, category }) {@@ -118,6 +118,7 @@ export async function prepareDeepAudit({ task, agentId, workspacePath }, deps =});const paths = deepAuditPaths(workspacePath, agentId);await (deps.write || atomicWrite)(paths.ledgerPath, ledger);+ await (deps.write || atomicWrite)(paths.assignmentPath, deepAuditAssignment(ledger, ledger.attempts[agentId]));return deepAuditInstructions({ ledger, attempt: ledger.attempts[agentId], ...paths });}diff --git a/server/services/deepAudit.test.js b/server/services/deepAudit.test.jsindex 1c04c036d9..3ccf250dca 100644--- a/server/services/deepAudit.test.js+++ b/server/services/deepAudit.test.js@@ -60,6 +60,89 @@ async function finish(agentId, selected = task, success = true) {}describe('Deep coverage workflow across serialized restarts', () => {+ it('batches serialized resumes without crediting omitted or out-of-batch units', async () => {+ pinned.files = Array.from({ length: 10 }, (_, i) => ({ path: `area-${i}/source.js`, blob, kind: 'blob' }));+ const writes = new Map();+ deps.write = async (path, value) => writes.set(path, structuredClone(value));+ const seen = new Set();+ for (let i = 0; i < 3; i++) {+ const id = `batch-${i}`;+ await prepare(id);+ const ledger = saved();+ const attempt = ledger.attempts[id];+ expect(attempt.pass).toBe('static');+ expect(attempt.unitIds.length).toBeLessThanOrEqual(12);+ for (const unit of attempt.unitIds) { expect(seen.has(unit)).toBe(false); seen.add(unit); }+ const projection = [...writes].find(([path]) => path.endsWith('-assignment.json') && writes.get(path).attempt.id === id)[1];+ expect(projection.units.map(unit => unit.id)).toEqual(attempt.unitIds);+ expect(projection).not.toHaveProperty('invalidated');+ expect(projection).not.toHaveProperty('attempts');+ expect(projection.progress.requiredPasses).toBe(120);+ if (i === 0) {+ const outside = ledger.units.find(unit => !attempt.unitIds.includes(unit.id));+ report = JSON.stringify(payload(id, { units: [{ ...payload(id).units[0], id: outside.id }] }));+ expect(await finish(id)).toMatchObject({ complete: false, satisfiedPasses: 0 });+ }+ report = JSON.stringify(payload(id));+ expect(await finish(id)).toMatchObject({ complete: false, discoveryComplete: false });+ }+ expect(seen.size).toBe(30);+ await prepare('next-pass');+ expect(saved().attempts['next-pass'].pass).toBe('trace');+ });++ it('preserves findings outside the batch and rejects candidate identity collisions', async () => {+ pinned.files = Array.from({ length: 5 }, (_, i) => ({ path: `area-${i}/source.js`, blob, kind: 'blob' }));+ await prepare('first');+ const firstUnit = saved().attempts.first.unitIds[0];+ const candidate = { id: 'first-finding', unitId: firstUnit, finding: 'Inspect the failure path', disposition: 'pending', resolution: 'Requires later validation' };+ report = JSON.stringify(payload('first', { candidates: [candidate] }));+ await finish('first');+ await prepare('second');+ const secondUnit = saved().attempts.second.unitIds[0];+ for (const invalid of [candidate, { ...candidate, unitId: secondUnit }]) {+ report = JSON.stringify(payload('second', { candidates: [invalid] }));+ expect(await finish('second')).toMatchObject({ satisfiedPasses: 12, complete: false });+ expect(saved().candidates['first-finding'].unitId).toBe(firstUnit);+ }+ report = JSON.stringify(payload('second'));+ await finish('second');+ expect(saved().candidates['first-finding']).toMatchObject(candidate);+ });++ it('retains full-scope delivery retries after all discovery receipts exist', async () => {+ pinned.files = Array.from({ length: 5 }, (_, i) => ({ path: `area-${i}/source.js`, blob, kind: 'blob' }));+ for (let i = 0; i < 8; i++) {+ const id = `discovery-${i}`;+ await prepare(id);+ report = JSON.stringify(payload(id));+ await finish(id, task, false);+ }+ expect(deepAuditProgress(saved())).toMatchObject({ discoveryComplete: true, deliveryComplete: false });+ await prepare('delivery-retry');+ expect(saved().attempts['delivery-retry'].unitIds).toHaveLength(15);+ });++ it('gives untouched units priority over blockers and isolates oversized units', async () => {+ pinned.files = [+ ...Array.from({ length: 100 }, (_, i) => ({ path: `large/${i}.js`, blob, kind: 'blob' })),+ { path: 'small/file.js', blob, kind: 'blob' },+ ];+ await prepare('oversized');+ expect(saved().attempts.oversized.unitIds).toHaveLength(1);+ const first = saved().attempts.oversized.unitIds[0];+ report = JSON.stringify(payload('oversized', { units: payload('oversized').units.map(unit => ({ ...unit, status: 'blocked' })) }));+ await finish('oversized');+ for (const id of ['second', 'third', 'small']) {+ await prepare(id);+ expect(saved().attempts[id].unitIds).not.toContain(first);+ report = JSON.stringify(payload(id));+ await finish(id);+ }+ await prepare('retry-blocker');+ expect(saved().attempts['retry-blocker'].unitIds).toEqual([first]);+ });+it('gives the agent exact evidence types and rejects array observations without crediting coverage', async () => {const prompt = await prepare('typed-report');const contract = JSON.parse(prompt.match(/```json\n([^]*?)\n```/)[1]);@@ -220,17 +303,26 @@ it('enrolls newly discovered workflows without shrinking the mechanically inventexpect(saved().attempts.b.unitIds).toHaveLength(1);});-it('does not combine post-fix checks from different source revisions', async () => {+it('does not combine post-fix batches from different source revisions and reassigns cleared units', async () => {+ pinned.files = Array.from({ length: 5 }, (_, i) => ({ path: `area-${i}/source.js`, blob, kind: 'blob' }));const fix = { ...task, metadata: { ...task.metadata, fileIssues: false } };- for (const agent of ['a', 'b', 'c', 'd']) { await prepare(agent, fix); report = JSON.stringify(payload(agent)); await finish(agent, fix); }- await prepare('x', fix); await prepare('y', fix);- const x = payload('x', { validationRevision: 'c'.repeat(40) });- const y = payload('y', { validationRevision: 'd'.repeat(40) });- x.units = x.units.slice(0, 3); y.units = y.units.slice(3);- pinned.revision = 'c'.repeat(40); report = JSON.stringify(x); await finish('x', fix);- pinned.revision = 'd'.repeat(40); report = JSON.stringify(y);+ for (let i = 0; i < 8; i++) {+ const agent = `discovery-${i}`;+ await prepare(agent, fix); report = JSON.stringify(payload(agent)); await finish(agent, fix);+ }+ await prepare('x', fix);+ const firstIds = saved().attempts.x.unitIds;+ expect(firstIds).toHaveLength(12);+ report = JSON.stringify(payload('x', { validationRevision: pinned.revision }));+ expect(await finish('x', fix)).toMatchObject({ complete: false });+ await prepare('y', fix);+ expect(saved().attempts.y.unitIds).toHaveLength(3);+ pinned.revision = 'd'.repeat(40);+ report = JSON.stringify(payload('y', { validationRevision: pinned.revision }));expect(await finish('y', fix)).toMatchObject({ discoveryComplete: true, deliveryComplete: false, complete: false });- expect(saved().units.filter(unit => unit.evidence['post-fix'])).toHaveLength(3);+ const ledger = saved();+ expect(ledger.units.filter(unit => unit.evidence['post-fix'])).toHaveLength(3);+ expect(assignDeepAuditAttempt(ledger, 'cleared').unitIds).toEqual(firstIds);});it('keeps scheduled and custom resume identities stable across task ids', async () => {