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 IMPLEMENTATION_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Recorded 14 October 2026 and revised 15 October 2026 after the first staging cas
- **Unavailable cases (15 October).** A Luna eval case's Durable Object began failing every request with "Internal error in Durable Object storage caused object to be reset". `RepositoryDO` now stops retrying a case after `unavailableAfterAttempts` failed forwards, posts one notice on the issue or PR, and lists it under `pnpm ops unavailable <repo-id>`. A new intake for the same issue routes to a fresh case (`<case-id>-r2`, ...), which starts from the issue as written. Operator calls that fail inside a case return the error as JSON instead of the runtime's error page.
- **Triage before the author (15 October).** Kimi took on feature requests despite the prompt (fixture #4 and #7 became PRs #6 and #8), so auto-intake issues are first classified by Clef (`src/runtime/triage.ts`): issue kind (choice), actionable (yes/no) and size (score). Fixed thresholds turn the probabilities into take-on, needs-info, decline (templated message) or decline-silently (spam, uncertain, or triage unavailable). The verdict is stored as case meta `triage` and logged. Triage is a gate on authority-free intake, not a state machine: once admitted, the author still judges the issue and may decline. Maintainer-assigned issues are never triaged.
- **Pull requests open ready for review** rather than as drafts, at the maintainer's request.
- **Partial fixes (7 November).** `submit_candidate` and `review` require `resolves: fully | partly`, with `remaining` for partly; there is no default, so the author cannot leave the issue link out by omission. Trusted code writes the only link line (`Closes #N`, or `Part of #N` with what remains) and turns every GitHub closing keyword in author text (title, summary, description, commit message) into "addresses". The reviewers check the declaration as a claim. When a later candidate changes the declaration, the publisher rewrites the link on the open pull request. When a partial pull request merges, the case ends and the issue's pointer comment says what remains; the issue stays open.

- **Intake.** GitHub Apps cannot be issue assignees. A maintainer applies the `emdash-bot` label (configurable) to a specific issue or same-repository PR, or assigns a configured machine-user login. Removal cancels. Sender authority comes from the repository permission API, or configured maintainers when no credential exists.
- **Effects outside Pi.** Publication, replies, the progress comment and a small heartbeat (run time cap, author slot, status refresh) run as Lifecycle host jobs on the same `CaseDO`. They execute trusted effects; they never decide what the author does.
Expand Down
1 change: 1 addition & 0 deletions evals/cases/delivery-greeting.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
{
"tool": "submit_candidate",
"args": {
"resolves": "fully",
"title": "fix: punctuate the greeting",
"summary": "Adds a comma and exclamation mark. `node test.js` passes."
}
Expand Down
130 changes: 124 additions & 6 deletions src/cases/case-do.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
import {
STATUS_CHECK_NAME,
renderMovedToPullRequest,
renderPartlyMerged,
renderStatus,
renderStatusCheck,
statusMarker,
Expand Down Expand Up @@ -60,6 +61,7 @@ import {
} from "../source/workspace.ts";
import {
type CaseRuntime,
type BranchUpdate,
type DefaultBranchMerge,
type MutationOutcome,
type ReviewSubject,
Expand All @@ -76,6 +78,7 @@ import type {
CaseEvent,
CaseIdentity,
CheckpointRow,
IssueResolution,
ReplyIntent,
Verification,
} from "./types.ts";
Expand Down Expand Up @@ -508,8 +511,8 @@ export class CaseDO extends DurableObject<Env> {
search: (pattern, path, glob) => this.#search(pattern, path, glob),
listFiles: (path) => this.#listFiles(path),
runCheck: (opId, name, args) => this.#runCheck(opId, name, args),
submitCandidate: (opId, title, summary, description) =>
this.#submitCandidate(opId, title, summary, description),
submitCandidate: (opId, title, summary, resolution, description) =>
this.#submitCandidate(opId, title, summary, resolution, description),
handoff: async (opId, reason, nextAction) => {
// A message queued behind this run already answers the handoff: it was
// submitted (clearing any earlier one) before the author asked.
Expand All @@ -525,6 +528,7 @@ export class CaseDO extends DurableObject<Env> {
await this.#handoff(opId, reason, nextAction);
},
mergeDefaultBranch: (opId) => this.#mergeDefaultBranch(opId),
updateFromBranch: (opId) => this.#updateFromBranch(opId),
attachScreenshot: (opId, path) => this.#attachScreenshot(opId, path),
reply: async (opId, inReplyTo, onIssue, body) => {
const intent = this.#queueReply(opId, inReplyTo, onIssue, body);
Expand Down Expand Up @@ -879,10 +883,62 @@ export class CaseDO extends DurableObject<Env> {
});
}

/**
* Merge the pull request's current head, with commits pushed by others, into
* the author's work. The checkout then starts from that head, so the next
* candidate builds on those commits instead of being rebased onto them blind.
*/
async #updateFromBranch(opId: string): Promise<BranchUpdate> {
return this.#source.run(async () => {
const receipt = this.store.operation(opId);
if (receipt?.status === "completed") return receipt.result as BranchUpdate;
await this.#ensureSandbox();
const github = this.#github();
const latest = this.store.latestCheckpoint()!;
const head = this.#currentHead();
if (!head) throw new Error("there is no pull request branch yet");
const pending = this.store.getMeta<DefaultMergeBase>("defaultMerge");
const merging = pending?.base === latest.baseCommit;
if (merging && head !== pending.branchHead)
throw new Error(
"your work contains an unpublished default-branch merge; submit it first, then update from the branch",
);
const comparison = merging
? { status: "identical", merge_base_commit: { sha: head } }
: await github.request<{
status: string;
merge_base_commit: { sha: string };
}>("GET", github.repoPath(`/compare/${head}...${latest.baseCommit}`));
let result: BranchUpdate;
if (comparison.status === "ahead" || comparison.status === "identical") {
result = { head, upToDate: true, conflicts: [] };
} else {
const merged = await mergeIntoCheckout(this.#authorSandbox(), {
remoteUrl: this.#remoteUrl(),
mergeBase: comparison.merge_base_commit.sha,
theirs: head,
timeoutMs: this.config.budgets.setupMs,
});
await this.#capture(opId, head);
result = { head, upToDate: false, conflicts: merged.conflicts };
}
this.store.putOperation(
opId,
"update_from_branch",
this.store.generation(),
"completed",
result,
);
this.store.log("branch.updated", { ...result });
return result;
});
}

async #submitCandidate(
opId: string,
title: string,
summary: string,
resolution: IssueResolution,
description?: string,
): Promise<Candidate> {
const receipt = this.store.operation(opId);
Expand Down Expand Up @@ -921,6 +977,10 @@ export class CaseDO extends DurableObject<Env> {
title: title.slice(0, 200),
summary: summary.slice(0, 20_000),
...(description?.trim() ? { description: description.slice(0, 60_000) } : {}),
resolution:
resolution.kind === "partial"
? { kind: "partial", remaining: resolution.remaining.slice(0, 2_000) }
: resolution,
origin: "author",
createdAt: Date.now(),
};
Expand Down Expand Up @@ -1807,16 +1867,23 @@ export class CaseDO extends DurableObject<Env> {
this.store.setMeta("observedHead", str(payload.after));
this.store.log("branch.advanced", { by: event.actor, head: payload.after });
const formatted = await this.#recordFormatPush(str(payload.before), str(payload.after));
return `## Branch updated\nFrom: ${from}\n\n${event.actor} pushed ${str(payload.after).slice(0, 12)} to the case branch${formatted ? ", applying only the repository's formatter" : ""}. Your next candidate is published on top of it.`;
return `## Branch updated\nFrom: ${from}\n\n${event.actor} pushed ${str(payload.after).slice(0, 12)} to the case branch${formatted ? ", applying only the repository's formatter" : ""}. Your next candidate is published on top of it; to read, test or build on it, call update_from_branch.`;
}
case "pr-opened":
return null;
case "closed": {
const isIssue = payload.issue === true;
if (isIssue && this.store.publications().some((p) => p.state === "pr-ensured")) return null;
let merged = payload.merged === true;
// Closing the issue leaves an open pull request's fate to that pull request.
if (isIssue && this.store.publications().some((p) => p.state === "pr-ensured")) {
const pr = await this.#pullRequestState();
if (!pr || pr.open) return null;
merged = pr.merged;
}
this.store.setMeta("state", "terminal");
this.store.setMeta("generation", this.store.generation() + 1);
this.store.log("case.terminal", { merged: payload.merged === true, issue: isIssue });
this.store.log("case.terminal", { merged, issue: isIssue });
if (merged && !isIssue) await this.#notePartlyMerged();
await this.#stopAuthor();
await this.#schedule("report", Date.now());
return null;
Expand Down Expand Up @@ -2027,13 +2094,38 @@ export class CaseDO extends DurableObject<Env> {
return null;
}

/** Whether the case's pull request is still open; null if unknown. */
async #pullRequestState(): Promise<{ open: boolean; merged: boolean } | null> {
const pr = this.store.getMeta<number>("pr");
if (!pr) return null;
try {
const data = await this.#github().request<{ state: string; merged: boolean }>(
"GET",
this.#github().repoPath(`/pulls/${pr}`),
);
return { open: data.state === "open", merged: data.merged === true };
} catch (error) {
this.store.log("observe.failed", { error: errorMessage(error) });
return null;
}
}

/** The tail of a CI job's log, for a check run this case has seen. */
async #ciLog(checkRunId: number, lines = 200): Promise<string> {
if (!this.store.verification(`check:${checkRunId}`))
throw new Error(`check run ${checkRunId} is not one of this case's checks`);
const log = await this.#github().jobLog(checkRunId);
if (log === null)
if (log === null) {
const annotations = await this.#github()
.checkAnnotations(checkRunId)
.catch(() => []);
this.store.log("ci.log", { checkRunId, lines: 0, annotations: annotations.length });
if (annotations.length)
return `No log is available for check run ${checkRunId}; its annotations:\n\n${annotations
.map((a) => `${a.path}:${a.line} [${a.level}] ${a.message}`)
.join("\n")}`;
return `No log is available for check run ${checkRunId} (expired, or not a GitHub Actions job).`;
}
const all = log
// oxlint-disable-next-line no-control-regex -- ANSI colour codes
.replace(/\x1b\[[0-9;]*m/g, "")
Expand Down Expand Up @@ -3072,6 +3164,32 @@ export class CaseDO extends DurableObject<Env> {
this.store.setMeta("statusCheck", { id, head, hash, completed: check.status === "completed" });
}

/** The issue stays open after a partial fix merges: say so where the reporter looks. */
async #notePartlyMerged(): Promise<void> {
const identity = this.#identity();
const resolution = this.store.latestCandidate()?.resolution;
const prNumber = this.store.publications().find((p) => p.state === "pr-ensured")?.prNumber;
if (!identity.issueNumber || !prNumber || resolution?.kind !== "partial") return;
const body = renderPartlyMerged(identity, prNumber, resolution.remaining);
const github = this.#github();
try {
const marker = statusMarker(identity.caseId);
const comments = await github.request<Array<{ id: number; body: string }>>(
"GET",
github.repoPath(`/issues/${identity.issueNumber}/comments?per_page=100`),
);
const id = comments.find((c) => c.body.includes(marker))?.id;
if (id) await github.request("PATCH", github.repoPath(`/issues/comments/${id}`), { body });
else
await github.request("POST", github.repoPath(`/issues/${identity.issueNumber}/comments`), {
body,
});
this.store.log("case.partly-merged", { pr: prNumber, issue: identity.issueNumber });
} catch (error) {
this.store.log("case.partly-merged-failed", { error: errorMessage(error) });
}
}

async #upsertStatusComment(target: number, body: string): Promise<void> {
const hash = await sha256Hex(body);
const stored = this.store.getMeta<{ id: number; hash: string; target?: number }>(
Expand Down
7 changes: 7 additions & 0 deletions src/cases/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ export interface CheckpointRow {
readonly createdAt: number;
}

/** Whether a candidate fully resolves its issue, as the author declared it. */
export type IssueResolution =
| { readonly kind: "full" }
| { readonly kind: "partial"; readonly remaining: string };

export interface Candidate {
readonly id: string;
readonly caseId: string;
Expand All @@ -72,6 +77,8 @@ export interface Candidate {
readonly summary: string;
/** The pull request description the author wrote from the repository's template. */
readonly description?: string;
/** Absent on candidates sealed before the declaration existed; they close the issue. */
readonly resolution?: IssueResolution;
readonly origin: "author" | "integration";
readonly createdAt: number;
}
Expand Down
15 changes: 15 additions & 0 deletions src/github/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,21 @@ export class GitHubClient {
return `/repos/${this.repo}${suffix}`;
}

/** A check run's annotations: where code scanners such as CodeQL report what they found. */
async checkAnnotations(
checkRunId: number,
): Promise<Array<{ path: string; line: number; level: string; message: string }>> {
const annotations = await this.request<
Array<{ path: string; start_line: number; annotation_level: string; message: string }>
>("GET", this.repoPath(`/check-runs/${checkRunId}/annotations?per_page=50`));
return annotations.map((a) => ({
path: a.path,
line: a.start_line,
level: a.annotation_level,
message: a.message,
}));
}

async branchHead(branch: string): Promise<string | null> {
const response = await this.raw<{ object?: { sha?: string } }>(
"GET",
Expand Down
Loading
Loading