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
8 changes: 5 additions & 3 deletions packages/cli/src/decideCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -693,7 +693,7 @@ export const DECIDE_VERB_HELP: Record<string, VerbHelpSpec> = {
ls: { usage: "cast decide ls [--mine | --stack <ds-N> | --answered-since <time>] [--json]", summary: "This session's decisions with their answers; --mine every pending one you hold; --answered-since a team's answered cards", flags: ["--mine", "--stack", "--answered-since", "--team", "--limit", "--calibration", "--session", "--json"] },
show: { usage: "cast decide show <sd-N> [--json]", summary: "One decision with its document, ladder and answer", flags: ["--json"] },
edit: { usage: "cast decide edit [sd-N] [--question …] [--context …] [-o … ]", summary: "Rewrite this session's open decision in place, keeping its spot in the queue (default: the open one)", flags: ["--question", "--context", "--option", "--option-body", "--option-page", "--report", "--doc", "--category", "--kind", "--impact", "--advisory", "--default", "--blocking", "--session", "--json"] },
cancel: { usage: "cast decide cancel [sd-N]", summary: "Withdraw this session's open decision when it no longer applies (default: the open one)", flags: ["--session", "--json"] },
cancel: { usage: "cast decide cancel [sd-N] [--note -]", summary: "Withdraw this session's open decision when it no longer applies (default: the open one); another session's, with --note saying why, and that session is told", flags: ["--note", "--session", "--json"] },
answer: { usage: 'cast decide answer <sd-N> <n | "1,3" | "2>1>3"> [--note -] [--form k=v]', summary: "Answer a decision: as a person at a plain shell, as the holder role under a grant, or for your human at their explicit word", flags: ["--note", "--form", "--for-human", "--json"] },
recommend: { usage: "cast decide recommend <sd-N> <n> [--note -]", summary: "As a role on the decision's ladder, recommend an option to the people who decide", flags: ["--note", "--session", "--json"] },
pass: { usage: "cast decide pass <sd-N> [--to <person>] [--note -]", summary: "Pass a decision up the ladder, or to a named teammate", flags: ["--to", "--note", "--session", "--json"] },
Expand Down Expand Up @@ -753,7 +753,7 @@ export function registerDecideCommand(program: Command, deps: PublishDeps): void
.option("--team <name|id>", "ls --answered-since: the team (default: the active one)")
.option("-n, --limit <n>", "ls --answered-since: rows per page (default 50, at most 100)", boundedCountOption(100))
.option("--calibration", "ls --answered-since: whether the cards' confidence holds, every answer in the window grouped by the confidence its card gave")
.option("--note <text>", stdinText("recommend / pass / escalate: one or two plain sentences the person needs that the card does not already say; never retell the card, never cite ids (escalate needs one). answer: your words with the pick, delivered with it"))
.option("--note <text>", stdinText("cancel: why another session's card no longer applies (its session is told). recommend / pass / escalate: one or two plain sentences the person needs that the card does not already say; never retell the card, never cite ids (escalate needs one). answer: your words with the pick, delivered with it"))
.addOption(new Option("--reason <text>", stdinText("same as --note")).hideHelp())
.option("--form <k=v>", "answer: a form field value (repeatable)", (val: string, acc: string[]) => [...acc, val], [] as string[])
.option("--for-human", "answer: from a session, answer as your human. Only when they explicitly told you in this conversation to answer this decision, or agreed to this choice; never on your own judgment")
Expand Down Expand Up @@ -850,6 +850,7 @@ export function registerDecideCommand(program: Command, deps: PublishDeps): void
const d: DecisionRow = result.decision;
console.log(formatDecisionList([d]));
if (d.context_md?.trim()) for (const line of d.context_md.trim().split("\n")) console.log(` ${line}`);
if (result.decision.asked_in) console.log(fmt.muted(` asked in session ${result.decision.asked_in}: only it can edit this card${result.decision.yours && d.status === "pending" ? `; any of your sessions can withdraw it: cast decide cancel ${d.short_id} --note "<why>"` : ""}`));
if (result.task) console.log(fmt.muted(` task: ${result.task.short_id} ${result.task.title} (${result.task.status})`));
if (result.stack) console.log(fmt.muted(` stack: ${result.stack.short_id} ${result.stack.title}`));
if (result.holder_role) console.log(fmt.muted(` holder: role ${result.holder_role.name} (@${result.holder_role.handle}) under a grant`));
Expand Down Expand Up @@ -934,7 +935,8 @@ export function registerDecideCommand(program: Command, deps: PublishDeps): void
}

if (sub === "cancel" || sub === "rm" || sub === "withdraw") {
const result = await decideApi(deps, { action: "cancel", session_id: sessionId, decision_id: target });
const reason: string | undefined = options.note?.trim() || undefined;
const result = await decideApi(deps, { action: "cancel", session_id: sessionId, decision_id: target, ...(reason ? { reason } : {}) });
if (options.json) console.log(JSON.stringify(result, null, 2));
else console.log(`${fmt.success("Decision withdrawn:")} ${target}. It leaves the queue; the conversation shows it as withdrawn.`);
return;
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2459,6 +2459,8 @@ async function refreshEnabledSnippets(config: Record<string, any>): Promise<void
if (config.publish_enabled) installPublishSnippet(true);
if (config.browser_enabled) installBrowserSnippet(true);
if (config.chat_enabled) installChatSnippet(true);
if (config.decide_enabled) installSnippetSection("decide", true);
if (config.state_enabled) installStateSnippet(true);
for (const slug of Object.keys(SECTION_SNIPPET_VERSIONS) as SectionSnippetSlug[]) {
if (config[snippetDescriptor(slug).enabledKey]) installSnippetSection(slug, true);
}
Expand Down
14 changes: 14 additions & 0 deletions packages/cli/src/snippets.wiring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,18 @@ describe("every catalog snippet is wired into the CLI", () => {
expect(indexSource).toContain("config.browser_enabled && config.browser_version");
expect(indexSource).toContain("if (config.browser_enabled) installBrowserSnippet(true)");
});

test("every enabled snippet is refreshed when the binary updates", () => {
// `cast update` and the daemon's automatic update both run
// refreshEnabledSnippets(); setup's stale check runs only on `cast setup`.
// A snippet missing from the refresh keeps the text it was first installed
// with: decide and state sat on their August bodies for months this way.
const start = indexSource.indexOf("async function refreshEnabledSnippets(");
const refresh = indexSource.slice(start, indexSource.indexOf("\n}\n", start));
const sectionTable = indexSource.slice(indexSource.indexOf("const SECTION_SNIPPET_VERSIONS"), indexSource.indexOf("};", indexSource.indexOf("const SECTION_SNIPPET_VERSIONS")));
const missing = SNIPPET_CATALOG.filter(
(s) => !refresh.includes(`config.${s.enabledKey}`) && !sectionTable.includes(` ${s.slug}:`),
).map((s) => s.slug);
expect(missing).toEqual([]);
});
});
27 changes: 22 additions & 5 deletions packages/convex/convex/deployCarries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { workspaceKeyHasFeature } from "./lib/teamFeatureGuard";
import { HANDED_EXIT } from "@codecast/shared/contracts/mergeOff";
import { deployStopOf } from "@codecast/shared/contracts/deployStop";
import { distinctShortRef } from "./conversationSessionLookup";
import { withdrawWithCard } from "./sessionDecisions";

/** How far back merges are read for the waiting set and a marker's carries. */
const MERGE_WINDOW_MS = 90 * DAY;
Expand Down Expand Up @@ -359,6 +360,10 @@ type UnmergedRun = Pick<Doc<"workflow_runs">, "status" | "current_node_id" | "me
export const endedBeforeMerge = (run: UnmergedRun): boolean =>
!run.merge && (run.status === "failed" || (run.status === "completed" && run.current_node_id === HANDED_EXIT));

/** A run paused on a card before its own merge: merging its pull request elsewhere answers the card (recordOutsideMerge). */
export const pausedBeforeMerge = (run: Pick<Doc<"workflow_runs">, "status" | "merge" | "gate_decision_id">): boolean =>
!run.merge && run.status === "paused" && !!run.gate_decision_id;

/** A run that ended before its own merge whose pull request was then merged outside it (recordOutsideMerge). */
export const mergedOutside = (run: UnmergedRun): boolean =>
!!run.merge?.outside && (run.status === "failed" || (run.status === "completed" && run.current_node_id === HANDED_EXIT));
Expand Down Expand Up @@ -387,7 +392,12 @@ async function outsideMergeRun(ctx: any, pr: Doc<"pull_requests">, now: number):
.withIndex("by_pr", (q: any) => q.eq("pr.repository", pr.repository).eq("pr.number", pr.number))
.order("desc")
.first();
return run && endedBeforeMerge(run) && !run.resume_queued && run.updated_at >= now - STOPPED_RUN_WINDOW_MS ? run : null;
if (!run || run.resume_queued || run.updated_at < now - STOPPED_RUN_WINDOW_MS) return null;
if (endedBeforeMerge(run)) return run;
// A card already answered resumes its run, whose Merge station reads the merged pull request itself.
if (!pausedBeforeMerge(run)) return null;
const card = await ctx.db.get(run.gate_decision_id!);
return card?.status === "pending" ? run : null;
}

/**
Expand All @@ -396,9 +406,11 @@ async function outsideMergeRun(ctx: any, pr: Doc<"pull_requests">, now: number):
* else; going live" in place of its stop, drops the blocker its stop left on the task, and completes at Live at once
* when deploys already carry the merge (else the deploy that does completes it, completeLiveRuns). A run still running
* sees the merge itself (its Merge station reads a merged pull request), and a run that recorded a merge is left alone.
* A run paused on a pending card (sd-5438: a person merged on GitHub instead of answering) has the card withdrawn with
* these words, which fails the run at its gate, and then records the merge like a stopped one.
*/
export async function recordOutsideMerge(ctx: any, pr: Doc<"pull_requests">, named: string | undefined, now = Date.now()): Promise<Id<"workflow_runs"> | null> {
const run = await outsideMergeRun(ctx, pr, now);
let run = await outsideMergeRun(ctx, pr, now);
if (!run || !pr.merge_commit_sha) return null;
const by = named ?? (await mergedByOf(ctx, pr));
const sha = pr.merge_commit_sha.toLowerCase();
Expand All @@ -410,6 +422,10 @@ export async function recordOutsideMerge(ctx: any, pr: Doc<"pull_requests">, nam
const graph = await runWorkflowOf(ctx, run);
const prefix = graph ? deployPrefixOf(graph as unknown as GraphShape) : null;
const words = outsideMergeWords(pr, sha, by, !!(prefix && liveExitOf(graph as unknown as GraphShape, prefix)));
if (pausedBeforeMerge(run)) {
await withdrawWithCard(ctx, (await ctx.db.get(run.gate_decision_id!))!, words, now);
run = (await ctx.db.get(run._id)) as Doc<"workflow_runs">;
}
await ctx.db.patch(run._id, { merge, ...(run.status === "failed" ? { fail_reason: words } : {}), updated_at: now });
const task: Doc<"tasks"> | null = run.task_id ? await ctx.db.get(run.task_id) : null;
if (task) await clearStopBlocker(ctx, task, run.fail_reason, now);
Expand Down Expand Up @@ -509,13 +525,14 @@ export const recordOutsideMergeOnPr = internalMutation({
* the webhook would have, and the runs that recorded such a merge, or stopped at Deploy (deployStopOf), but did not
* complete at Live though deploys carry it, and names who merged a run's recorded outside merge when the merge's event
* says and the record does not. Idempotent: a run that completed at Live is never healed again. A dry run by
* default; one page of runs of `status` (failed, or completed: a Deploy stop whose runner lost the exit's stop),
* default; one page of runs of `status` (failed; completed: a Deploy stop whose runner lost the exit's stop; or paused on a card),
* newest first, and with `auto` each page schedules the next until runs older than the window.
* packages/convex/run.sh deployCarries:healOutsideMerges '{"dry": false, "auto": true}'
* packages/convex/run.sh deployCarries:healOutsideMerges '{"dry": false, "auto": true, "status": "completed"}'
* packages/convex/run.sh deployCarries:healOutsideMerges '{"dry": false, "auto": true, "status": "paused"}' (a run paused on its card)
*/
export const healOutsideMerges = internalMutation({
args: { dry: v.optional(v.boolean()), auto: v.optional(v.boolean()), cursor: v.optional(v.union(v.string(), v.null())), status: v.optional(v.union(v.literal("failed"), v.literal("completed"))) },
args: { dry: v.optional(v.boolean()), auto: v.optional(v.boolean()), cursor: v.optional(v.union(v.string(), v.null())), status: v.optional(v.union(v.literal("failed"), v.literal("completed"), v.literal("paused"))) },
handler: async (ctx, args) => {
const now = Date.now();
const dry = args.dry !== false;
Expand All @@ -539,7 +556,7 @@ export const healOutsideMerges = internalMutation({
if (dry ? await runLiveAt(ctx, run, run.pr.repository, null, now) : await completeRunIfLive(ctx, run, run.pr.repository, null, now)) healed.push(String(run._id));
continue;
}
if (status !== "failed" || !endedBeforeMerge(run)) continue;
if (!(status === "failed" ? endedBeforeMerge(run) : status === "paused" && pausedBeforeMerge(run))) continue;
const pr: Doc<"pull_requests"> | null = await ctx.db.query("pull_requests").withIndex("by_repository_number", (q: any) => q.eq("repository", run.pr!.repository).eq("number", run.pr!.number)).first();
if (!pr) continue;
// The run a real pass records the merge on, which is the pull request's newest, not always the run this page read.
Expand Down
38 changes: 38 additions & 0 deletions packages/convex/convex/deployRunsLive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,44 @@ describe("a run whose pull request someone else merged reads that merge and goes
expect(await heal(false)).toEqual([]);
});

// sd-5438: a run paused on its card asking a person to approve the merge, and the person merged the pull request
// on GitHub instead. The card asked about a change that had landed, and nobody's session could take it back.
test("a run paused on its card withdraws the card, records the merge, and goes live with it", async () => {
const { t, mark, drain, mergedOnGitHub } = await world();
t.session_decisions = [{ _id: "dec_gate", short_id: "sd-9", user_id: ME, conversation_id: "conv_subject", session_id: "s_subject", question: "Ship the fix?", options: [{ label: "Ship" }, { label: "Revise" }], status: "pending", blocking: true, workflow_run_id: "run_p", task_id: "task_c", created_at: NOW - 35_000, updated_at: NOW - 35_000 }];
t.workflow_runs.push({ ...endedBeforeMerge("run_p", 14, "task_c", "stopped"), status: "paused", current_node_id: "land__card__decide", fail_reason: undefined, gate_node_id: "land__card__decide", gate_decision_id: "dec_gate" });
expect(await mergedOnGitHub(14, 2, "samvit")).toBe("run_p");
expect(t.session_decisions[0]).toMatchObject({ status: "withdrawn", withdrawn_reason: `Merged by someone else: #14 merged as ${sha(2).slice(0, 7)} by samvit; going live.` });
expect(run(t, "run_p")).toMatchObject({ status: "failed", fail_reason: `Merged by someone else: #14 merged as ${sha(2).slice(0, 7)} by samvit; going live.` });
expect(run(t, "run_p").merge).toMatchObject({ sha: sha(2), outside: true, by: "samvit" });
await mark("cli", 2, "live");
expect(await drain()).toContain("run_p");
expect(run(t, "run_p")).toMatchObject({ status: "completed", current_node_id: "exit" });
});

test("a paused run whose card was already answered is left to resume and see the merge itself", async () => {
const { t, mergedOnGitHub } = await world();
t.session_decisions = [{ _id: "dec_done", short_id: "sd-10", user_id: ME, conversation_id: "conv_subject", session_id: "s_subject", question: "Ship the fix?", options: [{ label: "Ship" }], status: "answered", answer_index: 0, blocking: true, workflow_run_id: "run_q", created_at: NOW - 35_000, updated_at: NOW - 35_000 }];
t.workflow_runs.push({ ...endedBeforeMerge("run_q", 15, "task_c", "stopped"), status: "paused", current_node_id: "land__card__decide", fail_reason: undefined, gate_node_id: "land__card__decide", gate_decision_id: "dec_done" });
expect(await mergedOnGitHub(15, 2)).toBeNull();
expect(run(t, "run_q")).toMatchObject({ status: "paused" });
expect(run(t, "run_q").merge).toBeUndefined();
});

test("the backfill finds a paused run whose pull request was merged on GitHub before this was fixed", async () => {
const { t, ctx } = await world();
t.session_decisions = [{ _id: "dec_old", short_id: "sd-11", user_id: ME, conversation_id: "conv_subject", session_id: "s_subject", question: "Ship the fix?", options: [{ label: "Ship" }], status: "pending", blocking: true, workflow_run_id: "run_r", created_at: NOW - 35_000, updated_at: NOW - 35_000 }];
t.workflow_runs.push({ ...endedBeforeMerge("run_r", 16, "task_c", "stopped"), status: "paused", current_node_id: "land__card__decide", fail_reason: undefined, gate_node_id: "land__card__decide", gate_decision_id: "dec_old" });
t.pull_requests.push({ _id: "pr_16", team_id: TEAM, github_pr_id: 16, repository: REPO, number: 16, title: "x", body: "", state: "merged", author_github_username: "ana", head_ref: "fix-16", base_ref: "main", linked_session_ids: [], merged_at: NOW - 20_000, merge_commit_sha: sha(2), created_at: NOW - 90_000, updated_at: NOW - 20_000 });
const pass = async (dry: boolean) => (await (healOutsideMerges as any)._handler(ctx, { dry, status: "paused" })).healed;
expect(await pass(true)).toEqual(["run_r"]);
expect(t.session_decisions[0].status).toBe("pending");
expect(await pass(false)).toEqual(["run_r"]);
expect(t.session_decisions[0].status).toBe("withdrawn");
expect(run(t, "run_r").merge.outside).toBe(true);
expect(await pass(false)).toEqual([]);
});

test("a running run, a run that recorded its own merge, and an older run on the same pull request are left alone", async () => {
const { t, mergedOnGitHub } = await world();
t.workflow_runs.push({ ...endedBeforeMerge("run_old7", 9, "task_c", "stopped"), created_at: NOW - 200_000 });
Expand Down
2 changes: 1 addition & 1 deletion packages/convex/convex/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1352,7 +1352,7 @@ http.route({
}
result =
action === "cancel"
? await ctx.runMutation(api.sessionDecisions.withdraw, { api_token, decision_id: body.decision_id, session_id })
? await ctx.runMutation(api.sessionDecisions.withdraw, { api_token, decision_id: body.decision_id, session_id, ...(typeof body.reason === "string" ? { reason: body.reason } : {}) })
: await ctx.runMutation(api.sessionDecisions.edit, {
api_token,
decision_id: body.decision_id,
Expand Down
Loading
Loading