diff --git a/apps/server/scripts/settle-audit.test.ts b/apps/server/scripts/settle-audit.test.ts new file mode 100644 index 0000000000000..30efc828fd020 --- /dev/null +++ b/apps/server/scripts/settle-audit.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; + +import { inferUnsettleCause, replayDecision } from "./settle-audit.ts"; + +const DECIDED_AT = "2026-11-13T14:13:58.616Z"; +const at = (iso: string) => DateTime.makeUnsafe(iso); + +// The fields the settle rules read, with the DateTime values the server holds. +const thread = (overrides: Record = {}) => ({ + id: "thread-1", + projectId: "project-1", + branch: null, + worktreePath: null, + pullRequests: [], + linkedPullRequest: null, + branchPullRequest: null, + createdAt: at("2026-11-01T00:00:00.000Z"), + updatedAt: at("2026-11-03T00:00:00.000Z"), + archivedAt: null, + settledOverride: null, + pinnedAt: null, + snoozedUntil: null, + snoozedAt: null, + status: "completed", + latestRunId: "run-1", + latestRunRequestedAt: at("2026-11-03T00:00:00.000Z"), + latestRunStartedAt: at("2026-11-03T00:00:00.000Z"), + latestRunCompletedAt: at("2026-11-03T00:10:00.000Z"), + latestUserMessageAt: at("2026-11-03T00:00:00.000Z"), + latestUserAuthoredMessageAt: at("2026-11-03T00:00:00.000Z"), + activityRunStatus: null, + activityRunStartedAt: null, + pendingRuntimeRequest: null, + pendingBackgroundTasks: [], + pendingGuestMessageCount: 0, + ...overrides, +}); + +const mergedLink = { + host: "github.com", + repository: "acme/app", + number: 42, + url: "https://github.com/acme/app/pull/42", + source: "agent", + linkedAt: "2026-11-02T00:00:00.000Z", + snapshot: { + state: "merged", + title: "Pull request", + headBranch: "feature", + baseBranch: "main", + isDraft: false, + updatedAt: "2026-11-13T14:13:37.000Z", + syncedAt: "2026-11-13T14:13:55.000Z", + mergedAt: "2026-11-13T14:13:37.000Z", + }, + stack: null, +}; + +// Rows as the decision log writes them: inputs and settings through JSON.stringify. +const row = (input: { + readonly inputs: ReturnType; + readonly replyCheck?: unknown; +}) => ({ + id: 1, + decided_at: DECIDED_AT, + thread_id: "thread-1", + outcome: "settled" as const, + rule: "auto_inactivity", + hold_reason: null, + trigger: "full_sweep", + run_id: "run-1", + reply_check_json: input.replyCheck === undefined ? null : JSON.stringify(input.replyCheck), + inputs_json: JSON.stringify({ thread: input.inputs, pullRequest: null }), + settings_json: JSON.stringify({ + onMerge: true, + afterDays: 3, + keepPullRequests: false, + replyCheck: true, + }), + server_version: "0.1.7-test", +}); + +describe("replayDecision", () => { + // Each row only replays right if the JSON dates come back as DateTimes. + it.each([ + { + name: "an idle thread settles on inactivity", + inputs: thread(), + expected: { outcome: "settled", rule: "auto_inactivity", holdReason: null }, + }, + { + name: "a snooze holds the inactivity rule", + inputs: thread({ snoozedUntil: at("2026-11-20T00:00:00.000Z"), snoozedAt: at(DECIDED_AT) }), + expected: { outcome: "held", rule: "auto_inactivity", holdReason: "snoozed" }, + }, + { + name: "a live watch holds the merge rule", + inputs: thread({ + pullRequests: [mergedLink], + pendingBackgroundTasks: [ + { taskId: "pull-request-watch:github.com/acme/app#42", kind: "monitor", awaited: true }, + ], + }), + expected: { + outcome: "held", + rule: "auto_pull_request_merged", + holdReason: "background_work", + }, + }, + { + name: "the recorded reply check holds the merge rule", + inputs: thread({ + pullRequests: [mergedLink], + latestRunCompletedAt: at("2026-11-13T14:10:02.000Z"), + latestUserMessageAt: at("2026-11-13T13:44:42.000Z"), + latestUserAuthoredMessageAt: at("2026-11-13T13:44:42.000Z"), + }), + replyCheck: { outcome: "holds", reason: "needs_user" }, + expected: { outcome: "held", rule: "auto_pull_request_merged", holdReason: "needs_user" }, + }, + ])("$name", ({ inputs, replyCheck, expected }) => { + expect(replayDecision(row({ inputs, replyCheck }))).toEqual(expected); + }); +}); + +describe("inferUnsettleCause", () => { + it.each([ + [ + "thread.unsettled", + { createdBy: "agent", scheduledTaskId: "task:check-in" }, + "scheduled_task", + ], + ["thread.unsettled", { createdBy: "agent", notification: { summary: "#7" } }, "notification"], + ["thread.unsettled", { createdBy: "user" }, "user_message"], + ["thread.unsettled", { createdBy: "agent" }, "agent_message"], + ["thread.unsettled", null, "user"], + ["thread.pinned", null, "pin"], + ["thread.guest-share-updated", null, "guest"], + ] as const)("%s with %j reads as %s", (eventType, message, cause) => { + expect(inferUnsettleCause(eventType, message)).toBe(cause); + }); +}); diff --git a/apps/server/scripts/settle-audit.ts b/apps/server/scripts/settle-audit.ts new file mode 100644 index 0000000000000..66ec602195001 --- /dev/null +++ b/apps/server/scripts/settle-audit.ts @@ -0,0 +1,481 @@ +#!/usr/bin/env node +// @effect-diagnostics nodeBuiltinImport:off - a read-only report over one SQLite file. +/** + * Labels past auto-settles by what happened next and, with --replay, reruns this checkout's rules + * on recorded decisions. Read-only. `node apps/server/scripts/settle-audit.ts --help` + */ +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeSqlite from "node:sqlite"; + +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import type { OrchestrationV2ThreadUnsettleCause } from "@t3tools/contracts"; +import * as Console from "effect/Console"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { Command, Flag } from "effect/cli"; + +import { + type AutoSettlement, + resolveAutoSettlement, +} from "../src/orchestration-v2/ThreadSettlementService.ts"; + +const HOUR_MS = 60 * 60 * 1_000; +const TEXT_LIMIT = 4_000; + +type Cause = OrchestrationV2ThreadUnsettleCause; + +export type SettleLabel = + | "reopened_by_user" + | "reopened_late_by_user" + | "reopened_automatically" + | "reopened_unknown" + | "stayed_settled"; + +const USER_CAUSES: ReadonlySet = new Set(["user", "pin", "user_message", "guest"]); + +/** A user reopening a settle soon after is the strongest sign it was wrong. */ +function labelSettle( + reopen: { readonly cause: Cause | null; readonly afterMs: number } | null, + windowMs: number, +): SettleLabel { + if (reopen === null) return "stayed_settled"; + if (reopen.cause === null) return "reopened_unknown"; + if (!USER_CAUSES.has(reopen.cause)) return "reopened_automatically"; + return reopen.afterMs <= windowMs ? "reopened_by_user" : "reopened_late_by_user"; +} + +/** Reopens from before `unsettleCause` was recorded: who sent the message that came with it. */ +export function inferUnsettleCause( + eventType: string, + message: { + readonly createdBy?: string; + readonly scheduledTaskId?: string | null; + readonly notification?: unknown; + } | null, +): Cause | null { + if (message !== null) { + if (message.scheduledTaskId != null) return "scheduled_task"; + if (message.notification != null) return "notification"; + return message.createdBy === "user" ? "user_message" : "agent_message"; + } + if (eventType === "thread.pinned") return "pin"; + if (eventType === "thread.guest-share-updated") return "guest"; + return eventType === "thread.unsettled" ? "user" : null; +} + +const NESTED_DATES: ReadonlyArray]> = [ + ["pendingRuntimeRequest", ["createdAt"]], +]; + +const revive = (value: unknown) => + typeof value === "string" && !Number.isNaN(Date.parse(value)) + ? DateTime.makeUnsafe(value) + : value; + +/** + * Turns a recorded decision's inputs back into what the rules read: JSON stored the thread's + * `DateTime` fields (the ones ending in At or Until) as ISO strings. Link snapshots keep strings. + */ +function reviveSettlementInputs(inputs: { + readonly thread: Record; + readonly pullRequest: unknown; +}) { + const thread: Record = {}; + for (const [key, value] of Object.entries(inputs.thread)) { + thread[key] = /(At|Until)$/.test(key) ? revive(value) : value; + } + for (const [key, fields] of NESTED_DATES) { + const nested = thread[key]; + if (nested == null || typeof nested !== "object") continue; + const copy: Record = { ...(nested as Record) }; + for (const field of fields) copy[field] = revive(copy[field]); + thread[key] = copy; + } + if (Array.isArray(thread["automatedRunWindows"])) { + thread["automatedRunWindows"] = thread["automatedRunWindows"].map( + (window: { startedAt: string; completedAt: string }) => ({ + startedAt: revive(window.startedAt), + completedAt: revive(window.completedAt), + }), + ); + } + return { + thread: thread as unknown as Parameters[0]["thread"], + pullRequest: inputs.pullRequest as Parameters[0]["pullRequest"], + }; +} + +interface DecisionRow { + readonly id: number; + readonly decided_at: string; + readonly thread_id: string; + readonly outcome: "settled" | "held"; + readonly rule: string; + readonly hold_reason: string | null; + readonly trigger: string; + readonly run_id: string | null; + readonly reply_check_json: string | null; + readonly inputs_json: string; + readonly settings_json: string; + readonly server_version: string; +} + +/** What this checkout's rules decide for a recorded decision, in the log's own terms. */ +export function replayDecision(row: DecisionRow) { + const settings = JSON.parse(row.settings_json); + const replyCheck = row.reply_check_json === null ? null : JSON.parse(row.reply_check_json); + const { thread, pullRequest } = reviveSettlementInputs(JSON.parse(row.inputs_json)); + const replayed: AutoSettlement | null = resolveAutoSettlement({ + thread, + pullRequest, + nowMs: Date.parse(row.decided_at), + autoSettleAfterDays: settings.afterDays, + autoSettleOnMerge: settings.onMerge, + autoSettleKeepPullRequests: settings.keepPullRequests, + pullRequestHeld: + replyCheck !== null && + replyCheck.outcome !== "settles" && + (settings.replyCheck === true || replyCheck.reason !== "needs_user"), + }); + if (replayed === null) return { outcome: "none", rule: null, holdReason: null } as const; + return { + outcome: replayed.outcome === "settle" ? "settled" : "held", + rule: replayed.source, + holdReason: + replayed.outcome === "settle" + ? null + : replayed.hold === "reply_check" + ? (replyCheck?.reason ?? replayed.hold) + : replayed.hold, + } as const; +} + +const truncate = (text: string | null | undefined) => + text == null ? null : text.length <= TEXT_LIMIT ? text : `${text.slice(0, TEXT_LIMIT)}…`; + +const defaultDatabase = () => + NodePath.join( + process.env.T3CODE_HOME ?? NodePath.join(NodeOS.homedir(), ".t3"), + "userdata", + "statev2.sqlite", + ); + +function audit(input: { + readonly database: string; + readonly days: number; + readonly reopenHours: number; + readonly json: string | undefined; + readonly replay: boolean; + readonly nowMs: number; +}) { + const db = new NodeSqlite.DatabaseSync(input.database, { readOnly: true }); + try { + const since = DateTime.formatIso(DateTime.makeUnsafe(input.nowMs - input.days * 24 * HOUR_MS)); + const windowMs = input.reopenHours * HOUR_MS; + const lines: Array = []; + + // occurred_at has no index, so find the window's first event by sequence. + const maxSequence = Number( + ( + db.prepare("SELECT max(sequence) AS max FROM orchestration_events").get() as { + max: number | null; + } + ).max ?? 0, + ); + const occurredAt = db.prepare( + "SELECT occurred_at FROM orchestration_events WHERE sequence >= ? ORDER BY sequence LIMIT 1", + ); + let low = 0; + let high = maxSequence; + while (low < high) { + const middle = Math.floor((low + high) / 2); + const row = occurredAt.get(middle) as { occurred_at: string } | undefined; + if (row === undefined || row.occurred_at >= since) high = middle; + else low = middle + 1; + } + + const settles = db + .prepare( + `SELECT sequence, stream_id AS thread_id, occurred_at, + json_extract(payload_json, '$.settlementSource') AS rule + FROM orchestration_events + WHERE sequence >= ? AND aggregate_kind = 'thread' AND event_type = 'thread.settled' + AND command_id LIKE 'server:auto-settle:%' AND occurred_at >= ? + ORDER BY sequence`, + ) + .all(low, since) as Array<{ + sequence: number; + thread_id: string; + occurred_at: string; + rule: string | null; + }>; + const nextChange = db.prepare( + `SELECT event_type, occurred_at, command_id, + json_extract(payload_json, '$.settledOverride') AS settled_override, + json_extract(payload_json, '$.unsettleCause') AS cause + FROM orchestration_events + WHERE aggregate_kind = 'thread' AND stream_id = ? AND sequence > ? + AND event_type IN ('thread.unsettled', 'thread.pinned', 'thread.guest-share-updated', + 'thread.settled') + ORDER BY sequence LIMIT 20`, + ); + const commandMessage = db.prepare( + `SELECT payload_json FROM orchestration_events + WHERE aggregate_kind = 'thread' AND stream_id = ? AND command_id = ? + AND event_type = 'message.updated' AND json_extract(payload_json, '$.role') = 'user' + ORDER BY sequence LIMIT 1`, + ); + const title = db.prepare( + "SELECT title FROM orchestration_v2_projection_threads WHERE thread_id = ?", + ); + const latestRun = db.prepare( + `SELECT run_id, json_extract(payload_json, '$.userMessageId') AS user_message_id + FROM orchestration_v2_projection_runs + WHERE thread_id = ? AND requested_at <= ? + ORDER BY ordinal DESC LIMIT 1`, + ); + const reply = db.prepare( + `SELECT json_extract(payload_json, '$.text') AS text FROM orchestration_v2_projection_messages + WHERE run_id = ? AND role = 'assistant' AND streaming = 0 + AND trim(coalesce(json_extract(payload_json, '$.text'), '')) <> '' + ORDER BY created_at DESC LIMIT 1`, + ); + const request = db.prepare( + `SELECT json_extract(payload_json, '$.text') AS text FROM orchestration_v2_projection_messages + WHERE message_id = ?`, + ); + const hasDecisions = + db + .prepare( + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'settlement_decisions'", + ) + .get() !== undefined; + const decisionFor = hasDecisions + ? db.prepare( + `SELECT * FROM settlement_decisions + WHERE thread_id = ? AND outcome = 'settled' + AND decided_at BETWEEN datetime(?, '-30 seconds') AND datetime(?, '+30 seconds') + ORDER BY id DESC LIMIT 1`, + ) + : null; + const holdsBefore = hasDecisions + ? db.prepare( + `SELECT decided_at, hold_reason FROM settlement_decisions + WHERE thread_id = ? AND outcome = 'held' AND decided_at BETWEEN ? AND ? + ORDER BY id`, + ) + : null; + + const rows = settles.map((settle, index) => { + const previous = settles + .slice(0, index) + .findLast((candidate) => candidate.thread_id === settle.thread_id); + const change = ( + nextChange.all(settle.thread_id, settle.sequence) as Array<{ + event_type: string; + occurred_at: string; + command_id: string | null; + settled_override: string | null; + cause: Cause | null; + }> + ).find( + (event) => event.event_type === "thread.settled" || event.settled_override !== "settled", + ); + const reopened = change !== undefined && change.event_type !== "thread.settled"; + const message = + reopened && change.command_id !== null + ? (commandMessage.get(settle.thread_id, change.command_id) as + | { payload_json: string } + | undefined) + : undefined; + const cause = reopened + ? (change.cause ?? + inferUnsettleCause( + change.event_type, + message === undefined ? null : JSON.parse(message.payload_json), + )) + : null; + const afterMs = reopened + ? Date.parse(change.occurred_at) - Date.parse(settle.occurred_at) + : 0; + const label = labelSettle(reopened ? { cause, afterMs } : null, windowMs); + const decision = decisionFor?.get( + settle.thread_id, + settle.occurred_at, + settle.occurred_at, + ) as DecisionRow | undefined; + const run = latestRun.get(settle.thread_id, settle.occurred_at) as + | { run_id: string; user_message_id: string | null } + | undefined; + const runId = decision?.run_id ?? run?.run_id ?? null; + const holds = (holdsBefore?.all( + settle.thread_id, + previous?.occurred_at ?? since, + settle.occurred_at, + ) ?? []) as Array<{ decided_at: string; hold_reason: string }>; + return { + settledAt: settle.occurred_at, + threadId: settle.thread_id, + title: (title.get(settle.thread_id) as { title: string } | undefined)?.title ?? null, + rule: settle.rule ?? "unrecorded", + label, + reopen: reopened + ? { at: change.occurred_at, cause, afterMinutes: Math.round(afterMs / 60_000) } + : null, + decision: + decision === undefined + ? null + : { + trigger: decision.trigger, + serverVersion: decision.server_version, + replyCheck: JSON.parse(decision.reply_check_json ?? "null"), + settings: JSON.parse(decision.settings_json), + }, + heldBefore: holds.map((hold) => ({ at: hold.decided_at, reason: hold.hold_reason })), + runId, + request: truncate( + run?.user_message_id == null + ? null + : (request.get(run.user_message_id) as { text: string } | undefined)?.text, + ), + reply: truncate( + runId === null ? null : (reply.get(runId) as { text: string } | undefined)?.text, + ), + }; + }); + + lines.push( + `auto-settles since ${since} (${input.days} days), reopen window ${input.reopenHours}h`, + ); + const labels: ReadonlyArray = [ + "reopened_by_user", + "reopened_late_by_user", + "reopened_automatically", + "reopened_unknown", + "stayed_settled", + ]; + lines.push(["rule".padEnd(34), "total", ...labels].join(" ")); + for (const rule of [...new Set(rows.map((row) => row.rule))].toSorted()) { + const ofRule = rows.filter((row) => row.rule === rule); + lines.push( + [ + rule.padEnd(34), + String(ofRule.length).padStart(5), + ...labels.map((label) => + String(ofRule.filter((row) => row.label === label).length).padStart(label.length), + ), + ].join(" "), + ); + } + const wrong = rows.filter((row) => row.label === "reopened_by_user"); + if (wrong.length > 0) { + lines.push("", "reopened by you within the window:"); + for (const row of wrong) { + lines.push( + ` ${row.settledAt} ${row.rule} back after ${row.reopen?.afterMinutes}m (${row.reopen?.cause}) ${row.title ?? row.threadId}`, + ); + } + } + + if (hasDecisions) { + const holds = db + .prepare( + `SELECT rule, hold_reason, count(*) AS count, count(DISTINCT thread_id) AS threads + FROM settlement_decisions WHERE outcome = 'held' AND decided_at >= ? + GROUP BY rule, hold_reason ORDER BY count DESC`, + ) + .all(since) as Array<{ rule: string; hold_reason: string; count: number; threads: number }>; + lines.push("", "holds recorded (a rule would have settled the thread):"); + if (holds.length === 0) lines.push(" none"); + for (const hold of holds) { + lines.push( + ` ${hold.rule.padEnd(34)} ${hold.hold_reason.padEnd(16)} ${hold.count} rows, ${hold.threads} threads`, + ); + } + } else { + lines.push( + "", + "no settlement_decisions table yet: holds and replay need a build that records them", + ); + } + + if (input.replay && hasDecisions) { + const decisions = db + .prepare("SELECT * FROM settlement_decisions WHERE decided_at >= ? ORDER BY id") + .all(since) as unknown as Array; + const changed = decisions.flatMap((row) => { + const replayed = replayDecision(row); + const same = + replayed.outcome === row.outcome && + replayed.rule === row.rule && + replayed.holdReason === row.hold_reason; + return same ? [] : [{ row, replayed }]; + }); + lines.push( + "", + `replayed ${decisions.length} recorded decisions with this checkout's rules: ${changed.length} change`, + ); + for (const { row, replayed } of changed) { + lines.push( + ` ${row.decided_at} ${row.thread_id} ${row.outcome} ${row.rule} ${row.hold_reason ?? ""} -> ${replayed.outcome} ${replayed.rule ?? ""} ${replayed.holdReason ?? ""}`, + ); + } + } + + if (input.json !== undefined) { + NodeFS.writeFileSync(input.json, rows.map((row) => JSON.stringify(row)).join("\n") + "\n"); + lines.push("", `wrote ${rows.length} settles to ${input.json}`); + } + return lines.join("\n"); + } finally { + db.close(); + } +} + +const settleAuditCommand = Command.make( + "settle-audit", + { + database: Flag.String("db").pipe( + Flag.optional, + Flag.withDescription("statev2.sqlite to read. Defaults to the T3 home's userdata."), + ), + days: Flag.Int("days").pipe(Flag.withDefault(7), Flag.withDescription("Days to look back.")), + reopenHours: Flag.Int("reopen-hours").pipe( + Flag.withDefault(24), + Flag.withDescription("A reopen by you within this many hours marks a settle as wrong."), + ), + json: Flag.String("json").pipe( + Flag.optional, + Flag.withDescription("Write one JSON line per settle, with the request and reply text."), + ), + replay: Flag.Boolean("replay").pipe( + Flag.withDefault(false), + Flag.withDescription("Rerun this checkout's rules on every recorded decision."), + ), + }, + ({ database, days, reopenHours, json, replay }) => + DateTime.now.pipe( + Effect.map((now) => + audit({ + database: Option.getOrElse(database, defaultDatabase), + days, + reopenHours, + json: Option.getOrUndefined(json), + replay, + nowMs: DateTime.toEpochMillis(now), + }), + ), + Effect.flatMap(Console.log), + ), +).pipe(Command.withDescription("Label past auto-settles and replay recorded settle decisions.")); + +if (import.meta.main) { + Command.run(settleAuditCommand, { version: "0.0.0" }).pipe( + Effect.provide(NodeServices.layer), + NodeRuntime.runMain, + ); +} diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index f968312437518..990ec10985454 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -353,8 +353,10 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { command = { ...common, type: "thread.snooze", snoozedUntil: input.snoozedUntil }; break; case "unsnooze": + command = { ...common, type: "thread.unsnooze", reason: "user" }; + break; case "unsettle": - command = { ...common, type: `thread.${input.action}`, reason: "user" }; + command = { ...common, type: "thread.unsettle", reason: "agent" }; break; case "mark_unread": command = { ...common, type: "thread.mark-unread" }; diff --git a/apps/server/src/orchestration-v2/GuestShareDecider.ts b/apps/server/src/orchestration-v2/GuestShareDecider.ts index 5890f61f40959..24997257c46d8 100644 --- a/apps/server/src/orchestration-v2/GuestShareDecider.ts +++ b/apps/server/src/orchestration-v2/GuestShareDecider.ts @@ -176,6 +176,7 @@ export function decideGuestShareCommand(input: { settledAt: null, settlementSource: null, unsettledAt: now, + unsettleCause: "guest", updatedAt: now, }) : withShare(guestShare); diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index d7e6136c412fe..a6590437ed9e2 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -15,6 +15,7 @@ import { RunAttemptId, RunId, RuntimeRequestId, + ScheduledTaskId, ThreadId, TurnItemId, } from "@t3tools/contracts"; @@ -1619,6 +1620,113 @@ it.effect("records what settled a thread until it is unsettled", () => }).pipe(Effect.provide(layerTest)), ); +// The settle audit counts a settle someone undid as wrong, and one a schedule or wake reopened as +// fine, so each way back records who did it. +it.effect("records what brought a settled thread back", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const settled = Effect.fn(function* (name: string) { + const threadId = ThreadId.make(`thread:unsettle-cause-${name}`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create-unsettle-cause-${name}`), + threadId, + projectId: ProjectId.make("project:unsettle-cause"), + title: name, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "thread.auto-settle", + commandId: CommandId.make(`settle-unsettle-cause-${name}`), + threadId, + snapshotAt: (yield* projections.getThread(threadId)).updatedAt, + settlementSource: "auto_pull_request_merged", + }); + return threadId; + }); + const cause = Effect.fn(function* (threadId: ThreadId) { + return (yield* projections.getThread(threadId)).unsettleCause ?? null; + }); + const message = ( + name: string, + extra: Partial<{ + createdBy: "user" | "agent"; + scheduledTaskId: ScheduledTaskId; + notification: { source: { kind: "monitor" }; outcome: "completed"; summary: string }; + }>, + ) => + Effect.gen(function* () { + const threadId = yield* settled(name); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`message-unsettle-cause-${name}`), + threadId, + messageId: MessageId.make(`message-unsettle-cause-${name}`), + text: "Back again", + attachments: [], + // Notifications must queue; the rest only need a run to exist. + dispatchMode: + extra.notification === undefined + ? { type: "defer_start" } + : { type: "queue_after_active" }, + createdBy: extra.createdBy ?? "agent", + creationSource: extra.createdBy === "user" ? "web" : "server", + ...(extra.scheduledTaskId === undefined + ? {} + : { scheduledTaskId: extra.scheduledTaskId }), + ...(extra.notification === undefined ? {} : { notification: extra.notification }), + }); + return yield* cause(threadId); + }); + + assert.equal(yield* message("user-message", { createdBy: "user" }), "user_message"); + assert.equal( + yield* message("scheduled", { scheduledTaskId: ScheduledTaskId.make("task:check-in") }), + "scheduled_task", + ); + assert.equal( + yield* message("wake", { + notification: { source: { kind: "monitor" }, outcome: "completed", summary: "#7: merged" }, + }), + "notification", + ); + assert.equal(yield* message("agent-message", {}), "agent_message"); + + for (const reason of ["user", "agent"] as const) { + const threadId = yield* settled(`unsettle-${reason}`); + yield* orchestrator.dispatch({ + type: "thread.unsettle", + commandId: CommandId.make(`unsettle-cause-${reason}`), + threadId, + reason, + }); + assert.equal(yield* cause(threadId), reason); + } + + const pinned = yield* settled("pin"); + yield* orchestrator.dispatch({ + type: "thread.pin", + commandId: CommandId.make("pin-unsettle-cause"), + threadId: pinned, + }); + assert.equal(yield* cause(pinned), "pin"); + // Settling again clears it, as unsettling clears the settlement source. + yield* orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make("resettle-unsettle-cause"), + threadId: pinned, + }); + assert.isNull(yield* cause(pinned)); + }).pipe(Effect.provide(layerTest)), +); + it.effect("keeps a snooze when a live question is cancelled or an approval is answered", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5f01650993caf..b9ed47b719e54 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -58,6 +58,7 @@ import { type OrchestrationV2StoredEvent, type OrchestrationV2Subagent, type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadUnsettleCause, type OrchestrationV2TurnItem, latestProviderTurnForAttempt, parseGoalCommand, @@ -723,6 +724,20 @@ function hasLiveRun(projection: Pick): return projection.runs.some(isLiveRun); } +/** Who sent the message that reopens a settled thread; the settle audit reads it. */ +function messageUnsettleCause( + command: Pick< + Extract, + "createdBy" | "scheduledTaskId" | "guestMessageId" | "delegatedCompletion" | "notification" + >, +): OrchestrationV2ThreadUnsettleCause { + if (command.scheduledTaskId !== undefined) return "scheduled_task"; + if (command.guestMessageId !== undefined) return "guest"; + if (command.delegatedCompletion !== undefined) return "subagent_result"; + if (command.notification !== undefined) return "notification"; + return command.createdBy === "user" ? "user_message" : "agent_message"; +} + function withPullRequestWatch( link: ThreadPullRequestLink, watch: ThreadPullRequestWatch | undefined, @@ -3810,6 +3825,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : (command.settlementSource ?? null), pullRequests: thread.pullRequests?.map((link) => withPullRequestWatch(link, undefined)), unsettledAt: null, + unsettleCause: null, pinnedAt: null, pinOrderKey: null, activeOrderKey: null, @@ -3829,6 +3845,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio settledAt: null, settlementSource: null, unsettledAt: alreadyPinnedActive ? (thread.unsettledAt ?? null) : now, + unsettleCause: alreadyPinnedActive ? (thread.unsettleCause ?? null) : command.reason, updatedAt: alreadyPinnedActive ? thread.updatedAt : now, }; } @@ -3873,7 +3890,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio thread.settledOverride === "settled" ? "active" : thread.settledOverride, settledAt: thread.settledOverride === "settled" ? null : thread.settledAt, ...(thread.settledOverride === "settled" - ? { unsettledAt: now, settlementSource: null } + ? { unsettledAt: now, unsettleCause: "pin" as const, settlementSource: null } : {}), snoozedUntil: null, snoozedAt: null, @@ -5858,6 +5875,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection.thread.settledOverride === "active" ? (projection.thread.unsettledAt ?? null) : now, + unsettleCause: + projection.thread.settledOverride === "active" + ? (projection.thread.unsettleCause ?? null) + : messageUnsettleCause(command), updatedAt: now, }; const event = yield* emit( diff --git a/apps/server/src/orchestration-v2/SettlementReplyGate.ts b/apps/server/src/orchestration-v2/SettlementReplyGate.ts index 644091b9e016f..6f4c6c10b50d3 100644 --- a/apps/server/src/orchestration-v2/SettlementReplyGate.ts +++ b/apps/server/src/orchestration-v2/SettlementReplyGate.ts @@ -29,14 +29,37 @@ const REMEMBERED_RUNS = 2_000; const RETRY_DELAYS_MS = [5 * 60_000, 30 * 60_000]; const CONCURRENT_CHECKS = 4; +/** The model's answer for a run; absent when a run status decided without asking. */ +export interface SettlementReplyVerdict { + readonly model: string; + readonly requestOrigin: SettlementReplyCheckInput["requestOrigin"]; + readonly needsUser: boolean; + readonly attempt: number; +} + type Decision = - | { readonly kind: "settles" } + | { readonly kind: "settles"; readonly verdict?: SettlementReplyVerdict } | { readonly kind: "holds"; readonly reason: Exclude; + readonly verdict?: SettlementReplyVerdict; } | { readonly kind: "deciding"; readonly decided: Deferred.Deferred } - | { readonly kind: "failed"; readonly attempts: number; readonly retryAtMs: number | null }; + | { + readonly kind: "failed"; + readonly attempts: number; + readonly retryAtMs: number | null; + readonly error: string; + }; + +/** What the gate decided for a run, as the settlement decision log stores it. */ +export interface SettlementReplyCheckRecord { + readonly outcome: "settles" | "holds" | "deciding" | "failed"; + readonly reason?: SettlementHoldReason; + readonly verdict?: SettlementReplyVerdict; + readonly attempts?: number; + readonly error?: string; +} type ReplyMessage = Pick< OrchestrationV2ConversationMessage, @@ -166,11 +189,43 @@ export const make = Effect.gen(function* () { needsUser, attempt: attempts + 1, }); + const verdict: SettlementReplyVerdict = { + model: `${input.modelSelection.instanceId}:${input.modelSelection.model}`, + requestOrigin: subject.requestOrigin, + needsUser, + attempt: attempts + 1, + }; return needsUser - ? ({ kind: "holds", reason: "needs_user" } as const) - : ({ kind: "settles" } as const); + ? ({ kind: "holds", reason: "needs_user", verdict } as const) + : ({ kind: "settles", verdict } as const); }); + /** The gate's decision for a run, or null when it never decided one. */ + const describe = (runId: RunId | null): SettlementReplyCheckRecord | null => { + const decision = runId === null ? undefined : decisions.get(runId); + switch (decision?.kind) { + case undefined: + return null; + case "deciding": + return { outcome: "deciding" }; + case "failed": + return { + outcome: "failed", + reason: "no_verdict", + attempts: decision.attempts, + error: decision.error, + }; + case "settles": + return decision.verdict === undefined + ? { outcome: "settles" } + : { outcome: "settles", verdict: decision.verdict }; + case "holds": + return decision.verdict === undefined + ? { outcome: "holds", reason: decision.reason } + : { outcome: "holds", reason: decision.reason, verdict: decision.verdict }; + } + }; + /** Why the pull request may not settle the thread yet, or null when it may. */ const check = (input: SettlementReplyGateInput): Effect.Effect => Effect.suspend(() => { @@ -225,7 +280,12 @@ export const make = Effect.gen(function* () { delayMs === undefined ? null : DateTime.toEpochMillis(yield* DateTime.now) + delayMs; - remember(runId, { kind: "failed", attempts: attempts + 1, retryAtMs }); + remember(runId, { + kind: "failed", + attempts: attempts + 1, + retryAtMs, + error: Cause.pretty(cause).slice(0, 500), + }); yield* Effect.logWarning("auto-settle reply check failed; holding the thread", { threadId: input.thread.id, runId, @@ -250,7 +310,7 @@ export const make = Effect.gen(function* () { ); }; - return { holds, check }; + return { holds, check, describe }; }); export type SettlementReplyGate = Effect.Success; diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index a0c71d1f2e8d7..4fb8de7a13ebe 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -28,6 +28,7 @@ import { } from "@t3tools/contracts"; import type { SettlementReplyCheckInput } from "@t3tools/provider-core/server/textGeneration"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -39,9 +40,11 @@ import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/sql/SqlClient"; import { TestClock } from "effect/testing"; import * as GitManager from "../git/GitManager.ts"; +import * as SettlementDecisions from "../persistence/SettlementDecisions.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import * as ServerActivation from "../serverActivation.ts"; @@ -1004,10 +1007,33 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: layer: Layer.effect( ThreadSettlementService.ThreadSettlementServiceV2, ThreadSettlementService.make, - ).pipe(Layer.provide(layerDependencies)), + ).pipe( + Layer.provide(layerDependencies), + Layer.provideMerge(SettlementDecisions.layer), + Layer.provideMerge(NodeSqliteClient.layer({ filename: ":memory:" })), + ), }; }); +/** The settlement decision log, oldest first. */ +const recordedDecisions = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return yield* sql<{ + readonly thread_id: string; + readonly outcome: string; + readonly rule: string; + readonly hold_reason: string | null; + readonly run_id: string | null; + readonly reply_check_json: string | null; + readonly inputs_json: string; + readonly server_version: string; + }>` + SELECT thread_id, outcome, rule, hold_reason, run_id, reply_check_json, inputs_json, + server_version + FROM settlement_decisions ORDER BY id + `; +}); + const startHarness = Effect.fn("startThreadSettlementHarness")(function* ( reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"], activation: Deferred.Deferred, @@ -1142,8 +1168,20 @@ describe("ThreadSettlementServiceV2 worker", () => { latestUserMessageAt: DateTime.makeUnsafe("2026-08-28T10:00:00.000Z"), }); const idle = makeThread("idle"); + // Its pull request merged, but the agent still waits on a watch, which holds it. + const watched = makeThread("watched-pull-request", { + pullRequests: [finishedLink("merged", "2026-08-20T00:00:00.000Z", NOW)], + pendingBackgroundTasks: [ + { + taskId: "pull-request-watch:example.test/owner/repository#42", + description: "Watching pull request #42", + kind: "monitor", + awaited: true, + }, + ], + }); const fixture = yield* makeHarness({ - snapshot: makeSnapshot([closed, merged, onBranch, idle]), + snapshot: makeSnapshot([closed, merged, onBranch, idle, watched]), settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3, @@ -1165,6 +1203,24 @@ describe("ThreadSettlementServiceV2 worker", () => { [idle.id, "auto_inactivity"], ]), ); + // Each settle is logged with its rule, and so is the rule the watch is holding back. + const decisions = yield* recordedDecisions; + expect( + new Map( + decisions.map((row) => [row.thread_id, [row.outcome, row.rule, row.hold_reason]]), + ), + ).toEqual( + new Map([ + [closed.id, ["settled", "auto_pull_request_closed", null]], + [merged.id, ["settled", "auto_pull_request_merged", null]], + [onBranch.id, ["settled", "auto_branch_pull_request_merged", null]], + [idle.id, ["settled", "auto_inactivity", null]], + [watched.id, ["held", "auto_pull_request_merged", "background_work"]], + ]), + ); + const watchedRow = decisions.find((row) => row.thread_id === watched.id); + expect(JSON.parse(watchedRow?.inputs_json ?? "null")?.thread.id).toBe(watched.id); + expect(decisions.every((row) => row.server_version !== "")).toBe(true); }).pipe(Effect.provide(fixture.layer)); }), ), @@ -1861,6 +1917,54 @@ describe("ThreadSettlementServiceV2 reply check", () => { new Map([[asks.id, "auto_pull_request_merged"]]), ); assert.equal((yield* Ref.get(fixture.replyChecks)).length, 3); + + // Three sweeps held each first run once, with what the model said; then the next run settled. + const decisions = (yield* recordedDecisions).map((row) => ({ + thread: row.thread_id, + run: row.run_id, + outcome: row.outcome, + rule: row.rule, + hold: row.hold_reason, + check: JSON.parse(row.reply_check_json ?? "null"), + })); + const model = `${settings.textGenerationModelSelection.instanceId}:${settings.textGenerationModelSelection.model}`; + expect(decisions).toEqual([ + { + thread: asks.id, + run: asks.latestRunId, + outcome: "held", + rule: "auto_pull_request_merged", + hold: "needs_user", + check: { + outcome: "holds", + reason: "needs_user", + verdict: { model, requestOrigin: "user", needsUser: true, attempt: 1 }, + }, + }, + { + thread: onBranch.id, + run: onBranch.latestRunId, + outcome: "held", + rule: "auto_branch_pull_request_merged", + hold: "needs_user", + check: { + outcome: "holds", + reason: "needs_user", + verdict: { model, requestOrigin: "user", needsUser: true, attempt: 1 }, + }, + }, + { + thread: asks.id, + run: nextRun.latestRunId, + outcome: "settled", + rule: "auto_pull_request_merged", + hold: null, + check: { + outcome: "settles", + verdict: { model, requestOrigin: "scheduled", needsUser: false, attempt: 1 }, + }, + }, + ]); }).pipe(Effect.provide(fixture.layer)); }), ), diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index ae3e6a15dccd8..e42c52d52dbb4 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -27,6 +27,7 @@ import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as GitManager from "../git/GitManager.ts"; +import * as SettlementDecisions from "../persistence/SettlementDecisions.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -47,6 +48,14 @@ export interface SettlementPullRequest { const DAY_MS = 24 * 60 * 60 * 1_000; const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000; +// Holds a rule change could alter. Pins, snoozes and running turns say nothing about the rules, +// and recording them would add a row for every turn of every pinned thread. +const RECORDED_HOLDS: ReadonlySet = new Set([ + "background_work", + "pending_request", + "guest_waiting", + "reply_check", +]); function toMillis(value: DateTime.Utc | null | undefined): number | null { return value == null ? null : DateTime.toEpochMillis(value); @@ -161,20 +170,44 @@ function pullRequestSettles( return pullRequestAtMs >= userAnchorMs; } -export function isAutoSettlementCandidate( +/** Why a thread may not auto-settle right now, whatever its rules say. */ +export type AutoSettlementHold = + | "archived" + | "settled" + | "kept_active" + | "pinned" + | "auto_settle_off" + | "pending_request" + | "guest_waiting" + | "run_active" + | "background_work" + | "queued_turn" + | "snoozed"; + +function autoSettlementHold( thread: Omit, nowMs: number, -): boolean { - if (thread.archivedAt !== null || thread.settledOverride !== null) return false; - if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false; - if (thread.pendingRuntimeRequest !== null) return false; +): AutoSettlementHold | null { + if (thread.archivedAt !== null) return "archived"; + if (thread.settledOverride === "settled") return "settled"; + if (thread.settledOverride === "active") return "kept_active"; + if (thread.pinnedAt != null) return "pinned"; + if (thread.autoSettleDisabledAt != null) return "auto_settle_off"; + if (thread.pendingRuntimeRequest !== null) return "pending_request"; // A guest is waiting on the owner; settling would hide the Request. - if ((thread.pendingGuestMessageCount ?? 0) > 0) return false; - if (thread.activityRunStatus != null) return false; - if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return false; - if (threadHasQueuedTurnStart(thread, nowMs)) return false; + if ((thread.pendingGuestMessageCount ?? 0) > 0) return "guest_waiting"; + if (thread.activityRunStatus != null) return "run_active"; + if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return "background_work"; + if (threadHasQueuedTurnStart(thread, nowMs)) return "queued_turn"; // Interrupted runs must keep the same snooze protection the sidebar shows. - return !isSnoozed(thread, nowMs); + return isSnoozed(thread, nowMs) ? "snoozed" : null; +} + +export function isAutoSettlementCandidate( + thread: Omit, + nowMs: number, +): boolean { + return autoSettlementHold(thread, nowMs) === null; } /** Match client effectiveSnoozed so agents and sidebar agree. */ @@ -222,16 +255,27 @@ type AutoSettlementInput = { }; export function resolveAutoSettlementAt(input: AutoSettlementInput): DateTime.Utc | null { - return resolveAutoSettlement(input)?.settledAt ?? null; + const settlement = resolveAutoSettlement(input); + return settlement?.outcome === "settle" ? settlement.settledAt : null; } -/** When the thread should settle and which rule settles it, or null if none does yet. */ -function resolveAutoSettlement(input: AutoSettlementInput): { - readonly settledAt: DateTime.Utc; - readonly source: OrchestrationV2AutoSettlementSource; - /** Set when a merged or closed pull request settles the thread. */ - readonly pullRequest?: SettlementPullRequest & { readonly state: "merged" | "closed" }; -} | null { +export type AutoSettlement = + | { + readonly outcome: "settle"; + readonly settledAt: DateTime.Utc; + readonly source: OrchestrationV2AutoSettlementSource; + /** Set when a merged or closed pull request settles the thread. */ + readonly pullRequest?: SettlementPullRequest & { readonly state: "merged" | "closed" }; + } + | { + /** A rule would settle the thread, but a hold, or the reply check for a PR rule, stops it. */ + readonly outcome: "hold"; + readonly source: OrchestrationV2AutoSettlementSource; + readonly hold: AutoSettlementHold | "reply_check"; + }; + +/** Which rule settles the thread, or holds it from settling, or null when no rule applies. */ +export function resolveAutoSettlement(input: AutoSettlementInput): AutoSettlement | null { const { thread } = input; let pullRequest = input.pullRequest; const visibleLinks = visibleThreadPullRequests(thread.pullRequests ?? []); @@ -257,7 +301,7 @@ function resolveAutoSettlement(input: AutoSettlementInput): { closedAt: latest.snapshot.closedAt ?? null, }; } - if (!isAutoSettlementCandidate(thread, input.nowMs)) return null; + const hold = autoSettlementHold(thread, input.nowMs); const activityAtMs = latestMillis([ toMillis(thread.latestUserMessageAt), @@ -265,34 +309,54 @@ function resolveAutoSettlement(input: AutoSettlementInput): { toMillis(thread.latestRunStartedAt), toMillis(thread.latestRunCompletedAt), ]) ?? DateTime.toEpochMillis(thread.createdAt); - if ( - pullRequest !== null && - input.pullRequestHeld !== true && - pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge) - ) { + let heldPullRequestSource: OrchestrationV2AutoSettlementSource | null = null; + if (pullRequest !== null && pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) { // With no link, the sweep found this pull request from the thread's branch. const fromBranch = visibleLinks.length === 0 && thread.linkedPullRequest == null; const state = pullRequest.state === "merged" ? "merged" : "closed"; - return { - settledAt: DateTime.makeUnsafe(activityAtMs), - source: fromBranch ? `auto_branch_pull_request_${state}` : `auto_pull_request_${state}`, - pullRequest: { ...pullRequest, state }, - }; + const source = fromBranch + ? (`auto_branch_pull_request_${state}` as const) + : (`auto_pull_request_${state}` as const); + if (hold === null && input.pullRequestHeld !== true) { + return { + outcome: "settle", + settledAt: DateTime.makeUnsafe(activityAtMs), + source, + pullRequest: { ...pullRequest, state }, + }; + } + heldPullRequestSource = source; } const hasPullRequest = hasOpenLink || pullRequest !== null || thread.linkedPullRequest != null || thread.branchPullRequest != null; - if (input.autoSettleKeepPullRequests === true && hasPullRequest) return null; - if (input.autoSettleAfterDays === null) return null; - const snoozedUntilMs = toMillis(thread.snoozedUntil); - const timerWakeAtMs = - snoozedUntilMs !== null && snoozedUntilMs <= input.nowMs ? snoozedUntilMs : null; - const inactivityAtMs = - latestMillis([activityAtMs, toMillis(thread.lastSnoozeWakeAt), timerWakeAtMs]) ?? activityAtMs; - return inactivityAtMs < input.nowMs - input.autoSettleAfterDays * DAY_MS - ? { settledAt: DateTime.makeUnsafe(inactivityAtMs), source: "auto_inactivity" } + const inactivityAtMs = (() => { + if (input.autoSettleKeepPullRequests === true && hasPullRequest) return null; + if (input.autoSettleAfterDays === null) return null; + const snoozedUntilMs = toMillis(thread.snoozedUntil); + const timerWakeAtMs = + snoozedUntilMs !== null && snoozedUntilMs <= input.nowMs ? snoozedUntilMs : null; + const inactiveSinceMs = + latestMillis([activityAtMs, toMillis(thread.lastSnoozeWakeAt), timerWakeAtMs]) ?? + activityAtMs; + return inactiveSinceMs < input.nowMs - input.autoSettleAfterDays * DAY_MS + ? inactiveSinceMs + : null; + })(); + if (inactivityAtMs !== null && hold === null) { + return { + outcome: "settle", + settledAt: DateTime.makeUnsafe(inactivityAtMs), + source: "auto_inactivity", + }; + } + if (heldPullRequestSource !== null) { + return { outcome: "hold", source: heldPullRequestSource, hold: hold ?? "reply_check" }; + } + return inactivityAtMs !== null && hold !== null + ? { outcome: "hold", source: "auto_inactivity", hold } : null; } @@ -359,8 +423,68 @@ export const make = Effect.gen(function* () { const terminals = yield* TerminalManager.TerminalManager; const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; const replyGate = yield* SettlementReplyGate.make; + const decisionLog = yield* SettlementDecisions.SettlementDecisionLog; // Repeated thread.settled retains settledAt; run the action only once per settlement. const settleActionRunAt = new Map(); + // The last hold recorded per thread, so a hold that every sweep repeats is written once. + const recordedHolds = new Map(); + + const recordDecision = (input: { + readonly thread: ProjectionStore.ProjectionSettlementCandidate; + readonly pullRequest: SettlementPullRequest | null; + readonly settlement: AutoSettlement; + readonly settings: Pick< + import("@t3tools/contracts").ServerSettings, + | "sidebarAutoSettleOnMerge" + | "sidebarAutoSettleAfterDays" + | "sidebarAutoSettleKeepPullRequests" + | "sidebarAutoSettleReplyCheck" + | "textGenerationModelSelection" + >; + readonly trigger: SettlementDecisions.SettlementDecisionTrigger; + readonly nowMs: number; + }) => + Effect.suspend(() => { + const { thread, settlement, settings } = input; + if (settlement.outcome === "hold" && !RECORDED_HOLDS.has(settlement.hold)) { + return Effect.void; + } + const replyCheck = replyGate.describe(thread.latestRunId); + const holdReason = + settlement.outcome === "settle" + ? null + : settlement.hold === "reply_check" + ? (replyCheck?.reason ?? settlement.hold) + : settlement.hold; + if (settlement.outcome === "hold") { + const key = [settlement.source, holdReason, thread.latestRunId].join(" "); + if (recordedHolds.get(thread.id) === key) return Effect.void; + recordedHolds.set(thread.id, key); + } else { + recordedHolds.delete(thread.id); + } + return decisionLog.record({ + decidedAt: DateTime.formatIso(DateTime.makeUnsafe(input.nowMs)), + threadId: thread.id, + projectId: thread.projectId, + outcome: settlement.outcome === "settle" ? "settled" : "held", + rule: settlement.source, + holdReason, + trigger: input.trigger, + runId: thread.latestRunId, + settledAt: + settlement.outcome === "settle" ? DateTime.formatIso(settlement.settledAt) : null, + replyCheck, + inputs: { thread, pullRequest: input.pullRequest }, + settings: { + onMerge: settings.sidebarAutoSettleOnMerge, + afterDays: settings.sidebarAutoSettleAfterDays, + keepPullRequests: settings.sidebarAutoSettleKeepPullRequests, + replyCheck: settings.sidebarAutoSettleReplyCheck, + replyCheckModel: settings.textGenerationModelSelection, + }, + }); + }); const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* ( mergedPullRequest: PullRequestService.PullRequestMergeEvent | null, @@ -375,8 +499,50 @@ export const make = Effect.gen(function* () { const projectShells = yield* projectStore.listShells(); const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const projects = new Map(projectShells.map((project) => [project.id, project])); + const trigger: SettlementDecisions.SettlementDecisionTrigger = + mergedPullRequest !== null + ? "merge_event" + : threadId !== undefined + ? "thread_event" + : "full_sweep"; // Merge events resweep all candidates because unlinked threads settle through branch lookup. const candidates = threads.filter((thread) => isAutoSettlementCandidate(thread, nowMs)); + const settlementFromLinks = (thread: (typeof threads)[number]) => { + const projectSettings = resolveProjectSettings(settings, thread.projectId).settings; + return resolveAutoSettlement({ + thread, + pullRequest: null, + nowMs, + autoSettleAfterDays: projectSettings.sidebarAutoSettleAfterDays, + autoSettleOnMerge: projectSettings.sidebarAutoSettleOnMerge, + autoSettleKeepPullRequests: projectSettings.sidebarAutoSettleKeepPullRequests, + pullRequestHeld: replyGate.holds( + thread, + nowMs, + projectSettings.sidebarAutoSettleReplyCheck, + ), + }); + }; + const recordHold = (thread: (typeof threads)[number], settlement: AutoSettlement | null) => + settlement?.outcome === "hold" + ? recordDecision({ + thread, + pullRequest: null, + settlement, + settings: resolveProjectSettings(settings, thread.projectId).settings, + trigger, + nowMs, + }) + : Effect.void; + // A thread a hold keeps out of the candidates still has its blocked rule recorded. + yield* Effect.forEach( + threads, + (thread) => + isAutoSettlementCandidate(thread, nowMs) + ? Effect.void + : recordHold(thread, settlementFromLinks(thread)), + { discard: true }, + ); // Runs per candidate thread, thousands per sweep on busy servers; the sweep owns the span. const settleThread = Effect.fnUntraced( @@ -399,7 +565,7 @@ export const make = Effect.gen(function* () { pullRequestHeld, }); let settlement = decide(replyGate.holds(thread, decisionNowMs, checkReply)); - if (settlement?.pullRequest !== undefined) { + if (settlement?.outcome === "settle" && settlement.pullRequest !== undefined) { const { state, mergedAt, closedAt } = settlement.pullRequest; const held = yield* replyGate.check({ thread, @@ -414,6 +580,18 @@ export const make = Effect.gen(function* () { if (held !== null) settlement = decide(true); } if (settlement === null) return thread; + const decided = { + thread, + pullRequest, + settlement, + settings: currentSettings, + trigger, + nowMs: decisionNowMs, + }; + if (settlement.outcome === "hold") { + yield* recordDecision(decided); + return thread; + } const uuid = yield* random.uuidV4(); yield* orchestrator.dispatch({ type: "thread.auto-settle", @@ -423,6 +601,7 @@ export const make = Effect.gen(function* () { settledAt: settlement.settledAt, settlementSource: settlement.source, }); + yield* recordDecision(decided); return null; }, (effect, thread) => @@ -441,22 +620,11 @@ export const make = Effect.gen(function* () { const lookupCandidates = (yield* Effect.forEach( candidates, (thread) => { - const projectSettings = resolveProjectSettings(settings, thread.projectId).settings; // Skip no-op decisions; actual settlement still reads fresh settings before dispatch. - const settledAt = resolveAutoSettlementAt({ - thread, - pullRequest: null, - nowMs, - autoSettleAfterDays: projectSettings.sidebarAutoSettleAfterDays, - autoSettleOnMerge: projectSettings.sidebarAutoSettleOnMerge, - autoSettleKeepPullRequests: projectSettings.sidebarAutoSettleKeepPullRequests, - pullRequestHeld: replyGate.holds( - thread, - nowMs, - projectSettings.sidebarAutoSettleReplyCheck, - ), - }); - return settledAt === null ? Effect.succeed(thread) : settleThread(thread, null); + const settlement = settlementFromLinks(thread); + return settlement?.outcome === "settle" + ? settleThread(thread, null) + : recordHold(thread, settlement).pipe(Effect.as(thread)); }, { concurrency: 8 }, )) diff --git a/apps/server/src/persistence/SettlementDecisions.ts b/apps/server/src/persistence/SettlementDecisions.ts new file mode 100644 index 0000000000000..64acabb1ef1d8 --- /dev/null +++ b/apps/server/src/persistence/SettlementDecisions.ts @@ -0,0 +1,96 @@ +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import type { OrchestrationV2AutoSettlementSource } from "@t3tools/contracts"; + +import packageJson from "../../package.json" with { type: "json" }; + +const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); + +/** What made the settlement service look at the thread. */ +export type SettlementDecisionTrigger = "merge_event" | "thread_event" | "full_sweep"; + +export interface SettlementDecision { + readonly decidedAt: string; + readonly threadId: string; + readonly projectId: string; + readonly outcome: "settled" | "held"; + /** The rule that settled the thread, or the one that would have without the hold. */ + readonly rule: OrchestrationV2AutoSettlementSource; + readonly holdReason: string | null; + readonly trigger: SettlementDecisionTrigger; + readonly runId: string | null; + readonly settledAt: string | null; + /** The reply check's record for `runId`, when it decided one. */ + readonly replyCheck: unknown; + /** The settlement candidate the rules read, so the audit can replay them. */ + readonly inputs: unknown; + readonly settings: unknown; +} + +export class SettlementDecisionLog extends Context.Service< + SettlementDecisionLog, + { readonly record: (decision: SettlementDecision) => Effect.Effect } +>()("t3/persistence/SettlementDecisions/SettlementDecisionLog") {} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + // Created here rather than in a migration: fork migration ids collide with upstream's + // (see reconcileForkMigration.ts), and nothing else reads this table. + yield* sql` + CREATE TABLE IF NOT EXISTS settlement_decisions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + decided_at TEXT NOT NULL, + thread_id TEXT NOT NULL, + project_id TEXT NOT NULL, + outcome TEXT NOT NULL, + rule TEXT NOT NULL, + hold_reason TEXT, + trigger TEXT NOT NULL, + run_id TEXT, + settled_at TEXT, + reply_check_json TEXT, + inputs_json TEXT NOT NULL, + settings_json TEXT NOT NULL, + server_version TEXT NOT NULL + ) + `; + yield* sql` + CREATE INDEX IF NOT EXISTS settlement_decisions_thread_idx + ON settlement_decisions(thread_id, id) + `; + + return SettlementDecisionLog.of({ + record: Effect.fn("SettlementDecisionLog.record")( + function* (decision) { + const replyCheck = + decision.replyCheck == null ? null : yield* encodeJson(decision.replyCheck); + const inputs = yield* encodeJson(decision.inputs); + const settings = yield* encodeJson(decision.settings); + yield* sql` + INSERT INTO settlement_decisions ( + decided_at, thread_id, project_id, outcome, rule, hold_reason, trigger, run_id, + settled_at, reply_check_json, inputs_json, settings_json, server_version + ) VALUES ( + ${decision.decidedAt}, ${decision.threadId}, ${decision.projectId}, + ${decision.outcome}, ${decision.rule}, ${decision.holdReason}, ${decision.trigger}, + ${decision.runId}, ${decision.settledAt}, ${replyCheck}, ${inputs}, ${settings}, + ${packageJson.version} + ) + `; + }, + // A lost audit row must never stop a thread from settling. + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.interrupt + : Effect.logWarning("settlement decision not recorded", { cause }), + ), + ), + }); +}); + +export const layer = Layer.effect(SettlementDecisionLog, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index f71729ca64dc6..495ffacf64969 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -52,6 +52,7 @@ import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderR import * as PullRequestService from "./pullRequest/PullRequestService.ts"; import * as SqlitePersistence from "./persistence/Sqlite.ts"; import * as PullRequestFilesViewed from "./persistence/PullRequestFilesViewed.ts"; +import * as SettlementDecisions from "./persistence/SettlementDecisions.ts"; import * as PullRequestReviewGuides from "./persistence/PullRequestReviewGuides.ts"; import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; @@ -587,7 +588,11 @@ const layerOrchestrationApplication = Layer.merge( const layerThreadSettlementWorker = Layer.effectDiscard( ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())), -).pipe(Layer.provide(layerPullRequestService), Layer.provide(ProjectionStoreV2.layer)); +).pipe( + Layer.provide(layerPullRequestService), + Layer.provide(ProjectionStoreV2.layer), + Layer.provide(SettlementDecisions.layer), +); const layerIdleCompactionWorker = Layer.effectDiscard( IdleCompactionService.make.pipe(Effect.flatMap((service) => service.start())), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 079c5261e58f7..374e5509fabac 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -472,6 +472,28 @@ const LenientThreadSettlementSource = Schema.NullOr(OrchestrationV2ThreadSettlem Schema.catchDecoding(() => Effect.succeedSome(null)), ); +/** + * What brought a settled thread back. `user` and `agent` are an explicit unsettle from the app or + * an agent's MCP call; the message causes name who sent the message that reopened it. Recorded so + * a settle that someone undid can be told apart from one a schedule or a wake reopened. + */ +export const OrchestrationV2ThreadUnsettleCause = Schema.Literals([ + "user", + "agent", + "pin", + "user_message", + "agent_message", + "scheduled_task", + "notification", + "subagent_result", + "guest", +]); +export type OrchestrationV2ThreadUnsettleCause = typeof OrchestrationV2ThreadUnsettleCause.Type; + +const LenientThreadUnsettleCause = Schema.NullOr(OrchestrationV2ThreadUnsettleCause).pipe( + Schema.catchDecoding(() => Effect.succeedSome(null)), +); + export const OrchestrationV2AppThread = Schema.Struct({ ...OrchestrationV2CreationFields, id: ThreadId, @@ -513,6 +535,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ ), settlementSource: Schema.optional(LenientThreadSettlementSource), unsettledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), + unsettleCause: Schema.optional(LenientThreadUnsettleCause), snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), @@ -3042,7 +3065,8 @@ export const OrchestrationV2Command = Schema.Union([ type: Schema.Literal("thread.unsettle"), commandId: CommandId, threadId: ThreadId, - reason: Schema.Literal("user"), + /** `agent` is an agent's MCP unsettle; the app always sends `user`. */ + reason: Schema.Literals(["user", "agent"]), }), Schema.Struct({ type: Schema.Literal("thread.snooze"),