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: distinguish audit execution assessment and delivery outcomes

Adam Eivy48d1aca1c785
diff --git a/client/src/components/cos/AgentResultLine.jsx b/client/src/components/cos/AgentResultLine.jsx
index 1b702e10cd..6b396d96f8 100644
--- a/client/src/components/cos/AgentResultLine.jsx
+++ b/client/src/components/cos/AgentResultLine.jsx
@@ -18,17 +18,29 @@ import { isAgentHandoff, agentHandoffReason } from '../../lib/agentOutcome';
export default function AgentResultLine({ agent, className = '' }) {
if (!agent?.result) return null;
const handoff = isAgentHandoff(agent);
- const tone = handoff ? 'text-port-accent' : agent.result.success ? 'text-port-success' : 'text-port-error';
+ const assessment = [agent.metadata?.auditAssessment, agent.result.auditAssessment]
+ .find(value => value?.status === 'recorded') || agent.metadata?.auditAssessment || agent.result.auditAssessment;
+ const assessmentUnverified = assessment && assessment.status !== 'recorded';
+ const validationFailed = agent.result.validationPassed === false;
+ const publication = agent.metadata?.publicationValidation;
+ const publicationIncomplete = ['running', 'blocked'].includes(publication?.status);
+ const incomplete = assessmentUnverified || validationFailed || publicationIncomplete;
+ const tone = handoff ? 'text-port-accent' : agent.result.success ? incomplete ? 'text-port-warning' : 'text-port-success' : 'text-port-error';
return (
- <div className={`text-sm flex items-center gap-2 ${tone} ${className}`.trim()}>
+ <div className={`text-sm ${tone} ${className}`.trim()}>
+ <div className="flex items-center gap-2">
{handoff ? (
<><RotateCcw size={14} aria-hidden="true" /> {agentHandoffReason(agent)}</>
) : agent.result.success ? (
- <><CheckCircle size={14} aria-hidden="true" /> Completed successfully</>
+ <><CheckCircle size={14} aria-hidden="true" /> {incomplete || assessment ? 'Execution completed' : 'Completed successfully'}</>
) : (
<><AlertCircle size={14} aria-hidden="true" /> {agent.result.error || 'Failed'}</>
)}
+ </div>
+ {!handoff && assessment && <div>{assessment.status === 'recorded' ? 'Assessment saved' : assessment.status === 'persistence-failed' ? 'Assessment could not be saved' : assessment.status === 'not-attempted' ? 'Assessment not attempted' : 'Assessment not verified as saved'}</div>}
+ {!handoff && validationFailed && <div>Delivery validation failed</div>}
+ {!handoff && publicationIncomplete && <div>{publication.status === 'running' ? 'Publication checks running' : 'Publication blocked; worktree preserved'}</div>}
</div>
);
}
diff --git a/client/src/components/cos/AgentResultLine.test.jsx b/client/src/components/cos/AgentResultLine.test.jsx
new file mode 100644
index 0000000000..1bebf2af56
--- /dev/null
+++ b/client/src/components/cos/AgentResultLine.test.jsx
@@ -0,0 +1,34 @@
+import { render, screen } from '@testing-library/react';
+import { expect, it } from 'vitest';
+import AgentResultLine from './AgentResultLine';
+
+it('separates clean execution, assessment persistence and delivery validation', () => {
+ const agent = { result: { success: true, validationPassed: false, auditAssessment: { status: 'persistence-failed' } } };
+ const view = render(<AgentResultLine agent={agent} />);
+ expect(screen.getByText('Execution completed')).toBeInTheDocument();
+ expect(screen.getByText('Assessment could not be saved')).toBeInTheDocument();
+ expect(screen.getByText('Delivery validation failed')).toBeInTheDocument();
+ expect(screen.queryByText('Completed successfully')).not.toBeInTheDocument();
+ view.rerender(<AgentResultLine agent={{ ...agent, metadata: { auditAssessment: { status: 'recorded' } } }} />);
+ expect(screen.getByText('Assessment saved')).toBeInTheDocument();
+ expect(screen.queryByText('Assessment could not be saved')).not.toBeInTheDocument();
+ expect(screen.getByText('Delivery validation failed')).toBeInTheDocument();
+ view.rerender(<AgentResultLine agent={{ result: { success: true, auditAssessment: { status: 'recorded' } }, metadata: { auditAssessment: { status: 'persistence-failed' } } }} />);
+ expect(screen.getByText('Assessment saved')).toBeInTheDocument();
+ expect(screen.queryByText('Assessment could not be saved')).not.toBeInTheDocument();
+});
+
+it('does not invent assessment or delivery validation for ordinary successful runs', () => {
+ render(<AgentResultLine agent={{ result: { success: true, validationPassed: null } }} />);
+ expect(screen.getByText('Completed successfully')).toBeInTheDocument();
+ expect(screen.queryByText('Assessment saved')).not.toBeInTheDocument();
+ expect(screen.queryByText('Delivery validation failed')).not.toBeInTheDocument();
+});
+
+
+it('does not present blocked publication as completed delivery', () => {
+ render(<AgentResultLine agent={{ result: { success: true, validationPassed: true }, metadata: { publicationValidation: { status: 'blocked', reason: 'pregate-nonzero' } } }} />);
+ expect(screen.getByText('Execution completed')).toBeInTheDocument();
+ expect(screen.getByText('Publication blocked; worktree preserved')).toBeInTheDocument();
+ expect(screen.queryByText('Completed successfully')).not.toBeInTheDocument();
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 19949d996b..dbebb54f75 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -599,7 +599,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `goalFidelityCalibration.js` | Goal-fidelity CALIBRATION contract — what happens when the follow-up investigation overturns a finding, i.e. the objective WAS delivered and the reviewer misjudged it. `GOAL_FIDELITY_CONTEXT_GAPS` is the closed vocabulary of what the reviewer could not see (`truncated-diff`, `truncated-objective`, `objective-omits-context`, `work-outside-diff`, `execution-step-misread`, `rubric-gap`, `other`), enforced ONLY by `normalizeGoalFidelityContextGap` (the report route takes a bounded string, so a near-miss gap name folds to `other` with its diagnosis intact instead of 400ing the report away). `GOAL_FIDELITY_REVIEW_SURFACES` addresses the reviewer's three context surfaces once — objective / diff / rubric — and `GOAL_FIDELITY_CONTEXT_GAP_FIXES` maps each gap onto one of them, so a rename cannot leave seven prose copies lying (`goalFidelityCalibration.pointers.test.js` walks the table against the real files). `goalFidelityCalibrationFingerprint(gap)` keys the dedup on the GAP alone, so many false positives from one blind spot fold into one fix instead of minting an agent each. `buildGoalFidelityCalibrationTask` composes the PortOS-side task body (including the do-not-disarm-the-detector contract) and `buildGoalFidelityFalsePositiveReportBlock` the `curl` instructions appended to a follow-up task, taking `apiBase` as an argument and the call shape from `agentApiToken.js`. I/O lives in `services/goalFidelityCalibration.js`. |
| `goalFidelityFollowUp.js` | Goal-fidelity FOLLOW-UP contract — what happens once the review HAS a finding, as opposed to what the finding is. `resolveGoalFidelityFollowUp(codeReview)` (`null` when neither action is configured; reads the RAW block, since a verdict already exists by the time this is asked), `normalizeGoalFidelityFollowUpTrigger` (shared with the settings projection so the form and the runtime cannot disagree), and `goalFidelityFollowUpApplies(review, trigger)` over `GOAL_FIDELITY_FOLLOW_UP_TRIGGERS` (`rethink` = only the verdict that holds a run, the default; `any-finding` also fires on the advisory `fix-first`). `goalFidelityFingerprint(task)` is the one dedup identity three parties share — the issue body marker (`goalFidelityIssueMarker` / `issueMatchesGoalFidelityMarker`), the tracker listing that reads it back, and the queued task fingerprint — keyed on taskType + app + objective slug so a perpetual task regenerating with a fresh id cannot re-file forever. Public issue markers hash that identity while matching legacy markers. `buildGoalFidelityIssue` requires a complete objective with verified tracker provenance and immutable diff references before publication; `buildGoalFidelityFollowUpTask` carries the finding issue snapshot and its resolution lifecycle. I/O and public-text scrubbing live in `services/goalFidelityFollowUp.js`. |
| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. Also `getNavPageForPath(pathname)` → `{ label, section, breadcrumb }` for the most specific command that owns a route (`null` for one nothing declares) — how user-facing copy NAMES a page it links to, instead of typing "Models → LLMs" beside the link and stranding it on the next move (#7414). `expandPageToken(text, runtime)` expands a `{page}` token in `text` using `getNavPageForPath(runtime?.manageUrl)`, falling back to generic prose rather than shipping a literal `{page}` (#7419). |
-| `noChangeCompletion.js` | `permitsNoChangeCompletion(task)` — the single predicate for "this run may finish successfully with an empty branch": the persisted `noChangeSuccess` marker AND (`autonomousJob` OR `isInvestigation`). Read by both the prompt builder and finalization so the agent is never told a contract finalize will not honour; whether the branch was really empty is the post-run `branchProvenEmpty` verdict. |
+| `noChangeCompletion.js` | `permitsNoChangeCompletion(task)` — the single predicate for "this run may finish successfully with an empty branch": the persisted `noChangeSuccess` marker AND (`autonomousJob` OR `isInvestigation` OR built-in quality audit). Read by both the prompt builder and finalization so the agent is never told a contract finalize will not honour; whether the branch was really empty is the post-run `branchProvenEmpty` verdict. |
| `noReplaceMove.js` | `moveWithoutReplace(from, to)` — publish a staged file into its final name WITHOUT ever clobbering an existing one. `fs.rename` silently replaces its destination, which is the wrong default for a derived artifact; this uses `link(2)` + `unlink(2)`, so an existing destination fails atomically with `MOVE_DEST_EXISTS` and both files survive. Refuses rather than degrading when the filesystem cannot express it (`MOVE_CROSS_DEVICE`, `MOVE_NO_REPLACE_UNSUPPORTED`) — a `stat`-then-`rename` fallback would be a race. Used by the rigging publication contract (`services/rigging/autoSkin.js`). |
| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. A pure leaf — `client/src/lib/personaTraitBlend.js` re-exports it for the Personas UI preview. |
| `textUtils.js` | Pure dependency-free prose helpers. `isStr(v)` and `isNonBlankStr(v)` are the ONLY string predicates under `server/` (#6837) — the bare type check, and type check plus a non-empty `trim()` for ids, keys, hosts, model names and prose fields where whitespace-only is already invalid; the "no private string predicate or bounder" guard in `textUtils.test.js` fails the suite when a copy of either, or a `trimTo`-shaped bounder, is re-declared in any non-test source under `server/` or any source under `client/src/` (`client/src/lib/textUtils.js` re-exports both for the browser bundle). `countWords(text)` is the canonical whitespace-token count (`\S+`) and the only one — every server word count (Writers Room, lettering density, rapid reader, autobiography, script-video beats) and the client's (`client/src/lib/textUtils.js` re-exports it) resolve here, and the "no private countWords" guard in `textUtils.test.js` fails the suite when a re-spelled count (the whitespace-token match, a split-and-filter, or a helper under either conventional name) reappears in any non-test source under `server/` or any source under `client/src/`; the editorial prose-analysis checks deliberately count LETTER words instead, through `editorial/proseTics.js#tokenizeWords`, which owns that tokenizer the same way; `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (the sibling guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — `client/src/lib/textUtils.js` re-exports this module for the browser bundle); `trimToClause(v, max)` is its boundary-aware twin for PROSE fields — it backs off to the last sentence terminator, then the last clause boundary, then the last whole word, so a capped field never ends mid-thought (it lives here rather than in `storyBible.js`, which re-exports it, so the pure story-model leaves the browser bundle shares can cap prose without pulling `crypto` / `fileUtils`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels), and `truncateOnBoundary(slug, max)` is its bounder — back off to the last `-` at or before `max` so a slug a human reads (a PLAN.md id, the app segment of a CoS worktree directory) is never cut mid-word, which `trimTo` would reintroduce; `clampToCharLimit(text, max)` is `trimTo`'s reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns `{ text, truncated }` so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). `firstLine(text)` is the first non-blank line, trimmed — the CoS task headline `addTask` dedupes on, declared here rather than in the task store so a closure-sensitive caller can reach it (`cosTaskStore.js` re-exports it). |
diff --git a/server/lib/noChangeCompletion.js b/server/lib/noChangeCompletion.js
index 50d83c0587..c8fa27ccec 100644
--- a/server/lib/noChangeCompletion.js
+++ b/server/lib/noChangeCompletion.js
@@ -2,17 +2,19 @@
* No-change completion contract.
*
* A task may complete successfully with an empty branch only when it opted in
- * (the persisted `noChangeSuccess` metadata marker) and is an autonomous job or
- * an investigation; whether the branch really was empty is `branchProvenEmpty`,
+ * (the persisted `noChangeSuccess` metadata marker) and is an autonomous job,
+ * investigation or built-in quality audit; whether the branch really was empty is `branchProvenEmpty`,
* decided after the run by the forge/branch check in agentFinalization.
*
* The prompt builder and finalization both read this one predicate, so the agent
* is only told a clean no-op exit is allowed where finalize will honour it.
*/
+import { isAuditTaskType } from './auditCatalog.js';
import { isTruthyMeta } from './metadataFlags.js';
export function permitsNoChangeCompletion(task) {
const meta = task?.metadata;
return isTruthyMeta(meta?.noChangeSuccess)
- && (isTruthyMeta(meta?.autonomousJob) || isTruthyMeta(meta?.isInvestigation));
+ && (isTruthyMeta(meta?.autonomousJob) || isTruthyMeta(meta?.isInvestigation)
+ || isAuditTaskType(meta?.analysisType || meta?.taskAnalysisType));
}
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 967ba9626d..7bcd2ea3c2 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -153,7 +153,10 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac
// no PR exists AND the branch was proven empty; the task marker narrows this
// exception to an explicitly opted-in autonomous job. Do not use the marker
// as a general no-commit exemption: a real change still needs the commit probe.
- if (success && branchProvenEmpty === true && permitsNoChangeCompletion(task)) return true;
+ if (success && branchProvenEmpty === true && permitsNoChangeCompletion(task)) {
+ // An empty audit branch is valid only when its actual report was saved.
+ return !isAuditTaskType(scheduledType) || hookResult?.auditAssessment?.status === 'recorded';
+ }
// A marked no-change audit needs a forge answer and an unambiguous empty-branch
// proof. If either check was inconclusive, leave learning undeclared rather than
// scoring a correct no-op as a commit miss. A non-empty branch remains a real
@@ -1005,6 +1008,10 @@ export function dispatchTaskOutputHookOnce({
if (existing) return existing;
const persistDispatchMarker = async (result) => {
+ 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 }));
+ }
if (!result.ran) return;
// Best-effort durability: completion must continue if the marker write
// fails, while the in-flight promise still protects concurrent callers
@@ -1018,6 +1025,13 @@ export function dispatchTaskOutputHookOnce({
const dispatch = (async () => {
const agent = await getAgent(agentId).catch(() => null);
+ // A saved assessment survives sentinel/worktree cleanup. Failed writes stay
+ // 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') {
+ return { ran: false, auditAssessment: savedAssessment };
+ }
if (agent?.metadata?.outputHookDispatchedAt) {
return { ran: false, alreadyDispatched: true };
}
@@ -1619,6 +1633,9 @@ export async function finalizeAgent({
await completeAgent(agentId, {
success: verdict.success,
validationPassed,
+ ...(isAuditTaskType(resolveTaskHookType(task)) ? {
+ auditAssessment: hookResult?.auditAssessment || { status: 'unverified' },
+ } : {}),
exitCode,
duration,
outputLength: outputBuffer?.length ?? 0,
@@ -1919,12 +1936,17 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, a
if (!taskType) return { ran: false };
if (isAuditTaskType(taskType)) {
const { recordAuditQuality } = await import('./appQuality.js');
- const recorded = await recordAuditQuality({ task, taskType, agentId, success, assessedAt,
+ const auditAssessment = await recordAuditQuality({ task, taskType, agentId, success, assessedAt,
workspacePath: hookPayloadDir({ task, workspacePath, recovery }) })
- .catch(err => emitLog('warn', `⚠️ Audit quality was not saved for ${agentId}: ${err.message}`, { agentId }));
+ .then(recorded => ({ status: recorded === true ? 'recorded' : success ? 'not-recorded' : 'not-attempted' }))
+ .catch(err => {
+ emitLog('warn', `⚠️ Audit quality was not saved for ${agentId}: ${err.message}`, { agentId });
+ return { status: 'persistence-failed' };
+ });
+ const recorded = auditAssessment.status === 'recorded';
if (recorded === true) await publishAppSnapshotFileAfterAudit(task?.metadata?.app);
// Assessment telemetry never waives commit/PR success criteria for fix mode.
- return { ran: false };
+ return { ran: false, auditAssessment };
}
const { getTaskOutputHook } = await import('./taskTypeHooks.js');
const hook = await getTaskOutputHook(taskType);
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index f544793908..240c49007a 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -1,3 +1,4 @@
+vi.mock('../lib/gitCommitProbe.js', () => ({ committedDuringRun: vi.fn(async () => false) }));
vi.mock('./appQuality.js', () => ({ recordAuditQuality: vi.fn(async () => true) }));
import { recordAuditQuality } from './appQuality.js';
// Hoisted doubles rather than static imports: the audit path reaches both modules
@@ -32,12 +33,13 @@ vi.mock('./taskTypeHooks.js', () => ({
getTaskOutputHook: vi.fn(),
getTaskOutputPayloadPredicate: vi.fn(async () => null),
declaresNoCommitCriterion: vi.fn(() => false),
+ isClaimFlowDispatch: vi.fn(() => false),
isProgrammaticIoTaskType: vi.fn(() => true),
resolveTaskHookType: vi.fn(task => task?.metadata?.analysisType || null),
}));
import { getAgent, updateAgent, completeAgent } from './cosAgentLifecycle.js';
-import { canRunTaskOutputHookWithoutPayload, getTaskOutputHook } from './taskTypeHooks.js';
+import { canRunTaskOutputHookWithoutPayload, getTaskOutputHook, isProgrammaticIoTaskType } from './taskTypeHooks.js';
import {
finalizeAgent,
dispatchRecoveredTaskOutputHook,
@@ -115,10 +117,10 @@ describe('recovery output-hook dispatch (#3182)', () => {
it('captures audit telemetry on the shared completion path without waiving fix-mode delivery criteria', async () => {
const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'better-complexity' } };
await expect(dispatchTaskOutputHookOnce({ agentId: 'agent-audit', task, success: true, workspacePath: '/worktree' }))
- .resolves.toEqual({ ran: false });
+ .resolves.toEqual({ ran: false, auditAssessment: { status: 'recorded' } });
expect(recordAuditQuality).toHaveBeenCalledWith({ task, taskType: 'better-complexity', agentId: 'agent-audit', success: true, workspacePath: '/worktree', assessedAt: persistedAgent.startedAt });
expect(hook).not.toHaveBeenCalled();
- expect(updateAgent).not.toHaveBeenCalled();
+ expect(updateAgent).toHaveBeenCalledWith('agent-audit', { metadata: { auditAssessment: { status: 'recorded' } } });
});
// Landing the app's `.quality.json` PR is opt-in and runs outside the request
@@ -127,11 +129,11 @@ describe('recovery output-hook dispatch (#3182)', () => {
it('commits a repo snapshot only for an opted-in app that just recorded a measurement', async () => {
const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'better-complexity' } };
let run = 0;
- const dispatch = () => dispatchTaskOutputHookOnce({ agentId: `agent-snapshot-${run += 1}`, task, success: true, workspacePath: '/worktree' });
+ const dispatch = () => { persistedAgent.metadata = {}; return dispatchTaskOutputHookOnce({ agentId: `agent-snapshot-${run += 1}`, task, success: true, workspacePath: '/worktree' }); };
const optedIn = { id: 'app-example', repoPath: '/repo/example-app', publishQualitySnapshot: true };
appsRegistry.getAppById.mockResolvedValue(optedIn);
- await expect(dispatch()).resolves.toEqual({ ran: false });
+ await expect(dispatch()).resolves.toEqual({ ran: false, auditAssessment: { status: 'recorded' } });
expect(snapshotFile.publishAppQualitySnapshot).toHaveBeenCalledWith(optedIn);
for (const app of [{ ...optedIn, publishQualitySnapshot: false }, { ...optedIn, publishQualitySnapshot: 'true' },
@@ -150,14 +152,59 @@ describe('recovery output-hook dispatch (#3182)', () => {
// A locked index or an unreadable registry must not fail the completion.
snapshotFile.publishAppQualitySnapshot.mockRejectedValueOnce(new Error('index.lock exists'));
- await expect(dispatch()).resolves.toEqual({ ran: false });
+ await expect(dispatch()).resolves.toEqual({ ran: false, auditAssessment: { status: 'recorded' } });
appsRegistry.getAppById.mockRejectedValueOnce(new Error('registry unreadable'));
- await expect(dispatch()).resolves.toEqual({ ran: false });
+ await expect(dispatch()).resolves.toEqual({ ran: false, auditAssessment: { status: 'recorded' } });
for (const reason of ['index.lock exists', 'registry unreadable']) {
expect(emitLog).toHaveBeenCalledWith('error', `❌ Quality snapshot publish failed for app app-example: ${reason}`, { appId: 'app-example' });
}
});
+ it('records assessment failure independently and allows recovery to persist it later', async () => {
+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security' } };
+ recordAuditQuality.mockRejectedValueOnce(new Error('storage unavailable'));
+ const first = await dispatchTaskOutputHookOnce({ agentId: 'audit-recovery', task, success: true, workspacePath: '/worktree' });
+ expect(first).toEqual({ ran: false, auditAssessment: { status: 'persistence-failed' } });
+ expect(persistedAgent.metadata.auditAssessment.status).toBe('persistence-failed');
+ await expect(dispatchRecoveredTaskOutputHook({ agentId: 'audit-recovery', task, success: true, workspacePath: '/worktree' }))
+ .resolves.toEqual({ ran: false, auditAssessment: { status: 'recorded' } });
+ expect(persistedAgent.metadata.auditAssessment.status).toBe('recorded');
+ recordAuditQuality.mockClear();
+ await dispatchRecoveredTaskOutputHook({ agentId: 'audit-recovery', task, success: true });
+ expect(recordAuditQuality).not.toHaveBeenCalled();
+ });
+
+ it('retains a saved result when an older failure marker survived a metadata write error', async () => {
+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security' } };
+ persistedAgent.metadata.auditAssessment = { status: 'persistence-failed' };
+ persistedAgent.result = { auditAssessment: { status: 'recorded' } };
+ await expect(dispatchRecoveredTaskOutputHook({ agentId: 'saved-result', task, success: true }))
+ .resolves.toEqual({ ran: false, auditAssessment: { status: 'recorded' } });
+ expect(recordAuditQuality).not.toHaveBeenCalled();
+ });
+
+ it('persists assessment and delivery verdicts without rewriting a clean execution', async () => {
+ isProgrammaticIoTaskType.mockImplementation(type => type !== 'security');
+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security' } };
+ recordAuditQuality.mockResolvedValueOnce(false);
+ await finalizeAgent({ agentId: 'audit-final', task, success: true, exitCode: 0, duration: 1000,
+ workspacePath: '/missing-audit-worktree', startedAt: Date.now() - 1000, outputBuffer: 'Audit complete' });
+ expect(completeAgent).toHaveBeenCalledWith('audit-final', expect.objectContaining({
+ success: true, validationPassed: false, auditAssessment: { status: 'not-recorded' },
+ }));
+ isProgrammaticIoTaskType.mockReturnValue(true);
+ });
+
+ 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);
+ await expect(dispatchTaskOutputHookOnce({ agentId: 'audit-no-report', task, success: true, workspacePath: '/worktree' }))
+ .resolves.toEqual({ ran: false, auditAssessment: { status: 'not-recorded' } });
+ await expect(dispatchTaskOutputHookOnce({ agentId: 'audit-execution-failed', task, success: false, workspacePath: '/worktree' }))
+ .resolves.toEqual({ ran: false, auditAssessment: { status: 'not-attempted' } });
+ recordAuditQuality.mockResolvedValue(true);
+ });
+
it.each([
['orphan cleanup', false],
['post-restart completion', true],
diff --git a/server/services/agentFinalization.successCriteria.test.js b/server/services/agentFinalization.successCriteria.test.js
index 9f29236f54..f0ba8726e7 100644
--- a/server/services/agentFinalization.successCriteria.test.js
+++ b/server/services/agentFinalization.successCriteria.test.js
@@ -577,3 +577,14 @@ describe('evaluateSuccessCriteria — claim-flow exemption', () => {
expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);
});
});
+
+
+describe('no-change quality audit delivery', () => {
+ it('requires both verified empty branch and saved assessment, without waiving changed-branch commit checks', async () => {
+ const args = { task: { id: 'audit', taskType: 'internal', metadata: { analysisType: 'security', noChangeSuccess: true } }, workspacePath: '/worktree', startedAt: 1000, success: true };
+ expect(await evaluateSuccessCriteria({ ...args, branchProvenEmpty: true, hookResult: { auditAssessment: { status: 'recorded' } } })).toBe(true);
+ expect(await evaluateSuccessCriteria({ ...args, branchProvenEmpty: true, hookResult: { auditAssessment: { status: 'not-recorded' } } })).toBe(false);
+ committedDuringRun.mockResolvedValue(false);
+ expect(await evaluateSuccessCriteria({ ...args, branchProvenEmpty: false, hookResult: { auditAssessment: { status: 'recorded' } } })).toBe(false);
+ });
+});
diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.js
index c11e933de7..4dd62144b2 100644
--- a/server/services/cosTaskGenerator.auditMode.test.js
+++ b/server/services/cosTaskGenerator.auditMode.test.js
@@ -382,6 +382,13 @@ describe('mode is honored identically from schedule, manual run, and quota burn'
expect(prompt).not.toContain('PortOS will merge it back after completion');
});
+ it('allows a verified no-change completion only in fix mode', async () => {
+ const fix = await generate('security', { skipPreconditions: true, runOverrides: { fileIssues: false } });
+ expect(fix.metadata.noChangeSuccess).toBe(true);
+ const filing = await generate('security', { skipPreconditions: true, runOverrides: { fileIssues: true } });
+ expect(filing.metadata.noChangeSuccess).not.toBe(true);
+ });
+
it('run overrides pass the same allowlist a stored override does', async () => {
const { getTaskInterval } = await import('./taskSchedule.js');
getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues: true } });
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 0760b1cae6..ee4e6d85e2 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -2638,6 +2638,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// Tracker-filing types (reference-watch, or an audit type with fileIssues):
// the {trackerInstructions} block for the app's resolved work tracker.
const fileIssues = isFileIssuesMode(taskType, metadata);
+ if (isAuditTaskType(taskType)) metadata.noChangeSuccess = !fileIssues;
const trackerFiling = await resolveTrackerFilingBlock(app, taskType, { fileIssues });
if (trackerFiling.workTracker) {
// Traceability + deliverable posture, derived from the SAME resolved tracker