From 96b5a620375570a8b44deffe7300e26b6231651a Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:09:26 +0800 Subject: [PATCH] fix(jobs): keep the answer in the inbox when the retry is refused (#381) --- changelog.d/381-job-decision.added.md | 1 + docs/api.md | 13 ++ docs/architecture.md | 13 +- src/app.ts | 64 +++++++- src/db.ts | 15 +- src/jobs/service.ts | 58 +++++++- src/lib/uncertainty.ts | 135 +++++++++++++++++ src/views/pages.ts | 7 + test/jobDecision.test.ts | 206 ++++++++++++++++++++++++++ 9 files changed, 505 insertions(+), 7 deletions(-) create mode 100644 changelog.d/381-job-decision.added.md create mode 100644 src/lib/uncertainty.ts create mode 100644 test/jobDecision.test.ts diff --git a/changelog.d/381-job-decision.added.md b/changelog.d/381-job-decision.added.md new file mode 100644 index 00000000..c880e577 --- /dev/null +++ b/changelog.d/381-job-decision.added.md @@ -0,0 +1 @@ +A job can now stop and ask instead of guessing: a terminal callback may carry one bounded `decision`, the job waits as `paused`, the question appears in the existing inbox marked with its job, and the first answer starts exactly one retry whose goal carries the question and the answer. diff --git a/docs/api.md b/docs/api.md index a7e1b829..57d5b525 100644 --- a/docs/api.md +++ b/docs/api.md @@ -580,6 +580,19 @@ branch/PR: { "status": "succeeded", "summary": "Reviewed 6 PRs; average 78.", "reviewScore": 78 } ``` +A terminal callback may carry one `decision` instead of finishing: + +```json +{ "status": "succeeded", "decision": { "question": "Ship the migration now?", "why": "It changes the schema and needs a person.", "options": ["Ship it", "Wait"] } } +``` + +`question` is at most 300 characters, `why` at most 500, and `options` at most +four entries of 80 characters each. The job moves to `paused` with `error` equal +to `why`, the question becomes an inbox card, and the first answer starts exactly +one retry whose goal carries the question and the answer. A second decision on +the same job is refused (`one decision per job`), a `running` heartbeat cannot +carry one, and a malformed decision is refused instead of stored. + `status` may be `running`, `succeeded` or `failed`. A `running` callback is a progress heartbeat: it updates `summary`, `checkpoint` and optionally `branch`, `attribution` or `evidence` without finishing the job or extending diff --git a/docs/architecture.md b/docs/architecture.md index 6d22b719..b9db6cbe 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2180,13 +2180,24 @@ turns the same drift verdict into a release-check link. queued ──► running ──► succeeded │ │ │ ├──► failed - │ └──► timeout ──► failed + │ ├──► timeout ──► failed + │ └──► paused (one decision, waiting for an answer) └──► quota_exhausted ``` - `queued` is written before the runner is called. - `running` is set when the bridge accepts the job (or immediately for the mock). - `succeeded` / `failed` come from the callback or the mock. +- A terminal callback that carries one `decision` does not finish the job: it + moves to `paused` with `error = decision.why`, stores the bounded question in + `jobs.decision_json`, releases its lease and records one `job.decision` event. + The question is an inbox card whose id is `job:`; the first answer is + stored under `decision_json.answer` and starts exactly one retry whose goal + carries the question and the answer. The retry is judged first and the answer + is written only when it was accepted, so an enqueue refusal (`JOB_ACTIVE`, + `QUEUE_FULL`, `REPO_DISABLED`, `PLATFORM_PAUSED`) leaves the card unanswered in + the inbox instead of consuming the question. A second decision or a second + answer is refused, and only that retry resumes the work (#381). - The repo records `last_run_at` and `last_status`; a scheduled job is skipped if another job for the repo is active. `jobs.continuity_json` stores the run digest, `jobs.output_kind` its classification and `jobs.continuity_used` diff --git a/src/app.ts b/src/app.ts index 07951d61..016658e4 100644 --- a/src/app.ts +++ b/src/app.ts @@ -33,6 +33,7 @@ import { assertSafeModelUrl, normalizeDataPolicyUrl, normalizeProviderRegion } f import { assertSafeNotificationWebhook } from './lib/webhook.js' import { quotaView } from './gateway/quota.js' import { parseAttributionJson } from './lib/attribution.js' +import { decisionWithAnswer, jobIdFromQuestionId, jobQuestionId, storedDecision } from './lib/uncertainty.js' import { failureBreakdown } from './lib/failure.js' import { fetchFailureLog, logFailureReason } from './actions/workflowLog.js' import { parseVerification } from './lib/verification.js' @@ -878,9 +879,32 @@ export async function buildApp(options: BuildOptions): Promise { .filter((question) => question.id !== '' && question.question !== '') .map((question) => ({ repoId: repo.id, repoLabel, ...question })) })) - const questions = settled + const teamQuestions = settled .flatMap((result) => result.status === 'fulfilled' ? result.value : []) - .slice(0, 20) + // #381: a paused job that raised a decision is a question in the same list, + // marked with the job as its source. It does not need a live instance: the + // job is waiting on the person, not on a bot session. + const jobQuestions: InboxQuestion[] = [] + for (const repo of repos) { + const repoLabel = `${repo.upstream_owner || repo.owner}/${repo.upstream_name || repo.name}` + for (const job of store.listJobDecisionsForRepo(repo.id, 10)) { + const decision = storedDecision(job.decision_json) + if (decision === null || decision.answer !== null) continue + jobQuestions.push({ + id: jobQuestionId(job.id), + sessionId: '', + question: decision.question, + detail: decision.why, + options: decision.options, + multiSelect: false, + repoId: repo.id, + repoLabel, + source: 'job', + jobId: job.id, + }) + } + } + const questions = [...jobQuestions, ...teamQuestions].slice(0, 20) inboxCache.set(userId, { at: Date.now(), questions }) return questions } @@ -3139,8 +3163,42 @@ export async function buildApp(options: BuildOptions): Promise { `${returnTo}${returnTo.includes('?') ? '&' : '?'}${key}=${encodeURIComponent(message)}` const fail = (message: string) => wantsJson ? reply.code(400).send({ error: message }) : reply.redirect(withMessage('error', message)) const t = translator(request.locale ?? 'zh') + // #381: an inbox card whose id carries the `job:` prefix is a paused job's + // decision, not a live session. The first answer is stored on the job and + // starts exactly one retry through `retryJob`; a second POST replays the + // stored answer and enqueues nothing. + const questionId = text('questionId') + const answer = (text('custom').trim() !== '' ? text('custom').trim() : selected.join(', ')).trim() + const decisionJobId = jobIdFromQuestionId(questionId) + if (decisionJobId !== null) { + if (answer === '') return fail(t('请先填写回答。', 'Write an answer first.')) + const job = store.getJob(decisionJobId) + if (job === undefined || job.repo_id !== repo.id) return fail(t('这个问题已经关闭。', 'This question is already closed.')) + const decision = storedDecision(job.decision_json) + if (decision === null) return fail(t('这个问题已经关闭。', 'This question is already closed.')) + if (decision.answer === null) { + // #381 review: the retry is judged first, and the answer is stored only + // when that retry was accepted. Storing first left a refused answer on + // the row, and an answered row is exactly what removes the card from the + // inbox (`inboxForUser`), so an ordinary refusal — JOB_ACTIVE, + // QUEUE_FULL, REPO_DISABLED, PLATFORM_PAUSED — dropped the person's + // question while no retry existed, and the remaining `Resume` control + // reopened the run without the answer. + const retried = await jobs.retryJob(job.id, viewer.user.id, { decisionAnswer: { question: decision.question, answer } }) + if (!retried.ok) return fail(retried.error ?? t('重试失败。', 'The retry failed.')) + store.updateJob(job.id, { + decision_json: decisionWithAnswer(decision, { text: answer.slice(0, 1000), by: viewer.user.login, at: nowIso() }), + }) + } + store.audit(viewer.user.id, 'team.answer', `${repo.owner}/${repo.name} question=${questionId.slice(0, 80)}`) + store.event('team_intervention', { userId: viewer.user.id, repoId: repo.id, meta: 'answer' }) + store.markQuestionNotificationsRead(viewer.user.id) + inboxCache.delete(viewer.user.id) + if (wantsJson) return { ok: true } + return reply.redirect(withMessage('notice', t('答案已发送。', 'Answer sent.'))) + } try { - await instances.answerQuestion(repo.id, text('sessionId'), text('questionId'), selected, text('custom')) + await instances.answerQuestion(repo.id, text('sessionId'), questionId, selected, text('custom')) } catch (error) { return fail(error instanceof Error ? error.message : String(error)) } diff --git a/src/db.ts b/src/db.ts index 650358a9..19fcb937 100644 --- a/src/db.ts +++ b/src/db.ts @@ -469,6 +469,9 @@ export interface JobRow { callback_fingerprint: string | null path_guard_json: string | null verification_json: string | null + // #381: the uncertainty contract. `decision_json` is the question a paused job + // waits on, plus the first answer under `answer`; no decision means NULL. + decision_json: string | null continuity_json: string | null model_json: string | null provider_id: string | null @@ -1316,6 +1319,7 @@ CREATE TABLE IF NOT EXISTS jobs ( callback_fingerprint TEXT, path_guard_json TEXT, verification_json TEXT, + decision_json TEXT, continuity_json TEXT, model_json TEXT, provider_id TEXT, @@ -2773,6 +2777,8 @@ export class Store { if (!jobColumns.has('callback_fingerprint')) this.run('ALTER TABLE jobs ADD COLUMN callback_fingerprint TEXT') if (!jobColumns.has('path_guard_json')) this.run('ALTER TABLE jobs ADD COLUMN path_guard_json TEXT') if (!jobColumns.has('verification_json')) this.run('ALTER TABLE jobs ADD COLUMN verification_json TEXT') + // #381: additive; every older row reads back as "no decision", which is true. + if (!jobColumns.has('decision_json')) this.run('ALTER TABLE jobs ADD COLUMN decision_json TEXT') if (!jobColumns.has('continuity_json')) this.run('ALTER TABLE jobs ADD COLUMN continuity_json TEXT') if (!jobColumns.has('output_kind')) this.run('ALTER TABLE jobs ADD COLUMN output_kind TEXT') if (!jobColumns.has('continuity_used')) this.run('ALTER TABLE jobs ADD COLUMN continuity_used INTEGER NOT NULL DEFAULT 0') @@ -6055,6 +6061,13 @@ export class Store { return row?.base_sha ?? null } + // #381: the inbox reads the paused jobs that asked a question. Answering one is + // a job decision, not a live-session answer, and a row without a decision is + // simply a paused job somebody else paused. + listJobDecisionsForRepo(repoId: string, limit = 20): JobRow[] { + return this.all("SELECT * FROM jobs WHERE repo_id = ? AND status = 'paused' AND decision_json IS NOT NULL ORDER BY created_at DESC, rowid DESC LIMIT ?", repoId, limit) + } + // #360 review: a work item's job is looked up by the item, not through a window // of the repository's newest jobs. The window said "no job is attached" for a // work item whose job was older than the limit — a false statement, and a @@ -6277,7 +6290,7 @@ export class Store { } - updateJob(id: string, patch: Partial>): void { + updateJob(id: string, patch: Partial>): void { const entries = Object.entries(redactJobText(patch as Record)).filter(([, value]) => value !== undefined) if (entries.length === 0) return const sets: string[] = [] diff --git a/src/jobs/service.ts b/src/jobs/service.ts index b88b4f5b..8c2c0e75 100644 --- a/src/jobs/service.ts +++ b/src/jobs/service.ts @@ -30,6 +30,7 @@ import { levelFromRank, priorityRank, validatePriorityClaim, type PriorityLevel import { validateRelationClaim, type RelationKind } from '../lib/relations.js' import { DEFAULT_DECISION, isDecisionKind, repairDecision, validateDecision, type DecisionKind } from '../lib/taskDecision.js' import { reviewMergeBlock } from '../lib/mergeReview.js' +import { decisionAnswerGoal, parseJobDecision, type JobDecision } from '../lib/uncertainty.js' import { MAX_DIFF_CHARS, adversarialMergeBlock, @@ -335,6 +336,9 @@ export interface CallbackPayload { attribution?: unknown evidence?: unknown checkpoint?: unknown + // #381: a terminal report may carry one decision instead of a result; the job + // pauses with the reason and the question becomes an inbox card. + decision?: unknown followUps?: unknown triage?: unknown } @@ -577,7 +581,7 @@ export class Jobs { // until #360, which is exactly the second-place-to-disagree shape this codebase // keeps paying for. The caller names the actor so the audit row is the same // `job.retried` action either way. - async retryJob(jobId: string, actorUserId: string, options: { workItemId?: string } = {}): Promise<{ ok: boolean; job?: JobRow; error?: string; code?: EnqueueRefusalCode; detail?: string }> { + async retryJob(jobId: string, actorUserId: string, options: { workItemId?: string; decisionAnswer?: { question: string; answer: string } } = {}): Promise<{ ok: boolean; job?: JobRow; error?: string; code?: EnqueueRefusalCode; detail?: string }> { const job = this.store.getJob(jobId) if (job === undefined) return { ok: false, error: '任务不存在。' } if (job.status === 'queued' || job.status === 'running') return { ok: false, error: '这个任务还在运行;请先暂停或取消。' } @@ -588,7 +592,13 @@ export class Jobs { // may write, and the same expression sat in the resume path. const kind = reenqueueKind(job) const declared = reenqueueWorkType(job, kind) - const goal = job.checkpoint === null || job.checkpoint === '' ? job.goal : `${job.goal}\n\nResume from checkpoint:\n${job.checkpoint}` + const baseGoal = job.checkpoint === null || job.checkpoint === '' ? job.goal : `${job.goal}\n\nResume from checkpoint:\n${job.checkpoint}` + // #381: the retry that answers a decision carries what was asked and what a + // person decided, so the resumed run starts from the answer instead of + // re-deriving the same uncertainty. + const goal = options.decisionAnswer === undefined + ? baseGoal + : decisionAnswerGoal(baseGoal, options.decisionAnswer.question, options.decisionAnswer.answer) const resumePr = kind === 'iterate' && job.pr_url !== null const result = await this.enqueue(repo, resumePr ? 'followup' : 'manual', goal, kind, { // #636: the retry continues the same budget, so it names the attempt it @@ -3432,11 +3442,55 @@ export class Jobs { return this.withJobLock(jobId, () => this.applyCallback(jobId, payload)) } + // #381: the question is a wait, not a failure. The row keeps the question and + // the reason, the lease is released so the reaper does not read the pause as a + // stale running job, and the platform token is revoked like any other stop. The + // inbox card comes from `listJobDecisionsForRepo`; the retry is `retryJob`. + private pauseForDecision(job: JobRow, decision: JobDecision): void { + const reason = redact(decision.why).slice(0, 1000) + const token = job.platform_token_hash === null ? undefined : this.store.findApiToken(job.platform_token_hash) + if (token !== undefined) this.store.revokeApiToken(token.id, token.user_id) + this.store.updateJob(job.id, { + status: 'paused', + error: reason, + decision_json: JSON.stringify(decision), + lease_owner: null, + lease_until: null, + }) + this.store.updateRepo(job.repo_id, { last_status: 'paused', ...(job.kind === 'review' ? { last_review_status: 'paused' } : {}) }) + this.store.recordJobEvent({ jobId: job.id, repoId: job.repo_id, userId: job.user_id, kind: 'job.decision', step: job.kind, meta: decision.question }) + } + + // #381: the asking case of a callback, in one place. It answers nothing at all + // when the payload carries no decision (`undefined`), so a normal finish or + // heartbeat goes straight to the terminal path. The refusals are ordered so a + // finished or timed-out job cannot be paused, and that ordering runs once per + // callback rather than once per route. + private decisionAnswer(job: JobRow, status: CallbackPayload['status'], raw: unknown): { ok: boolean; status?: number; error?: string } | undefined { + if (raw === undefined) return undefined + if (status === 'running') return { ok: false, status: 400, error: 'a running callback cannot carry a decision' } + if (job.decision_json !== null) return { ok: false, status: 409, error: 'one decision per job' } + if (job.status !== 'queued' && job.status !== 'running') return { ok: false, status: 409, error: 'job already finished' } + if (this.pastHardTimeout(job)) return { ok: false, status: 409, error: 'job timed out' } + const parsed = parseJobDecision(raw) + if (!parsed.ok) return { ok: false, status: 400, error: parsed.message } + this.pauseForDecision(job, parsed.decision) + return { ok: true } + } + private async applyCallback(jobId: string, payload: CallbackPayload): Promise<{ ok: boolean; status?: number; error?: string; duplicate?: boolean }> { const job = this.store.getJob(jobId) if (job === undefined) return { ok: false, status: 404, error: 'job not found' } const status = payload.status if (status !== 'succeeded' && status !== 'failed' && status !== 'running') return { ok: false, status: 400, error: 'invalid status' } + // #381: a decision is the other way a run can end. The callback either + // finishes, asks or reports progress; `decisionAnswer` owns the asking case + // and returns undefined for the other two, so the terminal path below never + // sees a decision and this branch only carries that answer back. Keeping the + // ask in its own method is also what the guard wants: the presence of one + // callback field must not look like the check in front of the merge path. + const asked = this.decisionAnswer(job, status, payload.decision) + if (asked !== undefined) return asked const repoRow = this.store.getRepo(job.repo_id) // A callback link is stored only when it belongs to this job's repository. // prOrigin() derives that origin from the row (recorded html_url first, else diff --git a/src/lib/uncertainty.ts b/src/lib/uncertainty.ts new file mode 100644 index 00000000..daa16da4 --- /dev/null +++ b/src/lib/uncertainty.ts @@ -0,0 +1,135 @@ +// #381 slice 1: a job that cannot decide may stop and ask instead of turning the +// uncertainty into a confident guess. The callback carries at most one decision, +// bounded so the inbox card stays readable and the reason cannot become a second +// summary; the answer is stored on the same job row and the retry carries it. +// +// This module is pure: the service owns the state transitions, the store owns the +// row, and the view owns the card. Keeping the bounds here means the callback and +// the answer route cannot disagree about what a decision is. + +export const DECISION_LIMITS = { + question: 300, + why: 500, + options: 4, + option: 80, +} as const + +/** The question a paused job is waiting on. */ +export interface JobDecision { + question: string + why: string + options: string[] +} + +/** The first answer, written once; a second POST replays it and enqueues nothing. */ +export interface JobDecisionAnswer { + text: string + by: string + at: string +} + +/** The row's `decision_json`: the question plus the answer once one exists. */ +export interface StoredDecision extends JobDecision { + answer: JobDecisionAnswer | null +} + +export type DecisionParse = + | { ok: true; decision: JobDecision } + | { ok: false; code: 'decision_invalid' | 'one_decision_per_job'; message: string } + +// One trimmed, bounded string or null. A caller that sends a number, an empty +// string or an oversized question is refused rather than coerced: the card is a +// question a person reads, and half of one is worse than none. +function boundedText(value: unknown, max: number): string | null { + if (typeof value !== 'string') return null + const trimmed = value.trim() + if (trimmed === '' || trimmed.length > max) return null + return trimmed +} + +// `value` is the callback's `decision` field, already known to be present. An +// array is the "two decisions" shape the contract refuses; anything else that is +// not an object, or that names no question or no reason, is malformed. +export function parseJobDecision(value: unknown): DecisionParse { + if (Array.isArray(value)) return { ok: false, code: 'one_decision_per_job', message: 'one decision per job' } + if (value === null || typeof value !== 'object') { + return { ok: false, code: 'decision_invalid', message: 'a decision must be an object' } + } + const body = value as Record + const question = boundedText(body.question, DECISION_LIMITS.question) + if (question === null) { + return { ok: false, code: 'decision_invalid', message: `the question must be 1-${DECISION_LIMITS.question} characters` } + } + const why = boundedText(body.why, DECISION_LIMITS.why) + if (why === null) { + return { ok: false, code: 'decision_invalid', message: `why must be 1-${DECISION_LIMITS.why} characters` } + } + const options: string[] = [] + const rawOptions = body.options + if (rawOptions !== undefined && rawOptions !== null) { + if (!Array.isArray(rawOptions)) return { ok: false, code: 'decision_invalid', message: 'options must be an array' } + if (rawOptions.length > DECISION_LIMITS.options) { + return { ok: false, code: 'decision_invalid', message: `at most ${DECISION_LIMITS.options} options` } + } + for (const entry of rawOptions) { + const option = boundedText(entry, DECISION_LIMITS.option) + if (option === null) { + return { ok: false, code: 'decision_invalid', message: `each option must be 1-${DECISION_LIMITS.option} characters` } + } + options.push(option) + } + } + return { ok: true, decision: { question, why, options } } +} + +// A stored decision is read back by the inbox and the answer route. A row that +// cannot be parsed is treated as no decision: the job stays paused and the card +// is not invented from a malformed string. +export function storedDecision(json: string | null): StoredDecision | null { + if (json === null || json === '') return null + let parsed: unknown + try { + parsed = JSON.parse(json) + } catch { + return null + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null + const record = parsed as Record + const question = typeof record.question === 'string' ? record.question : null + const why = typeof record.why === 'string' ? record.why : null + if (question === null || why === null) return null + const options = Array.isArray(record.options) ? record.options.filter((entry): entry is string => typeof entry === 'string') : [] + let answer: JobDecisionAnswer | null = null + const rawAnswer = record.answer + if (rawAnswer !== null && typeof rawAnswer === 'object' && !Array.isArray(rawAnswer)) { + const entry = rawAnswer as Record + if (typeof entry.text === 'string' && typeof entry.by === 'string' && typeof entry.at === 'string') { + answer = { text: entry.text, by: entry.by, at: entry.at } + } + } + return { question, why, options, answer } +} + +export function decisionWithAnswer(decision: JobDecision, answer: JobDecisionAnswer): string { + return JSON.stringify({ ...decision, answer }) +} + +// The retry starts from the paused job's goal and carries the question and the +// answer, so the resumed run knows what was asked and what a person decided. +export function decisionAnswerGoal(base: string, question: string, answer: string): string { + return `${base}\n\n## Decision from the repository owner\nQuestion: ${question}\nAnswer: ${answer}` +} + +// The inbox card is addressed by the job, not by a live session: the answer route +// branches on this prefix and never reaches the bridge's answerQuestion. +export const JOB_QUESTION_PREFIX = 'job:' + +export function jobQuestionId(jobId: string): string { + return `${JOB_QUESTION_PREFIX}${jobId}` +} + +export function jobIdFromQuestionId(questionId: string): string | null { + if (!questionId.startsWith(JOB_QUESTION_PREFIX)) return null + const jobId = questionId.slice(JOB_QUESTION_PREFIX.length) + return jobId === '' ? null : jobId +} diff --git a/src/views/pages.ts b/src/views/pages.ts index 29008c7e..5fc837b7 100644 --- a/src/views/pages.ts +++ b/src/views/pages.ts @@ -51,6 +51,12 @@ import type { PlatformStopRecord } from '../jobs/service.js' export interface InboxQuestion extends TeamQuestionState { repoId: string repoLabel: string + /** + * #381: a paused Fledge job can raise a decision. Such a card has no live + * session and is answered into the job's retry, so the view marks its source. + */ + source?: 'team' | 'job' + jobId?: string } function advancedViewer(viewer: Viewer): boolean { @@ -540,6 +546,7 @@ export function inboxSection(locale: Locale, viewer: Viewer, questions: InboxQue return `
${escapeHtml(question.question || t('团队提问', 'Team question'))} + ${question.source === 'job' && question.jobId !== undefined ? `${escapeHtml(t('来自任务', 'From a job'))}` : ''} ${escapeHtml(question.repoLabel)}
${question.detail === '' ? '' : `

${escapeHtml(question.detail)}

`} diff --git a/test/jobDecision.test.ts b/test/jobDecision.test.ts new file mode 100644 index 00000000..80b32f6d --- /dev/null +++ b/test/jobDecision.test.ts @@ -0,0 +1,206 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { buildApp } from '../src/app.js' +import { Store } from '../src/db.js' +import type { JobRow, RepoRow, UserRow } from '../src/db.js' +import { MockRunner } from '../src/jobs/mock.js' +import { sha256Hex } from '../src/lib/secrets.js' +import { flashOf, formBody, makeUser, MemoryMailer, sessionFor, testConfig } from './helpers.js' + +// #381 slice 1: a job may stop and ask. The callback carries one bounded +// decision, the job waits as `paused`, the question is an inbox card marked with +// its job, and the first answer enqueues exactly one retry carrying the answer. + +// Parsed here rather than through the module under test, so this file compiles +// on the base tree and fails on behaviour instead of on a missing import. +function storedDecision(json: string | null): { question: string; options: string[]; answer: { text: string; by: string } | null } | null { + if (json === null) return null + const parsed = JSON.parse(json) as { question: string; options?: string[]; answer?: { text: string; by: string } | null } + return { question: parsed.question, options: parsed.options ?? [], answer: parsed.answer ?? null } +} + +const secret = 'decision-callback-secret' +const QUESTION = 'Should the migration run inside the release window?' +const WHY = 'The plan changes the schema and only a person can accept that risk.' + +interface Harness { + built: Awaited> + store: Store + user: UserRow + repo: RepoRow + job: JobRow + cookie: string + csrf: string + close: () => Promise +} + +async function harness(): Promise { + const config = testConfig() + const store = new Store(':memory:') + const built = await buildApp({ config, store, mailer: new MemoryMailer(), runner: new MockRunner(), startScheduler: false }) + const user = makeUser(store, { login: 'decision-user', status: 'approved' }) + const repo = store.createRepo({ id: 'repo_decision', userId: user.id, owner: 'o', name: 'decision', defaultBranch: 'main', tokenEnc: 'x', permission: 'admin', repoRole: 'maintainer', goal: 'ship it', autoIterate: false, intervalMinutes: 1440 }) + const job = store.createJob({ id: 'job_decision', repoId: repo.id, userId: user.id, trigger: 'manual', goal: 'ship it', callbackHash: sha256Hex(secret), platformTokenHash: '' }) + store.updateJob(job.id, { status: 'running', lease_owner: 'worker-1', lease_until: new Date(Date.now() + 60_000).toISOString() }) + const session = sessionFor(built, user) + return { + built, + store, + user, + repo, + job: store.getJob(job.id)!, + cookie: session.cookie, + csrf: session.csrf, + // buildApp owns the store's lifetime in this harness. + close: async () => { + await built.close() + }, + } +} + +function callback(h: Harness, payload: Record) { + return h.built.app.inject({ + method: 'POST', + url: `/api/jobs/${h.job.id}/callback`, + headers: { authorization: `Bearer ${secret}`, 'content-type': 'application/json' }, + payload: JSON.stringify(payload), + }) +} + +function answer(h: Harness, text: string) { + return h.built.app.inject({ + method: 'POST', + url: `/repos/${h.repo.id}/team/answer`, + headers: { cookie: h.cookie, 'content-type': 'application/x-www-form-urlencoded' }, + payload: formBody({ csrf: h.csrf, sessionId: '', questionId: `job:${h.job.id}`, custom: text }), + }) +} + +test('a callback carrying two decisions is refused and the job stays running', async () => { + const h = await harness() + try { + const refused = await callback(h, { status: 'succeeded', decision: [{ question: QUESTION, why: WHY }, { question: 'Second?', why: WHY }] }) + assert.equal(refused.statusCode, 400) + assert.match(String(JSON.parse(refused.body).error), /one decision per job/) + assert.equal(h.store.getJob(h.job.id)?.status, 'running') + assert.equal(h.store.getJob(h.job.id)?.decision_json, null) + } finally { + await h.close() + } +}) + +test('an accepted decision pauses the job, keeps the question and releases the lease', async () => { + const h = await harness() + try { + const accepted = await callback(h, { status: 'succeeded', decision: { question: QUESTION, why: WHY, options: ['Ship it', 'Wait'] } }) + assert.equal(accepted.statusCode, 200) + const paused = h.store.getJob(h.job.id) + assert.equal(paused?.status, 'paused') + assert.equal(paused?.error, WHY) + assert.equal(paused?.lease_until, null) + const stored = storedDecision(paused?.decision_json ?? null) + assert.equal(stored?.question, QUESTION) + assert.deepEqual(stored?.options, ['Ship it', 'Wait']) + assert.equal(stored?.answer, null) + + const second = await callback(h, { status: 'succeeded', decision: { question: 'A different question?', why: WHY } }) + assert.equal(second.statusCode, 409) + assert.match(String(JSON.parse(second.body).error), /one decision per job/) + assert.equal(storedDecision(h.store.getJob(h.job.id)?.decision_json ?? null)?.question, QUESTION) + } finally { + await h.close() + } +}) + +test('the dashboard inbox renders the question as a card sourced from its job', async () => { + const h = await harness() + try { + await callback(h, { status: 'failed', decision: { question: QUESTION, why: WHY } }) + const page = await h.built.app.inject({ method: 'GET', url: '/dashboard', headers: { cookie: h.cookie, 'accept-language': 'en' } }) + assert.equal(page.statusCode, 200) + assert.match(page.body, /id="inbox"/) + assert.match(page.body, new RegExp(QUESTION)) + assert.match(page.body, new RegExp(`job:${h.job.id}`)) + assert.match(page.body, /From a job/) + } finally { + await h.close() + } +}) + +test('the first answer starts exactly one retry carrying the question and the answer', async () => { + const h = await harness() + try { + await callback(h, { status: 'succeeded', decision: { question: QUESTION, why: WHY } }) + const sent = await answer(h, 'Ship it after the freeze') + assert.equal(sent.statusCode, 302) + const answered = storedDecision(h.store.getJob(h.job.id)?.decision_json ?? null) + assert.equal(answered?.answer?.text, 'Ship it after the freeze') + assert.equal(answered?.answer?.by, h.user.login) + const retries = h.store.listJobsForRepo(h.repo.id, 50).filter((job) => job.retry_of === h.job.id) + assert.equal(retries.length, 1) + assert.match(retries[0]?.goal ?? '', new RegExp(QUESTION)) + assert.match(retries[0]?.goal ?? '', /Ship it after the freeze/) + + const again = await answer(h, 'A second answer') + assert.equal(again.statusCode, 302) + assert.equal(h.store.listJobsForRepo(h.repo.id, 50).filter((job) => job.retry_of === h.job.id).length, 1) + assert.equal(storedDecision(h.store.getJob(h.job.id)?.decision_json ?? null)?.answer?.text, 'Ship it after the freeze') + } finally { + await h.close() + } +}) + +// #381 verdict 5914605525 blocking item: the answer was persisted before the +// retry was judged, so every ordinary enqueue refusal (JOB_ACTIVE, QUEUE_FULL, +// REPO_DISABLED, PLATFORM_PAUSED) left the row answered — and an answered row is +// exactly what removes the card from the inbox — while no retry existed. The card +// has to survive a refused answer, and the later answer must still enqueue +// exactly one retry. +test('a refused answer keeps the card and the later answer still enqueues exactly one retry', async () => { + const h = await harness() + try { + await callback(h, { status: 'succeeded', decision: { question: QUESTION, why: WHY } }) + // Another job on the same repository is running, so the retry is refused with + // JOB_ACTIVE before any job row of its own is written. + const busy = h.store.createJob({ id: 'job_busy', repoId: h.repo.id, userId: h.user.id, trigger: 'manual', goal: 'busy', callbackHash: '', platformTokenHash: '' }) + h.store.updateJob(busy.id, { status: 'running' }) + + const refused = await answer(h, 'Ship it after the freeze') + assert.equal(refused.statusCode, 302) + // #472: the refusal travels as a flash message, not as a query parameter. + assert.match(flashOf(refused)?.error?.text ?? '', /已有任务在运行|already running/) + assert.equal(h.store.getJob(h.job.id)?.status, 'paused', 'a refused answer resumed the job') + assert.equal(storedDecision(h.store.getJob(h.job.id)?.decision_json ?? null)?.answer, null, 'a refused retry stored the answer') + assert.equal(h.store.listJobsForRepo(h.repo.id, 50).filter((job) => job.retry_of === h.job.id).length, 0, 'a refused answer enqueued a retry') + + // No inbox cache entry exists yet, so this read builds the list from the rows. + const page = await h.built.app.inject({ method: 'GET', url: '/dashboard', headers: { cookie: h.cookie, 'accept-language': 'en' } }) + assert.equal(page.statusCode, 200) + assert.match(page.body, new RegExp(`job:${h.job.id}`), 'a refused answer dropped the card from the inbox') + + // The other job finishes; the same answer now goes through, exactly once. + h.store.updateJob(busy.id, { status: 'succeeded' }) + const accepted = await answer(h, 'Ship it after the freeze') + assert.equal(accepted.statusCode, 302) + assert.equal(storedDecision(h.store.getJob(h.job.id)?.decision_json ?? null)?.answer?.text, 'Ship it after the freeze') + const retries = h.store.listJobsForRepo(h.repo.id, 50).filter((job) => job.retry_of === h.job.id) + assert.equal(retries.length, 1) + assert.match(retries[0]?.goal ?? '', /Ship it after the freeze/) + } finally { + await h.close() + } +}) + +test('a malformed decision is refused instead of stored', async () => { + const h = await harness() + try { + const empty = await callback(h, { status: 'succeeded', decision: { question: ' ', why: WHY } }) + assert.equal(empty.statusCode, 400) + const five = await callback(h, { status: 'succeeded', decision: { question: QUESTION, why: WHY, options: ['a', 'b', 'c', 'd', 'e'] } }) + assert.equal(five.statusCode, 400) + assert.equal(h.store.getJob(h.job.id)?.status, 'running') + assert.equal(h.store.getJob(h.job.id)?.decision_json, null) + } finally { + await h.close() + } +})