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

carry quota-burn task provenance through one block definition (#6406)

[._.]/ Adam Eivy5a1c9c13a382
diff --git a/server/lib/README.md b/server/lib/README.md
index b86eabb088..ed8b57886a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -64,7 +64,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
| `autonomousJobTask.js` | `generatedJobTaskFields` — flattens a `generateTaskFromJob` result into the top-level keys the non-raw `cos.addTask` path maps onto metadata. One allowlist shared by the manual "Run now" endpoint and the quota-burn lane, so a key added to the generator cannot reach one and not the other. Pure. |
| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. |
-| `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request: `normalizeQuotaBurnProvenance` (family + burn-step id required, plus the limiting-window reset and the provider/model/effort overrides) and `quotaBurnTaskMetadata`, the single spread both on-demand engines apply so a reference-dispatched burn stamps the same `quotaBurnFamily` / `quotaBurnLimitingResetAt` keys the retired direct executor did. Import-light on purpose — `taskScheduleConstants.js` declares the origin string and must not drag the quota-burn config graph. |
+| `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request and on the task it produces. `normalizeQuotaBurnProvenance` reads the request block (family + burn-step id required, plus the limiting-window reset and the provider/model/effort overrides); `QUOTA_BURN_PROVENANCE_FIELDS` is the ONE block definition every persistence and projection hop derives from, spread by `quotaBurnTaskMetadata` (flat task-metadata keys), `quotaBurnAgentMetadata` (the agent projection) and read back by `quotaBurnProvenance` / `hasQuotaBurnProvenance`, which accept both the flat keys and a nested `quotaBurn` block. `onDemandRequestMetadata` is the single spread both on-demand engines apply. Import-light on purpose — `taskScheduleConstants.js` declares the origin string and must not drag the quota-burn config graph. |
| `quotaBurnPresets.js` | `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`. |
| `auditCatalog.js` | Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. `isFileIssuesMode`, `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. |
| `quotaBurnTaskRef.js` | The quota-burn STEP model: a discriminated scheduled-task reference (`builtin` task type + validated target app, or `custom` app-job id whose own scope is authoritative) plus the per-invocation `overrides` bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). `normalizeQuotaBurnTaskRef` / `normalizeQuotaBurnOverrides` / `normalizeQuotaBurnParams`, the `QUOTA_BURN_UNAVAILABLE` reason codes, `resolveQuotaBurnStepAvailability` (catalog passed IN, so this stays pure) / `applyQuotaBurnAvailability`, and `quotaBurnStepIsDispatchable`. |
diff --git a/server/lib/quotaBurnOrigin.js b/server/lib/quotaBurnOrigin.js
index 8111a3c3d4..7a1f2f188c 100644
--- a/server/lib/quotaBurnOrigin.js
+++ b/server/lib/quotaBurnOrigin.js
@@ -17,11 +17,12 @@
* (server/AGENTS.md, "Import scoping"). That is also why `onDemandOrigin` below
* is copied through as an opaque string rather than validated against the enum.
*
- * The two long-lived keys — `quotaBurnFamily` and `quotaBurnLimitingResetAt` —
- * are the SAME ones the legacy `quotaBurnJobs/agentPrompt.js` executor stamps,
- * on purpose: `cosTaskGenerator.js#isCooldownExemptTask`, the runner's completion
- * continuation, and `quotaBurnDenials.js` all read them off the finished agent,
- * and a reference-dispatched burn must be indistinguishable to those readers.
+ * The provenance keys are the SAME ones the legacy `quotaBurnJobs/agentPrompt.js`
+ * executor stamps, on purpose: `cosTaskGenerator.js#isCooldownExemptTask`, the
+ * runner's completion continuation, and `quotaBurnDenials.js` all read them off
+ * the finished agent, and a reference-dispatched burn must be indistinguishable
+ * to those readers. `QUOTA_BURN_PROVENANCE_FIELDS` below is the one place they
+ * are named.
*/
import { isPlainObject } from './objects.js';
@@ -36,6 +37,100 @@ export const QUOTA_BURN_REQUEST_ORIGIN = 'quota-burn';
const MAX_FIELD = 64;
+/**
+ * THE quota-burn provenance block: the facts that say which burn a task is, in
+ * one place. Every hop that persists or projects them derives from this table
+ * rather than naming keys, so a fifth fact is one row here instead of four
+ * hand-written lines that can each be forgotten independently — which is exactly
+ * how `quotaBurnStepId` came to reach disk but never reach the agent (#6406).
+ *
+ * The three hops:
+ * - `onDemandRequestMetadata` below (raw path — the on-demand engines).
+ * - `cosTaskStore.js#addTask` (non-raw path — the synchronous custom-job lane).
+ * - `agentLifecycle.js` (the agent projection the runner and the denial
+ * ledger read a finished run back out of).
+ *
+ * The PERSISTED and cross-peer shape stays FLAT (`quotaBurnFamily`, …), not a
+ * nested `quotaBurn` object. CoS tasks federate as markdown replicated between
+ * peers that upgrade independently (`cosTaskMerge.js`), and `metadata.quotaBurnFamily`
+ * is what makes a burn cooldown-exempt and what credits a refusal to a family —
+ * so a nested-only write would make a burn queued on a new peer read as an
+ * ordinary task on an older one, for no functional gain. `quotaBurnProvenance`
+ * still ACCEPTS a nested block, so a producer may hand its provenance over as a
+ * unit and a task that ever arrives in that shape resolves identically.
+ *
+ * Readers coerce, because a COS-TASKS.md round-trip hands every scalar back as a
+ * string: a task written by a previous release must still read as burn-provenanced.
+ */
+const asId = (value) => (typeof value === 'string' && value.trim() ? value.trim() : undefined);
+const asEpochMs = (value) => {
+ const numeric = typeof value === 'number' ? value : (asId(value) === undefined ? NaN : Number(value));
+ return Number.isFinite(numeric) ? numeric : undefined;
+};
+
+export const QUOTA_BURN_PROVENANCE_FIELDS = Object.freeze([
+ // Which provider family's window this run is spending. The one field a burn
+ // cannot be attributed without — `isCooldownExemptTask` and the denial ledger
+ // both key on it.
+ { field: 'family', taskKey: 'quotaBurnFamily', agentKey: 'taskQuotaBurnFamily', read: asId },
+ // The reset of the SHORT rolling window that will refuse first, so a refused
+ // run blocks the family until that window rolls rather than re-dispatching
+ // into the same wall. See quotaBurnDenials.js.
+ { field: 'limitingResetAt', taskKey: 'quotaBurnLimitingResetAt', agentKey: 'taskQuotaBurnLimitingResetAt', read: asEpochMs },
+ // Which STEP of the burn plan asked.
+ { field: 'stepId', taskKey: 'quotaBurnStepId', agentKey: 'taskQuotaBurnStepId', read: asId },
+ // The on-demand REQUEST this task was generated for. Absent — never null, never
+ // synthesized — on the synchronous custom-job lane, which queues the task itself
+ // and has no request to name; a fake id would make a join over it silently wrong.
+ { field: 'requestId', taskKey: 'quotaBurnRequestId', agentKey: 'taskQuotaBurnRequestId', read: asId },
+].map(Object.freeze));
+
+/**
+ * Read the provenance block off anything carrying it — task metadata, an
+ * `addTask` payload, or a producer's own `quotaBurn` block. A field the source
+ * does not carry (or carries unreadably) is ABSENT from the result, so callers
+ * can tell "not recorded" from a legitimate value without a sentinel of their own.
+ */
+export function quotaBurnProvenance(source) {
+ const block = {};
+ if (!isPlainObject(source)) return block;
+ const nested = isPlainObject(source.quotaBurn) ? source.quotaBurn : null;
+ for (const { field, taskKey, read } of QUOTA_BURN_PROVENANCE_FIELDS) {
+ const value = read(nested?.[field] ?? source[taskKey]);
+ if (value !== undefined) block[field] = value;
+ }
+ return block;
+}
+
+/** The flat metadata keys a block persists as. Absent fields stay absent. */
+export function quotaBurnTaskMetadata(block) {
+ const metadata = {};
+ if (!isPlainObject(block)) return metadata;
+ for (const { field, taskKey, read } of QUOTA_BURN_PROVENANCE_FIELDS) {
+ const value = read(block[field]);
+ if (value !== undefined) metadata[taskKey] = value;
+ }
+ return metadata;
+}
+
+/**
+ * The provenance projection `agentLifecycle` stamps onto the agent record.
+ * agent.metadata is a hand-picked projection of task.metadata, so EVERY
+ * persisted field is listed here by construction — a field that reaches disk
+ * cannot fail to reach the runner's completion continuation or the denial ledger.
+ * `null` (not absent) for a field the task never carried, matching the rest of
+ * that projection's "not recorded" convention.
+ */
+export function quotaBurnAgentMetadata(taskMetadata) {
+ const block = quotaBurnProvenance(taskMetadata);
+ return Object.fromEntries(
+ QUOTA_BURN_PROVENANCE_FIELDS.map(({ field, agentKey }) => [agentKey, block[field] ?? null]),
+ );
+}
+
+/** Whether a task carries attributable burn provenance at all. */
+export const hasQuotaBurnProvenance = (taskMetadata) => Boolean(quotaBurnProvenance(taskMetadata).family);
+
const trimmed = (value, max = MAX_FIELD) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
const nullable = (value, max = MAX_FIELD) => trimmed(value, max) || null;
@@ -109,13 +204,11 @@ export function onDemandRequestMetadata(request) {
onDemand: true,
onDemandOrigin: nullable(request?.origin),
...(burn ? {
- quotaBurnFamily: burn.family,
- // Omitted rather than nulled when unreadable: `cosTaskStore` only persists
- // a FINITE value, so writing an explicit null here would make the raw-task
- // path disagree with the mapped one.
- ...(burn.limitingResetAt === null ? {} : { quotaBurnLimitingResetAt: burn.limitingResetAt }),
- quotaBurnStepId: burn.stepId,
- ...(requestId ? { quotaBurnRequestId: requestId } : {}),
+ // One spread of the shared block, so this path cannot carry a different
+ // set of provenance keys than the non-raw `addTask` mapping does. An
+ // unreadable reset (and an unnamed request) drops out rather than being
+ // written as null — see QUOTA_BURN_PROVENANCE_FIELDS.
+ ...quotaBurnTaskMetadata({ ...burn, requestId }),
...(burn.overrides.providerId ? { provider: burn.overrides.providerId } : {}),
...(burn.overrides.model ? { model: burn.overrides.model } : {}),
...(burn.overrides.effort ? { effort: burn.overrides.effort } : {}),
diff --git a/server/lib/quotaBurnOrigin.test.js b/server/lib/quotaBurnOrigin.test.js
index 0abf07d828..dc27b22f52 100644
--- a/server/lib/quotaBurnOrigin.test.js
+++ b/server/lib/quotaBurnOrigin.test.js
@@ -1,5 +1,13 @@
import { describe, expect, it } from 'vitest';
-import { normalizeQuotaBurnProvenance, onDemandRequestMetadata } from './quotaBurnOrigin.js';
+import {
+ QUOTA_BURN_PROVENANCE_FIELDS,
+ hasQuotaBurnProvenance,
+ normalizeQuotaBurnProvenance,
+ onDemandRequestMetadata,
+ quotaBurnAgentMetadata,
+ quotaBurnProvenance,
+ quotaBurnTaskMetadata,
+} from './quotaBurnOrigin.js';
const provenance = (overrides = {}) => ({ family: 'grok', stepId: 'step-1', ...overrides });
@@ -83,3 +91,63 @@ describe('onDemandRequestMetadata', () => {
.toEqual({ onDemand: true, onDemandOrigin: 'user' });
});
});
+
+describe('the quota-burn provenance block', () => {
+ it('reads a task written by the PREVIOUS release, whose keys are flat markdown strings', () => {
+ // The compatibility case the whole block exists to survive: a COS-TASKS.md
+ // round-trip hands every scalar back as a string, and a task queued (or
+ // back-filled by migration 225) before this refactor carries nothing but the
+ // flat keys. It must still read as burn-provenanced.
+ const legacy = { quotaBurnFamily: 'agy', quotaBurnLimitingResetAt: '1700000000000', quotaBurnStepId: 'step-9' };
+ expect(quotaBurnProvenance(legacy))
+ .toEqual({ family: 'agy', limitingResetAt: 1700000000000, stepId: 'step-9' });
+ expect(hasQuotaBurnProvenance(legacy)).toBe(true);
+ expect(hasQuotaBurnProvenance({ app: 'example-app' })).toBe(false);
+ });
+
+ it('accepts provenance handed over as one block, and prefers it per field over a flat key', () => {
+ expect(quotaBurnProvenance({ quotaBurn: { family: 'grok', stepId: 'step-1' }, quotaBurnRequestId: 'demand-3' }))
+ .toEqual({ family: 'grok', stepId: 'step-1', requestId: 'demand-3' });
+ });
+
+ it('leaves a field the task never carried ABSENT rather than null', () => {
+ // `quotaBurnRequestId` is the load-bearing one: the synchronous custom-job
+ // lane has no request to name, and a null (or synthesized) id would make a
+ // join over it silently wrong.
+ const metadata = quotaBurnTaskMetadata(quotaBurnProvenance({ quotaBurnFamily: 'grok', quotaBurnStepId: 'step-1' }));
+ expect(metadata).toEqual({ quotaBurnFamily: 'grok', quotaBurnStepId: 'step-1' });
+ expect(metadata).not.toHaveProperty('quotaBurnRequestId');
+ expect(quotaBurnTaskMetadata({ family: 'grok', limitingResetAt: null, requestId: '' }))
+ .toEqual({ quotaBurnFamily: 'grok' });
+ });
+
+ it('projects EVERY persisted provenance field onto the agent', () => {
+ // The regression this uniquely catches: a field that reaches disk but never
+ // reaches the agent record is invisible — `quotaBurnStepId` was persisted
+ // for a release without the runner's completion continuation or the denial
+ // ledger being able to read it. Driving both sides off the one table means a
+ // new row cannot be half-applied, and this asserts the table IS both sides.
+ const persisted = quotaBurnTaskMetadata({
+ family: 'grok', limitingResetAt: 1700000000000, stepId: 'step-1', requestId: 'demand-7',
+ });
+ const projected = quotaBurnAgentMetadata(persisted);
+ for (const { taskKey, agentKey } of QUOTA_BURN_PROVENANCE_FIELDS) {
+ expect(persisted).toHaveProperty(taskKey);
+ expect(projected[agentKey]).toBe(persisted[taskKey]);
+ }
+ expect(Object.keys(projected)).toHaveLength(Object.keys(persisted).length);
+ });
+
+ it('projects a field the task never carried as null, and coerces a round-tripped reset', () => {
+ // `quotaBurnDenials.js` reads `taskQuotaBurnLimitingResetAt` off the agent to
+ // decide how long a refused family stays blocked, and the value may have come
+ // back through markdown as a string.
+ expect(quotaBurnAgentMetadata({ quotaBurnFamily: 'grok', quotaBurnLimitingResetAt: '1700000000000' })).toEqual({
+ taskQuotaBurnFamily: 'grok',
+ taskQuotaBurnLimitingResetAt: 1700000000000,
+ taskQuotaBurnStepId: null,
+ taskQuotaBurnRequestId: null,
+ });
+ expect(quotaBurnAgentMetadata(undefined).taskQuotaBurnFamily).toBeNull();
+ });
+});
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 87525a093b..f64c5e2db3 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -58,6 +58,7 @@ import { buildAgentPrompt, getAppWorkspace, inlinePrLifecycleSection, isClaimFlo
import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';
import { prClaimWasVerified } from '../lib/prDisposition.js';
+import { quotaBurnAgentMetadata } from '../lib/quotaBurnOrigin.js';
import { composeProviderEnv } from '../lib/cliChildEnv.js';
import { cliProviderAuthDescriptor } from '../lib/processEnv.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
@@ -855,14 +856,13 @@ async function runAgentSpawn(task) {
// `taskLiProposal`: the runner listens for `agent:completed` and dispatches
// the NEXT job in this family's burn plan when the previous one finishes,
// so it must be able to tell a burn run from any other agent from the
- // agent record alone.
- taskQuotaBurnFamily: task.metadata?.quotaBurnFamily || null,
- // The reset of the short rolling window that refuses first, carried for the
- // same reason: when this run is REFUSED, the continuation blocks the family
- // until that window rolls instead of re-dispatching into the same wall
- // (see quotaBurnDenials.js). A COS-TASKS.md round-trip can hand it back as
- // a string, so coerce rather than projecting whatever arrived.
- taskQuotaBurnLimitingResetAt: Number(task.metadata?.quotaBurnLimitingResetAt) || null,
+ // agent record alone. Spread from the ONE block definition
+ // (`lib/quotaBurnOrigin.js`) so every field that reaches disk reaches the
+ // runner's continuation and the denial ledger — naming them here one at a
+ // time is how `quotaBurnStepId` ended up persisted but unprojected (#6406).
+ // Values are coerced on the way through: a COS-TASKS.md round-trip hands
+ // every scalar back as a string.
+ ...quotaBurnAgentMetadata(task.metadata),
// Same reason as taskLiProposal — a hand-picked projection, so this must be
// listed explicitly. `declaresNoCommitCriterion` (taskTypeHooks.js) reads it
// to decide whether a run declared a commit criterion at all,
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index af6ba7b32d..3b4694e94b 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -919,3 +919,17 @@ describe('runAgentSpawn source — local prompt/prefill budget (#6117)', () => {
expect(metaSlice).toMatch(/\blocalPromptBudget,/);
});
});
+
+// Source-level assertion (#6406): agent.metadata is a hand-picked projection of
+// task.metadata, so a provenance key the projection forgets is a field that
+// reaches disk and never reaches the runner's completion continuation or the
+// denial ledger — exactly what happened to `quotaBurnStepId`. The projection has
+// to derive from the one block definition in lib/quotaBurnOrigin.js (whose own
+// test pins that the block covers every persisted field), which means naming a
+// `taskQuotaBurn*` key by hand here is the regression.
+describe('runAgentSpawn source — quota-burn provenance projection (#6406)', () => {
+ it('spreads the shared provenance block instead of naming its keys', () => {
+ expect(AGENT_LIFECYCLE_SRC).toMatch(/\.\.\.quotaBurnAgentMetadata\(task\.metadata\)/);
+ expect(AGENT_LIFECYCLE_SRC.match(/^\s*taskQuotaBurn\w*\s*:/gm) || []).toEqual([]);
+ });
+});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index a825ff4332..b771726ca5 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -30,7 +30,7 @@ import { sanitizeTaskMetadata, PIPELINE_STAGE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS,
import { PATHS } from '../lib/fileUtils.js';
import { MODEL_ABUSE_GUARD_ID, normalizeEligibilityFacts } from '../lib/modelAbuseGuard.js';
import { isPlainObject } from '../lib/objects.js';
-import { onDemandRequestMetadata } from '../lib/quotaBurnOrigin.js';
+import { hasQuotaBurnProvenance, onDemandRequestMetadata } from '../lib/quotaBurnOrigin.js';
import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';
import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunning } from './cosState.js';
import { getDomainMode } from '../lib/domainAutonomy.js';
@@ -161,7 +161,10 @@ export function exceedsMaxSpawns(task) {
* exempt and therefore keeps completing) it never lapses — and the burn task
* sits in Pending until its window resets unspent, which is the exact outcome
* quota burn exists to prevent. (Tasks queued before this stamp existed are
- * back-filled by migration 225, so the predicate reads metadata only.)
+ * back-filled by migration 225, so the predicate reads metadata only.) Read
+ * through `hasQuotaBurnProvenance` rather than the raw key so this gate stays
+ * tied to the one block definition in `lib/quotaBurnOrigin.js` — a task
+ * written by any release, in either the flat or the block shape, is exempt.
*
* `metadata.perpetual` is a bare boolean set upstream, but it round-trips through
* COS-TASKS.md as the STRING `"true"` (taskParser serializes non-string/-object
@@ -178,7 +181,7 @@ export function isCooldownExemptTask(task) {
if (!meta) return false;
return meta.pipeline?.currentStage > 0
|| meta.perpetual === true || meta.perpetual === 'true'
- || Boolean(meta.quotaBurnFamily);
+ || hasQuotaBurnProvenance(meta);
}
/**
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index d97ad058cc..1c2bb9522d 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -449,6 +449,13 @@ describe('isCooldownExemptTask', () => {
it('exempts a quota-burn task so a busy app cannot starve it', () => {
expect(isCooldownExemptTask({ metadata: { app: 'app-1', quotaBurnFamily: 'agy' } })).toBe(true);
});
+ // Both provenance shapes, because installs upgrade independently: the flat key
+ // is what every task written by a previous release (and every task migration
+ // 225 back-filled) carries, and the block is what a producer may hand over as
+ // a unit. Neither may fall out of the exempt set. See lib/quotaBurnOrigin.js.
+ it('exempts a burn whose provenance arrives as one block', () => {
+ expect(isCooldownExemptTask({ metadata: { app: 'app-1', quotaBurn: { family: 'agy', stepId: 'step-1' } } })).toBe(true);
+ });
// Deliberately metadata-only — a task queued before the stamp existed is
// back-filled by scripts/migrations/225-quota-burn-task-provenance.js, not
// recognised here by sniffing its description. That keeps a user-visible
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 88d3f2b322..27bcaeb82e 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -26,6 +26,7 @@ import { REQUEUED_AT_KEY } from '../lib/taskRequeue.js';
import { isInvestigationTask } from '../lib/investigationTasks.js';
import { PAUSED_BLOCKED_CATEGORIES, USER_DECISION_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';
import { splitTaskPromptFields } from '../lib/cosTaskPrompt.js';
+import { quotaBurnProvenance, quotaBurnTaskMetadata } from '../lib/quotaBurnOrigin.js';
import { normalizeOrchestrationMode, normalizeOrchestrationProfile } from '../lib/orchestrationProfile.js';
import { loadState, withStateLock, ROOT_DIR } from './cosState.js';
import { cosEvents } from './cosEvents.js';
@@ -527,23 +528,16 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
if (taskData.liProposal && typeof taskData.liProposal === 'object' && !Array.isArray(taskData.liProposal)) {
metadata.liProposal = taskData.liProposal;
}
- // Which provider family's window this burn task is spending. Read by
- // `isCooldownExemptTask` (cosTaskGenerator.js, which owns the why) and by
- // quotaBurnRunner's completion continuation.
- if (taskData.quotaBurnFamily) metadata.quotaBurnFamily = taskData.quotaBurnFamily;
- // The reset of the SHORT rolling window that will refuse first, so a run the
- // provider refuses can block that family until the window rolls rather than
- // letting the continuation re-dispatch into the same wall (the weekly card
- // it gates on still reads healthy). See quotaBurnDenials.js.
- if (Number.isFinite(taskData.quotaBurnLimitingResetAt)) {
- metadata.quotaBurnLimitingResetAt = taskData.quotaBurnLimitingResetAt;
- }
- // Which STEP of the plan asked. The built-in lane stamps this (and the
- // request id) straight onto the generated task's metadata via
- // `lib/quotaBurnOrigin.js`; a custom-job burn reaches disk through this
- // non-raw path instead, so the key has to be mapped here or the two lanes
- // would carry different provenance for the same feature.
- if (taskData.quotaBurnStepId) metadata.quotaBurnStepId = taskData.quotaBurnStepId;
+ // Quota-burn provenance — which family's window this task spends, which
+ // window will refuse first, which burn step asked, and which on-demand
+ // request (if any) it was generated for. The built-in lane stamps these onto
+ // the generated task's metadata via `lib/quotaBurnOrigin.js` and reaches disk
+ // through the RAW path above; a custom-job burn reaches disk through this
+ // non-raw path instead. Both spread the SAME block so the two lanes cannot
+ // carry different provenance for the same feature — mapping the keys one at
+ // a time here is how `quotaBurnStepId` came to reach disk without ever
+ // reaching the agent (#6406). `quotaBurnOrigin.js` owns the why of each field.
+ Object.assign(metadata, quotaBurnTaskMetadata(quotaBurnProvenance(taskData)));
if (planOnly) {
// Plan-and-file is a single bounded CoS action. The bundled plan-task
// command is already issue-only, so pass its supported `--yes` flag to
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 2ce6ac9922..64eb1dec51 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -732,19 +732,46 @@ describe('cosTaskStore.addTask', () => {
expect(created.metadata.investigationFingerprint).toBeUndefined();
});
- it('persists quota-burn provenance and omits it for every other task', async () => {
+ it('persists the whole quota-burn provenance block and omits it for every other task', async () => {
// `metadata` is an allowlist, so an unlisted key is silently dropped — and a
// dropped `quotaBurnFamily` makes the queued burn indistinguishable from any
// other system task at the cooldown gate and the completion continuation.
+ // Every field of the block reaches disk together (#6406): mapping them one
+ // at a time is how `quotaBurnRequestId` came to reach disk on the raw path
+ // only, so the two burn lanes carried different provenance.
const burn = await addTask(
- { description: '[Quota burn: agy] Perf', app: 'portos', quotaBurnFamily: 'agy' },
+ {
+ description: '[Quota burn: agy] Perf',
+ app: 'portos',
+ quotaBurnFamily: 'agy',
+ quotaBurnLimitingResetAt: 1700000000000,
+ quotaBurnStepId: 'step-1',
+ quotaBurnRequestId: 'demand-7',
+ },
'internal',
);
- expect(burn.metadata.quotaBurnFamily).toBe('agy');
+ expect(burn.metadata).toMatchObject({
+ quotaBurnFamily: 'agy',
+ quotaBurnLimitingResetAt: 1700000000000,
+ quotaBurnStepId: 'step-1',
+ quotaBurnRequestId: 'demand-7',
+ });
const ordinary = await addTask({ description: 'not a burn' }, 'user');
expect(ordinary.metadata.quotaBurnFamily).toBeUndefined();
});
+ it('leaves the request id ABSENT on the synchronous custom-job burn lane', async () => {
+ // That lane queues the task itself, so there is no on-demand request to name
+ // and a synthesized (or null) id would make a join over it silently wrong.
+ const burn = await addTask(
+ { description: '[Quota burn: agy] Custom job', app: 'portos', quotaBurnFamily: 'agy', quotaBurnStepId: 'step-2' },
+ 'internal',
+ );
+ expect(burn.metadata).not.toHaveProperty('quotaBurnRequestId');
+ const { tasks } = await getCosTasks();
+ expect(tasks.find(t => t.id === burn.id).metadata).not.toHaveProperty('quotaBurnRequestId');
+ });
+
it('omits diagnostics metadata when none is supplied and ignores a non-object / array value', async () => {
const created = await addTask({ description: 'no diagnostics here' }, 'user');
expect(created.metadata.diagnostics).toBeUndefined();