Skip to content

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

fix: make Deep an extended regular audit with historical evidence preserved

Adam Eivyf05d8e766c6d
diff --git a/client/src/components/apps/AppQualityRunner.jsx b/client/src/components/apps/AppQualityRunner.jsx
index 37bbcbb795..6e64aea07e 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, resumeMaintenanceRun } from '../../services/apiAgents';
+import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun } from '../../services/apiAgents';
const RUN_EVENTS = ['cos:maintenance:updated'];
@@ -81,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, resume = false) => {
+ const stop = async (id) => {
setBusy(true);
setError('');
- const response = await (resume ? resumeMaintenanceRun : stopMaintenanceRun)(id, { silent: true }).catch(err => { if (appIdRef.current === app.id) setError(err.message); return null; });
+ const response = await 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);
@@ -109,7 +109,7 @@ export default function AppQualityRunner({ app, children }) {
<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>}
+ {auditDepth === 'deep' && <p className="text-xs text-gray-400">Spend more time investigating high-risk paths and fixing multiple worthwhile issues in one run. The summary reports coverage and remaining limits; Deep does not certify every file.</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>
@@ -129,7 +129,7 @@ export default function AppQualityRunner({ app, children }) {
{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.auditDepth === 'deep' && !run.auditWorkflow && <p className="text-xs text-gray-400">Historical exhaustive audit — evidence retained; start a new Deep run above.</p>}
{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 fdc99bf978..e43ebc6288 100644
--- a/client/src/components/apps/AppQualityRunner.test.jsx
+++ b/client/src/components/apps/AppQualityRunner.test.jsx
@@ -267,7 +267,7 @@ it('defaults audit fixes to draft review and lets the user explicitly inherit sa
});
-it('offers separate Deep depth, shows pass denominator and resumes a persisted partial run explicitly', async () => {
+it('explains extended Deep and preserves old evidence without offering legacy resume', 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] });
@@ -275,6 +275,8 @@ it('offers separate Deep depth, shows pass denominator and resumes a persisted p
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 }));
+ expect(screen.queryByRole('button', { name: 'Resume Deep audit' })).not.toBeInTheDocument();
+ expect(screen.getByText(/Historical exhaustive audit/)).toBeInTheDocument();
+ expect(screen.getByText(/multiple worthwhile issues in one run/)).toBeInTheDocument();
+ expect(resumeMaintenanceRun).not.toHaveBeenCalled();
});
diff --git a/client/src/components/apps/tabs/AutomationTab.jsx b/client/src/components/apps/tabs/AutomationTab.jsx
index 5516bc8cd5..7802b662fc 100644
--- a/client/src/components/apps/tabs/AutomationTab.jsx
+++ b/client/src/components/apps/tabs/AutomationTab.jsx
@@ -301,7 +301,7 @@ export default function AutomationTab({ appId, appName }) {
) : 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"
+ <select id={`audit-depth-${taskType}`} title="Deep spends more time investigating and fixing worthwhile issues in one run" 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>
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
index 12b2690658..4e7df08f9a 100644
--- a/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
@@ -42,8 +42,9 @@ export default function MaintenanceRunStatus({ run, showSteps = false, renderSte
)}
</div>
<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 max-h-36 overflow-y-auto pr-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>
+ {run.auditWorkflow === 'extended-v1' && <p>Extended Deep audit · coverage and limits are reported in the completion summary.</p>}
+ {run.auditDepth === 'deep' && !run.auditWorkflow && Object.entries(run.deepAudits || {}).map(([id, audit]) => <div key={id} className="space-y-1 max-h-36 overflow-y-auto pr-1">
+ <p>Historical 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>}
diff --git a/docs/DEEP-AUDITS-LEGACY.md b/docs/DEEP-AUDITS-LEGACY.md
new file mode 100644
index 0000000000..a86920560d
--- /dev/null
+++ b/docs/DEEP-AUDITS-LEGACY.md
@@ -0,0 +1,44 @@
+# Historical exhaustive Deep audits
+
+This describes retained certification records from before extended Deep. They remain incomplete history. New launches and normal resume no longer execute this workflow. The descriptions below document the stored evidence format, not current launch instructions.
+
+# 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 server-assigned batch of one pass, not the whole audit. Each subsystem/scenario is partitioned deterministically by sorted source paths into units of at most 24 files. Every source path belongs to exactly one partition of each scenario. Batches contain at most 12 partitions and 96 distinct owned paths. A very large individual file or unavailable required runtime evidence can still block a partition. Untouched obligations precede repeated blockers, with pass rotation and attempt counts preventing starvation. A partition advances through its own prerequisite passes; a blocked neighbor does not prevent useful trace, adversarial or challenge work elsewhere. The agent receives a compact assignment with pinned sources, prior evidence and relevant candidates; the full ledger remains available for targeted lookup. Batch limits never reduce the full coverage denominator. Publication-only retries at an unchanged revision use bounded rotating re-attestation batches while retaining the complete global coverage requirements. They are explicitly marked delivery retries, not new full-scope reviews. Failed publication remains incomplete; a changed validation revision invalidates prior post-fix receipts. A partial checkpoint stops the maintenance run. **Resume Deep audit** starts another invocation using the same coverage ledger. It can continue a partition into its next pass while other partitions still need earlier passes. Failed Deep tasks are parked rather than automatically retried. Completion keeps the task held until worktree cleanup finishes, then atomically parks it with any surviving branch/worktree pointer. Explicit resume waits for that handoff and reuses the persisted audit instructions. Recovery of an interrupted invocation also parks it for explicit resume instead of treating a commit or retry budget as permission to continue. Boot and reading status do not launch work.
+
+An app's **Automation** tab also exposes depth separately from delivery. An explicitly configured schedule can start a Deep audit; a partial task then parks and blocks further automatic dispatch for that app/category. Use Run Now to resume explicitly. Its app/category/delivery identity keeps the same ledger across those invocations. Custom agent jobs accept `taskMetadata.auditDepth: "deep"` and an optional `deepAuditId` for an explicitly selected checkpoint. A custom job without an audit category uses the code-quality coverage category. Different apps, categories and delivery modes cannot share a checkpoint.
+
+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. Fresh isolated workspaces initialize submodules recursively at their recorded commits before inventory. Retained submodule changes are refused rather than reset. Fresh resume workspaces use the server-owned ledger revision even when the default branch has advanced; an unavailable pinned commit blocks launch instead of falling back to a different source. An unexpanded submodule blocks completion. Ignored runtime assets are outside the source inventory; required runtime evidence that cannot be obtained must remain blocked.
+
+The coverage groups are category × source directory/subsystem × normal, failure, and concurrency/recovery scenarios. Each group owns deterministic source partitions. Group completion is the conjunction of actual partition receipts, never a synthetic review receipt. This is a minimum, not a claim that those three scenarios exhaust every workflow. Agents can add concrete workflows or entry-point scenarios through `additionalUnits`; additions increase the denominator and require the same passes. They cannot delete inventoried units.
+
+Every required unit needs evidence from:
+
+1. Static inspection, accounting for every file in that unit.
+2. End-to-end tracing, recording entry, exit, inbound callers, outbound dependencies, boundary observations and unresolved boundary questions. Follow relevant callers/callees outside the owned partition and cite their pinned identities as context; those references do not credit their separate coverage.
+3. Adversarial investigation, recording scenario, expected behavior, observed outcome and failures across the identified boundaries.
+4. An independent challenge invocation, bound to the preceding evidence and attributed to a different server-issued agent identity, explicitly challenging cross-boundary assumptions.
+
+Statuses are derived from receipts: pending, scanned, traced, validated, reviewed, blocked, or inapplicable with a reason. Inapplicability needs source references and pass-specific explanations, including independent confirmation. A scan count, quality score, successful process, first fix or five findings cannot complete discovery. Required units and passes must be accounted for and candidates triaged. A verified defect is reviewed evidence, not automatically a coverage blocker: a dangling tracked symlink can be inspected and its missing target verified without claiming to review nonexistent contents. Genuinely inaccessible required evidence remains blocked. The findings register retains confirmed, rejected, duplicate, deferred and resolved candidates separately from small remediation PRs.
+
+Fix delivery also requires a post-fix pass against a clean, exact tested revision. All current post-fix receipts must bind to that revision; evidence from different revisions cannot combine into completion. A resolved finding names that tested revision and its fix/test evidence; changing the validation revision requires re-attesting prior resolutions. Discovery, remediation and delivery have separate outcomes: deferred fixes keep remediation incomplete. Actual execution and verification results settle delivery after evidence ingestion. Existing PR policy still governs delivery; selecting Deep does not authorize merging or deploying.
+
+## 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.
+
+Contract v3 upgrades v1/v2 ledgers transactionally on explicit resume. The complete prior generation remains historical, and new partition/boundary obligations receive no inherited receipt credit. When the contract is the only scope change, enrolled groups and findings are retained. Legacy findings remain explicitly group-scoped, visible from each assigned partition in that group without conferring coverage credit. New findings must bind to assigned partitions. Migration records both old and new required-pass counts and is idempotent; stale in-flight reports cannot update the replacement generation.
+
+Source, inventory, capabilities, exclusions or other prompt changes conservatively invalidate current evidence and retain it as historical. This first version invalidates the full generation rather than trying to prove which dependencies were unaffected. That includes resuming against a changed HEAD after an interrupted fix; the earlier discovery remains readable but does not certify the new source. Preserve and use the retained worktree/branch when recovering incomplete remediation. Git cannot move a linked worktree containing submodules: for a verified inactive, clean owned workspace, Deep resume detaches the old tree at its exact HEAD and attaches the preserved branch in a new workspace. The old files remain intact. Dirty, locked or ambiguous submodule workspaces stay blocked for explicit recovery; they are never force-deinitialized or reset.
+
+Evidence is **agent-reported, source-verified**. The server checks assignment, scope, source blob identities, required evidence fields, ordering, separate invocation identity and exact revision bindings. It cannot prove that a natural-language trace is truthful or that a reported command actually ran. Independent challenge is a distinct invocation, not a guarantee of a different provider/model. Existing test and PR review requirements remain necessary. Deep mode may take many explicitly resumed invocations; it has no automatic repeat-until-perfect loop and launches no additional categories on its own.
diff --git a/docs/DEEP-AUDITS.md b/docs/DEEP-AUDITS.md
index 1ac1b803d8..5316bb233a 100644
--- a/docs/DEEP-AUDITS.md
+++ b/docs/DEEP-AUDITS.md
@@ -1,40 +1,15 @@
# 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.
+Deep is an extended regular audit, independent of **File issues** or **Audit and fix** delivery. Quick remains unchanged.
-## Run and resume
+Choose Deep for extra investigation of high-risk paths, deeper caller/dependency and failure-case tracing, and multiple worthwhile fixes where evidence supports them. Each run aims to finish useful investigation and its authorized delivery. It does not require every repository file, a fixed file batch, or four separate review invocations. Existing resource limits, tests, independent review and PR policy still apply. Deep never grants merge or deployment permission by itself.
-In an app's **Quality** tab, choose the categories, delivery policy, provider/model and **Audit depth → Deep**, then Run now. A launch performs one server-assigned batch of one pass, not the whole audit. Each subsystem/scenario is partitioned deterministically by sorted source paths into units of at most 24 files. Every source path belongs to exactly one partition of each scenario. Batches contain at most 12 partitions and 96 distinct owned paths. A very large individual file or unavailable required runtime evidence can still block a partition. Untouched obligations precede repeated blockers, with pass rotation and attempt counts preventing starvation. A partition advances through its own prerequisite passes; a blocked neighbor does not prevent useful trace, adversarial or challenge work elsewhere. The agent receives a compact assignment with pinned sources, prior evidence and relevant candidates; the full ledger remains available for targeted lookup. Batch limits never reduce the full coverage denominator. Publication-only retries at an unchanged revision use bounded rotating re-attestation batches while retaining the complete global coverage requirements. They are explicitly marked delivery retries, not new full-scope reviews. Failed publication remains incomplete; a changed validation revision invalidates prior post-fix receipts. A partial checkpoint stops the maintenance run. **Resume Deep audit** starts another invocation using the same coverage ledger. It can continue a partition into its next pass while other partitions still need earlier passes. Failed Deep tasks are parked rather than automatically retried. Completion keeps the task held until worktree cleanup finishes, then atomically parks it with any surviving branch/worktree pointer. Explicit resume waits for that handoff and reuses the persisted audit instructions. Recovery of an interrupted invocation also parks it for explicit resume instead of treating a commit or retry budget as permission to continue. Boot and reading status do not launch work.
+The final summary reports what was investigated, findings/fixes, actual validation, delivery and remaining risks or untested areas. Partial coverage is valid: successful task completion means the run finished its useful work, not that the repository is certified defect-free. Missing or invalid assessments still produce the normal warning. Interrupted work retains the ordinary failure, cleanup and worktree recovery behavior.
-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.
+New manual, scheduled and custom Deep launches persist `auditWorkflow: "extended-v1"`. This marker is assigned only at creation, never while loading or resuming an old record. Unsupported workflow versions and attempts to attach historical checkpoint IDs to extended runs are refused. Provider, model, effort and delivery pins remain separate.
-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"`.
+## Historical evidence
-## Coverage and completion
+Previous exhaustive Deep ledgers, source pins, findings and worktrees are preserved. They remain visibly historical and incomplete; new Deep runs neither reuse them nor credit their receipts. Normal resume of those certification runs is disabled on the server and in the Quality UI. Their authenticated ledger endpoint remains available at `GET /api/cos/schedule/deep-audits/:id`.
-The server pins a clean Git revision, tracked paths and blob IDs, inventory hash, detected capabilities, explicit exclusions, category prompt version, Deep contract version and effective task prompt hash. It inventories root files, code, tests, docs and configuration rather than filtering to popular source suffixes. Fresh isolated workspaces initialize submodules recursively at their recorded commits before inventory. Retained submodule changes are refused rather than reset. Fresh resume workspaces use the server-owned ledger revision even when the default branch has advanced; an unavailable pinned commit blocks launch instead of falling back to a different source. An unexpanded submodule blocks completion. Ignored runtime assets are outside the source inventory; required runtime evidence that cannot be obtained must remain blocked.
-
-The coverage groups are category × source directory/subsystem × normal, failure, and concurrency/recovery scenarios. Each group owns deterministic source partitions. Group completion is the conjunction of actual partition receipts, never a synthetic review receipt. This is a minimum, not a claim that those three scenarios exhaust every workflow. Agents can add concrete workflows or entry-point scenarios through `additionalUnits`; additions increase the denominator and require the same passes. They cannot delete inventoried units.
-
-Every required unit needs evidence from:
-
-1. Static inspection, accounting for every file in that unit.
-2. End-to-end tracing, recording entry, exit, inbound callers, outbound dependencies, boundary observations and unresolved boundary questions. Follow relevant callers/callees outside the owned partition and cite their pinned identities as context; those references do not credit their separate coverage.
-3. Adversarial investigation, recording scenario, expected behavior, observed outcome and failures across the identified boundaries.
-4. An independent challenge invocation, bound to the preceding evidence and attributed to a different server-issued agent identity, explicitly challenging cross-boundary assumptions.
-
-Statuses are derived from receipts: pending, scanned, traced, validated, reviewed, blocked, or inapplicable with a reason. Inapplicability needs source references and pass-specific explanations, including independent confirmation. A scan count, quality score, successful process, first fix or five findings cannot complete discovery. Required units and passes must be accounted for and candidates triaged. A verified defect is reviewed evidence, not automatically a coverage blocker: a dangling tracked symlink can be inspected and its missing target verified without claiming to review nonexistent contents. Genuinely inaccessible required evidence remains blocked. The findings register retains confirmed, rejected, duplicate, deferred and resolved candidates separately from small remediation PRs.
-
-Fix delivery also requires a post-fix pass against a clean, exact tested revision. All current post-fix receipts must bind to that revision; evidence from different revisions cannot combine into completion. A resolved finding names that tested revision and its fix/test evidence; changing the validation revision requires re-attesting prior resolutions. Discovery, remediation and delivery have separate outcomes: deferred fixes keep remediation incomplete. Actual execution and verification results settle delivery after evidence ingestion. Existing PR policy still governs delivery; selecting Deep does not authorize merging or deploying.
-
-## 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.
-
-Contract v3 upgrades v1/v2 ledgers transactionally on explicit resume. The complete prior generation remains historical, and new partition/boundary obligations receive no inherited receipt credit. When the contract is the only scope change, enrolled groups and findings are retained. Legacy findings remain explicitly group-scoped, visible from each assigned partition in that group without conferring coverage credit. New findings must bind to assigned partitions. Migration records both old and new required-pass counts and is idempotent; stale in-flight reports cannot update the replacement generation.
-
-Source, inventory, capabilities, exclusions or other prompt changes conservatively invalidate current evidence and retain it as historical. This first version invalidates the full generation rather than trying to prove which dependencies were unaffected. That includes resuming against a changed HEAD after an interrupted fix; the earlier discovery remains readable but does not certify the new source. Preserve and use the retained worktree/branch when recovering incomplete remediation. Git cannot move a linked worktree containing submodules: for a verified inactive, clean owned workspace, Deep resume detaches the old tree at its exact HEAD and attaches the preserved branch in a new workspace. The old files remain intact. Dirty, locked or ambiguous submodule workspaces stay blocked for explicit recovery; they are never force-deinitialized or reset.
-
-Evidence is **agent-reported, source-verified**. The server checks assignment, scope, source blob identities, required evidence fields, ordering, separate invocation identity and exact revision bindings. It cannot prove that a natural-language trace is truthful or that a reported command actually ran. Independent challenge is a distinct invocation, not a guarantee of a different provider/model. Existing test and PR review requirements remain necessary. Deep mode may take many explicitly resumed invocations; it has no automatic repeat-until-perfect loop and launches no additional categories on its own.
+See [historical evidence format](DEEP-AUDITS-LEGACY.md) for the archived architecture. No data migration marks those ledgers complete or removes them. Starting a new Deep audit creates a separate ordinary audit task; it does not delete or repurpose retained source work.
diff --git a/server/lib/README.md b/server/lib/README.md
index a4d191c750..7b13857437 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -880,3 +880,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `deepAuditCoverage.js` | Deterministic bounded source partitions, derived coverage groups and explicit contract-upgrade compatibility. |
| `deepAudit.js` | Strict Deep audit checkpoint schema, scope invalidation, server-assigned passes and mechanical completion rules. |
+
+- `auditWorkflow.js`: versioned extended Deep execution and historical certification classification.
diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.js
index ef5ecfad5d..d20d2405cd 100644
--- a/server/lib/agentRegistrationRecord.js
+++ b/server/lib/agentRegistrationRecord.js
@@ -239,7 +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' } : {}),
+ ...(task.metadata?.auditDepth === 'deep' ? { taskAuditDepth: 'deep', ...(task.metadata.auditWorkflow ? { auditWorkflow: task.metadata.auditWorkflow } : {}) } : {}),
// 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/auditWorkflow.js b/server/lib/auditWorkflow.js
new file mode 100644
index 0000000000..ead434e7a2
--- /dev/null
+++ b/server/lib/auditWorkflow.js
@@ -0,0 +1,33 @@
+/** Deep execution policy; absent markers on saved Deep records remain historical. */
+export const EXTENDED_AUDIT_WORKFLOW = 'extended-v1';
+
+export function auditWorkflow(meta = {}) {
+ meta ??= {};
+ if (meta.auditWorkflow != null && meta.auditWorkflow !== EXTENDED_AUDIT_WORKFLOW) throw new Error('Unsupported audit workflow version');
+ if (meta.auditDepth !== 'deep') {
+ if (meta.auditWorkflow != null) throw new Error('Audit workflow requires Deep depth');
+ return 'quick';
+ }
+ if (meta.auditWorkflow === EXTENDED_AUDIT_WORKFLOW) {
+ if (meta.deepAuditId) throw new Error('Extended Deep cannot reuse a historical certification checkpoint');
+ return EXTENDED_AUDIT_WORKFLOW;
+ }
+ return 'legacy';
+}
+export const isLegacyDeepAudit = (meta) => auditWorkflow(meta) === 'legacy';
+export const isExtendedDeepAudit = (meta) => auditWorkflow(meta) === EXTENDED_AUDIT_WORKFLOW;
+
+/** Only call at creation boundaries, never when loading or resuming saved work. */
+export function newAuditMetadata(meta = {}) {
+ auditWorkflow(meta);
+ if (meta.auditDepth !== 'deep') return meta;
+ if (meta.deepAuditId) throw new Error('Historical Deep checkpoints are read-only; start a new Deep audit');
+ return { ...meta, auditWorkflow: EXTENDED_AUDIT_WORKFLOW };
+}
+
+export const EXTENDED_AUDIT_INSTRUCTIONS = `## Deep audit — extended regular audit
+This execution policy takes precedence over conflicting investigation limits in the category or saved/custom prompt below. Keep its category, safety, resource, validation, review and delivery requirements.
+Spend extra effort on a useful risk-based audit in this run: orient broadly, prioritize current runtime paths and high-impact failure modes, trace callers and dependencies, challenge plausible findings, and verify concrete behavior. Follow evidence into adjacent code where needed. Do not divide the repository into exhaustive file batches or require separate static/trace/challenge invocations.
+Replace quick-mode caps such as investigating only five candidates, stopping after the first finding/fix, or an arbitrary short investigation window. In audit-and-fix mode, fix multiple worthwhile issues when supported by evidence; keep changes coherent and reviewable. Do not invent findings, force unrelated fixes into one PR, or exceed the configured resource limits. In file-issues mode, retain that delivery policy and report supported findings without silently switching to code changes.
+Use normal test, independent-review and PR requirements for the work actually changed. Finish this run when the worthwhile investigation and authorized delivery are done, or report a concrete blocker or resource limit. Do not automatically queue another run or launch other categories.
+Write a final completion summary stating scope investigated, findings and fixes, validation actually run, delivery status, and remaining risks or untested areas. Record the usual QUALITY_AUDIT_JSON assessment honestly: partial coverage is valid, a successful run does not certify every file, and a scan count does not prove substantive review. Preserve a checkpoint of unfinished work when interrupted. No exhaustive coverage ledger or four-pass completion gate is required for this workflow.`;
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index a0bc8fe7ae..9eceeb6b07 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -1,3 +1,4 @@
+import { auditWorkflow } from './auditWorkflow.js';
/**
* Chief-of-Staff (CoS) Zod schemas (split out of validation.js, issue #1831).
*
@@ -554,6 +555,7 @@ export const createCosJobSchema = z.object({
// without this row the flag never survives a job create/update.
fileIssues: z.boolean().optional(),
auditDepth: z.enum(['quick', 'deep']).optional(),
+ auditWorkflow: z.literal('extended-v1').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
@@ -1204,6 +1206,7 @@ export function sanitizeTaskMetadata(raw) {
clean.prCompletion = raw.prCompletion;
hasKeys = true;
}
+ if (raw.auditWorkflow != null) { auditWorkflow(raw); clean.auditWorkflow = raw.auditWorkflow; 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
diff --git a/server/lib/index.js b/server/lib/index.js
index 090e131920..a8fb4ecf78 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -862,3 +862,5 @@ export * from './runtimeFilePublication.js';
export * from './deepAudit.js';
export * from './deepAuditCoverage.js';
+
+export * from './auditWorkflow.js';
diff --git a/server/lib/maintenanceSequence.js b/server/lib/maintenanceSequence.js
index 0482db0d63..c183299b9a 100644
--- a/server/lib/maintenanceSequence.js
+++ b/server/lib/maintenanceSequence.js
@@ -1,3 +1,4 @@
+import { EXTENDED_AUDIT_WORKFLOW } from './auditWorkflow.js';
/**
* The maintenance ladder: the ordered audits PortOS recommends running against a
* managed app, with a perpetual `claim-issue` drain between every pair so each
@@ -70,6 +71,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 ? { ...(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 } : {}) } },
+ overrides: { ...(taskType === MAINTENANCE_DRAIN_TASK && claimHandler ? claimHandler : { providerId, model, effort }), params: taskTypes ? { ...(auditDepth === 'deep' ? { auditDepth, auditWorkflow: EXTENDED_AUDIT_WORKFLOW } : {}), fileIssues: mode !== 'fix', ...(mode === 'fix' ? { useWorktree: true, openPR: true, ...(prCompletion ? { prCompletion } : {}) } : {}), ...(explicitCheck || auditDepth === 'deep' ? { runInapplicableAudit: true } : {}) } : { ...(auditDepth === 'deep' ? { auditDepth, auditWorkflow: EXTENDED_AUDIT_WORKFLOW } : {}), ...maintenanceStepParams(taskType, mode), ...(prCompletion ? { prCompletion } : {}) } },
}));
}
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index f4fb4e142d..995b23ff15 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1,3 +1,4 @@
+import { isLegacyDeepAudit } from '../lib/auditWorkflow.js';
import { retryHoldMetadata } from '../lib/taskRetryHold.js';
import { PR_COMPLETIONS, resolvePrCompletion, PR_MISSING_CATEGORY, prClaimWasVerified } from '../lib/prDisposition.js';
import { isAuditTaskType } from '../lib/auditCatalog.js';
@@ -1040,7 +1041,7 @@ 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 (task.metadata?.auditDepth !== 'deep' && isAuditTaskType(resolveTaskHookType(task)) && savedAssessment?.status === 'recorded') {
+ if (!isLegacyDeepAudit(task.metadata) && isAuditTaskType(resolveTaskHookType(task)) && savedAssessment?.status === 'recorded') {
return { ran: false, auditAssessment: savedAssessment };
}
if (agent?.metadata?.outputHookDispatchedAt) {
@@ -1602,7 +1603,7 @@ export async function finalizeAgent({
});
const taskType = task?.taskType || 'user';
- const taskUpdate = task.metadata?.auditDepth === 'deep' && !terminatedByUser
+ const taskUpdate = isLegacyDeepAudit(task.metadata) && !terminatedByUser
? { status: 'in_progress', metadata: { ...preHookTask.metadata, ...retryHoldMetadata(agentId) } }
: terminatedByUser
? {
@@ -1638,7 +1639,7 @@ export async function finalizeAgent({
return null;
});
- if (task.metadata?.auditDepth === 'deep' && hookResult?.deepAudit) {
+ if (isLegacyDeepAudit(task.metadata) && 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}` }));
@@ -1959,14 +1960,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);
- const deepAudit = task.metadata?.auditDepth === 'deep'
+ const deepAudit = isLegacyDeepAudit(task.metadata)
? 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 } : {}),
+ ...(isLegacyDeepAudit(task.metadata) ? { deepDiscoveryComplete: deepAudit?.discoveryComplete === true } : {}),
workspacePath: hookPayloadDir({ task, workspacePath, recovery }) })
.then(recorded => ({ status: recorded === true ? 'recorded' : success ? 'not-recorded' : 'not-attempted' }))
.catch(err => {
@@ -1975,7 +1976,7 @@ 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 (task.metadata?.auditDepth !== 'deep' && recorded === true && resolvePrCompletion(task?.metadata) !== PR_COMPLETIONS.LEAVE_OPEN) {
+ if (!isLegacyDeepAudit(task.metadata) && 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.
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index e4ba3276ed..853d400cf6 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -262,6 +262,19 @@ describe('recovery output-hook dispatch (#3182)', () => {
}
});
+
+it('finishes extended Deep with an honest partial summary through ordinary completion without ledger gates', async () => {
+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security', auditDepth: 'deep', auditWorkflow: 'extended-v1', simplify: false } };
+ recordAuditQuality.mockResolvedValue(true);
+ await finalizeAgent({ agentId: 'extended-summary', task, success: true, exitCode: 0, duration: 1000,
+ workspacePath: '/example/repo', finalSummary: 'Investigated high-risk paths and fixed two coherent defects. Coverage remains partial.', outputBuffer: 'tool transcript' });
+ expect(deep.checkpointDeepAudit).not.toHaveBeenCalled();
+ expect(deep.settleDeepAuditDelivery).not.toHaveBeenCalled();
+ expect(updateTask).toHaveBeenCalledWith(task.id, expect.objectContaining({ status: 'completed' }), expect.anything());
+ expect(persistedAgent.metadata.taskSummary).toContain('Coverage remains partial');
+ expect(persistedAgent.metadata.taskSummarySource).toBe('terminal-result');
+});
+
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,
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 9540259b79..e6761c1f49 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -1,3 +1,4 @@
+import { isLegacyDeepAudit } from '../lib/auditWorkflow.js';
import { hasClaimFlowContract } from '../lib/claimFlowTaskTypes.js';
import { isFalsyMeta, isTruthyMeta } from '../lib/metadataFlags.js';
import { maintenance } from '../lib/maintenanceAdmission.js';
@@ -1507,7 +1508,7 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
// Recovery of a dead Deep invocation is a checkpoint, never permission to
// auto-launch another provider call or to treat commits as completed coverage.
- if (task.metadata?.auditDepth === 'deep') {
+ if (isLegacyDeepAudit(task.metadata)) {
if (task.status !== 'in_progress') return;
const held = isRetryHeld(task.metadata);
if (held && task.metadata[RETRY_HOLD_KEY] !== agentId) return;
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 74eb618d82..5a594ecc76 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -1,3 +1,4 @@
+import { auditWorkflow, EXTENDED_AUDIT_INSTRUCTIONS } from '../lib/auditWorkflow.js';
/**
* Agent Prompt Builder
*
@@ -374,9 +375,9 @@ 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 workflow = auditWorkflow(task.metadata);
+ if (workflow === 'legacy') throw new Error('Historical Deep certification runs are read-only; start a new Deep audit');
+ const deepAuditContract = workflow === 'extended-v1' ? EXTENDED_AUDIT_INSTRUCTIONS : null;
const withDeepAudit = prompt => !deepAuditContract ? prompt : typeof prompt === 'string'
? `${deepAuditContract}\n\n${prompt}`
: { ...prompt, systemPrompt: `${deepAuditContract}\n\n${prompt.systemPrompt || ''}` };
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 347fc61145..56b02400aa 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -4542,18 +4542,22 @@ describe('auto-merge posture (worktree, no PR) is commit-only on every path', ()
});
-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' } });
+it.each(['api', 'cli', 'tui'])('gives extended Deep precedence over customized quick limits on %s providers', async providerType => {
+ const task = makeTask({ description: 'Stop after one finding', metadata: { auditDepth: 'deep', auditWorkflow: 'extended-v1', 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);
+ expect(prompt.startsWith('## Deep audit — extended regular audit')).toBe(true);
+ expect(prompt).toContain('fix multiple worthwhile issues');
+ expect(prompt).toContain('partial coverage is valid');
const { prepareDeepAudit } = await import('./deepAudit.js');
- expect(prepareDeepAudit).toHaveBeenCalledWith(expect.objectContaining({ task: expect.objectContaining({ metadata: expect.objectContaining({ auditDepth: 'deep' }) }), agentId: 'deep-agent' }));
+ expect(prepareDeepAudit).not.toHaveBeenCalled();
});
-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();
+it('preserves the extended marker in split prompts, refuses unknown versions and legacy launches', async () => {
+ const metadata = sanitizeTaskMetadata({ auditDepth: 'deep', auditWorkflow: 'extended-v1' });
+ expect(metadata).toMatchObject({ auditDepth: 'deep', auditWorkflow: 'extended-v1' });
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);
+ expect(prompt.systemPrompt.startsWith('## Deep audit — extended regular audit')).toBe(true);
+ await expect(buildAgentPrompt(makeTask({ metadata: { auditDepth: 'deep', deepAuditId: 'old' } }), {}, '/r')).rejects.toThrow('read-only');
+ expect(() => sanitizeTaskMetadata({ auditDepth: 'deep', auditWorkflow: 'future-v9' })).toThrow('Unsupported');
+ expect(() => sanitizeTaskMetadata({ auditDepth: 'deep', auditWorkflow: 'extended-v1', deepAuditId: 'old' })).toThrow('cannot reuse');
});
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 672cf4f724..80f2db6384 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -1,3 +1,4 @@
+import { isLegacyDeepAudit } from '../lib/auditWorkflow.js';
import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';
/**
* Agent Workspace Preparation
@@ -170,7 +171,7 @@ async function prepareRequestedWorktree({
allowSharedWorkspaceFallback,
}) {
const isolateDependencies = resolveTaskHookType(task) === 'dependency-updates';
- const baseCommit = task.metadata?.auditDepth === 'deep'
+ const baseCommit = isLegacyDeepAudit(task.metadata)
? await (await import('./deepAudit.js')).getDeepAuditSourceRevision(task)
: null;
// Detecting the base branch and resolving the branch holder are independent
@@ -194,7 +195,7 @@ async function prepareRequestedWorktree({
preferredPath: resumeWorktreePath,
taskId: task.id,
allowLiveClaim: isNonCommittingCoordinatorTask(task),
- deepResume: task.metadata?.auditDepth === 'deep',
+ deepResume: isLegacyDeepAudit(task.metadata),
})
: Promise.resolve(null);
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index d1c7c2adc2..cad09a3e79 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -125,6 +125,17 @@ describe('prepareAgentWorkspace', () => {
expect(createWorktree).toHaveBeenCalledWith('agent-deep', expect.any(String), 'deep', expect.objectContaining({ baseCommit: 'a'.repeat(40) }));
});
+ it('provisions extended Deep from the ordinary source without reading old coverage pins', async () => {
+ const { getDeepAuditSourceRevision } = await import('./deepAudit.js');
+ getDeepAuditSourceRevision.mockClear();
+ createWorktree.mockResolvedValue({ worktreePath: '/mock/worktrees/extended', branchName: 'cos/extended', baseBranch: 'main' });
+ const task = { id: 'extended', taskType: 'internal', metadata: { useWorktree: true, auditDepth: 'deep', auditWorkflow: 'extended-v1' } };
+ expect(await prepareAgentWorkspace({ agentId: 'agent-extended', task })).toMatchObject({ outcome: 'ready' });
+ expect(getDeepAuditSourceRevision).not.toHaveBeenCalled();
+ expect(createWorktree.mock.calls[0][3]).not.toHaveProperty('baseCommit');
+ expect(createWorktree).toHaveBeenCalledWith('agent-extended', expect.any(String), 'extended', expect.objectContaining({ baseBranch: 'main' }));
+ });
+
it('normalizes legacy investigations into isolated PR delivery', async () => {
ensureLatest.mockResolvedValue({ success: true, upToDate: true });
createWorktree.mockResolvedValue({
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index dad0e5ff41..77a430b9af 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -1,3 +1,4 @@
+import { isLegacyDeepAudit } from '../lib/auditWorkflow.js';
/**
* Agent Worktree Cleanup
*
@@ -933,7 +934,7 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
*/
export async function releaseRetryHold({ agentId, task, success, agentMetadata }) {
if (!agentId || !task?.id) return {};
- if (success && task.metadata?.auditDepth !== 'deep') return {};
+ if (success && !isLegacyDeepAudit(task.metadata)) return {};
const { getTaskById, getAgentRecord } = await import('./cos.js');
const persisted = await getTaskById(task.id).catch(err => {
@@ -942,7 +943,7 @@ export async function releaseRetryHold({ agentId, task, success, agentMetadata }
});
if (!persisted) return {};
- if (task.metadata?.auditDepth === 'deep') {
+ if (isLegacyDeepAudit(task.metadata)) {
if (persisted.status !== 'in_progress' || !isRetryHoldOwner(persisted.metadata, agentId)) return {};
const metadata = agentMetadata === undefined
? (await getAgentRecord(agentId).catch(() => null))?.metadata : agentMetadata;
diff --git a/server/services/appQuality.js b/server/services/appQuality.js
index 3d5a37e652..871a1553de 100644
--- a/server/services/appQuality.js
+++ b/server/services/appQuality.js
@@ -1,3 +1,4 @@
+import { isLegacyDeepAudit } from '../lib/auditWorkflow.js';
/** DB-primary audit measurements with read-through app federation. Reads never dispatch AI work. */
import { ensureSchema, query } from '../lib/db.js';
import { doneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';
@@ -16,7 +17,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';
+ if (isLegacyDeepAudit(task.metadata) && !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/autonomousJobs/skillTemplates.js b/server/services/autonomousJobs/skillTemplates.js
index 3c7caf1767..2bca1ae993 100644
--- a/server/services/autonomousJobs/skillTemplates.js
+++ b/server/services/autonomousJobs/skillTemplates.js
@@ -1,3 +1,4 @@
+import { newAuditMetadata } from '../../lib/auditWorkflow.js';
/**
* Autonomous Jobs — skill templates and effective-prompt assembly.
*
@@ -180,7 +181,7 @@ async function generateTaskFromJob(job) {
: []
const taskPrompt = appendTaskDataInputs(prompt, inputs)
const description = taskPrompt.split('\n').map(line => line.trim()).find(Boolean) || job.name
- const meta = job.taskMetadata || {}
+ const meta = newAuditMetadata(job.taskMetadata || {})
return {
id: `${job.id}-${Date.now().toString(36)}`,
description,
@@ -188,6 +189,7 @@ async function generateTaskFromJob(job) {
metadata: {
autonomousJob: true,
...(meta.auditDepth ? { auditDepth: meta.auditDepth } : {}),
+ ...(meta.auditWorkflow ? { auditWorkflow: meta.auditWorkflow } : {}),
...(meta.deepAuditId ? { deepAuditId: meta.deepAuditId } : {}),
jobId: job.id,
jobName: job.name,
diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.js
index c313391743..2984cc1dc6 100644
--- a/server/services/cosTaskGenerator.auditMode.test.js
+++ b/server/services/cosTaskGenerator.auditMode.test.js
@@ -490,3 +490,20 @@ describe('programmatic scheduled handlers expose no issues-only toggle', () => {
}
});
});
+
+
+describe('new extended Deep creation boundaries', () => {
+ it.each(['schedule', 'manual'])('stamps a new %s task without creating a certification identity', async lane => {
+ const { getTaskInterval } = await import('./taskSchedule.js');
+ promptTemplate.body = AUDIT_TEMPLATE;
+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: lane === 'schedule' ? { auditDepth: 'deep', fileIssues: false } : {} });
+ const task = await generate('security', lane === 'manual' ? { skipPreconditions: true, runOverrides: { auditDepth: 'deep', fileIssues: false } } : {});
+ expect(task.metadata).toMatchObject({ auditDepth: 'deep', auditWorkflow: 'extended-v1', fileIssues: false });
+ expect(task.metadata.deepAuditId).toBeUndefined();
+ });
+ it('stamps custom jobs but rejects historical checkpoint injection', async () => {
+ const job = { id: 'job-example', name: 'Audit', promptTemplate: 'Investigate and fix', appId: 'app-1', taskMetadata: { auditDepth: 'deep', fileIssues: false, useWorktree: true, openPR: true } };
+ expect((await generateTaskFromJob(job)).metadata).toMatchObject({ auditWorkflow: 'extended-v1', useWorktree: true, openPR: true });
+ await expect(generateTaskFromJob({ ...job, taskMetadata: { ...job.taskMetadata, deepAuditId: 'historical' } })).rejects.toThrow('read-only');
+ });
+});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index c044f39bf2..36c2e29387 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1,3 +1,4 @@
+import { newAuditMetadata } from '../lib/auditWorkflow.js';
import { auditQualityInstructions } from '../lib/auditQuality.js';
import { isPrivateSecurityTask, PRIVATE_SECURITY_DELIVERY } from '../lib/privateSecurityPolicy.js';
/**
@@ -1497,6 +1498,7 @@ export async function generateSelfImprovementTaskForType(taskType, state) {
const sanitizedMeta = sanitizeTaskMetadata(interval.taskMetadata);
if (sanitizedMeta) {
Object.assign(metadata, sanitizedMeta);
+ Object.assign(metadata, newAuditMetadata(metadata));
}
// Use configured model/provider if specified, otherwise use default
@@ -2537,6 +2539,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// pass, so an invocation can carry nothing a stored override could not.
const sanitizedRunMeta = sanitizeTaskMetadata(runOverrides);
if (sanitizedRunMeta) Object.assign(metadata, sanitizedRunMeta);
+ Object.assign(metadata, newAuditMetadata(metadata));
// Audit applicability bail-out — before preflights or a spawn slot. On the
// SCHEDULED lane, a quality audit this repository cannot have findings for (a
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index e799151e16..b54829af28 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -1,3 +1,4 @@
+import { auditWorkflow, newAuditMetadata, isLegacyDeepAudit } from '../lib/auditWorkflow.js';
import { isForgeMaintenanceTask, hasCurrentForgeMaintenanceEvidence, LEGACY_FORGE_MAINTENANCE_REASON } from '../lib/forgeMaintenanceTasks.js';
import { getSkipReason } from './cosTaskClaim.js';
/**
@@ -467,6 +468,7 @@ export async function getTaskById(taskId) {
* consumers, but the normal scheduler must not race that dispatch.
*/
export async function addTask(taskData, taskType = 'user', { raw = false, ignoreTaskId = null, now = Date.now(), suppressDequeue = false } = {}) {
+ if (!raw && taskData.metadata) taskData = { ...taskData, metadata: newAuditMetadata(taskData.metadata) };
return withStateLock(async () => {
const state = await loadState();
const filePath = taskType === 'user'
@@ -532,7 +534,8 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
t.id !== ignoreTaskId &&
(t.status === 'pending' || t.status === 'in_progress' || t.status === 'blocked') &&
firstLine(t.description).toLowerCase() === normalizedDesc &&
- (t.metadata?.app || null) === targetApp
+ (t.metadata?.app || null) === targetApp &&
+ auditWorkflow(t.metadata) === auditWorkflow(taskData.metadata)
);
if (duplicate) {
console.log(`⚠️ Duplicate task rejected: "${normalizedDesc.substring(0, 60)}" matches ${duplicate.id}${duplicate.status === 'blocked' ? ` (blocked: ${duplicate.metadata?.blockedCategory || 'unknown'})` : ''}`);
@@ -777,6 +780,7 @@ async function writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressD
return { statusChanged: true, task: current };
}
+ if (updates.status === 'pending' && isLegacyDeepAudit(current.metadata)) return { error: 'Historical Deep certification tasks are read-only; start a new Deep audit' };
if (updates.status === 'pending' && current.metadata?.auditDepth === 'deep' && isRetryHeld(current.metadata)) {
return { error: 'Deep checkpoint cleanup is still pending; resume after cleanup finishes' };
}
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index bc70064d40..98f7a65647 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -224,10 +224,10 @@ describe('cosTaskStore.firstLine', () => {
});
describe('cosTaskStore.updateTask expectedStatus', () => {
- it('keeps Deep checkpoints paused through cleanup, rejects stale cleanup, and resumes the retained branch explicitly', async () => {
+ it('keeps extended Deep retry cleanup owned and preserves its retained branch', async () => {
await addTask({ id: 'sys-deep-cleanup', description: 'Deep audit' }, 'internal');
await updateTask('sys-deep-cleanup', { status: 'in_progress', metadata: {
- auditDepth: 'deep', retryPendingCleanup: 'agent-current',
+ auditDepth: 'deep', auditWorkflow: 'extended-v1', retryPendingCleanup: 'agent-current',
existingBranch: 'cos/retained', resumedFromAgentId: 'agent-current', resumeWorktreePath: '/fixture/retained',
} }, 'internal');
expect(isReapableBlockedFailure(await getTaskById('sys-deep-cleanup'))).toBe(false);
@@ -2620,3 +2620,14 @@ describe('shared development work admission', () => {
expect((await addTask({ description: 'Claim 42', app: 'different', claimFlow: true, claimTarget: '42' }, 'user')).duplicate).not.toBe(true);
});
});
+
+
+it('creates a fresh extended task rather than reviving a parked historical checkpoint', async () => {
+ const legacy = await addTask({ id: 'sys-legacy-audit', description: 'Audit example', status: 'blocked', metadata: { app: 'example', auditDepth: 'deep', deepAuditId: 'historic', blockedCategory: 'deep-audit-partial', existingBranch: 'cos/preserved' } }, 'internal', { raw: true });
+ const fresh = await addTask({ id: 'sys-extended-audit', description: 'Audit example', metadata: { app: 'example', auditDepth: 'deep', auditWorkflow: 'extended-v1' } }, 'internal', { raw: true });
+ expect(fresh.duplicate).not.toBe(true);
+ expect(fresh.id).not.toBe(legacy.id);
+ expect((await getTaskById(legacy.id)).metadata).toMatchObject({ deepAuditId: 'historic', existingBranch: 'cos/preserved' });
+ expect(await reviveBlockedTask(legacy.id, {}, 'internal')).toMatchObject({ error: expect.stringContaining('read-only') });
+ expect((await getTaskById(legacy.id)).status).toBe('blocked');
+});
diff --git a/server/services/deepAudit.js b/server/services/deepAudit.js
index e3dd5d4d8a..c4b60bc852 100644
--- a/server/services/deepAudit.js
+++ b/server/services/deepAudit.js
@@ -1,3 +1,4 @@
+import { isLegacyDeepAudit } from '../lib/auditWorkflow.js';
/** Machine-local, DB-primary coverage evidence. No timers or provider calls. */
import { join, resolve } from 'path';
import { ensureSchema, query, withTransaction } from '../lib/db.js';
@@ -78,7 +79,7 @@ export async function getDeepAuditLedger(id) {
/** Read the server-owned pin before provisioning a replacement workspace. */
export async function getDeepAuditSourceRevision(task, deps = {}) {
- if (task.metadata?.auditDepth !== 'deep') return null;
+ if (!isLegacyDeepAudit(task.metadata)) return null;
const ledger = await (deps.readLedger || getDeepAuditLedger)(deepAuditId(task));
if (!ledger) return null;
const category = isAuditTaskType(resolveTaskHookType(task)) ? normalizeAuditTaskType(resolveTaskHookType(task)) : 'code-quality';
@@ -100,7 +101,7 @@ async function initializeDeepAuditSubmodules(workspacePath) {
/** 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 (!isLegacyDeepAudit(task.metadata)) 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 });
@@ -124,7 +125,7 @@ export async function prepareDeepAudit({ task, agentId, workspacePath }, deps =
/** 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;
+ if (!isLegacyDeepAudit(task.metadata)) 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');
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
index 0b4684727e..fd339b71b5 100644
--- a/server/services/maintenanceRun.js
+++ b/server/services/maintenanceRun.js
@@ -1,3 +1,4 @@
+import { isLegacyDeepAudit, EXTENDED_AUDIT_WORKFLOW } from '../lib/auditWorkflow.js';
/**
* Manual maintenance runs — the Schedule tab's "Run maintenance now".
*
@@ -209,7 +210,7 @@ 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, ...(auditDepth === 'deep' ? { auditDepth, deepAudits: {}, deepCheckpointTaskIds: [], deepCheckpointAgentIds: [] } : {}),
+ taskTypes, ...(auditDepth === 'deep' ? { auditDepth, auditWorkflow: EXTENDED_AUDIT_WORKFLOW } : {}),
status: MAINTENANCE_RUN_STATUS.RUNNING,
steps: buildMaintenanceSteps({ appId, idPrefix: id, ...pins, mode, prCompletion, claimBetweenAudits, claimHandler: effectiveClaimHandler, taskTypes, explicitCheck, auditDepth }),
completed: {},
@@ -285,6 +286,7 @@ function latestRunHandoff(run, handoffs) {
export async function resumeMaintenanceRun(id) {
const resumed = await perRun(id, async () => {
const run = await getMaintenanceRun(id);
+ if (run && isLegacyDeepAudit(run)) throw new ServerError('Historical Deep certification runs are read-only; start a new Deep audit', { status: 409, code: 'DEEP_AUDIT_HISTORICAL' });
if (!run || run.status === MAINTENANCE_RUN_STATUS.RUNNING) return { run, alreadyRunning: true };
if (!run.taskTypes) await assertNoRunningRun(run.appId);
console.log(`🧹 Maintenance run ${id} resumed`);
@@ -313,7 +315,7 @@ export async function resumeMaintenanceRun(id) {
export const evaluateMaintenanceRun = (id, { ignoreTaskId = null, completeStepId = null } = {}) => perRun(id, async () => {
if (completeStepId) {
const run = await getMaintenanceRun(id);
- if (run?.auditDepth === 'deep' && run.deepAudits?.[completeStepId]?.complete !== true) {
+ if (isLegacyDeepAudit(run) && 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 });
@@ -421,9 +423,7 @@ 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 (isLegacyDeepAudit(run)) return holdRun(id, run, 'Historical Deep certification run; no further dispatch. Evidence remains available.');
if (run.status !== MAINTENANCE_RUN_STATUS.RUNNING) return { skipped: run.status };
const outstanding = await holdForOutstandingWork(id, run, ignoreTaskId);
@@ -470,7 +470,7 @@ function onMaintenanceAgentCompleted(agent) {
return getMaintenanceRun(id)
.then(async (run) => {
if (!run) return { skipped: 'unknown run' };
- if (run.auditDepth === 'deep') {
+ if (isLegacyDeepAudit(run)) {
return perRun(id, async () => {
const current = await getMaintenanceRun(id);
const proof = agent.result?.deepAudit || agent.metadata?.deepAudit || { complete: false, reason: 'Deep checkpoint missing' };
diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.js
index 49f1cf84e3..6b4d3e3a37 100644
--- a/server/services/maintenanceRun.test.js
+++ b/server/services/maintenanceRun.test.js
@@ -99,12 +99,14 @@ it.each(['draft', 'inherit', undefined])('carries the browser delivery choice %s
});
const response = await sendFromBrowser({
appId: 'app-1', providerId: 'codex', model: 'gpt-6-astra', effort: 'medium', mode: 'fix',
- taskTypes: ['security'], ...(prCompletion ? { prCompletion } : {}),
+ taskTypes: ['security'], auditDepth: 'deep', ...(prCompletion ? { prCompletion } : {}),
});
expect(wireBody.prCompletion).toBe(prCompletion);
expect(response.status).toBe(201);
const run = await getMaintenanceRun(response.body.run.id);
const expectedPolicy = prCompletion === 'inherit' ? null : 'draft';
+ expect(run).toMatchObject({ auditDepth: 'deep', auditWorkflow: 'extended-v1' });
+ expect(state.invoked[0].step.overrides.params.auditWorkflow).toBe('extended-v1');
expect(run.prCompletion).toBe(expectedPolicy);
expect(run.steps[0].overrides.params.prCompletion).toBe(expectedPolicy || undefined);
expect(state.invoked[0].step.overrides.params.prCompletion).toBe(expectedPolicy || undefined);
@@ -458,33 +460,25 @@ it('preserves draft delivery across persisted resume, provider edits and step co
});
-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();
+it('extended Deep completes a useful run without exhaustive receipts and preserves provider and delivery pins', async () => {
+ const { run } = await startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-6-astra', effort: 'medium', mode: 'fix', prCompletion: 'draft', taskTypes: ['security'], auditDepth: 'deep' });
+ expect(run).toMatchObject({ auditDepth: 'deep', auditWorkflow: 'extended-v1' });
+ expect(run.deepAudits).toBeUndefined();
+ expect(state.invoked[0].step.overrides).toMatchObject({ model: 'gpt-6-astra', effort: 'medium', params: { auditWorkflow: 'extended-v1', fileIssues: false, useWorktree: true, prCompletion: 'draft' } });
+ await __onMaintenanceAgentCompleted(agentFor(run, 0, true));
+ expect(await getMaintenanceRun(run.id)).toMatchObject({ status: 'completed' });
expect(state.invoked).toHaveLength(1);
- state.tasks = [{ id: agent.taskId, status: 'in_progress', metadata: { auditDepth: 'deep', retryPendingCleanup: agent.id, quotaBurnMaintenanceRunId: run.id, quotaBurnStepId: run.steps[0].id } }];
- await resumeMaintenanceRun(run.id);
- expect(state.invoked).toHaveLength(1); // Explicit resume cannot outrun cleanup.
- state.tasks[0].status = 'blocked';
- state.tasks[0].metadata.blockedCategory = 'deep-audit-partial';
- delete state.tasks[0].metadata.retryPendingCleanup;
- await evaluateMaintenanceRun(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('retains historical incomplete evidence and refuses every legacy resume or scheduler dispatch', async () => {
+ const { writeFile, mkdir } = await import('fs/promises');
+ const legacy = { id: 'legacy', appId: 'app-1', status: 'stopped', auditDepth: 'deep', steps: [], completed: {}, deepAudits: { old: { complete: false, satisfiedPasses: 3, requiredPasses: 12 } } };
+ await mkdir(join(tempRoot, 'cos'), { recursive: true });
+ await writeFile(join(tempRoot, 'cos', 'maintenance-runs.json'), JSON.stringify({ runs: [legacy] }));
+ await expect(resumeMaintenanceRun('legacy')).rejects.toMatchObject({ code: 'DEEP_AUDIT_HISTORICAL' });
+ await evaluateMaintenanceRun('legacy');
+ expect(state.invoked).toHaveLength(0);
+ expect(await getMaintenanceRun('legacy')).toMatchObject({ status: 'stopped', deepAudits: legacy.deepAudits, completed: {} });
});
it('Deep successful delivery alone never certifies discovery and deep proof alone never certifies failed delivery', async () => {
diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.js
index 62e211c6bb..227de51ed2 100644
--- a/server/services/onDemandDrain.js
+++ b/server/services/onDemandDrain.js
@@ -1,3 +1,4 @@
+import { isLegacyDeepAudit } from '../lib/auditWorkflow.js';
/**
* On-demand request drain — the ONE loop body both Priority 0 engines run.
*
@@ -310,7 +311,7 @@ export async function drainOnDemandRequests(ctx, adapter) {
await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);
// Deep resumes need the persisted branch pointer and original audit text,
// not a freshly rendered snapshot of volatile issue/PR preload data.
- const revived = task.metadata.auditDepth === 'deep' ? stored : { ...task, id: persisted.id };
+ const revived = isLegacyDeepAudit(task.metadata) ? stored : { ...task, id: persisted.id };
emitSpawn(revived);
emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });
} else if (!claim || quotaBurnProvenance(persisted.metadata).requestId === request.id) {