Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/381-job-decision.added.md
Original file line number Diff line number Diff line change
@@ -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.
13 changes: 13 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<jobId>`; 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`
Expand Down
64 changes: 61 additions & 3 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -878,9 +879,32 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
.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
}
Expand Down Expand Up @@ -3139,8 +3163,42 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
`${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))
}
Expand Down
15 changes: 14 additions & 1 deletion src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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<JobRow>("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
Expand Down Expand Up @@ -6277,7 +6290,7 @@ export class Store {
}


updateJob(id: string, patch: Partial<Pick<JobRow, 'status' | 'branch' | 'pr_url' | 'issue_url' | 'pr_state' | 'review_score' | 'attribution_json' | 'evidence_json' | 'checkpoint' | 'team_stats_json' | 'summary' | 'error' | 'error_code' | 'cost_usd' | 'started_at' | 'last_callback_at' | 'finished_at' | 'base_branch' | 'work_item_id' | 'priority' | 'plan_approved_at' | 'plan_approved_by' | 'plan_rejected_at' | 'plan_allow_paths' | 'plan_deny_paths' | 'base_sha' | 'temporal_json' | 'path_guard_json' | 'verification_json' | 'continuity_json' | 'model_json' | 'provider_model' | 'provider_region' | 'provider_label' | 'provider_id' | 'output_kind' | 'work_type' | 'triage_json' | 'continuity_used' | 'retry_attempt' | 'retry_of' | 'lease_owner' | 'lease_until' | 'callback_secret_enc' | 'platform_token_enc'>>): void {
updateJob(id: string, patch: Partial<Pick<JobRow, 'status' | 'branch' | 'pr_url' | 'issue_url' | 'pr_state' | 'review_score' | 'attribution_json' | 'evidence_json' | 'checkpoint' | 'team_stats_json' | 'summary' | 'error' | 'error_code' | 'cost_usd' | 'started_at' | 'last_callback_at' | 'finished_at' | 'base_branch' | 'work_item_id' | 'priority' | 'plan_approved_at' | 'plan_approved_by' | 'plan_rejected_at' | 'plan_allow_paths' | 'plan_deny_paths' | 'base_sha' | 'temporal_json' | 'path_guard_json' | 'verification_json' | 'decision_json' | 'continuity_json' | 'model_json' | 'provider_model' | 'provider_region' | 'provider_label' | 'provider_id' | 'output_kind' | 'work_type' | 'triage_json' | 'continuity_used' | 'retry_attempt' | 'retry_of' | 'lease_owner' | 'lease_until' | 'callback_secret_enc' | 'platform_token_enc'>>): void {
const entries = Object.entries(redactJobText(patch as Record<string, unknown>)).filter(([, value]) => value !== undefined)
if (entries.length === 0) return
const sets: string[] = []
Expand Down
58 changes: 56 additions & 2 deletions src/jobs/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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: '这个任务还在运行;请先暂停或取消。' }
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading