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: skip the task-learning write when a run was never evaluated (#4107)

[._.]/ Adam Eivyb0057ef31c86
diff --git a/server/lib/README.md b/server/lib/README.md
index 73a06287f0..970a75974b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -281,6 +281,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
+| `learningVerdict.js` | The three-way success-criteria verdict a completed agent run carries on `result.validationPassed` (#4107). `true`/`false` = a declared criterion was met/missed; `null` = none declared (record the run, fall back to the exit code); `SKIP_LEARNING_VERDICT` = nothing ever evaluated the run, so task-learning must not record it at all (a programmatic-I/O output hook that bailed on `no-app`/`app-not-found`). `isSkipLearningVerdict(v)` gates the skip; `toValidationVerdict(v)` narrows anything non-boolean — including the sentinel — back to `null` for downstream telemetry. JSON-safe string (not a Symbol) because the verdict is persisted and read back by the learning backfill, and older readers already narrow on `typeof v === 'boolean'`. Pure. |
| `investigationTasks.js` | Investigation-task identity, the approval policy, and the auto-retry decision — shared by the producers (`services/investigationTaskProducer.js`), the reaper (`cosTaskStore.js`, which used to hand-copy the predicate to dodge an import cycle) and the retry (`services/investigationRetry.js`). `isInvestigationTask(task)` (durable `isInvestigation` marker, falling back to the `INVESTIGATION_HEADLINE_PREFIX` headline for pre-#2615 / peer-synced tasks); `buildInvestigationFingerprint(task, analysis)` / `investigationFingerprint({category, kind, scope})` → the `category:kind:scope` dedup key; `resolveInvestigationApproval({fingerprint, tasks, recentCreations})` → unattended by default (#3714), held only on a `repeat-fingerprint` or `failure-storm` loop, with `approvalReason` + `loopProse` for the queue UI; `couldReleaseBlockedTasks(investigation)` is the pure pre-read gate for `resolveInvestigationRetryTargets({investigation, tasksById})`, which returns the failure-blocked tasks a just-completed investigation releases plus every skip and its `RETRY_SKIP_REASONS` reason (an `auto-expired` completion, a non-`blocked` task, a `NON_AUTO_RETRY_BLOCK_CATEGORIES` block, or a task past `MAX_AUTO_RETRIES_PER_TASK`); `autoRetryMetadata(task, investigationId, now)` stamps the budget that survives the revive's own `failureCount` reset. Pure. |
| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
| `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 489ef4d69a..464de06947 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -261,6 +261,7 @@ export * from './localModelHeuristics.js';
export * from './loraDataset.js';
export * from './issueLength.js';
export * from './investigationTasks.js';
+export * from './learningVerdict.js';
export * from './mediaItemKey.js';
export * from './migrationMarker.js';
export * from './modelPricing.js';
diff --git a/server/lib/learningVerdict.js b/server/lib/learningVerdict.js
new file mode 100644
index 0000000000..0785479184
--- /dev/null
+++ b/server/lib/learningVerdict.js
@@ -0,0 +1,60 @@
+/**
+ * Learning verdict sentinels (issue #4107)
+ *
+ * The success-criteria verdict a completed agent run carries on
+ * `result.validationPassed` has THREE distinct meanings, and the repo's
+ * sentinel rule ("never let absent/failed collapse into valid") applies to all
+ * of them:
+ *
+ * - `true` / `false` — a machine-checkable criterion was DECLARED and was met
+ * / missed (#2344). Task-learning records the run and lets this verdict
+ * override the runner's exit code.
+ * - `null` — NO criterion was declared for this task shape (interactive/user
+ * tasks, pipeline + media jobs, coordinator types that never commit).
+ * Task-learning records the run and falls back to the exit code.
+ * - `SKIP_LEARNING_VERDICT` — nothing evaluated the run AND it must not be
+ * recorded at all. Neither of the two answers above is honest here: `false`
+ * would blame the model for something it did not do (and poison the #2329
+ * failure-signature window with a non-failure), while `null` would bank the
+ * exit code as a free success for the task type. Emitted when a
+ * programmatic-I/O output hook bails BEFORE it ever looks at the agent's
+ * output — e.g. the task's app was deleted mid-run (`no-app` /
+ * `app-not-found`); see `resolveProgrammaticIoVerdict` in
+ * `services/agentFinalization.js`.
+ *
+ * A JSON-safe STRING rather than a Symbol, because the verdict is persisted
+ * onto the agent record and read back later by the learning backfill. Every
+ * pre-existing consumer already narrows with `typeof v === 'boolean'`, so an
+ * install running older code degrades the sentinel to `null` — i.e. to exactly
+ * the pre-#4107 behavior — instead of misreading it as a failure. That keeps a
+ * record written by a newer peer safe for an older reader.
+ *
+ * Pure and dependency-free so both the finalize path
+ * (`services/agentFinalization.js`) and the learning writer
+ * (`services/taskLearning/metrics.js`) can import it without touching the agent
+ * module import cycle those two sit on either side of.
+ */
+
+/** The "nothing evaluated this run — do not record it" verdict. */
+export const SKIP_LEARNING_VERDICT = 'skip-learning';
+
+/**
+ * True iff `verdict` is the skip sentinel. Strict equality on purpose: an
+ * unrecognized string (a future sentinel from a newer peer) is NOT a skip, so it
+ * falls through to `toValidationVerdict`'s `null` and gets the recorded,
+ * exit-code-fallback treatment rather than silently vanishing from the metrics.
+ */
+export function isSkipLearningVerdict(verdict) {
+ return verdict === SKIP_LEARNING_VERDICT;
+}
+
+/**
+ * Narrow a raw persisted verdict to the two-value validation contract
+ * (`true` / `false` / `null`) every downstream telemetry consumer expects.
+ * Anything that is not an explicit boolean — absent, malformed, or the skip
+ * sentinel — becomes `null`, so "not evaluated" can never masquerade as
+ * "declared and missed".
+ */
+export function toValidationVerdict(verdict) {
+ return typeof verdict === 'boolean' ? verdict : null;
+}
diff --git a/server/lib/learningVerdict.test.js b/server/lib/learningVerdict.test.js
new file mode 100644
index 0000000000..876a153d83
--- /dev/null
+++ b/server/lib/learningVerdict.test.js
@@ -0,0 +1,67 @@
+import { describe, it, expect } from 'vitest';
+import { SKIP_LEARNING_VERDICT, isSkipLearningVerdict, toValidationVerdict } from './learningVerdict.js';
+
+// The whole point of this module is that FOUR verdicts stay four verdicts
+// (#4107). These tests pin the sentinel's identity and the two narrowings that
+// keep it from leaking into consumers that only understand three.
+
+describe('SKIP_LEARNING_VERDICT', () => {
+ it('is a JSON-safe string that survives a persist/read round-trip', () => {
+ // Not a Symbol: the verdict is written onto the agent record and read back by
+ // the learning backfill, so it must survive JSON.
+ expect(typeof SKIP_LEARNING_VERDICT).toBe('string');
+ const roundTripped = JSON.parse(JSON.stringify({ validationPassed: SKIP_LEARNING_VERDICT }));
+ expect(isSkipLearningVerdict(roundTripped.validationPassed)).toBe(true);
+ });
+
+ it('is distinct from every value the pre-#4107 contract could produce', () => {
+ for (const other of [true, false, null, undefined, 0, '', 'true', 'false', 'skip']) {
+ expect(SKIP_LEARNING_VERDICT).not.toBe(other);
+ }
+ });
+});
+
+describe('isSkipLearningVerdict', () => {
+ it('recognizes only the exact sentinel', () => {
+ expect(isSkipLearningVerdict(SKIP_LEARNING_VERDICT)).toBe(true);
+ });
+
+ it('rejects the three verdicts that DO get recorded', () => {
+ // The regression this guards: collapsing "undeclared" or "criterion missed"
+ // into the skip path would silently stop recording ordinary runs.
+ expect(isSkipLearningVerdict(true)).toBe(false);
+ expect(isSkipLearningVerdict(false)).toBe(false);
+ expect(isSkipLearningVerdict(null)).toBe(false);
+ expect(isSkipLearningVerdict(undefined)).toBe(false);
+ });
+
+ it('rejects near-miss and truthy-but-unrecognized values', () => {
+ // An unknown string (a future sentinel written by a newer peer) must NOT be
+ // treated as a skip — it falls through to the recorded, exit-code-fallback
+ // path rather than silently vanishing from the metrics.
+ for (const other of ['skip', 'skip-learning ', 'SKIP-LEARNING', 'future-sentinel', 1, {}]) {
+ expect(isSkipLearningVerdict(other)).toBe(false);
+ }
+ });
+});
+
+describe('toValidationVerdict', () => {
+ it('passes explicit booleans through unchanged', () => {
+ expect(toValidationVerdict(true)).toBe(true);
+ expect(toValidationVerdict(false)).toBe(false);
+ });
+
+ it('narrows the skip sentinel to null rather than leaking a string downstream', () => {
+ // Consumers of `validationPassed` (failure signatures, LI execution verdicts)
+ // understand three values. The sentinel must never reach them as a string.
+ expect(toValidationVerdict(SKIP_LEARNING_VERDICT)).toBeNull();
+ });
+
+ it('narrows absent/malformed values to null, never to false', () => {
+ // "Not evaluated" masquerading as "declared and missed" is the exact
+ // conflation the repo sentinel rule forbids.
+ for (const absent of [undefined, null, '', 0, 'yes', {}, []]) {
+ expect(toValidationVerdict(absent)).toBeNull();
+ }
+ });
+});
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 318bb944b7..8ae8f943b5 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -34,6 +34,7 @@ import { completeExecution, errorExecution } from './toolStateMachine.js';
import { resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';
import { completeAgentRun } from './agentRunTracking.js';
import { committedDuringRun } from '../lib/gitCommitProbe.js';
+import { SKIP_LEARNING_VERDICT } from '../lib/learningVerdict.js';
import { detectPrimaryCheckoutDrift, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';
import { canRunTaskOutputHookWithoutPayload, getTaskOutputPayloadPredicate, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion } from './taskTypeHooks.js';
import { processAgentCompletion } from './agentCompletion.js';
@@ -92,6 +93,13 @@ export function releaseAgentLane({ agentId, success, duration, exitCode, executi
* those task types can be judged by their real deliverable; `success` is the
* runner's exit-code verdict that hook result is weighed against. Both are
* absent/null for every other task shape.
+ *
+ * That branch is also the only one that can return `SKIP_LEARNING_VERDICT` — the
+ * third answer, meaning "nothing evaluated this run, so don't record it at all"
+ * (#4107). It rides `result.validationPassed` like the boolean/null verdicts and
+ * is consumed by `buildTaskTelemetryContext`; see `lib/learningVerdict.js`.
+ *
+ * @returns {Promise<boolean|null|'skip-learning'>}
*/
export async function evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, startedAt = null, success = false, hookResult = null }) {
if (terminatedByUser) return null;
@@ -167,15 +175,20 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac
* verdict and the ledger can never drift apart on what counts as a bad run, and a
* new benign reason only has to be taught to one function.
*
- * Sentinel discipline throughout — three distinct answers, never collapsed:
+ * Sentinel discipline throughout — FOUR distinct answers, never collapsed:
* - `false` — the hook ran and REJECTED the output (threw, or `unparseable-response`).
* - `null` — NOTHING evaluated the output (no hook ran, it timed out, or it
* returned no structured outcome), so no criterion was declared and
* task-learning falls back to the exit code exactly as before. "Not evaluated"
* must never become "accepted".
* - `true` — the hook ran and accepted the output.
+ * - `SKIP_LEARNING_VERDICT` — the hook aborted BEFORE it could look at the
+ * output at all (`no-app` / `app-not-found`), so there is nothing to learn
+ * from and the run must not be recorded (#4107). Distinct from `null`,
+ * which still records the run against its exit code.
*
- * @returns {boolean|null} true = accepted, false = rejected, null = undeclared
+ * @returns {boolean|null|'skip-learning'} true = accepted, false = rejected,
+ * null = undeclared, SKIP_LEARNING_VERDICT = do not record this run
*/
export function resolveProgrammaticIoVerdict({ success, hookResult }) {
if (!hookResult?.ran) return null;
@@ -189,10 +202,14 @@ export function resolveProgrammaticIoVerdict({ success, hookResult }) {
// output, so declare no verdict rather than defaulting to "accepted".
if (!hookResult.outcome || typeof hookResult.outcome !== 'object') return null;
// Ran, but bailed out BEFORE it ever looked at the output (its app was deleted
- // mid-run, or the task carries no app). Nothing evaluated the agent's work — and
- // these paths don't even record a run — so this is "undeclared", not a free
- // success for the type.
- if (HOOK_ABORTED_BEFORE_EVALUATION.has(hookResult.outcome.reason)) return null;
+ // mid-run, or the task carries no app). Nothing evaluated the agent's work and
+ // the hook itself recorded nothing, so there is no honest verdict to bank:
+ // `false` would blame the model for a user deleting an app mid-run (and poison
+ // the #2329 failure-signature window with a non-failure), and the `null`
+ // sentinel this used to return still recorded the run against its EXIT CODE —
+ // an exit-0 run banked a free success for the task type (#4107). Skip the
+ // learning write entirely instead.
+ if (HOOK_ABORTED_BEFORE_EVALUATION.has(hookResult.outcome.reason)) return SKIP_LEARNING_VERDICT;
return resolveTypeFailureSignal({ success, hookResult }).record === 'success';
}
diff --git a/server/services/agentFinalization.successCriteria.test.js b/server/services/agentFinalization.successCriteria.test.js
index 5610410946..b78ab0bf75 100644
--- a/server/services/agentFinalization.successCriteria.test.js
+++ b/server/services/agentFinalization.successCriteria.test.js
@@ -19,6 +19,7 @@ vi.mock('../lib/gitCommitProbe.js', () => ({
import { evaluateSuccessCriteria, resolveProgrammaticIoVerdict, withOutputHookTimeout } from './agentFinalization.js';
import { committedDuringRun } from '../lib/gitCommitProbe.js';
+import { SKIP_LEARNING_VERDICT } from '../lib/learningVerdict.js';
// The run window every commit-criterion assertion below is evaluated against
// (#3637). A criterion-declaring call MUST pass one — without a window there is
@@ -213,6 +214,8 @@ describe('evaluateSuccessCriteria — programmatic-I/O criterion (#2727)', () =>
* pinned without routing every case through evaluateSuccessCriteria.
*/
describe('resolveProgrammaticIoVerdict (#2727)', () => {
+ beforeEach(() => vi.clearAllMocks());
+
it('rejects a run whose hook threw, and one whose output was unparseable', () => {
expect(resolveProgrammaticIoVerdict({ success: true, hookResult: { ran: true, threw: true } })).toBe(false);
expect(resolveProgrammaticIoVerdict({
@@ -258,17 +261,43 @@ describe('resolveProgrammaticIoVerdict (#2727)', () => {
}
});
- it('declares no verdict when the hook aborted before it could look at the output', () => {
+ it('asks task-learning to SKIP a run whose hook aborted before it could look at the output (#4107)', () => {
// `no-app` / `app-not-found` return before the payload is validated (and before
- // the hook records anything). Nothing evaluated the agent's output, so this is
- // the undeclared sentinel — NOT a success, which would bank a free win for the
- // type every time an app is deleted mid-run.
+ // the hook records anything). Nothing evaluated the agent's output, so neither
+ // recordable answer is honest: `false` blames the model for a user deleting an
+ // app mid-run, and the undeclared `null` this used to return still recorded the
+ // run against its EXIT CODE — banking a free win for the type on every exit-0.
for (const reason of ['no-app', 'app-not-found']) {
- expect(resolveProgrammaticIoVerdict({
+ const verdict = resolveProgrammaticIoVerdict({
success: true, hookResult: { ran: true, outcome: { action: 'no-op', reason } }
- })).toBeNull();
+ });
+ expect(verdict).toBe(SKIP_LEARNING_VERDICT);
+ // Explicitly NOT collapsed into any of the three recordable verdicts.
+ expect(verdict).not.toBeNull();
+ expect(typeof verdict).not.toBe('boolean');
}
});
+
+ it('still skips the run when the exit code says it FAILED', () => {
+ // The skip is about "nothing evaluated this run", not about the exit code —
+ // an aborted hook has no verdict either way, so a non-zero exit must not be
+ // banked as a failure for the type either.
+ expect(resolveProgrammaticIoVerdict({
+ success: false, hookResult: { ran: true, outcome: { action: 'no-op', reason: 'no-app' } }
+ })).toBe(SKIP_LEARNING_VERDICT);
+ });
+
+ it('propagates the skip verdict out through evaluateSuccessCriteria', async () => {
+ // finalizeAgent stamps whatever this returns onto `result.validationPassed`,
+ // which is the only channel the learning writer reads — so the sentinel has to
+ // survive the wrapper, not just the pure criterion.
+ const task = { id: 't10', taskType: 'layered-intelligence' };
+ expect(await evaluateSuccessCriteria({
+ task, workspacePath: '/w', success: true,
+ hookResult: { ran: true, outcome: { action: 'no-op', reason: 'app-not-found' } }
+ })).toBe(SKIP_LEARNING_VERDICT);
+ expect(committedDuringRun).not.toHaveBeenCalled();
+ });
});
/**
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index 0c9cf09b3a..99e35139da 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -35,6 +35,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
import { readFile } from 'fs/promises';
import { atomicWrite } from '../lib/fileUtils.js';
+import { SKIP_LEARNING_VERDICT } from '../lib/learningVerdict.js';
import { resetTaskTypeLearning, getSkippedTaskTypes, recordTaskCompletion, getRoutingAccuracy, suggestModelTier, recalculateModelTierMetrics, clearLearningCache, getTaskTypeConfidence, getConfidenceLevels, dismissRecommendation, restoreRecommendation, getDismissedRecommendations, clearDismissedRecommendations, getLearningInsights } from './taskLearning.js';
const makeLearningData = (overrides = {}) => ({
@@ -509,6 +510,85 @@ describe('TaskLearning - recordTaskCompletion routing accuracy', () => {
});
});
+/**
+ * The "don't record this run" channel (#4107). A programmatic-I/O output hook
+ * that aborted BEFORE evaluating the agent's output (`no-app` / `app-not-found`,
+ * e.g. the app was deleted mid-run) stamps SKIP_LEARNING_VERDICT rather than the
+ * undeclared `null` — which used to fall back to the exit code and bank a free
+ * success for the task type.
+ */
+describe('TaskLearning - skip-recording verdict (#4107)', () => {
+ let savedData;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ clearLearningCache();
+ savedData = null;
+ atomicWrite.mockImplementation(async (_path, data) => {
+ savedData = data;
+ });
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+ });
+
+ const skipAgent = () => ({
+ metadata: { modelTier: 'heavy', taskDescription: 'Study the app' },
+ result: { success: true, validationPassed: SKIP_LEARNING_VERDICT, duration: 60000 }
+ });
+ const task = { description: 'Study the app', taskType: 'internal', metadata: {} };
+
+ it('writes NOTHING at all for a skipped run', async () => {
+ const returned = await recordTaskCompletion(skipAgent(), task);
+
+ // The whole point: no persist, so no aggregate, window, or total moves.
+ expect(atomicWrite).not.toHaveBeenCalled();
+ expect(savedData).toBeNull();
+ expect(returned).toBeNull();
+ });
+
+ it('does not bank the exit code as a success for the task type', async () => {
+ // The exact overcount #4107 fixes: exit 0 + a hook that never looked at the
+ // output used to come out the other side as a recorded success.
+ await recordTaskCompletion(skipAgent(), task);
+ expect(savedData).toBeNull();
+
+ // ...while an otherwise-identical run with the UNDECLARED sentinel still
+ // records, so the skip can't have swallowed the ordinary null path.
+ const undeclared = { ...skipAgent(), result: { success: true, validationPassed: null, duration: 60000 } };
+ await recordTaskCompletion(undeclared, task);
+ expect(atomicWrite).toHaveBeenCalledTimes(1);
+ expect(savedData.byTaskType['internal-task'].succeeded).toBe(1);
+ expect(savedData.byTaskType['internal-task'].failed).toBe(0);
+ });
+
+ it('does not blame the model either — a failing exit is skipped the same way', async () => {
+ // `false` would have poisoned the #2329 failure-signature window with a
+ // non-failure, so an aborted hook must not record a failure either.
+ const failed = {
+ ...skipAgent(),
+ result: {
+ success: false,
+ validationPassed: SKIP_LEARNING_VERDICT,
+ duration: 60000,
+ errorAnalysis: { category: 'unknown', message: 'boom', origin: 'output-scan' }
+ }
+ };
+ await recordTaskCompletion(failed, task);
+
+ expect(atomicWrite).not.toHaveBeenCalled();
+ expect(savedData).toBeNull();
+ });
+
+ it('still records a genuine criterion MISS as a failure (#2344 unchanged)', async () => {
+ const missed = { ...skipAgent(), result: { success: true, validationPassed: false, duration: 60000 } };
+ await recordTaskCompletion(missed, task);
+
+ expect(atomicWrite).toHaveBeenCalledTimes(1);
+ expect(savedData.byTaskType['internal-task'].succeeded).toBe(0);
+ expect(savedData.byTaskType['internal-task'].failed).toBe(1);
+ expect(savedData.byModelTier['heavy'].failed).toBe(1);
+ });
+});
+
describe('TaskLearning - environmental failures (#2618)', () => {
let savedData;
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index f7428ececc..c15af3c0ec 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -29,6 +29,7 @@ import {
} from './store.js';
import { deriveFailureSignalAvoidance, isNonRoutableLearnedTier } from './routing.js';
import { recordCorrelationSample } from './correlationQuality.js';
+import { isSkipLearningVerdict, toValidationVerdict } from '../../lib/learningVerdict.js';
// Cap on retained per-category signature samples — bounds file growth the same
// way `recentUnknownErrors` does, while keeping enough recent context to spot
@@ -181,14 +182,25 @@ export function computeLatencySplit({ startedAt, completedAt, createdAt, duratio
* Stamped authoritatively at the completion chokepoint (finalizeAgent) onto
* `result.validationPassed`; surfaced here with an explicit null default so
* "absent" never masquerades as `false`.
+ * skipRecording — the "don't record this run" channel (issue #4107): true
+ * when `result.validationPassed` carries `SKIP_LEARNING_VERDICT`, i.e. the
+ * run was never evaluated AND banking it either way would lie. Its OWN
+ * boolean field rather than a fourth state on `validationPassed`, so no
+ * consumer has to re-derive it and none of the existing true/false/null
+ * branches change meaning.
*/
export function buildTaskTelemetryContext(agent, task) {
const meta = agent?.metadata || {};
const result = agent?.result || {};
const success = result.success || false;
- // Sentinel discipline: only an explicit boolean counts as a validation verdict;
- // anything else (undefined/null/non-bool) is "no criterion declared" → null.
- const validationPassed = typeof result.validationPassed === 'boolean' ? result.validationPassed : null;
+ // Sentinel discipline (#4107): the persisted verdict has FOUR values. The skip
+ // sentinel is read FIRST, off the raw field, because `toValidationVerdict`
+ // deliberately flattens it to `null` for every downstream consumer — reading it
+ // afterwards would be reading a value that no longer exists.
+ const skipRecording = isSkipLearningVerdict(result.validationPassed);
+ // Only an explicit boolean counts as a validation verdict; anything else
+ // (undefined/null/non-bool/the skip sentinel) is "no criterion declared" → null.
+ const validationPassed = toValidationVerdict(result.validationPassed);
// Validation-authoritative outcome (issue #2344): a declared verdict overrides
// the runner's exit code. Failure telemetry keys off THIS, not raw `success`,
// so a commit-found run (success:false, validationPassed:true) is NOT harvested
@@ -241,6 +253,10 @@ export function buildTaskTelemetryContext(agent, task) {
taskType,
success,
validationPassed,
+ // "Do not record this run" (#4107) — checked by recordTaskCompletion BEFORE
+ // it opens the learning store. When true, every other field here is
+ // informational only (the log line) and none of it is banked.
+ skipRecording,
// Validation-authoritative learning outcome (#2344): the single source of
// truth every aggregate/window/telemetry gate keys off, so they can't drift.
outcomeSuccess,
@@ -371,9 +387,37 @@ export function buildLiExecutionVerdict({ liProposal, success, validationPassed,
}
/**
- * Record a completed task for learning
+ * Record a completed task for learning.
+ *
+ * Returns the persisted learning data, or `null` when the run was SKIPPED —
+ * `result.validationPassed` carrying `SKIP_LEARNING_VERDICT` means nothing ever
+ * evaluated it, so there is no honest outcome to bank (#4107). Callers ignore
+ * the return today; the null is the machine-readable form of "no write happened".
*/
export async function recordTaskCompletion(agent, task) {
+ // Structured telemetry context (failure signature + execution context +
+ // latency breakdown) derived once and reused for the skip gate, the aggregates,
+ // and the log (issue #2329). Pure — no I/O — so it is built BEFORE the lock:
+ // an unrecordable run must not even open the learning store.
+ const telemetry = buildTaskTelemetryContext(agent, task);
+
+ // The "don't record this run" channel (#4107). A programmatic-I/O output hook
+ // that aborted before it ever looked at the agent's output (`no-app` /
+ // `app-not-found` — e.g. the app was deleted mid-run) leaves NO honest verdict:
+ // `false` would blame the model for a user's deletion and poison the #2329
+ // failure-signature window, and the exit-code fallback the undeclared `null`
+ // takes would bank a free success for the task type. Both aggregates and
+ // diagnostics are skipped — the run is not evidence of anything.
+ if (telemetry.skipRecording) {
+ emitLog('debug', `Skipped task completion: ${telemetry.taskType} (run never evaluated — nothing to learn from)`, {
+ taskType: telemetry.taskType,
+ modelTier: telemetry.executionContext.modelTier || 'unknown',
+ provider: telemetry.executionContext.provider,
+ success: telemetry.success
+ }, '[TaskLearning]');
+ return null;
+ }
+
// Per-proposal-domain execution attribution (#2765) — captured inside the lock (it
// needs this run's validation-authoritative outcome) but WRITTEN after it, so the LI
// outcome store's I/O never runs under the learning lock and the generic learning
@@ -382,9 +426,6 @@ export async function recordTaskCompletion(agent, task) {
const result = await withLock(async () => {
const data = await loadLearningData();
- // Structured telemetry context (failure signature + execution context +
- // latency breakdown) derived once and reused for aggregate + log (issue #2329).
- const telemetry = buildTaskTelemetryContext(agent, task);
const taskType = telemetry.taskType;
const modelTier = agent.metadata?.modelTier || 'unknown';
const success = telemetry.success;
diff --git a/server/services/taskLearning/metrics.test.js b/server/services/taskLearning/metrics.test.js
index 9ce0ee0c59..1bf5857fa3 100644
--- a/server/services/taskLearning/metrics.test.js
+++ b/server/services/taskLearning/metrics.test.js
@@ -12,6 +12,7 @@ vi.mock('./store.js', async (importActual) => {
import { buildTaskTelemetryContext, computeLatencySplit, recordFailureSignature, getWindowedStats, recordEnvironmentalFailure, shouldDivertToEnvironmental, ENVIRONMENTAL_ERROR_CATEGORIES } from './metrics.js';
import { loadLearningData } from './store.js';
+import { SKIP_LEARNING_VERDICT } from '../../lib/learningVerdict.js';
// buildTaskTelemetryContext + recordFailureSignature are the pure telemetry
// enrichment core added for issue #2329. They take no I/O, so every branch is
@@ -225,6 +226,37 @@ describe('buildTaskTelemetryContext', () => {
expect(bogus.validationPassed).toBeNull();
});
+ it('raises skipRecording for the skip sentinel WITHOUT letting it leak into validationPassed (#4107)', () => {
+ const skipped = buildTaskTelemetryContext(
+ { ...baseAgent, result: { success: true, duration: 1000, validationPassed: SKIP_LEARNING_VERDICT } }, {});
+ expect(skipped.skipRecording).toBe(true);
+ // The string is narrowed to the null sentinel for every downstream consumer —
+ // it must never reach one as a raw string, nor become a `false` verdict.
+ expect(skipped.validationPassed).toBeNull();
+ });
+
+ it('leaves skipRecording false for all three RECORDABLE verdicts (#4107)', () => {
+ // The regression guard for the skip channel: undeclared (null) and a genuine
+ // criterion miss (false) must keep flowing to the aggregates exactly as before.
+ const undeclared = buildTaskTelemetryContext(baseAgent, { taskType: 'user' });
+ expect(undeclared.skipRecording).toBe(false);
+ expect(undeclared.outcomeSuccess).toBe(true); // exit-code fallback, unchanged
+
+ for (const verdict of [true, false]) {
+ const ctx = buildTaskTelemetryContext(
+ { ...baseAgent, result: { success: true, duration: 1, validationPassed: verdict } }, {});
+ expect(ctx.skipRecording).toBe(false);
+ expect(ctx.validationPassed).toBe(verdict);
+ }
+
+ // An unrecognized non-boolean (a malformed value, or a sentinel from a newer
+ // peer) is undeclared-and-RECORDED, not silently skipped.
+ const bogus = buildTaskTelemetryContext(
+ { ...baseAgent, result: { success: true, duration: 1, validationPassed: 'nope' } }, {});
+ expect(bogus.skipRecording).toBe(false);
+ expect(bogus.validationPassed).toBeNull();
+ });
+
it('does NOT harvest a failure signature for a commit-found run (success:false, validationPassed:true) (#2344)', () => {
// Runner exit non-zero, but the declared criterion WAS met (commit found).
// The validation verdict is authoritative — no failure signature is built, so