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: stop misattributing maintenance dispatches as quota burn and scoring successful claim runs as failures

Adam Eivy2d0e59cb921a
diff --git a/scripts/migrations/411-purge-claim-flow-poisoned-learning-buckets.js b/scripts/migrations/411-purge-claim-flow-poisoned-learning-buckets.js
new file mode 100644
index 0000000000..39129f5ba1
--- /dev/null
+++ b/scripts/migrations/411-purge-claim-flow-poisoned-learning-buckets.js
@@ -0,0 +1,117 @@
+/**
+ * Purge the learning buckets poisoned by the PARENT-WORKSPACE commit criterion
+ * on CLAIM flows — the same #2696-class artifact migrations 197/198/234 handled
+ * for other routes, arriving by a new one.
+ *
+ * Background:
+ * A claim flow (plan-task / claim-issue / claim-issue-gitlab / claim-issue-jira /
+ * claim-work) runs with `useWorktree: false` in the app's live checkout while
+ * the AGENT cuts its own `claim/<item>` worktree, opens the PR/MR, merges, and
+ * cleans up. `evaluateSuccessCriteria`'s run-window commit probe
+ * (`server/lib/gitCommitProbe.js`) is workspace-scoped: it counts commits in
+ * the workspace it is handed, so on the common path it sees NOTHING the claim
+ * run did. The PR-claim verification cannot backstop it either — claim flows
+ * carry `openPR: false` (the claim prompt owns the forge lifecycle), so
+ * `prClaimExpected` is false and the forge check never runs.
+ *
+ * The declared boolean OVERRIDES the runner's exit code in task-learning
+ * (`outcomeSuccess = validationPassed ?? success`), so every exit-0 claim run
+ * recorded a FAILURE. On installs that lean on claim flows the bucket sits at
+ * ~0-25% while the runs visibly succeed — surfacing as the "may need prompt
+ * improvements" worst-performer warning on a healthy flow.
+ *
+ * The criterion is now exempted at the source (`isClaimFlowDispatch` in
+ * taskTypeHooks.js, consumed by evaluateSuccessCriteria and the history
+ * backfill's fossil sanitizer), but that fix is PROSPECTIVE. Existing installs
+ * still carry the fabricated failures.
+ *
+ * Approach:
+ * DELETE the poisoned buckets rather than repair them — `validationPassed:
+ * false` overwrote the runner's real verdict at record time, so the truth of
+ * each historical run is not on disk. Deleting resets each type to an honest
+ * "no runs recorded yet". `removeTaskTypeFromLearningData` unwinds the
+ * contribution from every aggregate the bucket touched.
+ *
+ * Scoped to the claim-flow buckets ONLY (both the `self-improve:` prefixed
+ * form a scheduled claim task lands in and the bare form a task typed on
+ * `taskType` alone can land in). Every other bucket keeps its history: the
+ * coordinator/tracker-filing shapes were handled by 197/198/234, and ordinary
+ * code-editing types have a satisfiable criterion.
+ *
+ * No-op by construction on installs with no learning store or no claim-flow
+ * bucket (an install that never ran a claim flow keeps everything).
+ *
+ * Destructive-rerun guard (#2770): opts into the runner's PURGE class
+ * (`purge: true`) so a rerun against a lost/rebuilt applied-list is recorded
+ * without executing, rather than dropping post-fix history.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+import { removeTaskTypeFromLearningData } from '../../server/services/taskLearning/metrics.js';
+import { CLAIM_FLOW_TASK_TYPES } from '../../server/lib/claimFlowTaskTypes.js';
+
+const LEARNING_REL = 'data/cos/learning.json';
+
+// The buckets this migration purges, derived from the runtime claim-flow set so
+// a type added there cannot drift out of this list. `self-improve:` matches
+// extractTaskType's first branch (taskLearning/store.js) for a scheduled claim
+// task carrying `analysisType`; the bare form covers a task typed on `taskType`
+// alone.
+export const CLAIM_FLOW_BUCKETS = [
+ ...[...CLAIM_FLOW_TASK_TYPES].map((t) => `self-improve:${t}`),
+ ...CLAIM_FLOW_TASK_TYPES,
+];
+
+/** The claim-flow buckets present in a given `byTaskType` map. Pure. */
+export function selectClaimFlowBuckets(byTaskType) {
+ if (!byTaskType || typeof byTaskType !== 'object' || Array.isArray(byTaskType)) return [];
+ return CLAIM_FLOW_BUCKETS.filter((bucket) => Object.hasOwn(byTaskType, bucket));
+}
+
+export default {
+ purge: true,
+ async up({ rootDir }) {
+ const path = join(rootDir, LEARNING_REL);
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) {
+ console.log('✅ Claim-flow learning: no learning store — nothing to purge');
+ return { purged: 0, reason: 'no-file' };
+ }
+
+ let data;
+ try {
+ data = JSON.parse(raw);
+ } catch {
+ // A corrupt learning store is not this migration's problem to fix, and
+ // rewriting it would risk destroying recoverable data.
+ console.warn('⚠️ Claim-flow learning: store is not valid JSON — skipping');
+ return { purged: 0, reason: 'unparseable' };
+ }
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
+ console.warn('⚠️ Claim-flow learning: store is not an object — skipping');
+ return { purged: 0, reason: 'unexpected-shape' };
+ }
+
+ const present = selectClaimFlowBuckets(data.byTaskType);
+ if (present.length === 0) {
+ console.log('✅ Claim-flow learning: no claim-flow bucket — no changes');
+ return { purged: 0 };
+ }
+
+ let purged = 0;
+ for (const bucket of present) {
+ const previous = removeTaskTypeFromLearningData(data, bucket);
+ purged += previous?.completed || 0;
+ }
+
+ await atomicWrite(path, JSON.stringify(data, null, 2) + '\n');
+ console.log(`🧹 Claim-flow learning: purged ${purged} mis-recorded run(s) across ${present.length} bucket(s) (parent-workspace commit criterion)`);
+ return { purged, buckets: present };
+ },
+};
diff --git a/scripts/migrations/411-purge-claim-flow-poisoned-learning-buckets.test.js b/scripts/migrations/411-purge-claim-flow-poisoned-learning-buckets.test.js
new file mode 100644
index 0000000000..7747860fe2
--- /dev/null
+++ b/scripts/migrations/411-purge-claim-flow-poisoned-learning-buckets.test.js
@@ -0,0 +1,110 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, mkdir, rm, readFile, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration, { CLAIM_FLOW_BUCKETS, selectClaimFlowBuckets } from './411-purge-claim-flow-poisoned-learning-buckets.js';
+
+let rootDir;
+
+const LEARNING_REL = 'data/cos/learning.json';
+
+async function seed(data) {
+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });
+ await writeFile(join(rootDir, LEARNING_REL), JSON.stringify(data, null, 2));
+}
+
+async function readLearning() {
+ return JSON.parse(await readFile(join(rootDir, LEARNING_REL), 'utf-8'));
+}
+
+beforeEach(async () => { rootDir = await mkdtemp(join(tmpdir(), 'mig411-')); });
+afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });
+
+describe('411-purge-claim-flow-poisoned-learning-buckets', () => {
+ it('purges the claim-flow buckets and preserves every other type', async () => {
+ await seed({
+ byTaskType: {
+ // Poisoned by the parent-workspace commit criterion → fabricated failures.
+ 'self-improve:claim-issue': { completed: 214, succeeded: 49, failed: 165, successRate: 23, recentOutcomes: [{ t: '2026-09-25T00:00:00Z', s: false }] },
+ 'self-improve:claim-work': { completed: 4, succeeded: 0, failed: 4, successRate: 0 },
+ 'claim-issue': { completed: 3, succeeded: 0, failed: 3, successRate: 0 },
+ // Honest history — must survive untouched.
+ 'user-task': { completed: 6, succeeded: 5, failed: 1, successRate: 83 },
+ 'self-improve:accessibility': { completed: 7, succeeded: 6, failed: 1, successRate: 86 },
+ 'self-improve:branch-reconcile': { completed: 2, succeeded: 2, failed: 0, successRate: 100 },
+ }
+ });
+
+ const out = await migration.up({ rootDir });
+
+ expect(out.purged).toBe(221);
+ expect(out.buckets.sort()).toEqual(['claim-issue', 'self-improve:claim-issue', 'self-improve:claim-work']);
+
+ const data = await readLearning();
+ expect(Object.keys(data.byTaskType).sort()).toEqual([
+ 'self-improve:accessibility', 'self-improve:branch-reconcile', 'user-task',
+ ]);
+ // Preserved buckets keep their real numbers — the purge must not touch them.
+ expect(data.byTaskType['user-task'].successRate).toBe(83);
+ expect(data.byTaskType['self-improve:accessibility'].succeeded).toBe(6);
+ });
+
+ it('unwinds the purged buckets from the aggregate totals, not just byTaskType', async () => {
+ await seed({
+ totals: { completed: 10, succeeded: 4, failed: 6, totalDurationMs: 10_000, successDurationMs: 4_000 },
+ byTaskType: {
+ 'self-improve:claim-issue': { completed: 6, succeeded: 0, failed: 6, totalDurationMs: 6_000, successDurationMs: 0, successRate: 0 },
+ 'user-task': { completed: 4, succeeded: 4, failed: 0, totalDurationMs: 4_000, successDurationMs: 4_000, successRate: 100 },
+ }
+ });
+
+ await migration.up({ rootDir });
+
+ const data = await readLearning();
+ expect(data.totals.completed).toBe(4);
+ expect(data.totals.failed).toBe(0);
+ expect(data.totals.succeeded).toBe(4);
+ });
+
+ it('is a no-op when no claim-flow bucket exists', async () => {
+ await seed({ byTaskType: { 'user-task': { completed: 3, succeeded: 3, failed: 0, successRate: 100 } } });
+ const out = await migration.up({ rootDir });
+ expect(out.purged).toBe(0);
+ expect((await readLearning()).byTaskType['user-task'].completed).toBe(3);
+ });
+
+ it('is a no-op with no learning store at all', async () => {
+ expect(await migration.up({ rootDir })).toEqual({ purged: 0, reason: 'no-file' });
+ });
+
+ it('leaves an unparseable or non-object store alone rather than rewriting it', async () => {
+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });
+ await writeFile(join(rootDir, LEARNING_REL), '{ not json');
+ expect(await migration.up({ rootDir })).toEqual({ purged: 0, reason: 'unparseable' });
+ expect(await readFile(join(rootDir, LEARNING_REL), 'utf-8')).toBe('{ not json');
+
+ await writeFile(join(rootDir, LEARNING_REL), '[]');
+ expect(await migration.up({ rootDir })).toEqual({ purged: 0, reason: 'unexpected-shape' });
+ });
+
+ // The runner records a purge migration as applied WITHOUT running it when the
+ // applied-list was rebuilt from [] (#2770) — without this flag a lost ledger
+ // would delete legitimately-earned post-fix learning data.
+ it('opts into the runner purge class', () => {
+ expect(migration.purge).toBe(true);
+ });
+
+ it('derives its bucket list from the runtime claim-flow set rather than a copy', () => {
+ // Kept in lockstep with claimFlowTaskTypes.js — a claim type added there must
+ // be purged here too, or its poisoned bucket would survive this migration.
+ for (const type of ['plan-task', 'claim-issue', 'claim-issue-gitlab', 'claim-issue-jira', 'claim-work']) {
+ expect(CLAIM_FLOW_BUCKETS).toContain(`self-improve:${type}`);
+ expect(CLAIM_FLOW_BUCKETS).toContain(type);
+ }
+ expect(selectClaimFlowBuckets({ 'self-improve:claim-issue': {}, 'auto-fix': {} })).toEqual(['self-improve:claim-issue']);
+ expect(selectClaimFlowBuckets({ 'claim-work': {}, 'auto-fix': {} })).toEqual(['claim-work']);
+ expect(selectClaimFlowBuckets(null)).toEqual([]);
+ expect(selectClaimFlowBuckets([])).toEqual([]);
+ });
+});
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 0f3a09be8a..1c9ba32e74 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -57,7 +57,7 @@ import { formatGoalFidelityFollowUpSummary, goalFidelityFollowUpApplies } from '
import { getGoalFidelityConfig, runLocalGoalFidelityReview } from './codeReview.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 { canRunTaskOutputHookWithoutPayload, getTaskOutputPayloadPredicate, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion, isClaimFlowDispatch } from './taskTypeHooks.js';
import { processAgentCompletion } from './agentCompletion.js';
import { extractSimplifySummaries } from './agentSummaryExtraction.js';
import { usesCreativeDirectorScratchCwd, removeCreativeDirectorScratchCwd } from '../lib/spawnCwd.js';
@@ -185,6 +185,19 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac
// so the same type still gets its commit criterion on a `plan`-tracker app
// where it legitimately commits PLAN.md items (#3273).
if (declaresNoCommitCriterion(task)) return null;
+ // A CLAIM flow (plan-task / claim-issue / claim-issue-gitlab / claim-issue-jira /
+ // claim-work) commits in the claim/<item> worktree the AGENT cuts, not in this
+ // workspace — the app's live checkout on the common path, since CoS keeps
+ // `useWorktree` false so it never provisions a nested worktree. The run-window
+ // probe is workspace-scoped, so it sees nothing and the declared false OVERRIDES
+ // the exit code in task-learning, scoring every successful claim run a failure
+ // and pinning the type's bucket at ~0% — the #2696 artifact by a new route.
+ // The goal-fidelity gate still judges the run against the claimed issue's
+ // requirements, so the exit code (not the probe) is the honest criterion here.
+ // Not folded into declaresNoCommitCriterion: that predicate also gates the
+ // goal-fidelity gate's no-diff bail, which claim flows must NOT take — their
+ // claim-worktree diff is exactly what the fidelity review reads.
+ if (isClaimFlowDispatch(task)) return null;
// No usable run window means no way to attribute a commit to THIS run — the
// sentinel, not a false verdict (#3637).
if (!Number.isFinite(startedAt)) return null;
diff --git a/server/services/agentFinalization.successCriteria.test.js b/server/services/agentFinalization.successCriteria.test.js
index 40aa7b79bc..138a1a26b2 100644
--- a/server/services/agentFinalization.successCriteria.test.js
+++ b/server/services/agentFinalization.successCriteria.test.js
@@ -521,3 +521,59 @@ describe('evaluateSuccessCriteria — gh/git coordinator exemption (#2696)', ()
expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);
});
});
+
+/**
+ * CLAIM flows (plan-task / claim-issue / claim-issue-gitlab / claim-issue-jira /
+ * claim-work): the agent cuts its OWN claim/<item> worktree and opens/merges the PR
+ * there, while CoS keeps `useWorktree: false` so the workspace this criterion probes
+ * is the app's live checkout — which the claim run never commits to. The probe is
+ * workspace-scoped, so it stamped `validationPassed: false` on every successful run
+ * (the boolean OVERRIDES the exit code in task-learning), pinning the type's bucket
+ * at ~0-25% while the runs visibly succeed. The exemption falls back to the exit
+ * code; the goal-fidelity gate still judges the run against the claimed issue's
+ * requirements, so nothing is lost but the misattributed probe.
+ */
+describe('evaluateSuccessCriteria — claim-flow exemption', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('declares NO commit criterion for every claim-flow type', async () => {
+ for (const analysisType of ['plan-task', 'claim-issue', 'claim-issue-gitlab', 'claim-issue-jira', 'claim-work']) {
+ const task = { id: 't1', taskType: 'internal', metadata: { analysisType } };
+ expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true, startedAt: STARTED_AT })).toBeNull();
+ }
+ expect(committedDuringRun).not.toHaveBeenCalled();
+ });
+
+ it('accepts the explicit claimFlow marker on a task of any type', async () => {
+ // A manually marked claim (e.g. a dependency task also marked claimFlow) or a
+ // schedule queued before the marker existed carries only the flag.
+ for (const claimFlow of [true, 'true']) {
+ const task = { id: 't2', taskType: 'internal', metadata: { claimFlow } };
+ expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true, startedAt: STARTED_AT })).toBeNull();
+ }
+ expect(committedDuringRun).not.toHaveBeenCalled();
+ });
+
+ it('exempts the archived-agent projection (metadata.taskAnalysisType) too', async () => {
+ // Same analysisType → taskAnalysisType → taskType chain the learning bucket
+ // uses, so the criterion agrees with the bucket on the archived shape.
+ const task = { id: 't3', taskType: 'internal', metadata: { taskAnalysisType: 'claim-issue' } };
+ expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true, startedAt: STARTED_AT })).toBeNull();
+ expect(committedDuringRun).not.toHaveBeenCalled();
+ });
+
+ it('exempts a claim task typed on taskType alone', async () => {
+ const task = { id: 't4', taskType: 'claim-work' };
+ expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true, startedAt: STARTED_AT })).toBeNull();
+ expect(committedDuringRun).not.toHaveBeenCalled();
+ });
+
+ it('does NOT exempt a task whose claimFlow flag is falsy or absent', async () => {
+ // The flag is the marker of a claim dispatch; a task that merely carries the
+ // string "false" (or nothing) is an ordinary committing run.
+ committedDuringRun.mockResolvedValueOnce(false);
+ const task = { id: 't5', taskType: 'internal', metadata: { analysisType: 'security', claimFlow: 'false' } };
+ expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', startedAt: STARTED_AT, success: true })).toBe(false);
+ expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);
+ });
+});
diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.js
index b437654b56..0dc5ac5b43 100644
--- a/server/services/quotaBurnInvoke.js
+++ b/server/services/quotaBurnInvoke.js
@@ -509,7 +509,15 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate, maintenan
});
if (request?.error) return declined(request.error);
- console.log(`🔥 Quota-burn requested scheduled task ${resolved.ref.taskType} for ${burnLabel(family)} (${request.id})`);
+ // Attribution, not decoration: this shared path serves BOTH the quota-burn
+ // loop and MANUAL maintenance runs (`maintenanceRunId` is set only by
+ // maintenanceRun.js). An unconditional 🔥 line makes a maintenance dispatch
+ // read as quota-burn activity on an install where quota burn is disabled —
+ // the operator cannot tell a feature they turned off from the maintenance
+ // ladder they clicked. Key the wording on the provenance, and name the run.
+ console.log(maintenanceRunId
+ ? `🧹 Maintenance run ${maintenanceRunId} requested scheduled task ${resolved.ref.taskType} (${request.id})`
+ : `🔥 Quota-burn requested scheduled task ${resolved.ref.taskType} for ${burnLabel(family)} (${request.id})`);
return {
dispatched: true,
// The ONLY lane whose acceptance is asynchronous: the request is recorded
@@ -562,7 +570,11 @@ async function runCustomJobStep({ resolved, step, family, candidate, maintenance
// other. Everything below OVERRIDES it — that is where the two legitimately
// differ.
...generatedJobTaskFields(generated),
- context: `Quota burn (${burnLabel(family)}): ${resolved.job.name}`,
+ // The queued task's context names who asked for it — a maintenance run's
+ // dispatch must not read as a quota-burn spend on the task card.
+ context: maintenanceRunId
+ ? `Maintenance run ${maintenanceRunId}: ${resolved.job.name}`
+ : `Quota burn (${burnLabel(family)}): ${resolved.job.name}`,
approvalRequired: !generated.autoApprove,
// The step's overrides win over the job's saved pins (see effectiveSettings),
// and an unpinned step still lands on THIS family's provider.
@@ -587,7 +599,11 @@ async function runCustomJobStep({ resolved, step, family, candidate, maintenance
// retry, and an unattended burn has no such intent to express.
if (persisted.duplicate) return declined(`an identical "${resolved.job.name}" task is already ${persisted.status}`);
- console.log(`🔥 Quota-burn queued custom job ${resolved.job.id} as task ${persisted.id} for ${burnLabel(family)}`);
+ // Same attribution rule as the built-in lane above: a maintenance run's
+ // custom-job dispatch must not wear the 🔥 quota-burn wording.
+ console.log(maintenanceRunId
+ ? `🧹 Maintenance run ${maintenanceRunId} queued custom job ${resolved.job.id} as task ${persisted.id}`
+ : `🔥 Quota-burn queued custom job ${resolved.job.id} as task ${persisted.id} for ${burnLabel(family)}`);
return {
dispatched: true,
summary: `Queued "${resolved.job.name}" via ${picked.provider.id}`,
diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.js
index 6067232417..3470160053 100644
--- a/server/services/quotaBurnInvoke.test.js
+++ b/server/services/quotaBurnInvoke.test.js
@@ -438,6 +438,25 @@ describe('built-in agent task invocation', () => {
expect(state.triggered[1].options.burn).not.toHaveProperty('maintenanceRunId');
});
+ // Attribution: this shared path serves both the quota-burn loop and MANUAL
+ // maintenance runs. An unconditional 🔥 line makes a maintenance dispatch read
+ // as quota-burn activity on an install where quota burn is disabled — the
+ // operator cannot tell a feature they turned off from the ladder they clicked.
+ it('attributes a dispatch log line to the maintenance run, not quota burn, when one is present', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ try {
+ await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate, maintenanceRunId: 'maint-1' });
+ expect(log).toHaveBeenCalledWith(expect.stringMatching(/^🧹 Maintenance run maint-1 requested scheduled task ux \(/));
+ expect(log).not.toHaveBeenCalledWith(expect.stringMatching(/🔥/));
+
+ log.mockClear();
+ await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate });
+ expect(log).toHaveBeenCalledWith(expect.stringMatching(/^🔥 Quota-burn requested scheduled task ux for grok \(/));
+ } finally {
+ log.mockRestore();
+ }
+ });
+
it('routes through the schedule\'s on-demand lane with quota-burn provenance', async () => {
const result = await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate });
expect(result.dispatched).toBe(true);
@@ -536,6 +555,28 @@ describe('custom app job invocation', () => {
const result = await invokeQuotaBurnStep({ step: jobStep(), family: grok, candidate });
expect(result).toEqual({ dispatched: false, reason: expect.stringContaining('already blocked') });
});
+
+ // Same attribution contract as the built-in lane: a maintenance run's custom-job
+ // dispatch must not wear quota-burn wording — in the log line OR on the queued
+ // task's context, which is what the task card shows.
+ it('attributes a maintenance custom-job dispatch to the run, in the log and the task context', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ try {
+ await invokeQuotaBurnStep({ step: jobStep(), family: grok, candidate, maintenanceRunId: 'maint-7' });
+ expect(log).toHaveBeenCalledWith('🧹 Maintenance run maint-7 queued custom job job-a as task sys-1');
+ expect(log).not.toHaveBeenCalledWith(expect.stringMatching(/🔥/));
+ const [{ task }] = state.added;
+ expect(task.context).toBe('Maintenance run maint-7: Nightly sweep');
+
+ log.mockClear();
+ state.added = [];
+ await invokeQuotaBurnStep({ step: jobStep(), family: grok, candidate });
+ expect(log).toHaveBeenCalledWith('🔥 Quota-burn queued custom job job-a as task sys-1 for grok');
+ expect(state.added[0].task.context).toBe('Quota burn (grok): Nightly sweep');
+ } finally {
+ log.mockRestore();
+ }
+ });
});
describe('programmatic handler invocation', () => {
diff --git a/server/services/taskLearning/lifecycle.js b/server/services/taskLearning/lifecycle.js
index c131a90a0d..98640e3d6a 100644
--- a/server/services/taskLearning/lifecycle.js
+++ b/server/services/taskLearning/lifecycle.js
@@ -9,7 +9,7 @@
import { cosEvents, emitLog } from './store.js';
import { recordTaskCompletion, recalculateModelTierMetrics } from './metrics.js';
-import { declaresNoCommitCriterion } from '../taskTypeHooks.js';
+import { declaresNoCommitCriterion, isClaimFlowDispatch } from '../taskTypeHooks.js';
import { isAgentHandoff } from '../../lib/agentOutcome.js';
// A pre-#2696 gh/git coordinator run (branch-reconcile/issue-reconcile/branch-cleanup/
@@ -25,8 +25,16 @@ import { isAgentHandoff } from '../../lib/agentOutcome.js';
// backfill also drops the fossil off a tracker-filing run (`worktreeChangesExpected: false`,
// e.g. a reference-watch run on a github-tracker app) — the identical artifact, just carried
// on a per-task flag instead of the static type set (#3273).
+//
+// CLAIM flows (plan-task / claim-issue / claim-issue-gitlab / claim-issue-jira /
+// claim-work) carry the same fossil for the same reason: their commits land in the
+// claim/<item> worktree the agent cuts, so the parent-workspace probe stamped
+// `validationPassed: false` on successful runs. Keyed on `isClaimFlowDispatch`
+// (not declaresNoCommitCriterion, which claim flows deliberately do NOT satisfy)
+// so a backfill re-recording an archived claim run drops the fossil instead of
+// restoring the poisoned bucket the claim-flow purge migration removed.
function withoutStaleCoordinatorVerdict(agent, task) {
- if (!declaresNoCommitCriterion(task)) return agent;
+ if (!declaresNoCommitCriterion(task) && !isClaimFlowDispatch(task)) return agent;
if (typeof agent?.result?.validationPassed !== 'boolean') return agent;
return { ...agent, result: { ...agent.result, validationPassed: null } };
}
diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.js
index 5c84bf2a77..ebdbec8b79 100644
--- a/server/services/taskTypeHooks.js
+++ b/server/services/taskTypeHooks.js
@@ -51,6 +51,7 @@
import { isFalsyMeta, isTruthyMeta } from './agentState.js';
import { TRACKER_FILING_TASK_TYPES, CONCRETE_WORK_TRACKERS } from '../lib/workTracker.js';
import { isAuditTaskType } from '../lib/auditCatalog.js';
+import { CLAIM_FLOW_TASK_TYPES } from '../lib/claimFlowTaskTypes.js';
// taskType → { load }. `load` is the module import thunk; a module may export
// either or both hooks, and a missing export means "no hook of that kind for this
@@ -141,10 +142,13 @@ export function resolveTaskHookType(task) {
* exactly like pipeline/media jobs.
*
* Deliberately NOT every self-improvement type: accessibility / security / code-quality
- * / plan-task / claim-issue / claim-work / jira-sprint-manager / do-replan all COMMIT
- * (fixing tasks, /claim flows, or a triage that commits PLAN.md), so their commit
- * criterion is real and must stay — exempting them would MASK genuine failures. Only
- * complete tasks whose DEFAULT contract is structurally no-commit belong here.
+ * / jira-sprint-manager / do-replan all COMMIT (fixing tasks, or a triage that commits
+ * PLAN.md), so their commit criterion is real and must stay — exempting them would
+ * MASK genuine failures. The claim flows (plan-task / claim-issue / claim-issue-gitlab /
+ * claim-issue-jira / claim-work) also commit, but in a worktree the agent itself cuts —
+ * they are exempted from the PARENT-workspace commit probe by their own predicate
+ * (`isClaimFlowDispatch` below), not by this set. Only complete tasks whose DEFAULT
+ * contract is structurally no-commit belong here.
*
* pr-watcher is intentionally excluded on a different axis: it is a review-of-others'-PRs
* TEMPLATE — its shipped prompt explicitly says "the operator customizes this prompt to
@@ -202,6 +206,37 @@ export function isNonCommittingCoordinatorTask(task) {
return NON_COMMITTING_COORDINATOR_TASK_TYPES.has(type);
}
+/**
+ * Whether a task runs a CLAIM flow — plan-task / claim-issue / claim-issue-gitlab /
+ * claim-issue-jira / claim-work — whose prompt owns its OWN claim/<item> worktree
+ * and forge lifecycle (worktree, PR/MR, merge, cleanup) while CoS keeps
+ * `useWorktree`/`openPR` false so it never provisions a nested worktree.
+ *
+ * NOT a `declaresNoCommitCriterion` shape, on purpose. A claim run's deliverable
+ * IS a commit — but it lands in the claim worktree the AGENT cut, not in the
+ * workspace `evaluateSuccessCriteria` probes (the app's live checkout for a
+ * first-run claim, or the claim tree only on a `claimResumeInPlace` continuation).
+ * The run-window commit probe is workspace-scoped, so on the common path it sees
+ * nothing and a declared `validationPassed: false` OVERRIDES the exit code in
+ * task-learning — scoring every successful claim run a failure and pinning the
+ * type's bucket at ~0% (the #2696 artifact arriving by a new route). The
+ * goal-fidelity gate still judges claim runs against the claimed issue's
+ * requirements (its claimFlow branch), so this exemption trades a redundant
+ * commit probe for the exit code without losing the fidelity review.
+ *
+ * Resolved the same way `evaluateGoalFidelity` resolves claimFlow (and the same
+ * analysisType → taskAnalysisType → taskType chain the learning bucket uses), so
+ * a LIVE queue task, the archived agent projection, and the bucket agree. The
+ * explicit `claimFlow` marker covers a schedule queued before the marker existed
+ * and a manually marked claim (a dependency task also marked claimFlow); the
+ * type set is the backstop for records carrying only the scheduled type.
+ */
+export function isClaimFlowDispatch(task) {
+ if (task?.metadata?.claimFlow === true || task?.metadata?.claimFlow === 'true') return true;
+ const type = task?.metadata?.analysisType || task?.metadata?.taskAnalysisType || task?.taskType || null;
+ return CLAIM_FLOW_TASK_TYPES.has(type);
+}
+
/**
* Whether a task declares NO commit criterion: the static
* coordinator set above, a NO-CODE-OUTPUT task (its deliverable is an action —
diff --git a/server/services/taskTypeHooks.noCommit.test.js b/server/services/taskTypeHooks.noCommit.test.js
index baf7df18ee..593d3be1f7 100644
--- a/server/services/taskTypeHooks.noCommit.test.js
+++ b/server/services/taskTypeHooks.noCommit.test.js
@@ -8,7 +8,7 @@
*/
import { describe, it, expect } from 'vitest';
-import { declaresNoCommitCriterion } from './taskTypeHooks.js';
+import { declaresNoCommitCriterion, isClaimFlowDispatch } from './taskTypeHooks.js';
const task = (metadata) => ({ id: 'task-1', metadata });
@@ -102,3 +102,43 @@ describe('declaresNoCommitCriterion', () => {
});
});
});
+
+/**
+ * `isClaimFlowDispatch` — the claim-flow predicate. Deliberately NOT folded into
+ * `declaresNoCommitCriterion`: that predicate also gates the goal-fidelity gate's
+ * no-diff bail, which claim flows must not take (their claim-worktree diff is what
+ * the fidelity review reads). Its only consumers are the success-criteria commit
+ * probe and the history-backfill fossil sanitizer.
+ */
+describe('isClaimFlowDispatch', () => {
+ it('recognizes every claim-flow type on analysisType', () => {
+ for (const analysisType of ['plan-task', 'claim-issue', 'claim-issue-gitlab', 'claim-issue-jira', 'claim-work']) {
+ expect(isClaimFlowDispatch(task({ analysisType }))).toBe(true);
+ }
+ });
+
+ it('recognizes the explicit claimFlow marker, boolean and string form', () => {
+ expect(isClaimFlowDispatch(task({ claimFlow: true }))).toBe(true);
+ expect(isClaimFlowDispatch(task({ claimFlow: 'true' }))).toBe(true);
+ });
+
+ it('resolves the archived-agent projection (taskAnalysisType) and a bare taskType', () => {
+ expect(isClaimFlowDispatch(task({ taskAnalysisType: 'claim-issue' }))).toBe(true);
+ expect(isClaimFlowDispatch({ id: 'task-1', taskType: 'claim-work' })).toBe(true);
+ });
+
+ it('does not treat an ordinary committing task as a claim flow', () => {
+ expect(isClaimFlowDispatch(task({}))).toBe(false);
+ expect(isClaimFlowDispatch(task({ analysisType: 'security' }))).toBe(false);
+ expect(isClaimFlowDispatch(task({ claimFlow: 'false' }))).toBe(false);
+ expect(isClaimFlowDispatch(task({ analysisType: 'branch-reconcile' }))).toBe(false);
+ });
+
+ it('is NOT a declaresNoCommitCriterion shape — the goal-fidelity gate depends on the distinction', () => {
+ // If claim flows ever satisfy declaresNoCommitCriterion, the goal-fidelity
+ // gate's no-diff bail (agentFinalization.js) fires before its claimFlow
+ // branch and the claimed-issue review silently stops running.
+ expect(declaresNoCommitCriterion(task({ analysisType: 'claim-issue' }))).toBe(false);
+ expect(declaresNoCommitCriterion(task({ claimFlow: true }))).toBe(false);
+ });
+});