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

fix: partition Deep coverage and advance independent obligations

Adam Eivybe17163c73a6
diff --git a/docs/DEEP-AUDITS.md b/docs/DEEP-AUDITS.md
index a0f06bfa69..1ac1b803d8 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 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, with feasible untouched units before indivisible oversized units. Blocked units rotate by attempt count regardless of size. 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.
+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. Each subsystem/scenario is partitioned deterministically by sorted source paths into units of at most 24 files. Every source path belongs to exactly one partition of each scenario. Batches contain at most 12 partitions and 96 distinct owned paths. A very large individual file or unavailable required runtime evidence can still block a partition. Untouched obligations precede repeated blockers, with pass rotation and attempt counts preventing starvation. A partition advances through its own prerequisite passes; a blocked neighbor does not prevent useful trace, adversarial or challenge work elsewhere. 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. Publication-only retries at an unchanged revision use bounded rotating re-attestation batches while retaining the complete global coverage requirements. They are explicitly marked delivery retries, not new full-scope reviews. Failed publication remains incomplete; a changed validation revision invalidates prior post-fix receipts. A partial checkpoint stops the maintenance run. **Resume Deep audit** starts another invocation using the same coverage ledger. It can continue a partition into its next pass while other partitions still need earlier passes. 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.
@@ -14,16 +14,16 @@ Manual runs show discovery, reviewed units, satisfied/required pass requirements
The server pins a clean Git revision, tracked paths and blob IDs, inventory hash, detected capabilities, explicit exclusions, category prompt version, Deep contract version and effective task prompt hash. It inventories root files, code, tests, docs and configuration rather than filtering to popular source suffixes. Fresh isolated workspaces initialize submodules recursively at their recorded commits before inventory. Retained submodule changes are refused rather than reset. Fresh resume workspaces use the server-owned ledger revision even when the default branch has advanced; an unavailable pinned commit blocks launch instead of falling back to a different source. An unexpanded submodule blocks completion. Ignored runtime assets are outside the source inventory; required runtime evidence that cannot be obtained must remain blocked.
-The initial units are category × source directory/subsystem × normal, failure, and concurrency/recovery scenarios. This is a minimum, not a claim that those three scenarios exhaust every workflow. Agents can add concrete workflows or entry-point scenarios through `additionalUnits`; additions increase the denominator and require the same passes. They cannot delete inventoried units.
+The coverage groups are category × source directory/subsystem × normal, failure, and concurrency/recovery scenarios. Each group owns deterministic source partitions. Group completion is the conjunction of actual partition receipts, never a synthetic review receipt. This is a minimum, not a claim that those three scenarios exhaust every workflow. Agents can add concrete workflows or entry-point scenarios through `additionalUnits`; additions increase the denominator and require the same passes. They cannot delete inventoried units.
Every required unit needs evidence from:
1. Static inspection, accounting for every file in that unit.
-2. End-to-end tracing, recording entry, exit and the intervening path.
-3. Adversarial investigation, recording scenario, expected behavior and observed outcome.
-4. An independent challenge invocation, bound to the preceding evidence and attributed to a different server-issued agent identity.
+2. End-to-end tracing, recording entry, exit, inbound callers, outbound dependencies, boundary observations and unresolved boundary questions. Follow relevant callers/callees outside the owned partition and cite their pinned identities as context; those references do not credit their separate coverage.
+3. Adversarial investigation, recording scenario, expected behavior, observed outcome and failures across the identified boundaries.
+4. An independent challenge invocation, bound to the preceding evidence and attributed to a different server-issued agent identity, explicitly challenging cross-boundary assumptions.
-Statuses are derived from receipts: pending, scanned, traced, validated, reviewed, blocked, or inapplicable with a reason. Inapplicability needs source references and pass-specific explanations, including independent confirmation. A scan count, quality score, successful process, first fix or five findings cannot complete discovery. Required units and passes must be accounted for and candidates triaged. The findings register retains confirmed, rejected, duplicate, deferred and resolved candidates separately from small remediation PRs.
+Statuses are derived from receipts: pending, scanned, traced, validated, reviewed, blocked, or inapplicable with a reason. Inapplicability needs source references and pass-specific explanations, including independent confirmation. A scan count, quality score, successful process, first fix or five findings cannot complete discovery. Required units and passes must be accounted for and candidates triaged. A verified defect is reviewed evidence, not automatically a coverage blocker: a dangling tracked symlink can be inspected and its missing target verified without claiming to review nonexistent contents. Genuinely inaccessible required evidence remains blocked. The findings register retains confirmed, rejected, duplicate, deferred and resolved candidates separately from small remediation PRs.
Fix delivery also requires a post-fix pass against a clean, exact tested revision. All current post-fix receipts must bind to that revision; evidence from different revisions cannot combine into completion. A resolved finding names that tested revision and its fix/test evidence; changing the validation revision requires re-attesting prior resolutions. Discovery, remediation and delivery have separate outcomes: deferred fixes keep remediation incomplete. Actual execution and verification results settle delivery after evidence ingestion. Existing PR policy still governs delivery; selecting Deep does not authorize merging or deploying.
@@ -33,6 +33,8 @@ Fix delivery also requires a post-fix pass against a clean, exact tested revisio
Agents atomically replace their checkpoint files after units, under `data/cos/deep-audit-checkpoints/`, outside source worktrees. Finalization imports them on success, failure or interruption before worktree cleanup. The JSON file preserves progress during an invocation; the UI's persisted counters advance when finalization imports it. Missing or malformed reports remain partial. The files contain private audit evidence and must not be committed. They are retained with CoS data for recovery; database receipts remain authoritative after import.
-Source, inventory, capabilities, exclusions or prompt changes conservatively invalidate current evidence and retain it as historical. This first version invalidates the full generation rather than trying to prove which dependencies were unaffected. That includes resuming against a changed HEAD after an interrupted fix; the earlier discovery remains readable but does not certify the new source. Preserve and use the retained worktree/branch when recovering incomplete remediation. Git cannot move a linked worktree containing submodules: for a verified inactive, clean owned workspace, Deep resume detaches the old tree at its exact HEAD and attaches the preserved branch in a new workspace. The old files remain intact. Dirty, locked or ambiguous submodule workspaces stay blocked for explicit recovery; they are never force-deinitialized or reset.
+Contract v3 upgrades v1/v2 ledgers transactionally on explicit resume. The complete prior generation remains historical, and new partition/boundary obligations receive no inherited receipt credit. When the contract is the only scope change, enrolled groups and findings are retained. Legacy findings remain explicitly group-scoped, visible from each assigned partition in that group without conferring coverage credit. New findings must bind to assigned partitions. Migration records both old and new required-pass counts and is idempotent; stale in-flight reports cannot update the replacement generation.
+
+Source, inventory, capabilities, exclusions or other prompt changes conservatively invalidate current evidence and retain it as historical. This first version invalidates the full generation rather than trying to prove which dependencies were unaffected. That includes resuming against a changed HEAD after an interrupted fix; the earlier discovery remains readable but does not certify the new source. Preserve and use the retained worktree/branch when recovering incomplete remediation. Git cannot move a linked worktree containing submodules: for a verified inactive, clean owned workspace, Deep resume detaches the old tree at its exact HEAD and attaches the preserved branch in a new workspace. The old files remain intact. Dirty, locked or ambiguous submodule workspaces stay blocked for explicit recovery; they are never force-deinitialized or reset.
Evidence is **agent-reported, source-verified**. The server checks assignment, scope, source blob identities, required evidence fields, ordering, separate invocation identity and exact revision bindings. It cannot prove that a natural-language trace is truthful or that a reported command actually ran. Independent challenge is a distinct invocation, not a guarantee of a different provider/model. Existing test and PR review requirements remain necessary. Deep mode may take many explicitly resumed invocations; it has no automatic repeat-until-perfect loop and launches no additional categories on its own.
diff --git a/server/lib/README.md b/server/lib/README.md
index 3176276e03..a4d191c750 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -878,4 +878,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoReviewDraft.js` | Pure imported Animatic review candidates, newest immutable version first; exact version URLs remain separate from native production approvals. |
+| `deepAuditCoverage.js` | Deterministic bounded source partitions, derived coverage groups and explicit contract-upgrade compatibility. |
| `deepAudit.js` | Strict Deep audit checkpoint schema, scope invalidation, server-assigned passes and mechanical completion rules. |
diff --git a/server/lib/deepAudit.js b/server/lib/deepAudit.js
index f1c46046a4..1dbcb44738 100644
--- a/server/lib/deepAudit.js
+++ b/server/lib/deepAudit.js
@@ -1,11 +1,12 @@
import { z } from 'zod';
import { POLLUTING_KEYS } from './objects.js';
import { canonicalSnapshotChecksum } from './snapshotChecksum.js';
+import { createDeepAuditCoverage, partitionDeepAuditGroup, isDeepAuditContractUpgrade } from './deepAuditCoverage.js';
+export { DEEP_AUDIT_SCENARIOS } from './deepAuditCoverage.js';
export const DEEP_AUDIT_VERSION = 1;
-export const DEEP_AUDIT_CONTRACT_VERSION = 2;
+export const DEEP_AUDIT_CONTRACT_VERSION = 3;
export const DEEP_AUDIT_PASSES = Object.freeze(['static', 'trace', 'adversarial', 'challenge']);
-export const DEEP_AUDIT_SCENARIOS = Object.freeze(['normal', 'failure', 'concurrency-recovery']);
const text = z.string().trim().min(1).max(12000);
const source = z.object({ path: text, blob: z.string().regex(/^[a-f0-9]{40,64}$/) }).strict();
export const deepAuditReportSchema = z.object({
@@ -34,18 +35,9 @@ export const deepAuditReportSchema = z.object({
/** Every tracked path belongs to a subsystem; unknown file types are not dropped. */
export function createDeepAuditLedger({ id, appId, category, scope, delivery }) {
- const groups = new Map();
- for (const file of scope.files) {
- const subsystem = file.path.includes('/') ? file.path.slice(0, file.path.lastIndexOf('/')) : '.';
- if (!groups.has(subsystem)) groups.set(subsystem, []);
- groups.get(subsystem).push(file.path);
- }
- const units = [...groups].flatMap(([subsystem, files]) => DEEP_AUDIT_SCENARIOS.map(scenario => ({
- id: canonicalSnapshotChecksum({ category, subsystem, scenario }), category, subsystem, scenario, files,
- evidence: {},
- })));
+ const { groups, units } = createDeepAuditCoverage(category, scope.files);
return { version: DEEP_AUDIT_VERSION, id, appId, category, scope, scopeHash: canonicalSnapshotChecksum(scope),
- delivery, units, candidates: {}, attempts: {}, invalidated: [], reason: 'Awaiting evidence', generation: 1 };
+ delivery, coverageVersion: DEEP_AUDIT_CONTRACT_VERSION, groups, units, candidates: {}, attempts: {}, invalidated: [], reason: 'Awaiting evidence', generation: 1 };
}
export function deepAuditProgress(ledger) {
@@ -62,6 +54,11 @@ export function deepAuditProgress(ledger) {
? 'inapplicable' : ['pending', 'scanned', 'traced', 'validated', 'reviewed'][count];
statuses[status]++;
}
+ const unitsById = new Map(ledger.units.map(unit => [unit.id, unit]));
+ const reviewedGroupIds = new Set((ledger.groups || []).filter(group => group.unitIds.every(id => {
+ const unit = unitsById.get(id);
+ return unit && DEEP_AUDIT_PASSES.every(pass => validReceipt(unit.evidence[pass]));
+ })).map(group => group.id));
const pendingCandidates = Object.values(ledger.candidates).filter(candidate => candidate.disposition === 'pending').length;
const required = ledger.units.length * DEEP_AUDIT_PASSES.length;
const discoveryComplete = required > 0 && !ledger.scope.files.some(file => file.kind === 'commit') && !ledger.invalidReason && satisfied === required && !blocked && !pendingCandidates;
@@ -74,51 +71,66 @@ export function deepAuditProgress(ledger) {
const remediationComplete = ledger.delivery === 'fix' && deliveryComplete && pendingRemediations === 0;
return { discoveryComplete, remediationComplete,
deliveryComplete, pendingRemediations, complete: discoveryComplete && deliveryComplete && (ledger.delivery !== 'fix' || remediationComplete),
+ totalGroups: ledger.groups?.length ?? ledger.units.length, reviewedGroups: reviewedGroupIds.size,
totalUnits: ledger.units.length, reviewedUnits: statuses.reviewed + statuses.inapplicable,
satisfiedPasses: satisfied, requiredPasses: required, blockedUnits: blocked, pendingCandidates, statuses,
reason: ledger.invalidReason || ledger.reason, resume: !discoveryComplete || !deliveryComplete || (ledger.delivery === 'fix' && !remediationComplete) };
}
+const priorPasses = pass => pass === 'post-fix' ? DEEP_AUDIT_PASSES : DEEP_AUDIT_PASSES.slice(0, DEEP_AUDIT_PASSES.indexOf(pass));
+const validReceipt = receipt => receipt && receipt.status !== 'blocked';
+function prerequisiteHash(ledger, pass, unitIds) {
+ return canonicalSnapshotChecksum({ validationRevision: pass === 'post-fix' ? ledger.validationRevision ?? null : null,
+ units: ledger.units.filter(unit => unitIds.includes(unit.id)).map(unit => ({ id: unit.id,
+ evidence: Object.fromEntries(Object.entries(unit.evidence).filter(([name]) => name !== pass)) })) });
+}
+
export function assignDeepAuditAttempt(ledger, agentId) {
if (ledger.attempts[agentId]) return ledger.attempts[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 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);
+ const counts = new Map();
+ for (const attempt of Object.values(ledger.attempts)) {
+ for (const id of attempt.unitIds) {
+ const key = `${attempt.pass}:${id}`;
+ counts.set(key, (counts.get(key) || 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]))
- // Review feasible untouched units before indivisible oversized ones. Once blocked,
- // all units rotate by attempt count rather than permanently preferring small blockers.
- || (!a.evidence[pass] && !b.evidence[pass] ? Number(a.files.length > 96) - Number(b.files.length > 96) : 0)
- || (assignedCounts.get(a.id) || 0) - (assignedCounts.get(b.id) || 0));
- const unitIds = [];
- const files = new Set();
- for (const unit of eligible) {
+ // Each partition advances independently; a blocked neighbor cannot starve its trace.
+ let eligible = ledger.units.flatMap(unit => {
+ const pass = DEEP_AUDIT_PASSES.find(name => !validReceipt(unit.evidence[name]));
+ return pass ? [{ unit, pass }] : [];
+ });
+ let deliveryOnly = false;
+ if (!eligible.length) {
+ const pass = ledger.delivery === 'fix' ? 'post-fix' : 'challenge';
+ eligible = ledger.units.filter(unit => !validReceipt(unit.evidence[pass])
+ || (pass === 'post-fix' && unit.evidence[pass]?.validationRevision !== ledger.validationRevision)).map(unit => ({ unit, pass }));
+ deliveryOnly = eligible.length === 0;
+ if (deliveryOnly) eligible = ledger.units.map(unit => ({ unit, pass }));
+ }
+ const passes = [...DEEP_AUDIT_PASSES, 'post-fix'];
+ const last = Object.values(ledger.attempts).at(-1)?.pass;
+ const next = (passes.indexOf(last) + 1) % passes.length;
+ const rank = item => [Number(Boolean(item.unit.evidence[item.pass])), counts.get(`${item.pass}:${item.unit.id}`) || 0,
+ (passes.indexOf(item.pass) - next + passes.length) % passes.length];
+ const compare = (a, b) => { const x = rank(a), y = rank(b); return x[0] - y[0] || x[1] - y[1] || x[2] - y[2] || a.unit.files[0].localeCompare(b.unit.files[0]) || a.unit.id.localeCompare(b.unit.id); };
+ eligible.sort(compare);
+ const pass = eligible[0].pass;
+ const unitIds = [], files = new Set();
+ for (const { unit } of eligible.filter(item => item.pass === pass)) {
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));
+ if (unitIds.length && (unitIds.length >= 12 || combined.size > 96)) continue;
+ 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 };
+ const attempt = { id: agentId, generation: ledger.generation, pass, unitIds, deliveryOnly,
+ prerequisiteHash: prerequisiteHash(ledger, pass, unitIds), scopeHash: ledger.scopeHash };
ledger.attempts[agentId] = attempt;
return attempt;
}
const EVIDENCE_FIELDS = {
- static: ['method', 'observations'], trace: ['entryPoint', 'exitPoint', 'trace'],
- adversarial: ['scenario', 'expected', 'observed'], challenge: ['challengedAssumption', 'conclusion'],
+ static: ['method', 'observations'], trace: ['entryPoint', 'exitPoint', 'trace', 'inbound', 'outbound', 'boundaryObservations', 'unresolvedBoundaries'],
+ adversarial: ['scenario', 'expected', 'observed', 'boundaryFailures'], challenge: ['challengedAssumption', 'conclusion', 'boundaryChallenge'],
'post-fix': ['command', 'result', 'review', 'delivery'],
};
@@ -133,8 +145,7 @@ export function mergeDeepAuditReport(ledger, agentId, raw, { deliverySuccess = f
const digest = canonicalSnapshotChecksum(report);
if (attempt.reportHash === digest) return ledger;
if (attempt.reportHash) throw new Error('Deep audit attempt already checkpointed; resume with a new agent');
- const prerequisites = canonicalSnapshotChecksum(ledger.units.map(unit => ({ id: unit.id,
- evidence: Object.fromEntries(Object.entries(unit.evidence).filter(([key]) => key !== attempt.pass)) })));
+ const prerequisites = prerequisiteHash(ledger, attempt.pass, attempt.unitIds);
if (prerequisites !== attempt.prerequisiteHash) throw new Error('Deep audit prerequisite evidence changed; resume with a fresh assignment');
const draft = structuredClone(ledger);
const paths = new Map(ledger.scope.files.map(file => [file.path, file.blob]));
@@ -161,11 +172,11 @@ export function mergeDeepAuditReport(ledger, agentId, raw, { deliverySuccess = f
if (result.status !== 'blocked' && EVIDENCE_FIELDS[attempt.pass].some(field => !result.evidence[field])) {
throw new Error(`Missing ${attempt.pass} evidence`);
}
- if (['challenge', 'post-fix'].includes(attempt.pass)) {
- const prerequisites = attempt.pass === 'challenge' ? DEEP_AUDIT_PASSES.slice(0, 3) : DEEP_AUDIT_PASSES;
+ if (attempt.pass !== 'static') {
+ const prerequisites = priorPasses(attempt.pass);
if (prerequisites.some(pass => !unit.evidence[pass] || unit.evidence[pass].status === 'blocked'
- || unit.evidence[pass].agentId === agentId)) throw new Error('Independent pass prerequisites are missing');
- if (result.status === 'inapplicable' && prerequisites.some(pass => unit.evidence[pass].status !== 'inapplicable')) {
+ || (['challenge', 'post-fix'].includes(attempt.pass) && unit.evidence[pass].agentId === agentId))) throw new Error('Independent pass prerequisites are missing');
+ if (attempt.pass === 'challenge' && result.status === 'inapplicable' && prerequisites.some(pass => unit.evidence[pass].status !== 'inapplicable')) {
throw new Error('Independent review must confirm prior inapplicability reasons');
}
}
@@ -176,23 +187,26 @@ export function mergeDeepAuditReport(ledger, agentId, raw, { deliverySuccess = f
...(attempt.pass === 'post-fix' ? { validationRevision } : {}), attestation: 'agent-reported, source-verified' };
}
const candidateUnits = new Set(attempt.unitIds);
+ const assignedGroups = new Set(draft.units.filter(unit => candidateUnits.has(unit.id)).map(unit => unit.groupId));
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);
+ const partitioned = partitionDeepAuditGroup({ ...addition, category: ledger.category });
+ if (draft.groups.some(group => group.id === partitioned.group.id)) throw new Error('Additional unit duplicates existing scope');
+ draft.groups.push(partitioned.group); draft.units.push(...partitioned.units);
+ partitioned.units.forEach(unit => candidateUnits.add(unit.id));
}
for (const candidate of report.candidates) {
if (POLLUTING_KEYS.has(candidate.id)) throw new Error('Invalid candidate identity');
- if (!candidateUnits.has(candidate.unitId)) throw new Error('Candidate references unassigned coverage unit');
+ const previous = draft.candidates[candidate.id];
+ const legacyGroup = previous?.groupScoped === true && previous.unitId === candidate.unitId && assignedGroups.has(candidate.unitId);
+ if (!candidateUnits.has(candidate.unitId) && !legacyGroup) 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');
}
- draft.candidates[candidate.id] = { ...candidate, agentId };
+ draft.candidates[candidate.id] = { ...candidate, agentId, ...(legacyGroup ? { groupScoped: true } : {}) };
}
draft.attempts[agentId].reportHash = digest;
draft.reason = report.stopReason;
@@ -206,8 +220,23 @@ export function refreshDeepAuditScope(ledger, scope) {
if (scopeHash === ledger.scopeHash && !ledger.invalidReason) return ledger;
const next = createDeepAuditLedger({ ...ledger, scope });
next.generation = ledger.generation + 1;
- next.invalidated = [...ledger.invalidated, { scope: ledger.scope, scopeHash: ledger.scopeHash,
- units: ledger.units, candidates: ledger.candidates, attempts: ledger.attempts }];
+ const historical = { ...ledger };
+ delete historical.invalidated;
+ next.invalidated = [...ledger.invalidated, historical];
+ if (isDeepAuditContractUpgrade(ledger.scope, scope)) {
+ // Preserve enrolled workflows and findings, but never manufacture new coverage.
+ for (const old of ledger.groups || ledger.units) {
+ if (next.groups.some(group => group.id === old.id)) continue;
+ const partitioned = partitionDeepAuditGroup({ ...old, category: ledger.category });
+ next.groups.push(partitioned.group); next.units.push(...partitioned.units);
+ }
+ const priorUnits = new Map(ledger.units.map(unit => [unit.id, unit]));
+ next.candidates = Object.fromEntries(Object.entries(ledger.candidates).map(([id, candidate]) => [id,
+ { ...candidate, unitId: priorUnits.get(candidate.unitId)?.groupId || candidate.unitId, groupScoped: true }]));
+ next.coverageMigration = { fromContract: ledger.scope.promptVersions?.contract, toContract: scope.promptVersions?.contract,
+ priorRequiredPasses: ledger.units.length * 4, requiredPasses: next.units.length * 4,
+ reason: 'Previous receipts are historical; partition and cross-boundary obligations require fresh evidence. Findings retained at original group scope.' };
+ }
next.reason = 'Source, inventory, capabilities or prompt changed; previous evidence retained as stale';
return next;
}
@@ -220,15 +249,17 @@ export function deepAuditAssignment(ledger, attempt) {
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 };
+ units, groups: ledger.groups?.filter(group => units.some(unit => unit.groupId === group.id)).map(({ files, ...group }) => ({ ...group, totalFiles: files.length })),
+ candidates: Object.values(ledger.candidates).filter(candidate => attempt.unitIds.includes(candidate.unitId)
+ || (candidate.groupScoped && units.some(unit => unit.groupId === candidate.unitId))),
+ progress: deepAuditProgress(ledger), coverageMigration: ledger.coverageMigration };
}
export function deepAuditInstructions({ ledger, attempt, ledgerPath, assignmentPath, reportPath }) {
return `## Deep audit coverage contract v${DEEP_AUDIT_CONTRACT_VERSION} — highest-priority audit scope
This 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 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.
+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; each deterministic partition owns at most 24 files for one subsystem/scenario. A single large file or genuinely unavailable runtime evidence may still require an honest blocker. Delivery-only retries are explicitly marked on the assignment: prior full coverage remains required, with bounded re-attestation and actual publication verification; they are not new full-scope reviews. 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 partitions, 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 required evidence remains blocked. A verified defect is reviewed evidence, not automatically a blocker: inspect a dangling tracked symlink blob and prove its target absent rather than claiming to review nonexistent target contents.
+Assignment: attemptId=${attempt.id}; scopeHash=${ledger.scopeHash}; prerequisiteHash=${attempt.prerequisiteHash}. Do not change the ledger or self-assign another pass. Each partition advances only after its own prerequisite passes; independent challenge is a separate server-assigned invocation. Trace must name concrete inbound caller paths, outbound dependency paths, boundary behavior and unresolved questions; adversarial evidence must test boundary failures, and challenge must independently examine these cross-file assumptions. Follow relevant callers/callees outside the partition and cite their pinned identities as context; context references never credit their owned coverage. Groups complete only when every partition meets every pass. New workflows require additionalUnits; do not hide cross-boundary work behind partition limits. 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.
Every evidence value must be a non-empty JSON string, never an array, object, number or boolean. Combine multiple observations or trace steps into one string using escaped newlines. Each text value must contain 1–12000 characters after trimming. Validate the entire checkpoint against this schema before atomically publishing it; do not coerce or invent evidence to satisfy validation.
@@ -236,5 +267,5 @@ Checkpoint JSON schema (authoritative field types and limits):
\`\`\`json
${JSON.stringify(z.toJSONSchema(deepAuditReportSchema))}
\`\`\`
-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.`;
+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 partitions. Legacy groupScoped findings are visible in every assigned partition of their original group; they remain group-scoped and their identity/group cannot move. New findings must name an assigned partition; relate newly discovered workflows to their originating assigned partition until the server assigns their additional partitions. Group visibility never grants coverage credit. 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/lib/deepAuditCoverage.js b/server/lib/deepAuditCoverage.js
new file mode 100644
index 0000000000..5634c6a386
--- /dev/null
+++ b/server/lib/deepAuditCoverage.js
@@ -0,0 +1,42 @@
+import { canonicalSnapshotChecksum } from './snapshotChecksum.js';
+
+export const DEEP_AUDIT_PARTITION_FILES = 24;
+export const DEEP_AUDIT_SCENARIOS = Object.freeze(['normal', 'failure', 'concurrency-recovery']);
+
+/** Partitions own source; groups are conjunctions, never synthetic review receipts. */
+export function partitionDeepAuditGroup({ category, subsystem, scenario, files, reason }) {
+ const sorted = [...new Set(files)].sort();
+ const id = canonicalSnapshotChecksum({ category, subsystem, scenario });
+ const units = [];
+ for (let offset = 0; offset < sorted.length; offset += DEEP_AUDIT_PARTITION_FILES) {
+ const owned = sorted.slice(offset, offset + DEEP_AUDIT_PARTITION_FILES);
+ units.push({ id: canonicalSnapshotChecksum({ groupId: id, files: owned }), groupId: id,
+ category, subsystem, scenario, files: owned, evidence: {} });
+ }
+ return { group: { id, category, subsystem, scenario, files: sorted,
+ unitIds: units.map(unit => unit.id), ...(reason ? { reason } : {}) }, units };
+}
+
+export function createDeepAuditCoverage(category, files) {
+ const directories = new Map();
+ for (const file of files) {
+ const directory = file.path.includes('/') ? file.path.slice(0, file.path.lastIndexOf('/')) : '.';
+ if (!directories.has(directory)) directories.set(directory, []);
+ directories.get(directory).push(file.path);
+ }
+ const groups = [], units = [];
+ for (const subsystem of [...directories.keys()].sort()) {
+ for (const scenario of DEEP_AUDIT_SCENARIOS) {
+ const partitioned = partitionDeepAuditGroup({ category, subsystem, scenario, files: directories.get(subsystem) });
+ groups.push(partitioned.group); units.push(...partitioned.units);
+ }
+ }
+ return { groups, units };
+}
+
+/** Only the contract may change when retaining the live findings register. */
+export function isDeepAuditContractUpgrade(previous, next) {
+ const withoutContract = scope => ({ ...scope, promptVersions: { ...scope.promptVersions, contract: null } });
+ return [1, 2].includes(previous.promptVersions?.contract) && next.promptVersions?.contract === 3
+ && canonicalSnapshotChecksum(withoutContract(previous)) === canonicalSnapshotChecksum(withoutContract(next));
+}
diff --git a/server/services/deepAudit.test.js b/server/services/deepAudit.test.js
index 9265595aea..e9060b5ea6 100644
--- a/server/services/deepAudit.test.js
+++ b/server/services/deepAudit.test.js
@@ -1,8 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { mkdtemp, writeFile, rm } from 'fs/promises';
+import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { execGit } from '../lib/execGit.js';
+import { canonicalSnapshotChecksum } from '../lib/snapshotChecksum.js';
import { assignDeepAuditAttempt, deepAuditProgress, mergeDeepAuditReport } from '../lib/deepAudit.js';
import { prepareDeepAudit, checkpointDeepAudit } from './deepAudit.js';
@@ -14,7 +15,7 @@ const scope = { revision: 'b'.repeat(40), inventoryHash: 'inventory-1', files: [
{ path: 'server/routes/other.js', blob, kind: 'blob' },
{ path: 'README.md', blob, kind: 'blob' },
], capabilities: { api: true }, exclusions: [], promptVersions: { contract: 1, category: 1 }, promptHash: 'prompt-1' };
-const evidence = { method: 'Read each listed file and search all registered callers', observations: 'No concrete defects in this scenario',
+const evidence = { inbound: 'routes/example.js caller', outbound: 'store/example.js dependency', boundaryObservations: 'Failure returns through route and store boundary', unresolvedBoundaries: 'None after tracing the pinned callers', boundaryFailures: 'Store rejection reaches the route error handler', boundaryChallenge: 'Independently traced rejection across route/store boundary', method: 'Read each listed file and search all registered callers', observations: 'No concrete defects in this scenario',
entryPoint: 'GET /example', exitPoint: 'JSON response', trace: 'route → service → store → response, including listed callers',
scenario: 'Two writes overlap and the first write fails', expected: 'Serialize and preserve the second write', observed: 'The failure path releases the queue; regression test passes',
challengedAssumption: 'Rechecked whether rejection strands the shared queue', conclusion: 'Queue tail catches rejection before next operation',
@@ -52,7 +53,7 @@ function payload(agentId, overrides = {}) {
return { version: 1, scopeHash: ledger.scopeHash, attemptId: agentId, prerequisiteHash: attempt.prerequisiteHash,
pass: attempt.pass, units: ledger.units.filter(unit => attempt.unitIds.includes(unit.id)).map(unit => ({
id: unit.id, status: 'evidenced', reason: 'Reviewed the full scenario with no surviving findings',
- sources: unit.files.map(path => ({ path, blob })), evidence,
+ sources: unit.files.map(path => ({ path, blob })), evidence: structuredClone(evidence),
})), candidates: [], stopReason: 'Checkpoint; continue remaining passes', ...overrides };
}
async function finish(agentId, selected = task, success = true) {
@@ -65,14 +66,13 @@ describe('Deep coverage workflow across serialized restarts', () => {
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++) {
+ for (let i = 0; i < 12 && seen.size < 30; 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); }
+ if (attempt.pass === 'static') 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');
@@ -87,8 +87,7 @@ describe('Deep coverage workflow across serialized restarts', () => {
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');
+ expect(Object.values(saved().attempts).some(attempt => attempt.pass === 'trace')).toBe(true);
});
it('preserves findings outside the batch and rejects candidate identity collisions', async () => {
@@ -98,11 +97,15 @@ describe('Deep coverage workflow across serialized restarts', () => {
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');
+ for (let i = 0; i < 3; i++) {
+ const id = `advance-${i}`; await prepare(id); report = JSON.stringify(payload(id)); await finish(id);
+ }
await prepare('second');
+ const before = deepAuditProgress(saved()).satisfiedPasses;
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(await finish('second')).toMatchObject({ satisfiedPasses: before, complete: false });
expect(saved().candidates['first-finding'].unitId).toBe(firstUnit);
}
report = JSON.stringify(payload('second'));
@@ -110,7 +113,7 @@ describe('Deep coverage workflow across serialized restarts', () => {
expect(saved().candidates['first-finding']).toMatchObject(candidate);
});
- it('retains full-scope delivery retries after all discovery receipts exist', async () => {
+ it('bounds publication retries while retaining all previously completed coverage', 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}`;
@@ -120,34 +123,40 @@ describe('Deep coverage workflow across serialized restarts', () => {
}
expect(deepAuditProgress(saved())).toMatchObject({ discoveryComplete: true, deliveryComplete: false });
await prepare('delivery-retry');
- expect(saved().attempts['delivery-retry'].unitIds).toHaveLength(15);
+ expect(saved().attempts['delivery-retry']).toMatchObject({ deliveryOnly: true, pass: 'challenge' });
+ expect(saved().attempts['delivery-retry'].unitIds).toHaveLength(12);
+ report = JSON.stringify(payload('delivery-retry'));
+ expect(await finish('delivery-retry', task, false)).toMatchObject({ satisfiedPasses: 60, deliveryComplete: false });
+ await prepare('published'); report = JSON.stringify(payload('published'));
+ expect(await finish('published')).toMatchObject({ satisfiedPasses: 60, complete: true });
});
- 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('feasible');
+ it('partitions 1626 files without omissions and advances other partitions past a persistent blocker', async () => {
+ pinned.files = Array.from({ length: 1626 }, (_, i) => ({ path: `large/${String(i).padStart(4, '0')}.js`, blob, kind: 'blob' }));
+ await prepare('first');
const initial = saved();
- expect(initial.attempts.feasible.unitIds).toHaveLength(3);
- expect(initial.units.filter(unit => initial.attempts.feasible.unitIds.includes(unit.id))
- .every(unit => unit.subsystem === 'small')).toBe(true);
- report = JSON.stringify(payload('feasible'));
- expect(await finish('feasible')).toMatchObject({ satisfiedPasses: 3, requiredPasses: 24, complete: false });
- 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']) {
- await prepare(id);
- expect(saved().attempts[id].unitIds).not.toContain(first);
- report = JSON.stringify(payload(id));
- await finish(id);
+ expect(initial.groups).toHaveLength(3);
+ for (const group of initial.groups) {
+ const owned = initial.units.filter(unit => unit.groupId === group.id).flatMap(unit => unit.files);
+ expect(owned).toEqual(pinned.files.map(file => file.path));
+ expect(new Set(owned).size).toBe(1626);
}
- await prepare('retry-blocker');
- expect(saved().attempts['retry-blocker'].unitIds).toEqual([first]);
+ expect(initial.units.every(unit => unit.files.length <= 24)).toBe(true);
+ const p = payload('first'); p.units[0].status = 'blocked';
+ const blocked = p.units[0].id;
+ report = JSON.stringify(p); await finish('first', task, false);
+ const passes = new Set();
+ for (let i = 0; i < 3; i++) {
+ const id = `resume-${i}`; await prepare(id);
+ const ledger = saved(), attempt = ledger.attempts[id];
+ passes.add(attempt.pass);
+ expect(attempt.unitIds).not.toContain(blocked);
+ expect(new Set(ledger.units.filter(unit => attempt.unitIds.includes(unit.id)).flatMap(unit => unit.files)).size).toBeLessThanOrEqual(96);
+ report = JSON.stringify(payload(id)); await finish(id);
+ }
+ expect([...passes]).toEqual(['trace', 'adversarial', 'challenge']);
+ expect(deepAuditProgress(saved())).toMatchObject({ blockedUnits: 1, complete: false, reviewedUnits: 11 });
+ expect(saved().units.find(unit => unit.id === blocked).evidence.trace).toBeUndefined();
});
it('gives the agent exact evidence types and rejects array observations without crediting coverage', async () => {
@@ -188,9 +197,10 @@ describe('Deep coverage workflow across serialized restarts', () => {
report = null;
expect(await finish('first', task, false)).toEqual(interrupted);
await prepare('resumed');
- expect(saved().attempts.resumed.unitIds).toHaveLength(5);
+ expect(saved().attempts.resumed).toMatchObject({ pass: 'trace', unitIds: [first.units[0].id] });
report = JSON.stringify(payload('resumed'));
- expect(await finish('resumed')).toMatchObject({ satisfiedPasses: 6, complete: false });
+ expect(await finish('resumed')).toMatchObject({ satisfiedPasses: 2, complete: false });
+ expect(saved().units.filter(unit => !unit.evidence.static)).toHaveLength(5);
});
it.each(['absent', 'malformed', 'forged unit', 'wrong blob', 'missing evidence', 'wrong pass', 'forged scope', 'incomplete inventory', 'invented complete flag'])('%s never credits discovery', async failure => {
@@ -213,8 +223,9 @@ describe('Deep coverage workflow across serialized restarts', () => {
p.candidates = [{ id: 'finding-1', unitId: p.units[1].id, finding: 'An error can lose the queued write', disposition: 'pending', resolution: 'Needs a reproduction' }];
report = JSON.stringify(p);
expect(await finish('a')).toMatchObject({ blockedUnits: 1, pendingCandidates: 1, complete: false });
- await prepare('b'); expect(saved().attempts.b.pass).toBe('static');
- expect(saved().attempts.b.unitIds).toEqual([p.units[0].id]);
+ await prepare('b'); expect(saved().attempts.b.pass).toBe('trace');
+ expect(saved().attempts.b.unitIds).not.toContain(p.units[0].id);
+ expect(saved().candidates['finding-1'].disposition).toBe('pending');
});
it.each(['revision', 'files', 'capabilities', 'promptVersions', 'exclusions'])('invalidates changed %s while retaining stale history', async field => {
@@ -287,7 +298,7 @@ it('pins an actual Git inventory and refuses tracked and untracked drift', async
const inspect = () => prepareDeepAudit({ task, agentId: 'git-agent', workspacePath: directory }, { ...deps, inventory: undefined });
await inspect();
const pinned = saved().scope;
- expect(pinned.promptVersions.contract).toBe(2);
+ expect(pinned.promptVersions.contract).toBe(3);
expect(pinned.files).toHaveLength(1);
expect(pinned.files[0]).toMatchObject({ path: 'source.js', kind: 'blob' });
await writeFile(join(directory, 'untracked.js'), 'new source');
@@ -306,8 +317,9 @@ it('enrolls newly discovered workflows without shrinking the mechanically invent
report = JSON.stringify(p);
expect(await finish('a')).toMatchObject({ totalUnits: 7, requiredPasses: 28, complete: false });
await prepare('b');
- expect(saved().attempts.b.pass).toBe('static');
- expect(saved().attempts.b.unitIds).toHaveLength(1);
+ expect(saved().attempts.b.pass).toBe('trace');
+ expect(saved().units.find(unit => unit.scenario === 'restart during response streaming').evidence).toEqual({});
+ expect(deepAuditProgress(saved()).requiredPasses).toBe(28);
});
it('does not combine post-fix batches from different source revisions and reassigns cleared units', async () => {
@@ -352,3 +364,94 @@ it('reopens remediation when a resolved candidate belongs to an older tested rev
ledger.candidates.example.resolvedRevision = ledger.validationRevision;
expect(deepAuditProgress(ledger)).toMatchObject({ remediationComplete: true, complete: true });
});
+
+
+it('migrates a serialized v2 generation transactionally without crediting old receipts or losing enrolled findings', async () => {
+ pinned.promptVersions.contract = 2;
+ pinned.files = Array.from({ length: 50 }, (_, i) => ({ path: `large/${String(i).padStart(3, '0')}.js`, blob, kind: 'blob' }));
+ const groups = ['normal', 'failure', 'concurrency-recovery', 'enrolled workflow'].map(scenario => ({
+ id: canonicalSnapshotChecksum({ category: 'code-quality', subsystem: 'large', scenario }),
+ category: 'code-quality', subsystem: 'large', scenario, files: pinned.files.map(file => file.path),
+ evidence: { static: { status: 'evidenced', agentId: 'old-agent', evidence, sources: pinned.files.map(({ path, blob }) => ({ path, blob })) } },
+ }));
+ const old = { version: 1, id: 'audit-1', appId: 'example-app', category: 'code-quality', delivery: 'file-issues',
+ scope: structuredClone(pinned), scopeHash: canonicalSnapshotChecksum(pinned), generation: 1,
+ units: groups, invalidated: [], attempts: { 'old-agent': { generation: 1, pass: 'static', unitIds: groups.map(group => group.id) } },
+ candidates: { legacy: { id: 'legacy', unitId: groups[0].id, finding: 'Verified broken source link', disposition: 'confirmed', resolution: 'Pinned target is absent' } } };
+ database.set('audit-1', JSON.stringify(old));
+ pinned.promptVersions.contract = 3;
+ await prepare('migrated');
+ const ledger = saved();
+ expect(ledger).toMatchObject({ generation: 2, coverageMigration: { priorRequiredPasses: 16, requiredPasses: 48 } });
+ expect(ledger.groups).toHaveLength(4);
+ expect(ledger.units).toHaveLength(12);
+ expect(deepAuditProgress(ledger).satisfiedPasses).toBe(0);
+ expect(ledger.invalidated).toHaveLength(1);
+ expect(ledger.invalidated[0].units[0].evidence.static.agentId).toBe('old-agent');
+ expect(ledger.candidates.legacy).toMatchObject({ unitId: groups[0].id, groupScoped: true, disposition: 'confirmed' });
+ await prepare('migrated');
+ expect(saved().invalidated).toHaveLength(1);
+ const legacy = saved().candidates.legacy;
+ report = JSON.stringify(payload('migrated', { candidates: [{ id: legacy.id, unitId: legacy.unitId,
+ finding: legacy.finding, disposition: 'confirmed', resolution: 'Rechecked the pinned broken link' }] }));
+ expect(await finish('migrated')).toMatchObject({ satisfiedPasses: 12, complete: false, pendingRemediations: 1 });
+ expect(saved().candidates.legacy.groupScoped).toBe(true);
+ expect(await finish('old-agent')).toMatchObject({ satisfiedPasses: 12, complete: false });
+});
+
+it('requires cross-boundary evidence before accepting a trace', async () => {
+ await prepare('static'); report = JSON.stringify(payload('static')); await finish('static');
+ await prepare('trace');
+ const p = payload('trace');
+ for (const unit of p.units) delete unit.evidence.boundaryObservations;
+ report = JSON.stringify(p);
+ expect(await finish('trace')).toMatchObject({ satisfiedPasses: 6, complete: false });
+ expect(saved().reason).toContain('Missing trace evidence');
+});
+
+it('resumes an interrupted real Git inventory of 1626 files without repeating or losing owned file coverage', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'deep-audit-partition-git-'));
+ try {
+ await mkdir(join(directory, 'large'));
+ await Promise.all(Array.from({ length: 1626 }, (_, i) => writeFile(join(directory, 'large', `${String(i).padStart(4, '0')}.js`), `export const value = ${i};\n`)));
+ await execGit(['init'], directory); await execGit(['add', '.'], directory);
+ await execGit(['-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-m', 'large fixture'], directory);
+ const realDeps = { ...deps, inventory: undefined };
+ await prepareDeepAudit({ task, agentId: 'large-first', workspacePath: directory }, realDeps);
+ const before = saved(), attempt = before.attempts['large-first'];
+ expect(before.scope.files).toHaveLength(1626);
+ expect(before.units).toHaveLength(204);
+ expect(before.groups.every(group => group.files.length === 1626)).toBe(true);
+ expect(before.units.every(unit => unit.files.length <= 24)).toBe(true);
+ const unit = before.units.find(unit => unit.id === attempt.unitIds[0]);
+ report = JSON.stringify({ version: 1, scopeHash: before.scopeHash, attemptId: attempt.id,
+ prerequisiteHash: attempt.prerequisiteHash, pass: 'static', units: [{ id: unit.id, status: 'evidenced',
+ reason: 'Fixture simulates one completed partition before interruption', sources: before.scope.files.filter(file => unit.files.includes(file.path)).map(({ path, blob }) => ({ path, blob })), evidence }],
+ candidates: [], stopReason: 'Interrupted after one bounded partition' });
+ const checkpoint = await checkpointDeepAudit({ task, agentId: attempt.id, workspacePath: directory, success: false }, realDeps);
+ expect(checkpoint).toMatchObject({ satisfiedPasses: 1, requiredPasses: 816, complete: false });
+ report = null;
+ expect(await checkpointDeepAudit({ task, agentId: attempt.id, workspacePath: directory, success: false }, realDeps)).toEqual(checkpoint);
+ await prepareDeepAudit({ task, agentId: 'large-resume', workspacePath: directory }, realDeps);
+ expect(saved().scopeHash).toBe(before.scopeHash);
+ expect(saved().attempts['large-resume']).toMatchObject({ pass: 'trace', unitIds: [unit.id] });
+ expect(saved().units.find(item => item.id === unit.id).evidence.static).toBeDefined();
+ expect(deepAuditProgress(saved()).complete).toBe(false);
+ } finally { await rm(directory, { recursive: true, force: true }); }
+}, 20000);
+
+
+it('rejects a late static report after its partition has advanced through independent review', async () => {
+ await prepare('static-a'); await prepare('static-b');
+ const late = payload('static-b');
+ report = JSON.stringify(payload('static-a')); await finish('static-a');
+ for (const id of ['trace', 'adversarial', 'challenge']) {
+ await prepare(id); report = JSON.stringify(payload(id)); await finish(id);
+ }
+ expect(deepAuditProgress(saved()).satisfiedPasses).toBe(24);
+ report = JSON.stringify(late);
+ expect(await finish('static-b')).toMatchObject({ satisfiedPasses: 24 });
+ expect(saved().reason).toContain('prerequisite evidence changed');
+ expect(saved().units.every(unit => unit.evidence.static.agentId === 'static-a')).toBe(true);
+ expect(saved().attempts['static-b'].reportHash).toBeUndefined();
+});