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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
require model:/effort: labels on quota-burn audit issues and front-load research
[._.]/ Adam Eivy58c105585336
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex abf72344d0..98139b1d2b 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -252,17 +252,33 @@ issues, and changes nothing:| Security issues | Real exposure under the documented threat model — findings that contradict it are noise |Presets are **templates**: picking one COPIES its prompt into the job's own-`params.prompt`, and nothing on disk points back at the preset id. So editing the-text here never rewrites a configured job on any install (no migration needed) —-and an improved prompt reaches an existing job only when the user re-picks it.--Each audit prompt now tells the agent to apply independent slashdo dispatch-hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) and-contributor labels (`good first issue`, `help wanted`) when the finding-justifies them, create missing labels lazily, and keep category labels-(`plan`, `ux`, `bug`, `tests`, …) intact. Existing jobs keep whatever prompt-was copied when they were created; re-pick the preset to pick up the new-filing contract.+`params.prompt`, and nothing on disk points back at the preset id. So a contract+revision reaches configured jobs only through a migration — and the shape of+that migration matters. Every rendered prompt is two halves split by the+`## How to run this audit` line: the **mission** above it (what to audit, one+per preset, essentially stable) and the **contract** below it (how to audit,+shared, and the half that keeps being revised). `upgradeStoredAuditPrompt`+matches on the mission and replaces the contract, so a job seeded several+revisions ago still upgrades; it refuses when the stored contract has lost the+sentences every shipped render carried, which is how a user's own procedure is+recognized and left alone. Copy migration 305 for the next contract edit —+**not** migration 294, whose byte-for-byte rule matched nothing older than one+revision and silently stranded every real job on a prompt that predated the+dispatch-label guidance entirely.++Each audit prompt spends **roughly the first two thirds of the window on+research**: trace each candidate end to end, read the tests and `git log` around+it, name the path that actually reaches the failure, and decide the fix (files,+tests, and the rejected alternative) before filing. The cap stays at 5 issues+with two or three as the target — depth over volume.++Filing carries a **required** label contract: exactly one `model:` and exactly+one `effort:` label on every issue, chosen as independent axes from the code the+agent just read (`MANDATORY_DISPATCH_HINT_GUIDANCE` in `server/lib/dispatchLabels.js`).+Contributor labels (`good first issue`, `help wanted`) stay optional, missing+labels are created lazily, category labels (`plan`, `ux`, `bug`, `tests`,+`area:*`, …) are preserved, and the agent reads each new issue's labels back to+repair any that did not stick.### The "lands no code" posturesAn `agent-prompt` job has two of them, and they are not the same thing:diff --git a/scripts/migrations/305-refresh-quota-burn-audit-contract.js b/scripts/migrations/305-refresh-quota-burn-audit-contract.jsnew file mode 100644index 0000000000..99753ac415--- /dev/null+++ b/scripts/migrations/305-refresh-quota-burn-audit-contract.js@@ -0,0 +1,68 @@+/**+ * Refresh stored quota-burn audit prompts to the current shared contract.+ *+ * Picking a preset COPIES its text into the job's own `params.prompt`, and that+ * snapshot carries no version marker, so a contract revision reaches existing+ * jobs only through a migration. Migration 294 supplied one, but matched a+ * stored prompt byte-for-byte against a single reconstructed prior render —+ * which a job seeded two revisions ago can never equal. Every real job on the+ * install that motivated this migration was therefore counted "user-edited" and+ * left running a contract that predated the dispatch-label guidance entirely,+ * so an entire backlog of filed issues arrived with no `model:`/`effort:` labels+ * for the dispatcher to route on.+ *+ * `upgradeStoredAuditPrompt` replaces that rule with one that survives any+ * number of contract revisions: match the MISSION half (what to audit — stable),+ * replace the CONTRACT half (how to audit — the part that keeps changing), and+ * refuse when the stored contract has lost the sentences every shipped render+ * carried, which is how a user's own procedure is recognized and left alone.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { upgradeStoredAuditPrompt } from '../../server/lib/quotaBurnPresets.js';++const QUOTA_BURN_PATH = join('data', 'cos', 'quota-burn.json');++async function readJson(path) {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++export default {+ async up({ rootDir }) {+ const fullPath = join(rootDir, QUOTA_BURN_PATH);+ const config = await readJson(fullPath);+ if (!config?.families) return { updated: 0 };++ let updated = 0;+ let skipped = 0;++ for (const [familyId, family] of Object.entries(config.families)) {+ for (const job of family?.jobs || []) {+ const stored = job?.params?.prompt;+ if (typeof stored !== 'string') continue;+ const upgraded = upgradeStoredAuditPrompt(stored);+ if (!upgraded) {+ skipped += 1;+ continue;+ }+ job.params.prompt = upgraded;+ updated += 1;+ console.log(`📝 ${QUOTA_BURN_PATH}: refreshed ${familyId}/${job.id || 'job'} audit contract`);+ }+ }++ if (updated) await writeFile(fullPath, `${JSON.stringify(config, null, 2)}\n`);+ if (skipped) console.log(`✋ ${QUOTA_BURN_PATH}: left ${skipped} custom or already-current prompt(s) untouched`);+ return { updated, skipped };+ },+};diff --git a/scripts/migrations/305-refresh-quota-burn-audit-contract.test.js b/scripts/migrations/305-refresh-quota-burn-audit-contract.test.jsnew file mode 100644index 0000000000..ad605b3ca4--- /dev/null+++ b/scripts/migrations/305-refresh-quota-burn-audit-contract.test.js@@ -0,0 +1,85 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './305-refresh-quota-burn-audit-contract.js';+import { AUDIT_CONTRACT_HEADING, QUOTA_BURN_PROMPT_PRESETS } from '../../server/lib/quotaBurnPresets.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++const preset = QUOTA_BURN_PROMPT_PRESETS[0];+const currentPrompt = preset.params.prompt;+const mission = currentPrompt.slice(0, currentPrompt.indexOf(AUDIT_CONTRACT_HEADING));++/**+ * A plausible OLD render: the shipped mission verbatim, plus a contract that+ * still carries the anchors every shipped revision has had but none of this+ * revision's wording. This is the shape migration 294 could not match — it is+ * neither the current render nor the one specific prior render 294 rebuilt.+ */+const staleContract = `${AUDIT_CONTRACT_HEADING}++1. **Pick a bounded slice and say so first.** Audit one area.+2. **File each finding.** \`gh issue create --title "..." --body-file "$BODY"\`.+ Suggested labels: \`ux\`, \`plan\`. Run \`gh label list\` first.+3. **Change no code.** The deliverable is the filed issues.+4. **Report at the end**: the slice you audited and each issue number.+`;+const stalePrompt = `${mission}${staleContract}`;++const config = (prompt) => ({+ families: { claude: { enabled: true, jobs: [{ id: 'job-1', jobType: 'agent-prompt', params: { appId: 'app-1', prompt } }] } },+});+const storedPrompt = (path) => readJson(path).families.claude.jobs[0].params.prompt;++describe('migration 305 — refresh quota-burn audit contract', () => {+ let rootDir;+ let configPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-305-'));+ mkdirSync(join(rootDir, 'data/cos'), { recursive: true });+ configPath = join(rootDir, 'data/cos/quota-burn.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('upgrades a stale shipped render that byte-for-byte matching would have skipped', async () => {+ writeJson(configPath, config(stalePrompt));+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ expect(storedPrompt(configPath)).toBe(currentPrompt);+ });++ it('leaves a prompt whose How-to-run section the user rewrote', async () => {+ // Mission intact, procedure replaced — the anchors are gone, so this is the+ // user's own contract and refreshing it would delete their instructions.+ const custom = `${mission}${AUDIT_CONTRACT_HEADING}\n\nJust tell me what you find in chat. Do not file anything.\n`;+ writeJson(configPath, config(custom));+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(storedPrompt(configPath)).toBe(custom);+ });++ it('leaves a prompt whose mission the user rewrote', async () => {+ const custom = `# Audit the payments flow only\n\n${staleContract}`;+ writeJson(configPath, config(custom));+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(storedPrompt(configPath)).toBe(custom);+ });++ it('is a no-op on an already-current prompt and rewrites no file', async () => {+ writeJson(configPath, config(currentPrompt));+ const before = readFileSync(configPath, 'utf8');+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(readFileSync(configPath, 'utf8')).toBe(before);+ });++ it('returns cleanly when the install has no quota-burn config', async () => {+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0 });+ });+});diff --git a/server/lib/dispatchLabels.js b/server/lib/dispatchLabels.jsindex a30f60ae09..77e3140753 100644--- a/server/lib/dispatchLabels.js+++ b/server/lib/dispatchLabels.js@@ -299,6 +299,30 @@ export const DISPATCH_HINT_GUIDANCE = [ISSUE_QUALITY_GUIDANCE,].join('\n');+/**+ * Mandatory-axis sibling of `DISPATCH_HINT_GUIDANCE`, for producers that read+ * the target code closely before filing — the quota-burn audits, which spend+ * most of a window researching one slice and arrive at a chosen fix.+ *+ * The general guidance keeps both axes optional because most callers file from+ * thinner evidence, and a guessed hint is worse than none. That reasoning does+ * not transfer here: an agent that has traced the failure and decided the fix+ * already knows how the work should run, so "omit rather than guess" just+ * strands the issue with no routing at all — which is exactly what happened to+ * the audit issues filed before this contract existed. Same vocabulary and the+ * same colors as the optional form; only the obligation differs.+ */+export const MANDATORY_DISPATCH_HINT_GUIDANCE = [+ 'Dispatch labels are REQUIRED on every issue you file: exactly one `model:` and exactly one `effort:`. They are two independent axes describing HOW to run the work, not how big it is — pick each from the code you just read.',+ '- `model:light|medium|heavy` — capability: light is mechanical (rename, config, a well-specified single-file edit); medium is routine multi-file work; heavy is genuinely hard reasoning (concurrency, schema/compatibility design, redesign).',+ '- `effort:low|medium|high|xhigh|max` — reasoning budget per step, independent of model. `model:light` + `effort:max` is a mechanical sweep across many call sites; `model:heavy` + `effort:low` is a two-line change that hinges on one idea.',+ 'Never derive one axis from the other, and do NOT stamp `medium` on both by reflex — where that genuinely is the answer, justify it in one line of the body. Do NOT put `[model:…]` / `[effort:…]` / `[category]` / `[SEVERITY]` in the title; those belong in labels.',+ 'Create each label immediately before applying it (`gh label create <name> --color <hex> 2>/dev/null || true`; glab needs `--name` and `#<hex>`). Colors: model:light D4C5F9, model:medium A371F7, model:heavy 6F42C1, effort:low BFE5E5, effort:medium 76C7C7, effort:high 1D7874, effort:xhigh 0E4F4C, effort:max 05403D.',+ 'Contributor labels stay OPTIONAL and independent: `good first issue` (color 7057FF) when the work is self-contained enough for a new contributor with no deep repo context — a `model:light` 40-file sweep is NOT one — and `help wanted` (color 008672) when the body is scoped enough to pick up cold. Same `label create` form.',+ 'Use repeated `--label` flags (one per label). Preserve existing category/scope labels (`plan`, `ux`, `bug`, `tests`, `area:*`, …). After creating each issue, read its labels back (`gh issue view <number> --json labels`) and apply any that did not stick. Never relabel a deduplicated existing issue.',+ ISSUE_QUALITY_GUIDANCE,+].join('\n');+/*** Jira sibling of `DISPATCH_HINT_GUIDANCE`. Same vocabulary, hyphenated label* names (`model-light`, `effort-max`) because a colon is unsafe on some Jiradiff --git a/server/lib/dispatchLabels.test.js b/server/lib/dispatchLabels.test.jsindex 62482297fd..0d451ab038 100644--- a/server/lib/dispatchLabels.test.js+++ b/server/lib/dispatchLabels.test.js@@ -5,6 +5,7 @@ import {DISPATCH_LABEL_COLORS,ISSUE_QUALITY_GUIDANCE,DISPATCH_HINT_GUIDANCE,+ MANDATORY_DISPATCH_HINT_GUIDANCE,JIRA_DISPATCH_HINT_GUIDANCE,PORTOS_AREA_LABELS,PORTOS_AREA_LABEL_GUIDANCE,@@ -196,6 +197,26 @@ describe('shared guidance', () => {expect(JIRA_DISPATCH_HINT_GUIDANCE).not.toMatch(/model:light/);});+ it('keeps the mandatory variant on the same vocabulary but inverts the obligation', () => {+ // Same axes, same colors, same label-create idiom — the ONLY difference is+ // that both axes are required. A drifted second copy of the vocabulary is+ // exactly what this module exists to prevent.+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).toContain('model:light|medium|heavy');+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).toContain('effort:low|medium|high|xhigh|max');+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).toContain('good first issue');+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).toContain('help wanted');+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).toContain('Issue-quality gate');+ for (const name of Object.keys(DISPATCH_LABEL_COLORS)) {+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).toContain(`${name} ${DISPATCH_LABEL_COLORS[name]}`);+ }+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).toContain('REQUIRED on every issue you file');+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).not.toContain('Omit an axis rather than guessing');+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).not.toContain('are optional');+ // Contributor labels stay optional in BOTH forms — requiring them would+ // advertise unattended-agent work to humans who never asked for it.+ expect(MANDATORY_DISPATCH_HINT_GUIDANCE).toContain('stay OPTIONAL');+ });+it('keeps the PortOS area vocabulary and repo-study complete-label contract explicit', () => {expect(PORTOS_AREA_LABELS).toContain('area:cos-agents');expect(PORTOS_AREA_LABELS).toContain('area:media');diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.jsindex 884b3d4dde..57d38c527f 100644--- a/server/lib/quotaBurnConfig.js+++ b/server/lib/quotaBurnConfig.js@@ -97,7 +97,13 @@ export const QUOTA_BURN_BOUNDS = Object.freeze({jobsPerFamily: { max: 25 },idLength: { max: 64 },labelLength: { max: 120 },- paramLength: { max: 8000 },+ // Sized for the longest thing a param actually holds: an audit preset's work+ // prompt. At 8000 the largest shipped preset rendered to 7999 — one character+ // of headroom — so the next sentence added to the shared audit contract would+ // have been silently sliced off the END of every stored preset job, taking the+ // "change no code" and redaction rules with it and leaving nothing on screen+ // saying so. The cap exists to bound a runaway paste, not to fit the presets.+ paramLength: { max: 16000 },});const BOUNDS = QUOTA_BURN_BOUNDS;diff --git a/server/lib/quotaBurnPresets.js b/server/lib/quotaBurnPresets.jsindex 9275c44198..5b6be6114f 100644--- a/server/lib/quotaBurnPresets.js+++ b/server/lib/quotaBurnPresets.js@@ -15,19 +15,26 @@* on any install and there is no migration to write — the cost is that an* improved prompt reaches existing jobs only when the user re-picks the preset.*- * ONE exception exists: #4852 renamed the agent-instructions file this contract- * tells the agent to read, and a stored job naming CLAUDE.md but not AGENTS.md- * would send an agent to a file its target repo may no longer have. Migration- * 294 rewrites those job prompts — but ONLY where the stored string is byte-for-byte- * a prior unmodified render, which is the same 'unmodified default ⇒ safe to- * upgrade' rule PREVIOUS_DEFAULT_PROMPTS uses. Any future preset edit that must- * reach existing jobs needs the same treatment.+ * A contract change that must reach EXISTING jobs therefore needs a migration.+ * Two exist, and the second supersedes the first's matching rule:+ *+ * - Migration 294 (#4852, the CLAUDE.md → AGENTS.md rename) matched a stored+ * prompt byte-for-byte against a reconstructed prior render. That rule turned+ * out to be too strict to be useful: a job seeded two contract revisions ago+ * matches no single reconstructed render, so 294 skipped every real job on+ * this install as "user-edited" and they kept running a prompt that predated+ * the dispatch-label guidance entirely — which is why a whole quota-burn+ * backlog arrived with no `model:`/`effort:` routing on it.+ * - Migration 305 matches on the MISSION half instead (everything above+ * `## How to run this audit`, the part that says WHAT to audit) and replaces+ * the contract half, which is the part this file owns and revises. Copy that+ * migration for the next contract edit rather than 294's.** Pure module: strings only, no I/O. `routes/quotaBurn.js` serves the list in* the config catalog; the client's preset picker applies one to a job row.*/-import { DISPATCH_HINT_GUIDANCE } from './dispatchLabels.js';+import { MANDATORY_DISPATCH_HINT_GUIDANCE } from './dispatchLabels.js';import { QUOTA_BURN_JOB_TYPE } from './quotaBurnConfig.js';/** Params every audit preset sets, and why they differ from the job defaults. */@@ -58,6 +65,16 @@ const AUDIT_PARAMS = Object.freeze({simplify: false,});+/**+ * The line that splits a rendered audit prompt in two: above it the MISSION+ * (what to audit — one per preset, essentially stable), below it the CONTRACT+ * (how to audit — shared, and the half this file keeps revising).+ *+ * Exported because that split is what lets a migration tell a stale shipped+ * render apart from a prompt the user wrote over. See `upgradeStoredAuditPrompt`.+ */+export const AUDIT_CONTRACT_HEADING = '## How to run this audit';+/*** The half of every audit prompt that is about HOW to audit rather than WHAT to* audit. Written once so a lesson learned from one bad run (a preset that filed@@ -65,21 +82,37 @@ const AUDIT_PARAMS = Object.freeze({* preset at once.*/const auditContract = ({ labels, dedupeSearch }) => `-## How to run this audit+${AUDIT_CONTRACT_HEADING}++Most of this window belongs to RESEARCH, not to filing. Two issues another agent+can execute cold — trigger named, fix decided, files listed — are worth more than+five it has to re-investigate from scratch. Spend roughly the first two thirds of+the window reading and tracing, and only then start filing.1. **Pick a bounded slice and say so first.** Do NOT attempt the wholerepository. Choose one coherent area (a feature directory, a route group, ahandful of related screens) — prefer one that recent audit issues have notalready covered — and open your report by naming the slice in one line.-2. **Read the actual code.** Every finding must cite \`path/to/file.js:LINE\` and- describe a concrete, reproducible failure: what a user does, in what state,- and what goes wrong. Delete any finding you cannot state that way — that+2. **Research each candidate before you judge it.** Read the whole file, not the+ lines your search matched. Trace the value end to end: where it is set, who+ else reads it, and what each caller does when it fails. Read the tests that+ already cover it, and check \`git log -n 5 -- <file>\` for why the code is+ shaped the way it is — code that looks wrong is often load-bearing. Drop any+ candidate you cannot walk through this way; a hunch is not a finding.+3. **Prove the trigger.** Every finding must cite \`path/to/file.js:LINE\` and+ name the path that actually reaches it — which user action, route, event, or+ scheduled job, in what state — plus what goes wrong and who notices. If you+ cannot name a reachable trigger, the finding is a guess: delete it. Thatfilter is the whole point of this job.-3. **De-duplicate before filing.** Run+4. **Decide the fix before you file it.** Name the approach, every file it+ touches, and the tests to add or change. Where you had a real choice, say+ which option you rejected and why in one line. If the only obstacle was a+ design decision, make the call — do not file a question.+5. **De-duplicate before filing.** Run\`gh issue list --state open --limit 200 --search "${dedupeSearch}"\` (and aplain keyword search per finding). If it is already filed, skip it; comment onthe existing issue only when you have genuinely new evidence.-4. **File each surviving finding as its own issue.** Write the body to a scratch+6. **File each surviving finding as its own issue.** Write the body to a scratchfile OUTSIDE the repository — \`BODY=$(mktemp)\` — then create with repeated\`--label\` flags:\`gh issue create --title "..." --body-file "$BODY" --label ...\`. Keep scratch@@ -88,21 +121,24 @@ const auditContract = ({ labels, dedupeSearch }) => `anything you leave behind is left in the user's working tree. Categorylabels (create each missing one immediately before applying it —\`gh label create <name> --color 0366D6 2>/dev/null || true\`):- ${labels}. Then add independent dispatch hints when the finding justifies- them. ${DISPATCH_HINT_GUIDANCE.split('\n').join(' ')} One problem per+ ${labels}. Then the required dispatch labels.+ ${MANDATORY_DISPATCH_HINT_GUIDANCE.split('\n').join(' ')} One problem perissue — never a bundle. Do not relabel an existing issue you skipped as aduplicate.-5. **Bodies must be decision-complete**, in this shape:+7. **Bodies must be decision-complete**, in this shape:- **Problem** — what is wrong, with file:line references.+ - **Trigger** — the path that reaches it: the action, the state, the caller.- **Impact** — the user-visible consequence, not the code smell.- - **Fix** — the approach you have DECIDED on, with the files it touches. If- the only obstacle was a design choice, make the call and state it with a- one-line rationale. Do not file a question.+ - **Fix** — the approach you have DECIDED on, the files it touches, the tests+ to add or change, and the alternative you rejected with a one-line+ rationale. Do not file a question.- **Acceptance criteria** — checkboxes another agent can verify cold.-6. **Cap yourself at 5 issues.** A handful of well-evidenced, ready-to-work- issues is worth more than a wall of nits, and a long tail of low-value issues- costs a human real triage time. Fewer than 5 real problems? File fewer.-7. **Redact before you publish.** An issue is world-readable the moment it is+8. **Cap yourself at 5 issues, and aim for two or three.** Depth is the+ deliverable: a handful of researched, ready-to-work issues is worth more than+ a wall of nits, and a long tail of low-value issues costs a human real triage+ time. Fewer than 5 real problems? File fewer, and spend the time you save+ going deeper on the ones you keep or widening the slice you researched.+9. **Redact before you publish.** An issue is world-readable the moment it isfiled. Never paste a secret, credential, token, hostname, IP address, absolutepath containing a username, or any personal record into a title or body — citethe location and redact the value (\`<token>\`, \`<hostname>\`, \`<user-email>\`).@@ -111,13 +147,14 @@ const auditContract = ({ labels, dedupeSearch }) => `Report it in your final summary to the user, say it needs rotating, and fileat most a location-free issue ("a committed credential needs rotating andpurging from history — details in the run summary").-8. **Change no code.** No edits, no commits, no branches, no pull requests, and+10. **Change no code.** No edits, no commits, no branches, no pull requests, andno \`git checkout\`/\`switch\` — you are standing in the user's live checkout ofthis repository, so an edit or a branch change is felt immediately by whoeveris working in it. The deliverable is the filed issues, and the run must endwith the same \`git status\` and the same branch it started on.-9. **Report at the end**: the slice you audited, each issue number and title, and- anything you deliberately did not file and why.+11. **Report at the end**: the slice you audited, what you traced and ruled out,+ each issue number and title, and anything you deliberately did not file and+ why.If \`gh\` cannot reach the network (errors like "bad file descriptor" or aconnect timeout), do not give up silently — fall back to the REST API with the@@ -608,3 +645,49 @@ proposed replacement text with rationale.`,export function findQuotaBurnPreset(id) {return QUOTA_BURN_PROMPT_PRESETS.find((preset) => preset.id === id) || null;}++/**+ * Sentences every shipped render of the contract has carried. A stored prompt+ * missing one is not a shipped contract — it is a user's own How-to-run section,+ * and refreshing it would silently delete their instructions.+ *+ * Deliberately drawn from the OLDEST wording still in the field, not the newest:+ * a phrase this revision introduced would match nothing and make the upgrade a+ * no-op on exactly the stale jobs it exists to rescue.+ */+const SHIPPED_CONTRACT_ANCHORS = Object.freeze([+ 'Pick a bounded slice and say so first',+ 'gh issue create',+ 'Change no code.',+ 'Report at the end',+]);++/**+ * The current render for a stored audit prompt that is still a shipped preset,+ * or `null` to leave the stored text exactly as it is.+ *+ * Matching is on the MISSION half — everything above `AUDIT_CONTRACT_HEADING` —+ * rather than on the whole string. A job seeded N contract revisions ago matches+ * no reconstructed prior render byte-for-byte (that is why migration 294 skipped+ * every real job as "user-edited"), but its mission half is unchanged, because+ * revisions land in the contract. Requiring the stored contract to still carry+ * `SHIPPED_CONTRACT_ANCHORS` keeps the looser rule from overwriting a user who+ * kept a preset's mission and wrote their own procedure under it.+ *+ * Returns `null` when the prompt is already current, so a caller can count real+ * upgrades without diffing.+ */+export function upgradeStoredAuditPrompt(stored) {+ if (typeof stored !== 'string' || !stored.includes(AUDIT_CONTRACT_HEADING)) return null;+ const index = stored.indexOf(AUDIT_CONTRACT_HEADING);+ const storedMission = stored.slice(0, index);+ const storedContract = stored.slice(index);+ if (!SHIPPED_CONTRACT_ANCHORS.every((anchor) => storedContract.includes(anchor))) return null;++ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {+ const current = preset.params.prompt;+ if (current.slice(0, current.indexOf(AUDIT_CONTRACT_HEADING)) !== storedMission) continue;+ return current === stored ? null : current;+ }+ return null;+}diff --git a/server/lib/quotaBurnPresets.test.js b/server/lib/quotaBurnPresets.test.jsindex be1e6e0fc4..45154e3734 100644--- a/server/lib/quotaBurnPresets.test.js+++ b/server/lib/quotaBurnPresets.test.js@@ -1,5 +1,10 @@import { describe, expect, it } from 'vitest';-import { QUOTA_BURN_PROMPT_PRESETS, findQuotaBurnPreset } from './quotaBurnPresets.js';+import {+ AUDIT_CONTRACT_HEADING,+ QUOTA_BURN_PROMPT_PRESETS,+ findQuotaBurnPreset,+ upgradeStoredAuditPrompt,+} from './quotaBurnPresets.js';import { QUOTA_BURN_BOUNDS, QUOTA_BURN_JOB_CATALOG, QUOTA_BURN_JOB_TYPES, normalizeQuotaBurnJob } from './quotaBurnConfig.js';import { quotaBurnConfigUpdateSchema } from './quotaBurnValidation.js';@@ -94,12 +99,18 @@ describe('QUOTA_BURN_PROMPT_PRESETS', () => {}});- it('teaches every audit preset the independent model/effort dispatch contract', () => {+ it('requires both dispatch axes on every issue an audit files', () => {+ // The optional form of this guidance ("omit an axis rather than guessing")+ // is right for producers filing from thin evidence and wrong here: an audit+ // that traced the failure and chose the fix already knows how the work+ // should run, and omitting the axes strands the issue with no routing —+ // which is what shipped a whole backlog of unlabeled audit issues.for (const preset of QUOTA_BURN_PROMPT_PRESETS) {const prompt = preset.params.prompt;+ expect(prompt).toContain('REQUIRED on every issue you file');expect(prompt).toContain('model:light|medium|heavy');expect(prompt).toContain('effort:low|medium|high|xhigh|max');- expect(prompt).toContain('Omit an axis rather than guessing');+ expect(prompt).not.toContain('Omit an axis rather than guessing');expect(prompt).toContain('repeated `--label`');expect(prompt).toContain('gh label create');expect(prompt).toContain('Do not relabel an existing issue');@@ -109,6 +120,57 @@ describe('QUOTA_BURN_PROMPT_PRESETS', () => {expect(prompt).toContain('current refactors that pay off now are valid');}});++ it('spends the window on research and demands a traced trigger and a decided fix', () => {+ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {+ const prompt = preset.params.prompt;+ expect(prompt).toContain('Most of this window belongs to RESEARCH');+ expect(prompt).toContain('Research each candidate before you judge it');+ expect(prompt).toContain('Prove the trigger');+ expect(prompt).toContain('Decide the fix before you file it');+ expect(prompt).toContain('the tests to add or change');+ }+ });++ it('keeps real headroom under the param length bound', () => {+ // Not a duplicate of the truncation assertion above: that one passed at+ // 7999/8000, one character from silently slicing the redaction and+ // "change no code" rules off the END of every stored preset job. A bound a+ // sentence away from binding is a bound that will bind on the next edit.+ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {+ expect(preset.params.prompt.length).toBeLessThanOrEqual(QUOTA_BURN_BOUNDS.paramLength.max * 0.8);+ }+ });+});++describe('upgradeStoredAuditPrompt', () => {+ const preset = QUOTA_BURN_PROMPT_PRESETS[0];+ const current = preset.params.prompt;+ const mission = current.slice(0, current.indexOf(AUDIT_CONTRACT_HEADING));++ it('refreshes a stale shipped contract while keeping the mission', () => {+ const stale = `${mission}${AUDIT_CONTRACT_HEADING}+1. **Pick a bounded slice and say so first.** Audit one area.+2. \`gh issue create --title "..."\`. Suggested labels: \`ux\`, \`plan\`.+3. **Change no code.**+4. **Report at the end**: each issue number.+`;+ expect(upgradeStoredAuditPrompt(stale)).toBe(current);+ });++ it('returns null for an already-current prompt, so callers count real upgrades', () => {+ expect(upgradeStoredAuditPrompt(current)).toBeNull();+ });++ it('returns null when the user replaced the How-to-run section', () => {+ expect(upgradeStoredAuditPrompt(`${mission}${AUDIT_CONTRACT_HEADING}\n\nJust report findings in chat.\n`)).toBeNull();+ });++ it('returns null for a prompt that is not a preset render at all', () => {+ expect(upgradeStoredAuditPrompt('Refactor the billing module and open a PR.')).toBeNull();+ expect(upgradeStoredAuditPrompt(undefined)).toBeNull();+ expect(upgradeStoredAuditPrompt(null)).toBeNull();+ });});describe('findQuotaBurnPreset', () => {