Skip to content

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

feat: add resumable Deep audits with persistent coverage gates (#10541)

[._.]/0c2da0776f1a
diff --git a/client/src/components/apps/AppQualityRunner.jsx b/client/src/components/apps/AppQualityRunner.jsx
index b5d9b3b092..37bbcbb795 100644
--- a/client/src/components/apps/AppQualityRunner.jsx
+++ b/client/src/components/apps/AppQualityRunner.jsx
@@ -5,7 +5,7 @@ import MaintenanceRunStatus from '../cos/tabs/schedule/MaintenanceRunStatus';
import useProviderModels from '../../hooks/useProviderModels';
import { useSocketResource } from '../../hooks/useSocketResource';
import { enabledProcessProviderFilter } from '../../utils/providers';
-import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun } from '../../services/apiAgents';
+import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun, resumeMaintenanceRun } from '../../services/apiAgents';
const RUN_EVENTS = ['cos:maintenance:updated'];
@@ -33,6 +33,7 @@ export default function AppQualityRunner({ app, children }) {
return next;
});
const [mode, setMode] = useState('file-issues');
+ const [auditDepth, setAuditDepth] = useState('quick');
const [prCompletion, setPrCompletion] = useState('draft');
const [effort, setEffort] = useState('');
const [busy, setBusy] = useState(false);
@@ -71,7 +72,7 @@ export default function AppQualityRunner({ app, children }) {
setBusy(true);
setError('');
const response = await startMaintenanceRun({ appId: app.id, providerId: picker.selectedProviderId, model: picker.selectedModel,
- effort: effort || null, mode, claimBetweenAudits: false, taskTypes,
+ effort: effort || null, mode, ...(auditDepth === 'deep' ? { auditDepth } : {}), claimBetweenAudits: false, taskTypes,
...(mode === 'fix' && prCompletion ? { prCompletion } : {}),
// A category picked by name is the user's explicit choice and runs even if
// the repository scan says it cannot apply; batch selections stay gated.
@@ -80,10 +81,10 @@ export default function AppQualityRunner({ app, children }) {
if (response) setRuns(previous => [response.run, ...(previous ?? []).filter(entry => entry.id !== response.run.id)]);
setBusy(false);
};
- const stop = async (id) => {
+ const stop = async (id, resume = false) => {
setBusy(true);
setError('');
- const response = await stopMaintenanceRun(id, { silent: true }).catch(err => { if (appIdRef.current === app.id) setError(err.message); return null; });
+ const response = await (resume ? resumeMaintenanceRun : stopMaintenanceRun)(id, { silent: true }).catch(err => { if (appIdRef.current === app.id) setError(err.message); return null; });
if (appIdRef.current !== app.id) return;
if (response) setRuns(previous => (previous ?? []).map(entry => entry.id === response.run.id ? response.run : entry));
setBusy(false);
@@ -102,6 +103,13 @@ export default function AppQualityRunner({ app, children }) {
</select>
</label>
</div>
+ <label htmlFor="quality-depth" className="block text-sm">Audit depth
+ <select id="quality-depth" className="block w-full bg-port-bg border border-port-border rounded p-2" value={auditDepth} disabled={busy} onChange={event => setAuditDepth(event.target.value)}>
+ <option value="quick">Quick — broad scan, focused review</option>
+ <option value="deep">Deep — persistent coverage and independent passes</option>
+ </select>
+ </label>
+ {auditDepth === 'deep' && <p className="text-xs text-gray-400">Each launch works one review pass and saves a checkpoint. Resume explicitly for remaining evidence and independent challenge. Source changes invalidate prior coverage. No audits start until Run now.</p>}
{mode === 'fix' && <label htmlFor="quality-publication" className="block text-sm">Pull requests
<select id="quality-publication" className="block w-full bg-port-bg border border-port-border rounded p-2" value={prCompletion} disabled={busy} onChange={event => setPrCompletion(event.target.value)}>
<option value="draft">Drafts for review — never merge</option>
@@ -118,9 +126,10 @@ export default function AppQualityRunner({ app, children }) {
className="px-3 py-2 rounded bg-port-accent text-port-bg text-sm font-medium disabled:opacity-50">{taskTypes.length === 1 ? 'Run now' : `Run ${taskTypes.length} checks now`}</button>
{(loading || loadError) && <p className="text-xs" role="status">{loadError ? 'Runner status is unavailable.' : 'Loading runner status…'} <button type="button" className="text-port-accent" onClick={loadRuns}>Retry</button></p>}
{error && <p role="alert" className="text-sm text-port-error">{error}</p>}
- {runs.filter((run, index) => run.status === 'running' || index === 0).map(run => <div key={run.id} className="space-y-2">
+ {runs.filter((run, index) => run.status === 'running' || run.auditDepth === 'deep' || index === 0).map(run => <div key={run.id} className="space-y-2">
<MaintenanceRunStatus run={run} />
{run.reason && <p className="text-xs break-words">{run.reason} <Link className="text-port-accent underline" to="/cos/schedule">Open runner settings</Link></p>}
+ {run.auditDepth === 'deep' && run.status === 'stopped' && <button type="button" className="text-xs text-port-accent" disabled={busy} onClick={() => stop(run.id, true)}>Resume Deep audit</button>}
{run.status === 'running' && <button type="button" className="text-xs text-port-accent" disabled={busy} onClick={() => stop(run.id)}>Stop remaining checks</button>}
</div>)}
</section>;
diff --git a/client/src/components/apps/AppQualityRunner.test.jsx b/client/src/components/apps/AppQualityRunner.test.jsx
index 4b1235492e..fdc99bf978 100644
--- a/client/src/components/apps/AppQualityRunner.test.jsx
+++ b/client/src/components/apps/AppQualityRunner.test.jsx
@@ -21,9 +21,9 @@ import AppQualityRunner from './AppQualityRunner';
import AppQuality from './AppQuality';
import { awaitEnabled, findEnabledByLabelText, findEnabledByRole } from '../../test/enabledBarrier.js';
vi.mock('./AppQualityHistory', () => ({ default: () => null }));
-import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun } from '../../services/apiAgents';
+import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun, resumeMaintenanceRun } from '../../services/apiAgents';
import useProviderModels from '../../hooks/useProviderModels';
-vi.mock('../../services/apiAgents', () => ({ getMaintenanceRuns: vi.fn(), startMaintenanceRun: vi.fn(), stopMaintenanceRun: vi.fn() }));
+vi.mock('../../services/apiAgents', () => ({ getMaintenanceRuns: vi.fn(), startMaintenanceRun: vi.fn(), stopMaintenanceRun: vi.fn(), resumeMaintenanceRun: vi.fn() }));
vi.mock('../../hooks/useProviderModels', () => ({ default: vi.fn(() => ({ providers: [], selectedProviderId: 'codex', selectedModel: 'gpt-5', availableModels: [], loading: false })) }));
vi.mock('../ProviderModelSelector', () => ({ default: ({ onEffortChange }) => <button onClick={() => onEffortChange('high')}>Use high effort</button> }));
const app = { id: 'app-1', quality: { categories: [
@@ -265,3 +265,16 @@ it('defaults audit fixes to draft review and lets the user explicitly inherit sa
await waitFor(() => expect(startMaintenanceRun).toHaveBeenCalledTimes(2));
expect(startMaintenanceRun.mock.lastCall[0].prCompletion).toBe('inherit');
});
+
+
+it('offers separate Deep depth, shows pass denominator and resumes a persisted partial run explicitly', async () => {
+ const run = { id: 'deep-run', appId: app.id, status: 'stopped', auditDepth: 'deep', steps: [], reason: 'Budget exhausted',
+ deepAudits: { step: { discoveryComplete: false, reviewedUnits: 0, totalUnits: 8, satisfiedPasses: 8, requiredPasses: 32, blockedUnits: 1, pendingCandidates: 2, deliveryComplete: false } } };
+ getMaintenanceRuns.mockResolvedValue({ runs: [run] });
+ resumeMaintenanceRun.mockResolvedValue({ run: { ...run, status: 'running' } });
+ render(<MemoryRouter><AppQualityRunner app={app} /></MemoryRouter>);
+ fireEvent.change(screen.getByLabelText('Audit depth'), { target: { value: 'deep' } });
+ expect(await screen.findByText(/8\/32 pass requirements/)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Resume Deep audit' }));
+ await waitFor(() => expect(resumeMaintenanceRun).toHaveBeenCalledWith('deep-run', { silent: true }));
+});
diff --git a/client/src/components/apps/tabs/AutomationTab.jsx b/client/src/components/apps/tabs/AutomationTab.jsx
index d1caab0afc..5516bc8cd5 100644
--- a/client/src/components/apps/tabs/AutomationTab.jsx
+++ b/client/src/components/apps/tabs/AutomationTab.jsx
@@ -300,6 +300,13 @@ export default function AutomationTab({ appId, appName }) {
</button>
) : null}
<div className="flex flex-wrap items-center gap-1">
+ {globalConfig.fileIssuesCapable && <label className="text-xs" htmlFor={`audit-depth-${taskType}`}>Depth
+ <select id={`audit-depth-${taskType}`} title="Deep checkpoints pause; use Run Now to resume" disabled={saving} className="ml-1 bg-port-bg border border-port-border rounded"
+ value={override.taskMetadata?.auditDepth ?? globalConfig.taskMetadata?.auditDepth ?? 'quick'}
+ onChange={event => saveOverride(taskType, { taskMetadata: { ...override.taskMetadata, auditDepth: event.target.value } })}>
+ <option value="quick">Quick</option><option value="deep">Deep</option>
+ </select>
+ </label>}
{globalConfig.fileIssuesCapable && (() => {
const effective = override.taskMetadata?.fileIssues ?? globalConfig.taskMetadata?.fileIssues ?? globalConfig.defaultFileIssues === true;
const hasOverride = override.taskMetadata?.fileIssues !== undefined;
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
index 56df966f64..0d4ddfb608 100644
--- a/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
@@ -1,3 +1,4 @@
+import { formatCount } from '../../../../utils/formatters';
import MaintenanceStepChecklist from './MaintenanceStepChecklist';
/**
@@ -28,6 +29,12 @@ export default function MaintenanceRunStatus({ run, showSteps = false, renderSte
return <div className={`space-y-1 text-xs min-w-0 ${showSteps ? 'w-full' : ''}`} role="status">
<p>{run.status} · {current}/{total} steps{run.status === 'running' && step ? ` · ${step}` : ''}</p>
<progress aria-label="Maintenance steps completed" value={done} max={total || 1} className="w-full h-1 accent-port-accent" />
+ {run.auditDepth === 'deep' && Object.entries(run.deepAudits || {}).map(([id, audit]) => <div key={id} className="space-y-1">
+ <p>Deep discovery: {audit.discoveryComplete ? 'complete' : 'partial'} · {formatCount(audit.reviewedUnits)}/{formatCount(audit.totalUnits)} units reviewed · {formatCount(audit.satisfiedPasses)}/{formatCount(audit.requiredPasses)} pass requirements</p>
+ <p>{formatCount(audit.blockedUnits)} blocked · {formatCount(audit.pendingCandidates)} candidates awaiting triage · Delivery: {audit.deliveryComplete ? 'complete' : 'pending'} · {formatCount(audit.pendingRemediations)} remediations pending</p>
+ {audit.revision && <p>Source revision: <code>{audit.revision.slice(0, 12)}</code></p>}
+ {audit.reason && <p className="break-words">{audit.reason}</p>}
+ </div>)}
{run.active && <p className="flex items-center gap-2">
{run.active.status === 'running' && <span aria-hidden="true" className="w-2 h-2 rounded-full bg-port-accent motion-safe:animate-pulse" />}
{run.active.status || 'queued'}
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index d1bb71b553..0ae2a930e6 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -382,11 +382,12 @@ export const updateCosTaskInterval = (taskType, settings, options = {}) => reque
// Manual maintenance runs — the Schedule tab's "Run maintenance now" (server:
// services/maintenanceRun.js).
export const getMaintenanceRuns = (options) => request('/cos/schedule/maintenance-runs', options);
-export const startMaintenanceRun = ({ appId, providerId, model, effort = null, mode = 'file-issues', prCompletion, claimBetweenAudits = true, claimHandler, taskTypes, explicitCheck }, options = {}) => request('/cos/schedule/maintenance-runs', {
+export const startMaintenanceRun = ({ appId, providerId, model, effort = null, mode = 'file-issues', prCompletion, claimBetweenAudits = true, claimHandler, taskTypes, explicitCheck, auditDepth }, options = {}) => request('/cos/schedule/maintenance-runs', {
method: 'POST',
- body: JSON.stringify({ appId, providerId, model, effort, mode, prCompletion, claimBetweenAudits, claimHandler, taskTypes, explicitCheck }),
+ body: JSON.stringify({ appId, providerId, model, effort, mode, prCompletion, claimBetweenAudits, claimHandler, taskTypes, explicitCheck, auditDepth }),
...options
});
+export const resumeMaintenanceRun = (id, options = {}) => request(`/cos/schedule/maintenance-runs/${id}/resume`, { method: 'POST', ...options });
export const stopMaintenanceRun = (id, options = {}) => request(`/cos/schedule/maintenance-runs/${id}/stop`, { method: 'POST', ...options });
export const triggerCosOnDemandTask = (taskType, appId = null, options = {}) => request('/cos/schedule/trigger', {
diff --git a/docs/DEEP-AUDITS.md b/docs/DEEP-AUDITS.md
new file mode 100644
index 0000000000..ac95dde240
--- /dev/null
+++ b/docs/DEEP-AUDITS.md
@@ -0,0 +1,38 @@
+# Deep audits
+
+Deep is an audit depth, independent of **File issues** or **Audit and fix** delivery. Quick remains the default and retains its broad scan followed by a bounded investigation.
+
+## 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. 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.
+
+Manual runs show discovery, reviewed units, satisfied/required pass requirements, blockers, pending candidates and delivery separately. Incomplete Deep runs remain in history even beyond the ordinary finished-run cap. The full local ledger and derived progress are available through authenticated `GET /api/cos/schedule/deep-audits/:id`; manual IDs are the maintenance step IDs, and scheduled/custom IDs are returned in the agent's `result.deepAudit.id`. Normal maintenance start/stop/resume endpoints remain the launch controls; start accepts `auditDepth: "quick" | "deep"`.
+
+## Coverage and completion
+
+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. Initialized submodules are recursively inventoried at their recorded commits. 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.
+
+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.
+
+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.
+
+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.
+
+## Persistence and limitations
+
+`deep_audit_ledgers` is machine-local PostgreSQL state. A row lock serializes checkpoint merges, and server-assigned attempt IDs plus report hashes make completion replay idempotent. The DB stores evidence, candidates, assignments and invalidated history. It is covered by PostgreSQL backup and does not federate. Additive, idempotent schema initialization provisions the table on upgrades and fresh installs; there is no seed or legacy data transform.
+
+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.
+
+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/docs/README.md b/docs/README.md
index 76c2da1711..bba1b55a13 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -25,6 +25,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| [ITERM.md](./ITERM.md) | The Shell page's iTerm2 view — requirements, status states and their fixes, why iTerm2 sessions stay separate from PortOS shells, the clean-room protocol rule |
| [INSTANCE_FEATURES.md](./INSTANCE_FEATURES.md) | Optional per-install features — registry, client-side nav gating, feature groups, reconcile-at-toggle |
| [PM2.md](./PM2.md) | Recommended PM2 ecosystem patterns for sub-projects |
+| [DEEP-AUDITS.md](./DEEP-AUDITS.md) | Persistent audit coverage, independent passes, checkpoint/resume and completion rules |
| [QUOTA-BURN.md](./QUOTA-BURN.md) | Quota-burn automation — spending subscription-backed CLI quota before expiry |
| [AI_PROVIDERS.md](./AI_PROVIDERS.md) | The AI Providers page: a run composed from Harness × Method × Service × Model × Effort, its Presets / Harnesses / Services views, compatibility matrix, derived vs legacy presets, and what federates (nothing) |
| [PROVIDER_COMPOSITION.md](./PROVIDER_COMPOSITION.md) | Composite provider ids (`harness.method@service[+bootstrap]`): the grammar, per-harness enablement, bootstrap apps, how every run path resolves one, and the preset-only surfaces |
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index fb308cf3c5..11c15d3c25 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -59,6 +59,9 @@ therefore starts conservatively if it contains a hold or outstanding operations.
## `db-primary` — app-native relational records
+- Deep audit evidence — `deep_audit_ledgers` stores each app/category coverage ledger, source/prompt pins, server-assigned attempts, candidates, receipts and invalidated history. Machine-local and covered by the PostgreSQL dump; it does not federate (no sync cursor or tombstones). JSONB holds structured evidence, not binary assets, and row locking serializes updates. No full-text index is needed for keyed checkpoint reads. Additive schema initialization creates the table for existing and fresh installs without transforming old records or seeding data. Agent-written checkpoint JSON under `data/cos/deep-audit-checkpoints/` is a retained recovery input outside source checkouts, captured by normal CoS filesystem backup; imported database receipts remain authoritative. See [Deep audits](./DEEP-AUDITS.md).
+
+
- Beeper's `beeper_reconcile_cursors` stores a machine-local per-account rotating checkpoint and a fixed per-rotation upper bound over already mirrored message IDs. Each sweep refetches at most 20 stored messages per account, independently of forward ingestion; failed retrievals retain the archive and retry on the next rotation. Checkpoints survive restart, cascade on account deletion, and are covered by PostgreSQL backup. They never federate. `beeper_messages.observed_at` records fetch-start time to break equal source-version ties; source edit timestamps prevent stale sweep/outbox writes from replacing edits. Additive schema initialization upgrades existing installs without a data seed.
diff --git a/scripts/lib/dbTestFiles.js b/scripts/lib/dbTestFiles.js
index 2074c9ce16..6fad201cc5 100644
--- a/scripts/lib/dbTestFiles.js
+++ b/scripts/lib/dbTestFiles.js
@@ -14,6 +14,7 @@ export const DB_TEST_INCLUDE = [
'services/voice/studio.db.test.js',
'../scripts/perf/collectionFixture.db.test.js',
'services/appQuality.db.test.js',
+ 'services/deepAudit.db.test.js',
'**/db.test.js',
'services/codeAnimation/stages.db.test.js',
'services/codeAnimation/sound.db.test.js',
diff --git a/server/lib/README.md b/server/lib/README.md
index 8361ad37fe..b9296c46c7 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -874,3 +874,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `peerAdminValidation.js` | Strict, separate planning and execution schemas with fixed intents, signed receipts and explicit grant scopes. |
| `musicVideoReviewDraft.js` | Pure imported Animatic review candidates, newest immutable version first; exact version URLs remain separate from native production approvals. |
+
+| `deepAudit.js` | Strict Deep audit checkpoint schema, scope invalidation, server-assigned passes and mechanical completion rules. |
diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.js
index bc40e527b9..ef5ecfad5d 100644
--- a/server/lib/agentRegistrationRecord.js
+++ b/server/lib/agentRegistrationRecord.js
@@ -239,6 +239,7 @@ export function buildAgentRegistration({
// Values are coerced on the way through: a COS-TASKS.md round-trip hands
// every scalar back as a string.
...quotaBurnAgentMetadata(task.metadata),
+ ...(task.metadata?.auditDepth === 'deep' ? { taskAuditDepth: 'deep' } : {}),
// Same reason as taskLiProposal — a hand-picked projection, so this must be
// listed explicitly. `declaresNoCommitCriterion` (taskTypeHooks.js) reads it
// to decide whether a run declared a commit criterion at all,
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index eb07a44521..a0bc8fe7ae 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -553,6 +553,8 @@ export const createCosJobSchema = z.object({
// useWorktree/openPR/simplify keys above. Zod strips unknown keys, so
// without this row the flag never survives a job create/update.
fileIssues: z.boolean().optional(),
+ auditDepth: z.enum(['quick', 'deep']).optional(),
+ deepAuditId: z.string().regex(/^[a-zA-Z0-9_-]{1,160}$/).optional(),
// The two "lands no code" postures, which are NOT the same. `noCodeOutput`
// = the deliverable is something the agent DOES during the run (files an
// issue, calls an endpoint), so there is no branch and every commit/push/PR
@@ -1202,6 +1204,8 @@ export function sanitizeTaskMetadata(raw) {
clean.prCompletion = raw.prCompletion;
hasKeys = true;
}
+ if (['quick', 'deep'].includes(raw.auditDepth)) { clean.auditDepth = raw.auditDepth; hasKeys = true; }
+ if (typeof raw.deepAuditId === 'string' && /^[a-zA-Z0-9_-]{1,160}$/.test(raw.deepAuditId)) { clean.deepAuditId = raw.deepAuditId; hasKeys = true; }
// Schedule dispatch must preserve the workflow and its reviewer pin. Reuse
// the task-input schemas so command paths and argument bounds stay identical.
for (const key of ['slashdoCommand', 'slashdoArgs']) {
diff --git a/server/lib/db/schema/core.js b/server/lib/db/schema/core.js
index b70ba2bc47..bef42bbb0d 100644
--- a/server/lib/db/schema/core.js
+++ b/server/lib/db/schema/core.js
@@ -79,6 +79,13 @@ END$$`,
];
export const coreDdl = [
+ `CREATE TABLE IF NOT EXISTS deep_audit_ledgers (
+ id TEXT PRIMARY KEY,
+ app_id TEXT NOT NULL,
+ category TEXT NOT NULL,
+ ledger JSONB NOT NULL,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ )`,
...memoryHistoryDdl,
`CREATE TABLE IF NOT EXISTS app_quality_measurements (
app_id TEXT NOT NULL,
diff --git a/server/lib/deepAudit.js b/server/lib/deepAudit.js
new file mode 100644
index 0000000000..920ab2507f
--- /dev/null
+++ b/server/lib/deepAudit.js
@@ -0,0 +1,195 @@
+import { z } from 'zod';
+import { POLLUTING_KEYS } from './objects.js';
+import { canonicalSnapshotChecksum } from './snapshotChecksum.js';
+
+export const DEEP_AUDIT_VERSION = 1;
+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({
+ version: z.literal(DEEP_AUDIT_VERSION),
+ scopeHash: text,
+ attemptId: text,
+ prerequisiteHash: text,
+ pass: z.enum([...DEEP_AUDIT_PASSES, 'post-fix']),
+ units: z.array(z.object({
+ id: text,
+ status: z.enum(['evidenced', 'blocked', 'inapplicable']),
+ reason: text,
+ sources: z.array(source).min(1),
+ evidence: z.record(z.string(), text),
+ }).strict()).max(50000),
+ candidates: z.array(z.object({
+ id: text, unitId: text, finding: text,
+ disposition: z.enum(['pending', 'confirmed', 'rejected', 'duplicate', 'deferred', 'resolved']),
+ resolvedRevision: z.string().regex(/^[a-f0-9]{40,64}$/).optional(),
+ resolution: text,
+ }).strict()).max(50000),
+ additionalUnits: z.array(z.object({ subsystem: text, scenario: text, files: z.array(text).min(1), reason: text }).strict()).max(1000).optional(),
+ stopReason: text,
+ validationRevision: z.string().regex(/^[a-f0-9]{40,64}$/).optional(),
+}).strict();
+
+/** 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: {},
+ })));
+ return { version: DEEP_AUDIT_VERSION, id, appId, category, scope, scopeHash: canonicalSnapshotChecksum(scope),
+ delivery, units, candidates: {}, attempts: {}, invalidated: [], reason: 'Awaiting evidence', generation: 1 };
+}
+
+export function deepAuditProgress(ledger) {
+ let satisfied = 0;
+ let blocked = 0;
+ const statuses = { pending: 0, scanned: 0, traced: 0, validated: 0, reviewed: 0, blocked: 0, inapplicable: 0 };
+ for (const unit of ledger.units) {
+ const receipts = DEEP_AUDIT_PASSES.map(pass => unit.evidence[pass]);
+ const hasBlocker = receipts.some(receipt => receipt?.status === 'blocked');
+ const count = receipts.filter(receipt => receipt && receipt.status !== 'blocked').length;
+ satisfied += count;
+ if (hasBlocker) blocked++;
+ const status = hasBlocker ? 'blocked' : count === 4 && receipts.every(receipt => receipt.status === 'inapplicable')
+ ? 'inapplicable' : ['pending', 'scanned', 'traced', 'validated', 'reviewed'][count];
+ statuses[status]++;
+ }
+ 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;
+ const postFixComplete = Boolean(ledger.validationRevision) && ledger.units.length > 0 && ledger.units.every(unit => unit.evidence['post-fix']?.status === 'evidenced'
+ && unit.evidence['post-fix'].validationRevision === ledger.validationRevision);
+ const deliveryComplete = ledger.delivery === 'file-issues' ? ledger.deliveryVerified === true
+ : postFixComplete && ledger.deliveryVerified === true;
+ const pendingRemediations = Object.values(ledger.candidates).filter(candidate => ['pending', 'confirmed', 'deferred'].includes(candidate.disposition)
+ || (candidate.disposition === 'resolved' && candidate.resolvedRevision !== ledger.validationRevision)).length;
+ const remediationComplete = ledger.delivery === 'fix' && deliveryComplete && pendingRemediations === 0;
+ return { discoveryComplete, remediationComplete,
+ deliveryComplete, pendingRemediations, complete: discoveryComplete && deliveryComplete && (ledger.delivery !== 'fix' || remediationComplete),
+ 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) };
+}
+
+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 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 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 };
+ ledger.attempts[agentId] = attempt;
+ return attempt;
+}
+
+const EVIDENCE_FIELDS = {
+ static: ['method', 'observations'], trace: ['entryPoint', 'exitPoint', 'trace'],
+ adversarial: ['scenario', 'expected', 'observed'], challenge: ['challengedAssumption', 'conclusion'],
+ 'post-fix': ['command', 'result', 'review', 'delivery'],
+};
+
+/** Agent text never chooses scope, assignment, identity, or a completion flag. */
+export function mergeDeepAuditReport(ledger, agentId, raw, { deliverySuccess = false, validationRevision = null } = {}) {
+ const report = deepAuditReportSchema.parse(raw);
+ const attempt = ledger.attempts[agentId];
+ if (!attempt || attempt.generation !== ledger.generation || report.scopeHash !== ledger.scopeHash
+ || report.attemptId !== agentId || report.pass !== attempt.pass || report.prerequisiteHash !== attempt.prerequisiteHash) {
+ throw new Error('Deep audit report does not match the assigned scope and pass');
+ }
+ 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)) })));
+ 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]));
+ if (attempt.pass === 'post-fix') {
+ if (draft.validationRevision !== validationRevision) {
+ for (const unit of draft.units) delete unit.evidence['post-fix'];
+ draft.deliveryVerified = false;
+ }
+ draft.validationRevision = validationRevision;
+ }
+ const seen = new Set();
+ for (const result of report.units) {
+ const unit = draft.units.find(entry => entry.id === result.id);
+ if (!unit || !attempt.unitIds.includes(unit.id) || seen.has(unit.id)) throw new Error('Unknown, unassigned or repeated Deep audit unit');
+ seen.add(unit.id);
+ if (result.status !== 'blocked' && ledger.scope.files.some(file => file.kind === 'commit' && unit.files.includes(file.path))) {
+ throw new Error('Unexpanded submodule requires a blocked unit, not a coverage claim');
+ }
+ if (result.sources.some(ref => paths.get(ref.path) !== ref.blob)) throw new Error('Deep audit source evidence does not match pinned inventory');
+ if (!result.sources.some(ref => unit.files.includes(ref.path))) throw new Error('Deep audit evidence must reference its own unit');
+ if (attempt.pass === 'static' && unit.files.some(path => !result.sources.some(ref => ref.path === path))) {
+ throw new Error('Static evidence must account for every inventory member');
+ }
+ 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 (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')) {
+ throw new Error('Independent review must confirm prior inapplicability reasons');
+ }
+ }
+ if (attempt.pass === 'post-fix' && (!validationRevision || report.validationRevision !== validationRevision)) {
+ throw new Error('Post-fix evidence must bind to the verified workspace revision');
+ }
+ unit.evidence[attempt.pass] = { ...result, agentId, prerequisiteHash: attempt.prerequisiteHash,
+ ...(attempt.pass === 'post-fix' ? { validationRevision } : {}), attestation: 'agent-reported, source-verified' };
+ }
+ 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: {} });
+ }
+ 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 (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.attempts[agentId].reportHash = digest;
+ draft.reason = report.stopReason;
+ draft.lastReportAgent = agentId;
+ draft.deliveryVerified = deliverySuccess;
+ return draft;
+}
+
+export function refreshDeepAuditScope(ledger, scope) {
+ const scopeHash = canonicalSnapshotChecksum(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 }];
+ next.reason = 'Source, inventory, capabilities or prompt changed; previous evidence retained as stale';
+ return next;
+}
+
+export function deepAuditInstructions({ ledger, attempt, ledgerPath, reportPath }) {
+ return `## Deep audit coverage contract v${DEEP_AUDIT_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 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.
+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.
+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.`;
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index baf317b9eb..b31ce9a786 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -856,3 +856,5 @@ export * from './speechMatch.js';
export * from './musicVideoReviewDraft.js';
export * from './backupSharedAdmission.js';
export * from './runtimeFilePublication.js';
+
+export * from './deepAudit.js';
diff --git a/server/lib/maintenanceSequence.js b/server/lib/maintenanceSequence.js
index 506585cf03..0482db0d63 100644
--- a/server/lib/maintenanceSequence.js
+++ b/server/lib/maintenanceSequence.js
@@ -56,7 +56,7 @@ export const maintenanceStepParams = (taskType, mode = 'file-issues') => (taskTy
* invocation yields fresh step identities. An optional claimHandler replaces
* the provider/model/effort bundle for drains only; omitted keeps legacy pins.
*/
-export function buildMaintenanceSteps({ appId, idPrefix, providerId = null, model = null, effort = null, mode = 'file-issues', prCompletion = null, claimBetweenAudits = true, claimHandler = null, taskTypes = null, explicitCheck = false }) {
+export function buildMaintenanceSteps({ appId, idPrefix, providerId = null, model = null, effort = null, mode = 'file-issues', prCompletion = null, claimBetweenAudits = true, claimHandler = null, taskTypes = null, explicitCheck = false, auditDepth = 'quick' }) {
if (taskTypes !== null && (!Array.isArray(taskTypes) || !taskTypes.length || taskTypes.some(type => !Object.hasOwn(AUDIT_DEFINITIONS, type)))) {
throw new Error('Quality checks must name known audit categories');
}
@@ -70,6 +70,6 @@ export function buildMaintenanceSteps({ appId, idPrefix, providerId = null, mode
jobType: null,
runOnce: true,
drain: taskType === MAINTENANCE_DRAIN_TASK,
- overrides: { ...(taskType === MAINTENANCE_DRAIN_TASK && claimHandler ? claimHandler : { providerId, model, effort }), params: taskTypes ? { fileIssues: mode !== 'fix', ...(mode === 'fix' ? { useWorktree: true, openPR: true, ...(prCompletion ? { prCompletion } : {}) } : {}), ...(explicitCheck ? { runInapplicableAudit: true } : {}) } : { ...maintenanceStepParams(taskType, mode), ...(prCompletion ? { prCompletion } : {}) } },
+ overrides: { ...(taskType === MAINTENANCE_DRAIN_TASK && claimHandler ? claimHandler : { providerId, model, effort }), params: taskTypes ? { ...(auditDepth === 'deep' ? { auditDepth } : {}), fileIssues: mode !== 'fix', ...(mode === 'fix' ? { useWorktree: true, openPR: true, ...(prCompletion ? { prCompletion } : {}) } : {}), ...(explicitCheck || auditDepth === 'deep' ? { runInapplicableAudit: true } : {}) } : { ...(auditDepth === 'deep' ? { auditDepth } : {}), ...maintenanceStepParams(taskType, mode), ...(prCompletion ? { prCompletion } : {}) } },
}));
}
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index a056ebc5f0..bf7458018c 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -45,6 +45,7 @@ const maintenanceRunStartSchema = z.object({
// so each runs even where the repository scan says it cannot apply.
explicitCheck: z.boolean().optional(),
mode: z.enum(['file-issues', 'fix']).optional(),
+ auditDepth: z.enum(['quick', 'deep']).optional(),
prCompletion: z.enum([...PR_COMPLETION_VALUES, 'inherit']).optional(),
claimBetweenAudits: z.boolean().optional(),
claimHandler: z.object({
@@ -290,6 +291,14 @@ router.post('/schedule/trigger', asyncHandler(async (req, res) => {
// Manual maintenance runs — the Schedule tab's "Run maintenance now"; see
// services/maintenanceRun.js for why this is not a quota burn.
+router.get('/schedule/deep-audits/:id', asyncHandler(async (req, res) => {
+ const { getDeepAuditLedger } = await import('../services/deepAudit.js');
+ const ledger = await getDeepAuditLedger(req.params.id);
+ if (!ledger) throw new ServerError('Deep audit not found', { status: 404 });
+ const { deepAuditProgress } = await import('../lib/deepAudit.js');
+ res.json({ ...ledger, progress: deepAuditProgress(ledger) });
+}));
+
router.get('/schedule/maintenance-runs', asyncHandler(async (_req, res) => {
res.json({ runs: await listMaintenanceRuns() });
}));
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index e4968403ec..efe63d8ea3 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -2432,3 +2432,12 @@ CREATE TABLE IF NOT EXISTS peer_execution_generation_floors (
PRIMARY KEY (host_instance_id, peer_instance_id, action),
CHECK (host_instance_id <> peer_instance_id)
);
+
+-- Machine-local Deep audit checkpoints and immutable evidence history.
+CREATE TABLE IF NOT EXISTS deep_audit_ledgers (
+ id TEXT PRIMARY KEY,
+ app_id TEXT NOT NULL,
+ category TEXT NOT NULL,
+ ledger JSONB NOT NULL,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ );
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 5171cd73f3..d9d52d4a39 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1015,6 +1015,9 @@ export function dispatchTaskOutputHookOnce({
if (existing) return existing;
const persistDispatchMarker = async (result) => {
+ if (result.deepAudit) {
+ await updateAgent(agentId, { metadata: { deepAudit: result.deepAudit } });
+ }
if (result.auditAssessment) {
await updateAgent(agentId, { metadata: { auditAssessment: result.auditAssessment } })
.catch(err => emitLog('warn', `⚠️ Failed to persist audit assessment status for ${agentId}: ${err.message}`, { agentId }));
@@ -1036,11 +1039,11 @@ export function dispatchTaskOutputHookOnce({
// retryable on recovery rather than being mistaken for a successful report.
const savedAssessment = [agent?.metadata?.auditAssessment, agent?.result?.auditAssessment]
.find(assessment => assessment?.status === 'recorded');
- if (isAuditTaskType(resolveTaskHookType(task)) && savedAssessment?.status === 'recorded') {
+ if (task.metadata?.auditDepth !== 'deep' && isAuditTaskType(resolveTaskHookType(task)) && savedAssessment?.status === 'recorded') {
return { ran: false, auditAssessment: savedAssessment };
}
if (agent?.metadata?.outputHookDispatchedAt) {
- return { ran: false, alreadyDispatched: true };
+ return { ran: false, alreadyDispatched: true, ...(agent.metadata?.deepAudit ? { deepAudit: agent.metadata.deepAudit } : {}) };
}
const hookDispatch = dispatchTaskOutputHook({
@@ -1597,7 +1600,9 @@ export async function finalizeAgent({
});
const taskType = task?.taskType || 'user';
- const taskUpdate = terminatedByUser
+ const taskUpdate = task.metadata?.auditDepth === 'deep' && !terminatedByUser
+ ? { status: 'blocked', metadata: { ...preHookTask.metadata, blockedReason: 'Deep audit checkpoint; resume explicitly', blockedCategory: 'deep-audit-partial', blockedAt: new Date().toISOString() } }
+ : terminatedByUser
? {
status: 'blocked',
metadata: {
@@ -1631,6 +1636,17 @@ export async function finalizeAgent({
return null;
});
+ if (task.metadata?.auditDepth === 'deep' && hookResult?.deepAudit) {
+ hookResult.deepAudit = await (await import('./deepAudit.js')).settleDeepAuditDelivery({
+ task, agentId, success: verdict.success && !terminatedByUser, validationPassed,
+ }).catch(err => ({ ...hookResult.deepAudit, complete: false, deliveryComplete: false, reason: `Delivery persistence failed: ${err.message}` }));
+ await updateAgent(agentId, { metadata: { deepAudit: hookResult.deepAudit } });
+ if (hookResult.deepAudit.complete && verdict.success && !terminatedByUser) {
+ taskUpdate.status = 'completed';
+ taskUpdate.metadata = { ...task.metadata };
+ }
+ }
+
// Sequential by design: completeAgent + updateTask share the cosState
// mutex (`withStateLock`) so parallelism gains nothing, AND ordering
// matters — if completeAgent throws, we must not mark the task completed.
@@ -1640,6 +1656,7 @@ export async function finalizeAgent({
await completeAgent(agentId, {
success: verdict.success,
validationPassed,
+ ...(hookResult?.deepAudit ? { deepAudit: hookResult.deepAudit } : {}),
...(isAuditTaskType(resolveTaskHookType(task)) ? {
auditAssessment: hookResult?.auditAssessment || { status: 'unverified' },
} : {}),
@@ -1940,10 +1957,14 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, a
// Shared resolver with evaluateSuccessCriteria's gate — "runs a hook" and "gets
// the programmatic-I/O criterion" must stay the same question (#2727).
const taskType = resolveTaskHookType(task);
- if (!taskType) return { ran: false };
+ const deepAudit = task.metadata?.auditDepth === 'deep'
+ ? await (await import('./deepAudit.js')).checkpointDeepAudit({ task, agentId, success: false,
+ workspacePath: hookPayloadDir({ task, workspacePath, recovery }) }) : null;
+ if (!taskType) return { ran: false, ...(deepAudit ? { deepAudit } : {}) };
if (isAuditTaskType(taskType)) {
const { recordAuditQuality } = await import('./appQuality.js');
const auditAssessment = await recordAuditQuality({ task, taskType, agentId, success, assessedAt,
+ ...(task.metadata?.auditDepth === 'deep' ? { deepDiscoveryComplete: deepAudit?.discoveryComplete === true } : {}),
workspacePath: hookPayloadDir({ task, workspacePath, recovery }) })
.then(recorded => ({ status: recorded === true ? 'recorded' : success ? 'not-recorded' : 'not-attempted' }))
.catch(err => {
@@ -1952,15 +1973,15 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, a
});
const recorded = auditAssessment.status === 'recorded';
// A review-only run must not land a separate snapshot behind the user's back.
- if (recorded === true && resolvePrCompletion(task?.metadata) !== PR_COMPLETIONS.LEAVE_OPEN) {
+ if (task.metadata?.auditDepth !== 'deep' && recorded === true && resolvePrCompletion(task?.metadata) !== PR_COMPLETIONS.LEAVE_OPEN) {
await publishAppSnapshotFileAfterAudit(task?.metadata?.app);
}
// Assessment telemetry never waives commit/PR success criteria for fix mode.
- return { ran: false, auditAssessment };
+ return { ran: false, auditAssessment, ...(deepAudit ? { deepAudit } : {}) };
}
const { getTaskOutputHook } = await import('./taskTypeHooks.js');
const hook = await getTaskOutputHook(taskType);
- if (!hook) return { ran: false };
+ if (!hook) return { ran: false, ...(deepAudit ? { deepAudit } : {}) };
const cwd = hookPayloadDir({ task, workspacePath, recovery });
const payload = cwd ? await readHookPayload({ agentId, taskType, cwd }) : null;
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index 35dc23e34c..6774b42897 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -1,3 +1,5 @@
+const deep = vi.hoisted(() => ({ checkpointDeepAudit: vi.fn(async () => ({ id: 'deep-1', complete: false, reason: 'Checkpoint partial' })), settleDeepAuditDelivery: vi.fn(async () => ({ id: 'deep-1', complete: false, reason: 'Checkpoint partial' })) }));
+vi.mock('./deepAudit.js', () => deep);
vi.mock('../lib/gitCommitProbe.js', () => ({ committedDuringRun: vi.fn(async () => false) }));
vi.mock('./appQuality.js', () => ({ recordAuditQuality: vi.fn(async () => true) }));
import { recordAuditQuality } from './appQuality.js';
@@ -206,6 +208,16 @@ describe('recovery output-hook dispatch (#3182)', () => {
isProgrammaticIoTaskType.mockReturnValue(true);
});
+ it('parks a failed Deep attempt without the normal automatic retry path', async () => {
+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security', auditDepth: 'deep' } };
+ await finalizeAgent({ agentId: 'deep-failed', task, success: false, exitCode: 1, duration: 1000,
+ workspacePath: '/example/repo', startedAt: Date.now() - 1000, outputBuffer: 'Context exhausted',
+ errorAnalysis: { type: 'transient', retryable: true, error: 'context exhausted' } });
+ expect(resolveFailedTaskUpdate).not.toHaveBeenCalled();
+ expect(updateTask).toHaveBeenCalledWith(task.id, expect.objectContaining({ status: 'blocked', metadata: expect.objectContaining({ blockedCategory: 'deep-audit-partial' }) }), expect.anything());
+ expect(deep.checkpointDeepAudit).toHaveBeenCalledWith(expect.objectContaining({ success: false }));
+ });
+
it('distinguishes a clean execution with no usable assessment from a failed execution', async () => {
const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security' } };
recordAuditQuality.mockResolvedValue(false);
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index fbe38cd2ff..74eb618d82 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -374,6 +374,13 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
task = { ...task, metadata: { ...task.metadata, prompt: featurePrompt } };
}
}
+ const deepAuditContract = task.metadata?.auditDepth === 'deep'
+ ? await (await import('./deepAudit.js')).prepareDeepAudit({ task, agentId: options.agentId,
+ workspacePath: worktreeInfo?.worktreePath || workspaceDir }) : null;
+ const withDeepAudit = prompt => !deepAuditContract ? prompt : typeof prompt === 'string'
+ ? `${deepAuditContract}\n\n${prompt}`
+ : { ...prompt, systemPrompt: `${deepAuditContract}\n\n${prompt.systemPrompt || ''}` };
+
const providerType = options.providerType || PROVIDER_TYPES.API;
const providerId = options.providerId || null;
const providerCommand = options.providerCommand || null;
@@ -419,9 +426,9 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
if (LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) {
const forgeCli = await resolveManualForgeCli(workspaceDir, worktreeInfo, task);
const lightOptions = { isTui, providerId, providerCommand, providerModel, leanMode, agentId, defaultReviewers, codeReviewDefaults, localAgentLoopBody: localAgentLoopBodyForInline, localAgentLoopBodyPath, forgeCli };
- return options.split === true
+ return withDeepAudit(options.split === true
? buildLightContextPromptParts(task, workspaceDir, worktreeInfo, lightOptions)
- : buildLightContextPrompt(task, workspaceDir, worktreeInfo, lightOptions);
+ : buildLightContextPrompt(task, workspaceDir, worktreeInfo, lightOptions));
}
// Creative Director tasks (scene evaluation, treatment/plan run via API) judge
@@ -606,14 +613,14 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
: buildIssueFilingSection({ providerId, model: providerModel, taskBody: [task.description, contextBlock] });
const uiAuditRuntimeSection = isUiAuditTask(task) ? UI_AUDIT_RUNTIME_RULE : '';
- return buildFullAgentPrompt({
+ return withDeepAudit(buildFullAgentPrompt({
task, workspaceDir, agentInstructionsSection, memorySection, digitalTwinSection, contextBlock,
worktreeSection, pipelineSection, jiraSection, orchestrationSection,
issueFilingSection, simplifySection, tuiCompletionSection,
reviewLoopSection, reviewLoopFollowUpSection, compactionSection, skillSection,
toolsSection, planningContextSection, uiAuditRuntimeSection,
completionBullet, completionInstructions, noChangeSuccess, completionMode,
- });
+ }));
}
/**
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 0c9cb82175..347fc61145 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -1,3 +1,4 @@
+vi.mock('./deepAudit.js', () => ({ prepareDeepAudit: vi.fn(async () => '## SERVER DEEP CONTRACT — overrides bounded prompts') }));
/**
* Tests for the light-vs-full context split in buildAgentPrompt.
*
@@ -4539,3 +4540,20 @@ describe('auto-merge posture (worktree, no PR) is commit-only on every path', ()
expect(bullet).not.toMatch(/`\/do:push`/);
});
});
+
+
+it.each(['api', 'cli', 'tui'])('puts Deep contract ahead of customized shallow instructions on %s providers', async providerType => {
+ const task = makeTask({ description: 'Stop after one finding', metadata: { auditDepth: 'deep', app: 'example', prompt: 'Only inspect five candidates', analysisType: 'security' } });
+ const prompt = await buildAgentPrompt(task, {}, '/r', null, { providerType, agentId: 'deep-agent' });
+ expect(prompt.startsWith('## SERVER DEEP CONTRACT')).toBe(true);
+ const { prepareDeepAudit } = await import('./deepAudit.js');
+ expect(prepareDeepAudit).toHaveBeenCalledWith(expect.objectContaining({ task: expect.objectContaining({ metadata: expect.objectContaining({ auditDepth: 'deep' }) }), agentId: 'deep-agent' }));
+});
+
+it('puts the Deep contract in the split system channel and preserves depth through schedule metadata', async () => {
+ const metadata = sanitizeTaskMetadata({ auditDepth: 'deep', deepAuditId: 'checkpoint-1' });
+ expect(metadata).toMatchObject({ auditDepth: 'deep', deepAuditId: 'checkpoint-1' });
+ expect(sanitizeTaskMetadata({ auditDepth: 'unbounded' })).toBeNull();
+ const prompt = await buildAgentPrompt(makeTask({ metadata: { ...metadata, app: 'example' } }), {}, '/r', null, { providerType: 'cli', split: true, agentId: 'deep-agent' });
+ expect(prompt.systemPrompt.startsWith('## SERVER DEEP CONTRACT')).toBe(true);
+});
diff --git a/server/services/appQuality.js b/server/services/appQuality.js
index 95a2c957a7..3d5a37e652 100644
--- a/server/services/appQuality.js
+++ b/server/services/appQuality.js
@@ -6,7 +6,7 @@ import { normalizeAuditTaskType } from '../lib/auditCatalog.js';
import { parseAuditQualityReport, summarizeAppQuality, buildAppQualityHistory, latestQualityRecords } from '../lib/auditQuality.js';
import { collectAppQuality, qualityRecord, readQualityRecords, readReleaseQuality } from './appQualityFederation.js';
-export async function recordAuditQuality({ task, taskType, agentId, workspacePath, success, assessedAt }, deps = {}) {
+export async function recordAuditQuality({ task, taskType, agentId, workspacePath, success, assessedAt, deepDiscoveryComplete = false }, deps = {}) {
if (!success || !workspacePath || !task?.metadata?.app || !agentId) return false;
const contents = await (deps.readFile || tryReadFile)(doneSentinelPath(workspacePath, agentId));
const { summary } = parseSentinelPayload(contents);
@@ -16,6 +16,7 @@ export async function recordAuditQuality({ task, taskType, agentId, workspacePat
console.warn(`⚠️ Audit quality report missing or invalid for ${agentId} (${taskType})`);
return false;
}
+ if (task.metadata.auditDepth === 'deep' && !deepDiscoveryComplete && report.coverage === 'broad') report.coverage = 'partial';
// Immutable run measurements make completion replay idempotent.
if (!Number.isFinite(Date.parse(assessedAt))) {
console.warn(`⚠️ Audit quality skipped for ${agentId}: no valid run start time`);
diff --git a/server/services/appQualitySchedule.js b/server/services/appQualitySchedule.js
index 25c59b34ee..996ccf20fa 100644
--- a/server/services/appQualitySchedule.js
+++ b/server/services/appQualitySchedule.js
@@ -123,12 +123,12 @@ async function listRepoFiles(repoPath) {
* @param {object} app - The managed app record (needs `repoPath`, optionally `uiPort`)
* @returns {Promise<{ capabilities: Record<string, boolean>, scanned: number }>}
*/
-export async function detectRepoCapabilities(app) {
+export async function detectRepoCapabilities(app, { refresh = false } = {}) {
const empty = Object.fromEntries(AUDIT_REPO_CAPABILITIES.map(key => [key, false]));
if (!app?.repoPath) return { capabilities: empty, scanned: 0, complete: false };
const cached = capabilityCache.get(app.repoPath);
- const scan = cached && Date.now() - cached.at < CAPABILITY_TTL_MS
+ const scan = !refresh && cached && Date.now() - cached.at < CAPABILITY_TTL_MS
? cached.value
: await scanRepoCapabilities(app.repoPath);
if (scan !== cached?.value) capabilityCache.set(app.repoPath, { at: Date.now(), value: scan });
diff --git a/server/services/autonomousJobs/skillTemplates.js b/server/services/autonomousJobs/skillTemplates.js
index c80163c992..3c7caf1767 100644
--- a/server/services/autonomousJobs/skillTemplates.js
+++ b/server/services/autonomousJobs/skillTemplates.js
@@ -187,6 +187,8 @@ async function generateTaskFromJob(job) {
priority: job.priority,
metadata: {
autonomousJob: true,
+ ...(meta.auditDepth ? { auditDepth: meta.auditDepth } : {}),
+ ...(meta.deepAuditId ? { deepAuditId: meta.deepAuditId } : {}),
jobId: job.id,
jobName: job.name,
jobCategory: job.category,
diff --git a/server/services/deepAudit.db.test.js b/server/services/deepAudit.db.test.js
new file mode 100644
index 0000000000..abed7ced65
--- /dev/null
+++ b/server/services/deepAudit.db.test.js
@@ -0,0 +1,41 @@
+// The DB runner forces portos_test; never run this against the live database.
+import { afterAll, describe, expect, it } from 'vitest';
+import { checkHealth, query, close } from '../lib/db.js';
+import { requireDbOrSkip } from '../lib/dbTestGate.js';
+import { prepareDeepAudit, checkpointDeepAudit, getDeepAuditLedger } from './deepAudit.js';
+
+const health = await checkHealth().catch(error => ({ connected: false, error: error.message }));
+const runDb = requireDbOrSkip('deepAudit', health.connected, health.error);
+const id = `test-deep-${process.pid}-${Date.now()}`;
+const blob = 'a'.repeat(40);
+const task = { id, description: 'Example audit', metadata: { app: id, deepAuditId: id, auditDepth: 'deep', fileIssues: true } };
+const scope = { revision: 'b'.repeat(40), files: [{ path: 'source.js', blob }], capabilities: {}, exclusions: [], promptHash: 'example', promptVersions: { contract: 1 } };
+const deps = { inventory: async () => scope, write: async () => {} };
+
+afterAll(async () => {
+ if (runDb) await query('DELETE FROM deep_audit_ledgers WHERE id=$1', [id]);
+ await close();
+});
+
+describe.skipIf(!runDb)('Deep audit PostgreSQL persistence', () => {
+ it('serializes overlapping checkpoint merges without losing evidence and replays after output loss', async () => {
+ await Promise.all(['first', 'second'].map(agentId => prepareDeepAudit({ task, agentId, workspacePath: '/example' }, deps)));
+ const initial = await getDeepAuditLedger(id);
+ const checkpoint = async (agentId, index) => {
+ const attempt = initial.attempts[agentId];
+ const unit = initial.units[index];
+ const report = { version: 1, scopeHash: initial.scopeHash, attemptId: agentId, prerequisiteHash: attempt.prerequisiteHash,
+ pass: 'static', units: [{ id: unit.id, status: 'evidenced', reason: 'Full static inspection of this scenario', sources: [{ path: 'source.js', blob }],
+ evidence: { method: 'Read source and callers', observations: 'No findings in this scenario' } }], candidates: [], stopReason: 'Interrupted' };
+ return checkpointDeepAudit({ task, agentId, workspacePath: '/example', success: false }, { ...deps, read: async () => JSON.stringify(report) });
+ };
+ await Promise.all([checkpoint('first', 0), checkpoint('second', 1)]);
+ const persisted = await getDeepAuditLedger(id);
+ expect(persisted.units.filter(unit => unit.evidence.static)).toHaveLength(2);
+ expect(persisted.attempts.first.reportHash).toBeTruthy();
+ expect(persisted.attempts.second.reportHash).toBeTruthy();
+ const replay = await checkpointDeepAudit({ task, agentId: 'first', workspacePath: null, success: false }, { read: async () => { throw new Error('Output no longer exists'); } });
+ expect(replay).toMatchObject({ satisfiedPasses: 2, discoveryComplete: false });
+ expect((await query('SELECT id FROM deep_audit_ledgers WHERE id=$1', [id])).rows).toHaveLength(1);
+ });
+});
diff --git a/server/services/deepAudit.js b/server/services/deepAudit.js
new file mode 100644
index 0000000000..ed69f32657
--- /dev/null
+++ b/server/services/deepAudit.js
@@ -0,0 +1,144 @@
+/** Machine-local, DB-primary coverage evidence. No timers or provider calls. */
+import { join } from 'path';
+import { ensureSchema, query, withTransaction } from '../lib/db.js';
+import { execGit } from '../lib/execGit.js';
+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,
+ mergeDeepAuditReport, refreshDeepAuditScope, DEEP_AUDIT_VERSION } from '../lib/deepAudit.js';
+import { PROMPT_VERSIONS } from './taskPromptDefaults/versions.js';
+import { resolveTaskHookType } from './taskTypeHooks.js';
+
+function deepAuditId(task) {
+ const meta = task.metadata || {};
+ return meta.deepAuditId || meta.quotaBurnStepId || (meta.app
+ ? `deep-${canonicalSnapshotChecksum({ app: meta.app, category: resolveTaskHookType(task) || 'code-quality', job: meta.jobId || null, fileIssues: meta.fileIssues === true || meta.fileIssues === 'true' }).slice(0, 32)}`
+ : task.id);
+}
+
+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`) };
+}
+
+async function inventoryDeepAudit(workspacePath, { promptHash, category }) {
+ if ((await execGit(['rev-parse', '--show-prefix'], workspacePath)).stdout.trim()) throw new Error('Deep inventory requires an initialized repository root');
+ const revision = (await execGit(['rev-parse', 'HEAD'], workspacePath)).stdout.trim();
+ const tree = (await execGit(['ls-tree', '-rz', '--full-tree', revision], workspacePath)).stdout;
+ let files = tree.split('\0').filter(Boolean).map(entry => {
+ const tab = entry.indexOf('\t');
+ const [mode, kind, blob] = entry.slice(0, tab).split(' ');
+ return { path: entry.slice(tab + 1), blob, mode, kind };
+ }).sort((a, b) => a.path.localeCompare(b.path));
+ const nested = [];
+ for (const entry of files.filter(file => file.kind === 'commit')) {
+ try {
+ const snapshot = await inventoryDeepAudit(join(workspacePath, entry.path), { promptHash, category });
+ if (snapshot.revision !== entry.blob) throw new Error('Submodule revision does not match pin');
+ nested.push(...snapshot.files.map(file => ({ ...file, path: `${entry.path}/${file.path}` })));
+ entry.expanded = true;
+ } catch { /* An unreadable submodule stays in scope as an explicit blocker. */ }
+ }
+ files = [...files.filter(file => !file.expanded), ...nested].sort((a, b) => a.path.localeCompare(b.path));
+ const dirty = (await execGit(['diff', '--name-only', 'HEAD', '--'], workspacePath)).stdout.trim();
+ const untracked = (await execGit(['ls-files', '--others', '--exclude-standard', '-z'], workspacePath)).stdout
+ .split('\0').filter(path => path && !/^\.agent-done(?:-[a-zA-Z0-9_-]+)?(?:\.json)?$/.test(path));
+ if (dirty || untracked.length) throw new Error('Deep audit needs a clean source snapshot; tracked or untracked changes require a fresh inventory');
+ if (!files.length) throw new Error('Deep audit cannot certify an empty inventory');
+ // Submodules are kept in the inventory and require an explicit blocker or nested-repo evidence.
+ const { detectRepoCapabilities } = await import('./appQualitySchedule.js');
+ const detected = await detectRepoCapabilities({ repoPath: workspacePath }, { refresh: true });
+ const capabilities = { ...detected.capabilities, git: true, trackedFiles: files.length, submodules: files.filter(file => file.kind === 'commit').map(file => file.path) };
+ return { revision, inventoryHash: canonicalSnapshotChecksum(files), files, capabilities,
+ exclusions: ['Git-ignored files are outside the tracked-source inventory; required runtime evidence must be reported blocked when unavailable.'],
+ promptVersions: { contract: DEEP_AUDIT_VERSION, category: PROMPT_VERSIONS[category] ?? null }, promptHash };
+}
+
+async function mutateLedger(id, initial, mutate) {
+ await ensureSchema();
+ return withTransaction(async client => {
+ if (initial) await client.query(`INSERT INTO deep_audit_ledgers (id, app_id, category, ledger)
+ VALUES ($1,$2,$3,$4::jsonb) ON CONFLICT (id) DO NOTHING`, [id, initial.appId, initial.category, JSON.stringify(initial)]);
+ const { rows } = await client.query('SELECT ledger FROM deep_audit_ledgers WHERE id=$1 FOR UPDATE', [id]);
+ if (!rows.length) throw new Error('Deep audit ledger is unavailable');
+ const updated = await mutate(rows[0].ledger);
+ await client.query('UPDATE deep_audit_ledgers SET ledger=$2::jsonb, updated_at=NOW() WHERE id=$1', [id, JSON.stringify(updated)]);
+ return updated;
+ });
+}
+
+export async function getDeepAuditLedger(id) {
+ await ensureSchema();
+ const { rows } = await query('SELECT ledger FROM deep_audit_ledgers WHERE id=$1', [id]);
+ return rows[0]?.ledger ?? null;
+}
+
+/** Inject at the common spawn boundary, after all saved/custom/legacy task rendering. */
+export async function prepareDeepAudit({ task, agentId, workspacePath }, deps = {}) {
+ if (task.metadata?.auditDepth !== 'deep') return null;
+ if (!agentId || !workspacePath || !task.metadata?.app || !deepAuditId(task)) throw new Error('Deep audit needs an identified agent, app and workspace');
+ const category = isAuditTaskType(resolveTaskHookType(task)) ? normalizeAuditTaskType(resolveTaskHookType(task)) : 'code-quality';
+ const promptHash = canonicalSnapshotChecksum({ description: task.description, prompt: task.metadata?.prompt, context: task.metadata?.context });
+ const scope = await (deps.inventory || inventoryDeepAudit)(workspacePath, { promptHash, category });
+ const initial = createDeepAuditLedger({ id: deepAuditId(task), appId: task.metadata.app, category, scope,
+ delivery: task.metadata.fileIssues === true || task.metadata.fileIssues === 'true' ? 'file-issues' : 'fix' });
+ const ledger = await (deps.mutate || mutateLedger)(initial.id, initial, current => {
+ if (current.appId !== initial.appId || current.category !== initial.category || current.delivery !== initial.delivery) {
+ throw new Error('Deep audit resume must keep the same app, category and delivery mode');
+ }
+ const refreshed = refreshDeepAuditScope(current, scope);
+ assignDeepAuditAttempt(refreshed, agentId);
+ return refreshed;
+ });
+ const paths = deepAuditPaths(workspacePath, agentId);
+ await (deps.write || atomicWrite)(paths.ledgerPath, ledger);
+ return deepAuditInstructions({ ledger, attempt: ledger.attempts[agentId], ...paths });
+}
+
+/** Import even on failure; absent/malformed output preserves a partial, resumable ledger. */
+export async function checkpointDeepAudit({ task, agentId, workspacePath, success }, deps = {}) {
+ if (task.metadata?.auditDepth !== 'deep') return null;
+ const id = deepAuditId(task);
+ const ledger = await (deps.mutate || mutateLedger)(id, null, async current => {
+ if (current.appId !== task.metadata.app) throw new Error('Deep audit app mismatch');
+ const attempt = current.attempts[agentId];
+ if (!attempt) return { ...current, reason: 'No server-assigned Deep audit attempt; resume required' };
+ if (attempt.reportHash) return current; // Durable idempotence after files have been cleaned.
+ try {
+ if (!workspacePath) throw new Error('Checkpoint workspace is unavailable');
+ const pass = attempt.pass;
+ let validationRevision = null;
+ if (pass === 'post-fix') {
+ const validationScope = await (deps.inventory || inventoryDeepAudit)(workspacePath, { promptHash: current.scope.promptHash, category: current.category });
+ validationRevision = validationScope.revision;
+ } else {
+ const scope = await (deps.inventory || inventoryDeepAudit)(workspacePath, {
+ promptHash: current.scope.promptHash, category: current.category,
+ });
+ if (canonicalSnapshotChecksum(scope) !== current.scopeHash) throw new Error('Source changed during review; resume to invalidate and re-inventory');
+ }
+ const contents = await (deps.read || tryReadFile)(deepAuditPaths(workspacePath, agentId).reportPath);
+ if (!contents) throw new Error('Deep audit checkpoint missing; no coverage credited');
+ return mergeDeepAuditReport(current, agentId, JSON.parse(contents), { deliverySuccess: success === true, validationRevision });
+ } catch (err) {
+ return { ...current, invalidReason: /Source changed|clean source snapshot/.test(err.message) ? err.message : current.invalidReason,
+ reason: `Partial: ${err.message}` };
+ }
+ });
+ return { id, revision: ledger.scope.revision, ...deepAuditProgress(ledger) };
+}
+
+
+export async function settleDeepAuditDelivery({ task, agentId, success, validationPassed }, deps = {}) {
+ const ledger = await (deps.mutate || mutateLedger)(deepAuditId(task), null, current => {
+ const attempt = current.attempts[agentId];
+ if (!attempt?.reportHash || attempt.generation !== current.generation || current.lastReportAgent !== agentId) return current;
+ const deliverablePass = current.delivery === 'fix' ? 'post-fix' : 'challenge';
+ if (attempt.pass !== deliverablePass) return current;
+ return { ...current, deliveryVerified: success === true && (current.delivery !== 'fix' || validationPassed === true) };
+ });
+ return { id: ledger.id, revision: ledger.scope.revision, ...deepAuditProgress(ledger) };
+}
diff --git a/server/services/deepAudit.test.js b/server/services/deepAudit.test.js
new file mode 100644
index 0000000000..32fada0d0d
--- /dev/null
+++ b/server/services/deepAudit.test.js
@@ -0,0 +1,240 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, writeFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { execGit } from '../lib/execGit.js';
+import { assignDeepAuditAttempt, deepAuditProgress, mergeDeepAuditReport } from '../lib/deepAudit.js';
+import { prepareDeepAudit, checkpointDeepAudit } from './deepAudit.js';
+
+vi.mock('./appQualitySchedule.js', () => ({ detectRepoCapabilities: async () => ({ capabilities: { api: true } }) }));
+
+const blob = 'a'.repeat(40);
+const scope = { revision: 'b'.repeat(40), inventoryHash: 'inventory-1', files: [
+ { path: 'server/routes/example.js', blob, kind: 'blob' },
+ { 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',
+ 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',
+ command: 'npm test -- example.test.js', result: 'Both failure and concurrent write regression checks pass', review: 'Reviewed the diff and callers', delivery: 'No source change was needed' };
+const task = { id: 'task-1', description: 'Audit the repository', metadata: { auditDepth: 'deep', app: 'example-app', fileIssues: true, deepAuditId: 'audit-1' } };
+let database, report, pinned, deps;
+beforeEach(() => {
+ database = new Map(); report = null; pinned = structuredClone(scope);
+ let tail = Promise.resolve();
+ deps = {
+ inventory: async () => structuredClone(pinned),
+ write: async () => {}, read: async () => report,
+ git: async () => ({ stdout: 'c'.repeat(40) }),
+ // Simulate independent database reads, JSON serialization and serialized updates.
+ mutate: (id, initial, fn) => {
+ const result = tail.then(async () => {
+ if (!database.has(id) && initial) database.set(id, JSON.stringify(initial));
+ if (!database.has(id)) throw new Error('Deep audit ledger is unavailable');
+ const next = await fn(JSON.parse(database.get(id)));
+ database.set(id, JSON.stringify(next));
+ return JSON.parse(database.get(id));
+ });
+ tail = result.catch(() => {});
+ return result;
+ },
+ };
+});
+const saved = () => JSON.parse(database.get('audit-1'));
+async function prepare(agentId, selected = task) {
+ return prepareDeepAudit({ task: selected, agentId, workspacePath: '/example/repo' }, deps);
+}
+function payload(agentId, overrides = {}) {
+ const ledger = saved();
+ const attempt = ledger.attempts[agentId];
+ 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,
+ })), candidates: [], stopReason: 'Checkpoint; continue remaining passes', ...overrides };
+}
+async function finish(agentId, selected = task, success = true) {
+ return checkpointDeepAudit({ task: selected, agentId, workspacePath: '/example/repo', success }, deps);
+}
+
+describe('Deep coverage workflow across serialized restarts', () => {
+ it('does not equate no findings, successful exit or all files scanned with complete discovery', async () => {
+ for (const [index, pass] of ['static', 'trace', 'adversarial', 'challenge'].entries()) {
+ const agentId = `agent-${index}`;
+ const prompt = await prepare(agentId);
+ expect(prompt).toContain(`pass ${pass}`);
+ report = JSON.stringify(payload(agentId));
+ const result = await finish(agentId);
+ expect(result.discoveryComplete).toBe(index === 3);
+ expect(result.complete).toBe(index === 3);
+ expect(result.requiredPasses).toBe(24);
+ expect(result.satisfiedPasses).toBe((index + 1) * 6);
+ }
+ expect(saved().units).toHaveLength(6); // includes root README, no suffix-based omissions
+ });
+
+ it('imports an interrupted partial checkpoint, resumes remaining units, and replays idempotently', async () => {
+ await prepare('first');
+ const first = payload('first'); first.units = first.units.slice(0, 1);
+ report = JSON.stringify(first);
+ const interrupted = await finish('first', task, false);
+ expect(interrupted).toMatchObject({ complete: false, satisfiedPasses: 1 });
+ report = null;
+ expect(await finish('first', task, false)).toEqual(interrupted);
+ await prepare('resumed');
+ expect(saved().attempts.resumed.unitIds).toHaveLength(5);
+ report = JSON.stringify(payload('resumed'));
+ expect(await finish('resumed')).toMatchObject({ satisfiedPasses: 6, complete: false });
+ });
+
+ 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 => {
+ await prepare('a');
+ const p = payload('a');
+ if (failure === 'forged unit') p.units[0].id = 'unassigned';
+ if (failure === 'wrong blob') p.units[0].sources[0].blob = 'e'.repeat(40);
+ if (failure === 'missing evidence') p.units[0].evidence = {};
+ if (failure === 'wrong pass') p.pass = 'challenge';
+ if (failure === 'forged scope') p.scopeHash = 'forged';
+ if (failure === 'incomplete inventory') p.units.find(unit => unit.sources.length > 1).sources.pop();
+ if (failure === 'invented complete flag') p.complete = true;
+ report = failure === 'absent' ? null : failure === 'malformed' ? '{' : JSON.stringify(p);
+ expect(await finish('a')).toMatchObject({ complete: false, satisfiedPasses: 0 });
+ });
+
+ it('keeps blocked units and untriaged candidates visible after the first finding', async () => {
+ await prepare('a'); const p = payload('a');
+ p.units[0].status = 'blocked';
+ 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]);
+ });
+
+ it.each(['revision', 'files', 'capabilities', 'promptVersions', 'exclusions'])('invalidates changed %s while retaining stale history', async field => {
+ await prepare('a'); report = JSON.stringify(payload('a')); await finish('a');
+ pinned[field] = field === 'files' ? [...pinned.files, { path: 'new.js', blob }] : field === 'revision' ? 'd'.repeat(40) : { changed: true };
+ await prepare('b');
+ expect(saved().generation).toBe(2);
+ expect(saved().invalidated[0].units[0].evidence.static).toBeDefined();
+ expect(deepAuditProgress(saved()).satisfiedPasses).toBe(0);
+ report = JSON.stringify({ ...payload('b'), attemptId: 'a' });
+ expect(await finish('a')).toMatchObject({ complete: false, satisfiedPasses: 0 });
+ });
+
+ it('refuses source drift during inspection and accounts it as partial', async () => {
+ await prepare('a'); report = JSON.stringify(payload('a')); pinned.revision = 'f'.repeat(40);
+ expect(await finish('a')).toMatchObject({ complete: false, satisfiedPasses: 0 });
+ expect(saved().invalidReason).toContain('Source changed');
+ });
+
+ it('requires separate challenge identity bound to preceding evidence', async () => {
+ for (const agent of ['static', 'trace', 'adversarial']) { await prepare(agent); report = JSON.stringify(payload(agent)); await finish(agent); }
+ await prepare('challenge'); const p = payload('challenge');
+ let ledger = saved();
+ ledger.units[0].evidence.trace.reason = 'Evidence changed after challenge assignment';
+ expect(() => mergeDeepAuditReport(ledger, 'challenge', p)).toThrow('prerequisite evidence changed');
+ ledger = saved();
+ delete ledger.attempts.static;
+ const attempt = assignDeepAuditAttempt(ledger, 'static');
+ expect(() => mergeDeepAuditReport(ledger, 'static', { ...p, attemptId: 'static', prerequisiteHash: attempt.prerequisiteHash })).toThrow('Independent pass prerequisites');
+ });
+
+ it('requires reasoned inapplicability in all independent passes', async () => {
+ for (const agent of ['a', 'b', 'c', 'd']) {
+ await prepare(agent); const p = payload(agent);
+ p.units.forEach(unit => { unit.status = 'inapplicable'; unit.reason = 'Documentation-only subsystem has no executable concurrency path; inspected linked declarations'; });
+ report = JSON.stringify(p); await finish(agent);
+ }
+ expect(deepAuditProgress(saved())).toMatchObject({ discoveryComplete: true, statuses: { inapplicable: 6 } });
+ });
+
+ it('separates discovery from a revision-bound post-fix and delivery outcome', async () => {
+ 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); }
+ expect(deepAuditProgress(saved())).toMatchObject({ discoveryComplete: true, deliveryComplete: false });
+ await prepare('fix', fix);
+ report = JSON.stringify(payload('fix', { validationRevision: 'e'.repeat(40) }));
+ expect(await finish('fix', fix)).toMatchObject({ complete: false });
+ pinned.revision = 'c'.repeat(40);
+ report = JSON.stringify(payload('fix', { validationRevision: 'c'.repeat(40) }));
+ expect(await finish('fix', fix)).toMatchObject({ complete: true, deliveryComplete: true });
+ });
+
+ it('keeps quick and legacy tasks free of ledger work, refuses cross-app resume', async () => {
+ const legacy = { id: 'legacy', metadata: {} };
+ expect(await prepare('a', legacy)).toBeNull();
+ expect(await finish('a', legacy)).toBeNull();
+ expect(database.size).toBe(0);
+ await prepare('a');
+ await expect(prepare('b', { ...task, metadata: { ...task.metadata, app: 'another-app' } })).rejects.toThrow('same app');
+ });
+});
+
+it('pins an actual Git inventory and refuses tracked and untracked drift', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'deep-audit-test-'));
+ try {
+ await execGit(['init'], directory);
+ await writeFile(join(directory, 'source.js'), 'export const value = 1;\n');
+ await execGit(['add', '.'], directory);
+ await execGit(['-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-m', 'fixture'], directory);
+ const inspect = () => prepareDeepAudit({ task, agentId: 'git-agent', workspacePath: directory }, { ...deps, inventory: undefined });
+ await inspect();
+ const pinned = saved().scope;
+ expect(pinned.files).toHaveLength(1);
+ expect(pinned.files[0]).toMatchObject({ path: 'source.js', kind: 'blob' });
+ await writeFile(join(directory, 'untracked.js'), 'new source');
+ await expect(inspect()).rejects.toThrow('clean source snapshot');
+ await rm(join(directory, 'untracked.js'));
+ await writeFile(join(directory, 'source.js'), 'changed source');
+ await expect(inspect()).rejects.toThrow('clean source snapshot');
+ } finally { await rm(directory, { recursive: true, force: true }); }
+});
+
+
+it('enrolls newly discovered workflows without shrinking the mechanically inventoried scope', async () => {
+ await prepare('a');
+ const p = payload('a');
+ p.additionalUnits = [{ subsystem: 'server/routes', scenario: 'restart during response streaming', files: ['server/routes/example.js'], reason: 'A stateful streaming route needs its own recovery trace' }];
+ 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);
+});
+
+it('does not combine post-fix checks from different source revisions', async () => {
+ 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);
+ expect(await finish('y', fix)).toMatchObject({ discoveryComplete: true, deliveryComplete: false, complete: false });
+ expect(saved().units.filter(unit => unit.evidence['post-fix'])).toHaveLength(3);
+});
+
+it('keeps scheduled and custom resume identities stable across task ids', async () => {
+ const scheduled = { ...task, metadata: { ...task.metadata, deepAuditId: undefined } };
+ await prepare('a', scheduled);
+ await prepare('b', { ...scheduled, id: 'next-scheduled-task' });
+ expect(database.size).toBe(1);
+});
+
+it('reopens remediation when a resolved candidate belongs to an older tested revision', async () => {
+ 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('fix', fix);
+ pinned.revision = 'c'.repeat(40);
+ report = JSON.stringify(payload('fix', { validationRevision: pinned.revision }));
+ await finish('fix', fix);
+ const ledger = saved();
+ ledger.candidates.example = { disposition: 'resolved', resolvedRevision: 'd'.repeat(40) };
+ expect(deepAuditProgress(ledger)).toMatchObject({ discoveryComplete: true, deliveryComplete: true, remediationComplete: false, pendingRemediations: 1, complete: false });
+ ledger.candidates.example.resolvedRevision = ledger.validationRevision;
+ expect(deepAuditProgress(ledger)).toMatchObject({ remediationComplete: true, complete: true });
+});
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
index ea44b5a088..a458b486bd 100644
--- a/server/services/maintenanceRun.js
+++ b/server/services/maintenanceRun.js
@@ -52,7 +52,7 @@ import { ServerError } from '../lib/errorHandler.js';
import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
-import { buildMaintenanceSteps } from '../lib/maintenanceSequence.js';
+import { buildMaintenanceSteps, MAINTENANCE_TASK_ORDER } from '../lib/maintenanceSequence.js';
import { familyForProvider } from '../lib/providerFamilies.js';
import { quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
import { QUOTA_BURN_UNAVAILABLE } from '../lib/quotaBurnTaskRef.js';
@@ -123,7 +123,7 @@ export async function listMaintenanceRuns() {
*/
async function writeRuns(runs) {
let finished = 0;
- await atomicWrite(runsFile(), { runs: runs.filter((entry) => entry.status === MAINTENANCE_RUN_STATUS.RUNNING || ++finished <= RUN_HISTORY_LIMIT) });
+ await atomicWrite(runsFile(), { runs: runs.filter((entry) => entry.status === MAINTENANCE_RUN_STATUS.RUNNING || (entry.auditDepth === 'deep' && entry.status !== MAINTENANCE_RUN_STATUS.COMPLETED) || ++finished <= RUN_HISTORY_LIMIT) });
}
const insertRun = (run) => writeQueue(async () => {
@@ -178,7 +178,7 @@ async function assertNoRunningRun(appId) {
* The first evaluation runs before this returns, so the caller learns whether
* step one actually went out (or why it is holding) in the same response.
*/
-export async function startMaintenanceRun({ appId, providerId, model = null, effort = null, mode = 'file-issues', prCompletion = null, claimBetweenAudits = true, claimHandler = null, taskTypes = null, explicitCheck = false }) {
+export async function startMaintenanceRun({ appId, providerId, model = null, effort = null, mode = 'file-issues', prCompletion = null, claimBetweenAudits = true, claimHandler = null, taskTypes = null, explicitCheck = false, auditDepth = 'quick' }) {
const [{ getAppById }, { getProviderById }, { resolveBurnProvider }] = await Promise.all([
import('./apps.js'), import('./providers.js'), import('./scheduledHandlers/providerPick.js'),
]);
@@ -187,6 +187,8 @@ export async function startMaintenanceRun({ appId, providerId, model = null, eff
const familyId = familyForProvider(provider);
const pinned = await resolveBurnProvider({ job: { providerId }, family: manualBurnFamily(familyId) });
if (!pinned) throw new ServerError(unavailableProvider(providerId), { status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });
+ // Deep launches never drain unrelated work, and a checkpoint requires explicit resume.
+ if (auditDepth === 'deep') taskTypes = taskTypes || [...MAINTENANCE_TASK_ORDER];
// File-only runs never validate or retain a hidden claim selection.
const effectiveClaimHandler = !taskTypes && (mode === 'fix' || claimBetweenAudits) ? claimHandler : null;
let claimFamilyId = familyId;
@@ -206,9 +208,9 @@ export async function startMaintenanceRun({ appId, providerId, model = null, eff
const pins = { providerId, model: model || null, effort: effort || null };
const run = await insertRun({
id, appId, familyId, claimFamilyId, ...pins, prCompletion,
- taskTypes,
+ taskTypes, ...(auditDepth === 'deep' ? { auditDepth, deepAudits: {}, deepCheckpointTaskIds: [], deepCheckpointAgentIds: [] } : {}),
status: MAINTENANCE_RUN_STATUS.RUNNING,
- steps: buildMaintenanceSteps({ appId, idPrefix: id, ...pins, mode, prCompletion, claimBetweenAudits, claimHandler: effectiveClaimHandler, taskTypes, explicitCheck }),
+ steps: buildMaintenanceSteps({ appId, idPrefix: id, ...pins, mode, prCompletion, claimBetweenAudits, claimHandler: effectiveClaimHandler, taskTypes, explicitCheck, auditDepth }),
completed: {},
active: null,
reason: null,
@@ -293,7 +295,13 @@ export async function resumeMaintenanceRun(id) {
* the ledger between the completion and the evaluation it triggers.
*/
export const evaluateMaintenanceRun = (id, { ignoreTaskId = null, completeStepId = null } = {}) => perRun(id, async () => {
- if (completeStepId) await patchRun(id, { completed: { [completeStepId]: new Date().toISOString() }, active: null });
+ if (completeStepId) {
+ const run = await getMaintenanceRun(id);
+ if (run?.auditDepth === 'deep' && run.deepAudits?.[completeStepId]?.complete !== true) {
+ return { dispatched: false, reason: 'Deep coverage and delivery are incomplete' };
+ }
+ await patchRun(id, { completed: { [completeStepId]: new Date().toISOString() }, active: null });
+ }
return evaluate(id, { ignoreTaskId });
});
@@ -306,6 +314,7 @@ async function holdForOutstandingWork(id, run, ignoreTaskId) {
const [{ getAllTasks }, { getOnDemandRequests }] = await Promise.all([import('./cosTaskStore.js'), import('./taskSchedule.js')]);
const { user, cos } = await getAllTasks();
const ownTask = [...(user?.tasks || []), ...(cos?.tasks || [])].find((task) => task.id !== ignoreTaskId
+ && !(task.status === 'blocked' && run.deepCheckpointTaskIds?.includes(task.id))
&& quotaBurnProvenance(task.metadata).maintenanceRunId === id && ACTIVE_TASK_STATUSES.has(task.status));
if (ownTask) {
const { loadState } = await import('./cosState.js');
@@ -380,6 +389,9 @@ async function finishExhaustedSequence(id, run, { completed, skipped }) {
async function evaluate(id, { ignoreTaskId }) {
const run = await getMaintenanceRun(id);
if (!run) return { skipped: 'unknown run' };
+ if (run.auditDepth === 'deep' && Object.keys(run.completed || {}).some(stepId => !run.deepAudits?.[stepId]?.complete && !run.skipped?.[stepId])) {
+ return holdRun(id, run, 'Deep completion evidence is missing; no further dispatch');
+ }
if (run.status !== MAINTENANCE_RUN_STATUS.RUNNING) return { skipped: run.status };
const outstanding = await holdForOutstandingWork(id, run, ignoreTaskId);
@@ -424,8 +436,23 @@ function onMaintenanceAgentCompleted(agent) {
const stepId = agent.metadata?.taskQuotaBurnStepId;
const success = agent.result?.success === true;
return getMaintenanceRun(id)
- .then((run) => {
+ .then(async (run) => {
if (!run) return { skipped: 'unknown run' };
+ if (run.auditDepth === 'deep') {
+ return perRun(id, async () => {
+ const current = await getMaintenanceRun(id);
+ const proof = agent.result?.deepAudit || agent.metadata?.deepAudit || { complete: false, reason: 'Deep checkpoint missing' };
+ // Duplicate events cannot stop a resumed run or regress its newer proof.
+ if (agent.id && current.deepCheckpointAgentIds?.includes(agent.id)) return { skipped: 'checkpoint already recorded' };
+ return patchRun(id, { status: MAINTENANCE_RUN_STATUS.STOPPED, active: null,
+ deepAudits: { ...current.deepAudits, [stepId]: proof },
+ deepCheckpointTaskIds: [...new Set([...(current.deepCheckpointTaskIds || []), agent.taskId].filter(Boolean))],
+ deepCheckpointAgentIds: [...(current.deepCheckpointAgentIds || []), agent.id].filter(Boolean),
+ ...(proof.complete && success ? { completed: { [stepId]: new Date().toISOString() } } : {}),
+ reason: proof.complete && success ? 'Deep step complete; resume to continue remaining checks' : `Deep audit partial — ${proof.reason || 'required evidence or delivery missing'}. Resume explicitly to continue.`,
+ finishedAt: new Date().toISOString() });
+ });
+ }
const step = run.steps.find((entry) => entry.id === stepId);
const completeStepId = success && step && !step.drain ? step.id : null;
return evaluateMaintenanceRun(id, { ignoreTaskId: success ? agent.taskId || null : null, completeStepId });
diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.js
index d86a2ec8ae..bd7a963dc3 100644
--- a/server/services/maintenanceRun.test.js
+++ b/server/services/maintenanceRun.test.js
@@ -57,6 +57,7 @@ const {
const start = () => startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: 'high' });
const agentFor = (run, index, success = true) => ({
+ id: `agent-${index}`,
taskId: `task-${index}`,
result: { success },
metadata: { taskQuotaBurnFamily: run.familyId, taskQuotaBurnStepId: run.steps[index].id, taskQuotaBurnMaintenanceRunId: run.id },
@@ -454,3 +455,35 @@ it('preserves draft delivery across persisted resume, provider edits and step co
expect(state.invoked.at(-1).step.overrides).toMatchObject({ model: 'gpt-6-astra', effort: 'medium', params: { fileIssues: false, useWorktree: true, openPR: true, prCompletion: 'draft' } });
expect((await getMaintenanceRun(run.id)).steps.map(s => s.taskRef.taskType)).toEqual(['security', 'documentation']);
});
+
+
+it('Deep checkpoints pause on successful exit without evidence, resume explicitly, and cannot bypass central completion', async () => {
+ const { run } = await startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', taskTypes: ['security'], auditDepth: 'deep' });
+ expect(state.invoked[0].step.overrides.params.auditDepth).toBe('deep');
+ await evaluateMaintenanceRun(run.id, { completeStepId: run.steps[0].id });
+ expect((await getMaintenanceRun(run.id)).completed).toEqual({});
+ const agent = agentFor(run, 0, true);
+ agent.result.deepAudit = { complete: false, discoveryComplete: false, satisfiedPasses: 3, requiredPasses: 12, reason: 'Budget exhausted' };
+ await __onMaintenanceAgentCompleted(agent);
+ expect(await getMaintenanceRun(run.id)).toMatchObject({ status: 'stopped', completed: {} });
+ await __retryMaintenanceRuns();
+ expect(state.invoked).toHaveLength(1);
+ await resumeMaintenanceRun(run.id);
+ expect(state.invoked).toHaveLength(2);
+ // A duplicate completion from the prior attempt cannot stop the resumed run.
+ await __onMaintenanceAgentCompleted(agent);
+ expect((await getMaintenanceRun(run.id)).status).toBe('running');
+ state.tasks = [{ id: agent.taskId, status: 'in_progress', metadata: { quotaBurnMaintenanceRunId: run.id, quotaBurnStepId: run.steps[0].id } }];
+ await evaluateMaintenanceRun(run.id);
+ expect(state.invoked).toHaveLength(2);
+ await __onMaintenanceAgentCompleted({ ...agent, id: 'resumed-agent', result: { success: true, deepAudit: { ...agent.result.deepAudit, satisfiedPasses: 6 } } });
+ expect(await getMaintenanceRun(run.id)).toMatchObject({ status: 'stopped', deepAudits: { [run.steps[0].id]: { satisfiedPasses: 6 } } });
+});
+
+it('Deep successful delivery alone never certifies discovery and deep proof alone never certifies failed delivery', async () => {
+ const { run } = await startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', taskTypes: ['security'], auditDepth: 'deep' });
+ const agent = agentFor(run, 0, false);
+ agent.result.deepAudit = { complete: true, discoveryComplete: true, deliveryComplete: true };
+ await __onMaintenanceAgentCompleted(agent);
+ expect((await getMaintenanceRun(run.id)).completed).toEqual({});
+});
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index 34d98b63fd..b8a6a760fa 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -710,7 +710,10 @@ function onBurnAgentCompleted(agent) {
// a manual maintenance run's agent spends this family's window — so the
// denial ledger still hears about it — but its completion advances that run,
// never this plan.
- const walkPlan = () => completeQuotaBurnSequenceStep(agent)
+ const deepAudit = agent?.result?.deepAudit || agent?.metadata?.deepAudit;
+ const walkPlan = () => (agent?.metadata?.taskAuditDepth === 'deep' || deepAudit) && deepAudit?.complete !== true
+ ? Promise.resolve({ skipped: 'deep-audit-checkpoint', reason: deepAudit.reason })
+ : completeQuotaBurnSequenceStep(agent)
.then(() => runQuotaBurnCycle({ trigger: 'continuation', familyId, ignoreTaskId: agent?.result?.success ? agent?.taskId : null }));
return recordBurnAgentCompletion(agent)
.catch((err) => console.error(`⚠️ Quota-burn denial ledger for ${familyId}: ${err.message}`))
diff --git a/server/services/quotaBurnSequence.js b/server/services/quotaBurnSequence.js
index e31b0c7c27..35a5ec473d 100644
--- a/server/services/quotaBurnSequence.js
+++ b/server/services/quotaBurnSequence.js
@@ -103,6 +103,8 @@ export async function nextQuotaBurnSequenceJob(family, { completions, reservatio
export async function completeQuotaBurnSequenceStep(agent) {
if (!burnPlanOwnsAgent(agent)) return;
+ const deepAudit = agent?.result?.deepAudit || agent?.metadata?.deepAudit;
+ if ((agent?.metadata?.taskAuditDepth === 'deep' || deepAudit) && deepAudit?.complete !== true) return;
const familyId = agent.metadata.taskQuotaBurnFamily;
const jobId = agent.metadata.taskQuotaBurnStepId;
if (!jobId) return;
diff --git a/server/services/quotaBurnSequence.test.js b/server/services/quotaBurnSequence.test.js
index 4051101599..86ff49b9bb 100644
--- a/server/services/quotaBurnSequence.test.js
+++ b/server/services/quotaBurnSequence.test.js
@@ -72,3 +72,9 @@ describe('maintenance sequence workflow', () => {
expect(recordQuotaBurnJobCompletion).not.toHaveBeenCalled();
});
});
+
+
+it.each([undefined, { complete: false }])('never advances Deep quota sequences with absent or partial proof: %j', async deepAudit => {
+ await completeQuotaBurnSequenceStep({ result: { success: true, deepAudit }, metadata: { taskAuditDepth: 'deep', taskQuotaBurnFamily: 'codex', taskQuotaBurnStepId: 'audit' } });
+ expect(recordQuotaBurnJobCompletion).not.toHaveBeenCalled();
+});