From dc6bc30ce87a8226da2f9de88344ea92399154d2 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:35:56 -0300 Subject: [PATCH 1/5] refactor: require a prepared plan issue for guarded writes Tie the verified viewer to a writable issue. Send an assignee ID only while the claim is pending and require the confirmed login on subsequent writes. Verified: bun run check:types; targeted lint and format; bun run test:unit cli/test/unit/plan/write-postconditions.test.ts (9 passed) --- cli/src/plan/commands.ts | 113 +++++++++++++++------------ cli/src/plan/github.ts | 165 +++++++++++++++++++++++++++------------ cli/src/plan/types.ts | 13 +-- 3 files changed, 185 insertions(+), 106 deletions(-) diff --git a/cli/src/plan/commands.ts b/cli/src/plan/commands.ts index 08d57936..f105042b 100644 --- a/cli/src/plan/commands.ts +++ b/cli/src/plan/commands.ts @@ -27,6 +27,7 @@ import { readPullRequest, readRepositorySnapshot, readSnapshot, + readWriteSnapshot, runGh, withBodyFile, writeIssueIfUnchanged, @@ -103,6 +104,7 @@ import { type IssueSummary, type PlanFailure, type PlanIssue, + type WritablePlanIssue, } from "./types"; export type PlanServices = PlanProcess | PlanRepository | PlanFiles | PlanWaits; @@ -156,14 +158,17 @@ const printAdvice = Effect.fn("plan.printAdvice")(function* ( const isClosed = (issue: Pick): boolean => String(issue.state).toUpperCase() === "CLOSED"; -/** A plan issue with its parsed body, its derived status, and the acting viewer of a write read. */ +/** A plan issue with its parsed body and its derived status. */ interface PlanRead { readonly issue: PlanIssue; readonly parsed: ParsedPlan; readonly status: string; +} + +/** A plan read for a write: the issue prepared for mutation and the plan label ids that the read looked up. */ +interface WritablePlanRead extends PlanRead { + readonly issue: WritablePlanIssue; readonly labelIds: ReadonlyMap | undefined; - readonly login: string | undefined; - readonly viewerId: string | undefined; } const hasPlanLabel = (issue: Pick): boolean => @@ -174,35 +179,42 @@ const lacksPlanLabel = (number: number): string => const readPlanIssue = Effect.fn("plan.readPlanIssue")(function* ( value: string | undefined, - forWrite = false, connections: SnapshotOptions = {}, ) { const number = yield* attempt(() => parseIssueNumber(value)); - const { issue, login, viewerId, labelIds } = yield* readSnapshot(number, { - acting: forWrite, - ...connections, - }); + const { issue } = yield* readSnapshot(number, connections); if (!contractVersion(issue.body)) return yield* refuse(`unreadable plan contract: #${issue.number}`); - if (forWrite) { - const owners = issue.assignees.map((owner) => owner.login); - const foreign = owners.find((owner) => owner !== login); - if (foreign) return yield* refuse(`plan #${issue.number} is owned by ${foreign}`); - // `list` finds plans by the base label, so a write keeps an open plan findable. - if (!isClosed(issue) && !hasPlanLabel(issue)) - return yield* refuse(lacksPlanLabel(issue.number)); - // The write claims an unassigned plan for the acting viewer. - if (!owners.length) issue.claimantId = viewerId; - issue.actingLogin = login; - } - const parsed = yield* attempt(() => parsePlan(issue.body)); const read: PlanRead = { issue, - parsed, + parsed: yield* attempt(() => parsePlan(issue.body)), status: statusFromIssueOf(issue), + }; + return read; +}); + +// The read of a plan for a write: it refuses a foreign owner and an open plan without the base label, and prepares the +// issue for the acting viewer. +const readWritablePlan = Effect.fn("plan.readWritablePlan")(function* ( + value: string | undefined, + connections: SnapshotOptions = {}, +) { + const number = yield* attempt(() => parseIssueNumber(value)); + const { issue, viewer, labelIds } = yield* readWriteSnapshot(number, connections); + if (!contractVersion(issue.body)) + return yield* refuse(`unreadable plan contract: #${issue.number}`); + const foreign = issue.assignees.find((owner) => owner.login !== viewer.login); + if (foreign) return yield* refuse(`plan #${issue.number} is owned by ${foreign.login}`); + // `list` finds plans by the base label, so a write keeps an open plan findable. + if (!isClosed(issue) && !hasPlanLabel(issue)) return yield* refuse(lacksPlanLabel(issue.number)); + // The write claims an unassigned plan for the acting viewer. + const claim: WritablePlanIssue["claim"] = issue.assignees.length ? "assigned" : "pending"; + const writable: WritablePlanIssue = Object.assign(issue, { viewer, claim }); + const read: WritablePlanRead = { + issue: writable, + parsed: yield* attempt(() => parsePlan(writable.body)), + status: statusFromIssueOf(writable), labelIds, - login, - viewerId, }; return read; }); @@ -375,7 +387,7 @@ const showPlan = Effect.fn("plan.show")(function* (args: ReadonlyArray) if (!value || flags.length > 1 || flags.some((flag) => flag !== "--body")) return yield* refuse("show requires an issue and optional --body"); const connections = { comments: true, closure: true, children: true, parent: true }; - const { issue, parsed, status } = yield* readPlanIssue(value, false, connections); + const { issue, parsed, status } = yield* readPlanIssue(value, connections); const reviews = reviewVerdicts(issue); const grant = yield* readGrantState(issue, parsed.sections.get("Goal") ?? ""); const metadata = [ @@ -496,7 +508,7 @@ const editPlan = Effect.fn("plan.edit")(function* (args: ReadonlyArray) "latin1", ); const originBytes = Buffer.concat([fileBytes, ORIGIN_SUFFIX]); - const { issue, parsed, status } = yield* readPlanIssue(value, true, { + const { issue, parsed, status } = yield* readWritablePlan(value, { history: true, comments: true, }); @@ -558,7 +570,7 @@ const setPlanStatus = Effect.fn("plan.status")(function* (args: ReadonlyArray readPlanIssue(String(number), true, archiveConnections), + read: () => readWritablePlan(String(number), archiveConnections), command: "archive", stillReopenable: (plan) => attempt(() => { @@ -821,7 +833,7 @@ const checkAfterOwnClose = Effect.fn("plan.checkAfterOwnClose")(function* ( number: number, snapshot: ReadonlyArray, ) { - const after = yield* readPlanIssue(String(number), true, archiveConnections); + const after = yield* readWritablePlan(String(number), archiveConnections); const work = openWork(after, snapshot); if (work) return yield* reopenForOpenWork(after, work, snapshot); if (!isClosed(after.issue)) @@ -843,14 +855,15 @@ function isParentPlan({ issue, parsed }: PlanRead): boolean { // An unassigned plan is claimed before archive closes it, so that the record of the close is a trusted comment when the // read after the close needs it. -const claimBeforeClose = Effect.fn("plan.claimBeforeClose")(function* (plan: PlanRead) { - if (plan.issue.claimantId === undefined) return; - yield* writeIssueIfUnchanged(plan.issue); - plan.issue.claimantId = undefined; +const claimBeforeClose = Effect.fn("plan.claimBeforeClose")(function* (plan: WritablePlanRead) { + if (plan.issue.claim === "pending") yield* writeIssueIfUnchanged(plan.issue); }); // Post the archive `record` on a plan that archive did not close itself, unless a rerun posted it already. -const postRecordOnce = Effect.fn("plan.postRecordOnce")(function* (plan: PlanRead, record: string) { +const postRecordOnce = Effect.fn("plan.postRecordOnce")(function* ( + plan: WritablePlanRead, + record: string, +) { if (recorded(plan.issue, record)) return; const current = yield* preWriteIssue(plan.issue.number); yield* refuseChangedIssue(plan.issue, current); @@ -870,7 +883,7 @@ const postRecordOnce = Effect.fn("plan.postRecordOnce")(function* (plan: PlanRea // while its children show open work, such as after a failed read that followed the close, is reopened safely. The // close posts the parent archive record. const archiveParent = Effect.fn("plan.archiveParent")(function* (number: number) { - const plan = yield* readPlanIssue(String(number), true, archiveConnections); + const plan = yield* readWritablePlan(String(number), archiveConnections); const work = plan.status === "finished" ? openWork(plan) : undefined; if (work) return yield* reopenForOpenWork(plan, work); const { children } = plan.issue; @@ -939,7 +952,7 @@ const archivePlan = Effect.fn("plan.archive")(function* (args: ReadonlyArray 0 || issue.claimantId !== undefined; + const wrote = remove.length > 0 || issue.claim === "pending"; yield* writeIssueIfUnchanged(issue, { remove, verify: true }); - issue.claimantId = undefined; // After its own write, retire reads the plan once more right before the close, which then holds no phase label. if (wrote) yield* writeIssueIfUnchanged(issue, { verify: true, phases: [] }); const { nameWithOwner } = yield* currentRepository(); @@ -1083,11 +1095,12 @@ interface MutationCall { // expected phase label, and the acting login as its single owner; a plan that reads closed again was closed by someone // after the write, and the refusal names `command`, whose rerun reads that close and decides again. const writeReopen = Effect.fn("plan.writeReopen")(function* ( - plan: PlanRead, + plan: WritablePlanRead, comment: string, command: string, ) { - const { issue, login, viewerId, labelIds } = plan; + const { issue, labelIds } = plan; + const { login } = issue.viewer; const phases = issue.labels.map((label) => token(label.name)).filter(isPhaseLabel); const restoresPhase = phases.length === 0; // A plan that already lacks the base label gets its repair, not a retry that meets the same refusal. @@ -1171,7 +1184,7 @@ const writeReopen = Effect.fn("plan.writeReopen")(function* ( "-f", `issue=${id}`, ...(restoresPhase ? ["-f", `labels[]=${phaseLabelId}`] : []), - ...(claims ? ["-f", `assignees[]=${viewerId}`] : []), + ...(claims ? ["-f", `assignees[]=${issue.viewer.id}`] : []), ]).pipe( // GitHub answers the reopen of a stuck plan with "Could not reopen the issue." (#90); the request is not retried. // Any other failure is reported with what the plan reads now; no comment was posted. @@ -1221,8 +1234,7 @@ const writeReopen = Effect.fn("plan.writeReopen")(function* ( return yield* refuse( `plan #${issue.number} ${isClosed(current) ? "closed again after the reopen" : `reopened, but it reads phase labels ${phaseList(current.labels)} and owners ${current.assignees.map((owner) => owner.login).join(", ") || "none"}`}; no comment was posted; ${reopenRecovery(current, login, expectedPhase, command, comment)}`, ); - issue.confirmedOwner = login; - yield* postReopenComment(issue, id, login, expectedPhase, comment, command); + yield* postReopenComment(issue, id, expectedPhase, comment, command); yield* printLine(`plan #${issue.number} reopened: ${statusFromIssueOf(current)}`); }); @@ -1232,7 +1244,7 @@ const writeReopen = Effect.fn("plan.writeReopen")(function* ( // sets the expected phase label; then the comment, which only the single owner can post as a trusted record. function reopenRecovery( now: PlanIssue, - login: string | undefined, + login: string, expectedPhase: string, command: string, comment: string, @@ -1265,9 +1277,8 @@ const phaseList = (labels: ReadonlyArray<{ readonly name: string }>): string => // The second write of a reopen. When it fails, the comments show whether it landed: a trusted comment with its text that // is newer than the close that this reopen observed belongs to this attempt. const postReopenComment = Effect.fn("plan.postReopenComment")(function* ( - issue: PlanIssue, + issue: WritablePlanIssue, id: string, - login: string | undefined, expectedPhase: string, comment: string, command: string, @@ -1292,7 +1303,7 @@ const postReopenComment = Effect.fn("plan.postReopenComment")(function* ( ); if (landed) return Effect.void; return refuse( - `plan #${issue.number} ${isClosed(now) ? "closed again after the reopen" : "is open again"}, but its reopen comment did not post (${error.message}); ${reopenRecovery(now, login, expectedPhase, command, comment)}`, + `plan #${issue.number} ${isClosed(now) ? "closed again after the reopen" : "is open again"}, but its reopen comment did not post (${error.message}); ${reopenRecovery(now, issue.viewer.login, expectedPhase, command, comment)}`, ); }), ), @@ -1302,7 +1313,7 @@ const postReopenComment = Effect.fn("plan.postReopenComment")(function* ( interface SettleOptions { readonly observed: PlanRead; - readonly read: () => Effect.Effect; + readonly read: () => Effect.Effect; readonly command: string; readonly stillReopenable: (plan: PlanRead) => Effect.Effect; readonly comment: string; @@ -1370,7 +1381,7 @@ const reopenPlan = Effect.fn("plan.reopen")(function* (args: ReadonlyArray readPlanIssue(String(number), true, { closure: true, labelLookup: true }); + const read = () => readWritablePlan(String(number), { closure: true, labelLookup: true }); const waits = yield* PlanWaits; let observed = yield* read(); for (let reads = 1; !(yield* closedByPullRequest(observed.issue, pullRequest)); reads += 1) { diff --git a/cli/src/plan/github.ts b/cli/src/plan/github.ts index e22b6eeb..cac02352 100644 --- a/cli/src/plan/github.ts +++ b/cli/src/plan/github.ts @@ -32,6 +32,7 @@ import { type PullRequestNode, type RepositoryInfo, type SpawnError, + type WritablePlanIssue, } from "./types"; const ACTING_LOGIN_ERROR = @@ -330,11 +331,9 @@ export const issueSummaries = Effect.fn("plan.issueSummaries")(function* ( return summaries; }); -export interface SnapshotOptions { - readonly acting?: boolean; +/** The repository fields and issue connections that a snapshot selects, apart from the acting viewer. */ +export interface SnapshotConnections { readonly labelLookup?: boolean; - /** Read the acting login and the plan label names without their node ids, for `new`, which writes by name. */ - readonly namesOnly?: boolean; readonly comments?: boolean; readonly history?: boolean; readonly defaultBranch?: boolean; @@ -343,19 +342,35 @@ export interface SnapshotOptions { readonly parent?: boolean; } -export interface RepositorySnapshot { - readonly login: string | undefined; - readonly viewerId: string | undefined; +/** A read-only snapshot: `acting` also reads the acting login. */ +export interface SnapshotOptions extends SnapshotConnections { + readonly acting?: boolean; + /** Read the plan label names without their node ids, for `new`, which creates the issue with label names. */ + readonly namesOnly?: boolean; +} + +interface RepositoryLabels { /** Each plan label name maps to its node id, or to null when the repository lacks the label. */ readonly labelIds: ReadonlyMap | undefined; /** The plan labels that the repository lacks, when the read looked labels up. */ readonly missingLabels: ReadonlyArray; } +export interface RepositorySnapshot extends RepositoryLabels { + /** The acting login of an `acting` read. */ + readonly login: string | undefined; +} + export interface IssueSnapshot extends RepositorySnapshot { readonly issue: PlanIssue; } +/** The read that prepares a write: the plan issue, the acting viewer that a claim assigns, and the plan labels. */ +export interface WriteSnapshot extends RepositoryLabels { + readonly issue: PlanIssue; + readonly viewer: WritablePlanIssue["viewer"]; +} + const decodeClosure = malformed( Schema.Struct({ nodes: Schema.Array(Schema.Unknown) }), "latest closure", @@ -380,7 +395,14 @@ const latestCloser = Effect.fn("plan.latestCloser")(function* (latestClosure: un return { closer, closedEventAt: event.createdAt }; }); -function snapshotQuery(number: number | undefined, options: SnapshotOptions): string { +/** The viewer fields of a snapshot: none, the acting login, or the login and the node id that a write claims with. */ +type ViewerFields = "" | "login" | "login id"; + +function snapshotQuery( + number: number | undefined, + options: SnapshotOptions, + viewerFields: ViewerFields, +): string { const issueFields = number === undefined ? "" @@ -402,9 +424,8 @@ function snapshotQuery(number: number | undefined, options: SnapshotOptions): st options.children ? issueConnectionSelection("subIssues", ISSUE_SUMMARY_FIELDS) : "", options.parent ? "parent{number repository{nameWithOwner}}" : "", ].join(" "); - const viewerFields = options.namesOnly ? "login" : "login id"; const labels = options.namesOnly ? REPOSITORY_LABEL_NAMES : REPOSITORY_LABELS; - return `query($owner:String!,$name:String!${number === undefined ? "" : ",$number:Int!"}){${options.acting ? `viewer{${viewerFields}}` : ""} repository(owner:$owner,name:$name){nameWithOwner visibility ${options.defaultBranch ? "defaultBranchRef{name}" : ""} ${options.labelLookup ? labels : ""} ${number === undefined ? "" : `issue(number:$number){${issueFields}}`}}}`; + return `query($owner:String!,$name:String!${number === undefined ? "" : ",$number:Int!"}){${viewerFields ? `viewer{${viewerFields}}` : ""} repository(owner:$owner,name:$name){nameWithOwner visibility ${options.defaultBranch ? "defaultBranchRef{name}" : ""} ${options.labelLookup ? labels : ""} ${number === undefined ? "" : `issue(number:$number){${issueFields}}`}}}`; } const decodeRepository = malformed(RepositoryFields, "repository"); @@ -417,13 +438,17 @@ const decodeViewerId = malformed(Schema.NonEmptyString, "viewer"); const decodeOptionalLabel = malformed(OptionalLabel, "repository labels"); const decodeOptionalLabelName = malformed(Schema.NullOr(LabelName), "repository labels"); -/** The repository part of a snapshot. It records the repository for the later writes of the command. */ -const readRepository = Effect.fn("plan.readRepository")(function* ( +/** + * The GraphQL read of a snapshot and its repository part, which records the repository for the later writes of the + * command. Returns the repository and the viewer that `viewerFields` selected, for the caller to decode. + */ +const queryRepository = Effect.fn("plan.queryRepository")(function* ( number: number | undefined, options: SnapshotOptions, + viewerFields: ViewerFields, ) { const data = yield* graphql( - snapshotQuery(number, options), + snapshotQuery(number, options, viewerFields), number === undefined ? {} : { number }, ); const repo = field(data, "repository"); @@ -433,10 +458,23 @@ const readRepository = Effect.fn("plan.readRepository")(function* ( : undefined; const repository = yield* PlanRepository; repository.current = { nameWithOwner, visibility, defaultBranch } satisfies RepositoryInfo; - const viewer = field(data, "viewer"); - const login = options.acting ? yield* decodeLogin(field(viewer, "login")) : undefined; - const viewerId = - options.acting && !options.namesOnly ? yield* decodeViewerId(field(viewer, "id")) : undefined; + return { repo, viewer: field(data, "viewer") }; +}); + +/** The acting viewer of a write read: its login, then the node id that a claim assigns. */ +const decodeViewer = Effect.fn("plan.decodeViewer")(function* (viewer: unknown) { + const decoded: WritablePlanIssue["viewer"] = { + login: yield* decodeLogin(field(viewer, "login")), + id: yield* decodeViewerId(field(viewer, "id")), + }; + return decoded; +}); + +/** The plan labels of the repository `repo`, when `options` looks them up. */ +const repositoryLabels = Effect.fn("plan.repositoryLabels")(function* ( + repo: unknown, + options: SnapshotOptions, +) { let labelIds: Map | undefined; const missingLabels: Array = []; if (options.labelLookup) { @@ -455,7 +493,19 @@ const readRepository = Effect.fn("plan.readRepository")(function* ( labelIds?.set(name, label?.id ?? null); } } - const snapshot: RepositorySnapshot = { login, viewerId, labelIds, missingLabels }; + const labels: RepositoryLabels = { labelIds, missingLabels }; + return labels; +}); + +/** The repository part of a read-only snapshot. */ +const readRepository = Effect.fn("plan.readRepository")(function* ( + number: number | undefined, + options: SnapshotOptions, +) { + const viewerFields = options.acting ? "login" : ""; + const { repo, viewer } = yield* queryRepository(number, options, viewerFields); + const login = options.acting ? yield* decodeLogin(field(viewer, "login")) : undefined; + const snapshot: RepositorySnapshot = { login, ...(yield* repositoryLabels(repo, options)) }; return { repo, snapshot }; }); @@ -474,12 +524,12 @@ const decodeComments = malformed(Schema.Array(CommentFields), "issue comments"); const decodeHistory = malformed(Schema.Array(LabeledEvent), "label history"); const decodeParent = malformed(ParentFields, "parent issue"); -/** One GraphQL read of the repository and the plan issue, with the connections that `options` select. */ -export const readSnapshot = Effect.fn("plan.readSnapshot")(function* ( +/** The plan issue of the snapshot read `repo`, with the connections that `options` select. */ +const snapshotIssue = Effect.fn("plan.snapshotIssue")(function* ( number: number, - options: SnapshotOptions = {}, + repo: unknown, + options: SnapshotConnections, ) { - const { repo, snapshot } = yield* readRepository(number, options); const rawIssue = field(repo, "issue"); const issue = yield* decodeIssue(rawIssue); if (issue.number !== number) @@ -541,9 +591,34 @@ export const readSnapshot = Effect.fn("plan.readSnapshot")(function* ( closedEventAt: closure.closedEventAt, children, parent, - claimantId: undefined, }; - const result: IssueSnapshot = { ...snapshot, issue: planIssue }; + return planIssue; +}); + +/** One read-only GraphQL read of the repository and the plan issue, with the connections that `options` select. */ +export const readSnapshot = Effect.fn("plan.readSnapshot")(function* ( + number: number, + options: SnapshotOptions = {}, +) { + const { repo, snapshot } = yield* readRepository(number, options); + const issue = yield* snapshotIssue(number, repo, options); + const result: IssueSnapshot = { ...snapshot, issue }; + return result; +}); + +/** The read before a write: a snapshot that always reads the acting viewer with the node id that a claim assigns. */ +export const readWriteSnapshot = Effect.fn("plan.readWriteSnapshot")(function* ( + number: number, + connections: SnapshotConnections = {}, +) { + const { repo, viewer } = yield* queryRepository(number, connections, "login id"); + const actor = yield* decodeViewer(viewer); + const labels = yield* repositoryLabels(repo, connections); + const result: WriteSnapshot = { + ...labels, + issue: yield* snapshotIssue(number, repo, connections), + viewer: actor, + }; return result; }); @@ -698,11 +773,11 @@ const currentIssue = Effect.fn("plan.currentIssue")(function* (number: number, c * Refuse a write when the pre-write read `read` shows a change that governs the write: the body, the open or closed * state and the close reason, the base `plan` label of an open plan, the phase labels, or the owners. `expected` gives * the state and the phase labels after the command's own earlier writes; by default they are the snapshot's. An owner - * other than the snapshot owner, the acting login, and the claim is refused by name; a snapshot owner that is gone is - * a change. Returns the read to write with. + * other than the snapshot owners, the acting login, and the viewer ID of a pending claim is refused by name; a snapshot + * owner that is gone is a change, and so is a confirmed claim without the acting login. Returns the read to write with. */ export const refuseChangedIssue = Effect.fn("plan.refuseChangedIssue")(function* ( - issue: PlanIssue, + issue: WritablePlanIssue, read: PreWrite, { state = issue.state, @@ -723,12 +798,13 @@ export const refuseChangedIssue = Effect.fn("plan.refuseChangedIssue")(function* ) return yield* new PlanRefusal({ message: CHANGED_REMOTELY }); const owners = new Set(issue.assignees.map((owner) => owner.login)); + const { viewer, claim } = issue; const foreign = current.assignees.find( (owner) => - owner.id !== issue.claimantId && + !(claim === "pending" && owner.id === viewer.id) && !( Predicate.isString(owner.login) && - (owners.has(owner.login) || owner.login === issue.actingLogin) + (owners.has(owner.login) || owner.login === viewer.login) ), ); if (foreign) @@ -738,10 +814,7 @@ export const refuseChangedIssue = Effect.fn("plan.refuseChangedIssue")(function* if (owners.size > 0 && current.assignees.length === 0) return yield* new PlanRefusal({ message: CHANGED_REMOTELY }); // A claim that an earlier write of the command confirmed must still hold. - if ( - issue.confirmedOwner !== undefined && - !current.assignees.some((owner) => owner.login === issue.confirmedOwner) - ) + if (claim === "confirmed" && !current.assignees.some((owner) => owner.login === viewer.login)) return yield* new PlanRefusal({ message: CHANGED_REMOTELY }); return current; }); @@ -752,11 +825,11 @@ export const refuseChangedIssue = Effect.fn("plan.refuseChangedIssue")(function* // removals, so a non-phase label that someone else adds meanwhile survives. The last field returns the stored state, // which the post-write checks read: the body, the claim, and exactly the expected phase labels. export const writeIssueIfUnchanged = Effect.fn("plan.writeIssueIfUnchanged")(function* ( - issue: PlanIssue, + issue: WritablePlanIssue, { body, add, remove = [], labelIds, state, stateReason, phases, verify = false }: IssueWrite = {}, ) { - const claimantId = issue.claimantId; - const sends = body !== undefined || !!add || remove.length > 0 || claimantId !== undefined; + const claims = issue.claim === "pending"; + const sends = body !== undefined || !!add || remove.length > 0 || claims; if (!sends && !verify) return; const addId = add ? (labelIds?.get(add) ?? (yield* createdLabelId(add))) : undefined; const current = yield* refuseChangedIssue(issue, yield* preWriteIssue(issue.number), { @@ -768,22 +841,16 @@ export const writeIssueIfUnchanged = Effect.fn("plan.writeIssueIfUnchanged")(fun const removeIds = issue.labels .filter((label) => removed.has(token(label.name))) .map((label) => label.id); - if ( - body === undefined && - addId === undefined && - removeIds.length === 0 && - claimantId === undefined - ) - return; + if (body === undefined && addId === undefined && removeIds.length === 0 && !claims) return; const idLists: Array]> = []; const fields: Array = []; - if (body !== undefined || claimantId !== undefined) { + if (body !== undefined || claims) { const input = ["id:$issue"]; if (body !== undefined) input.push("body:$body"); - if (claimantId !== undefined) { + if (claims) { idLists.push([ "assignees", - [...new Set([...current.assignees.map((owner) => owner.id), claimantId])], + [...new Set([...current.assignees.map((owner) => owner.id), issue.viewer.id])], ]); input.push("assigneeIds:$assignees"); } @@ -833,12 +900,12 @@ export const writeIssueIfUnchanged = Effect.fn("plan.writeIssueIfUnchanged")(fun const stored = yield* decodeStored(rawStored); if (body !== undefined && stored.body !== body) return yield* new PlanRefusal({ message: "plan issue body differs after edit" }); - if (claimantId !== undefined) { - if (!stored.assignees.nodes.some((owner) => owner.id === claimantId)) + if (claims) { + if (!stored.assignees.nodes.some((owner) => owner.id === issue.viewer.id)) return yield* new PlanRefusal({ message: "plan issue claim did not land; re-read and retry", }); - issue.confirmedOwner = issue.actingLogin; + issue.claim = "confirmed"; } const storedLabels = yield* decodeStoredLabels( yield* issueNodes(issue.number, field(rawStored, "labels"), "labels", "name"), diff --git a/cli/src/plan/types.ts b/cli/src/plan/types.ts index b245ed6e..2ccd98fa 100644 --- a/cli/src/plan/types.ts +++ b/cli/src/plan/types.ts @@ -152,12 +152,13 @@ export interface PlanIssue { readonly closedEventAt: string | undefined; readonly children: ReadonlyArray; readonly parent: ParentLink | null | undefined; - /** The viewer id that a write claims an unassigned plan for. */ - claimantId: string | undefined; - /** The acting login of a write read, which a write accepts as an owner of the plan. */ - actingLogin?: string; - /** The owner that a write of the command claimed and confirmed; a later write requires it. */ - confirmedOwner?: string; +} + +/** An issue prepared for mutation after the command checks its contract, labels and owners. */ +export interface WritablePlanIssue extends PlanIssue { + readonly viewer: { readonly id: string; readonly login: string }; + /** A pending claim sends the viewer ID; confirmation requires the viewer login on later writes. */ + claim: "assigned" | "pending" | "confirmed"; } /** The fields that the status derivation reads; a plan issue and an issue summary both have them. */ From d1996efbf75b9df0f7e6e49004b294efdfef97a5 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:36:06 -0300 Subject: [PATCH 2/5] refactor: use the prepared viewer in reopen confirmation Include the formatted stored-ID comparison from the verified ownership change. Verified: bun run check:types; focused lint and format; write-postconditions.test.ts (9 passed) --- cli/src/plan/commands.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/src/plan/commands.ts b/cli/src/plan/commands.ts index f105042b..519dd306 100644 --- a/cli/src/plan/commands.ts +++ b/cli/src/plan/commands.ts @@ -1212,7 +1212,7 @@ const writeReopen = Effect.fn("plan.writeReopen")(function* ( yield* attempt(() => refuseStuck({ number: issue.number, state, stateReason })); if (claims) { const owners = field(field(payload, "assignees"), "nodes"); - if (!Array.isArray(owners) || !owners.some((owner) => field(owner, "id") === viewerId)) { + if (!Array.isArray(owners) || !owners.some((owner) => field(owner, "id") === issue.viewer.id)) { const now = (yield* readSnapshot(issue.number)).issue; return yield* refuse( `plan #${issue.number} reopened, but its claim did not land; no comment was posted; ${reopenRecovery(now, login, expectedPhase, command, comment)}`, From 3e1d72864b783016767782993854b826e2e0de70 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:38:07 -0300 Subject: [PATCH 3/5] refactor: couple plan closure evidence to the observed event Return merge evidence only for a merged pull request. Preserve the close-event comparison and carry the fallback parent with the created issue. Verified: 174 public CLI tests in eight plan suites; bun run check:types; targeted lint and format --- cli/src/plan/commands.ts | 46 ++++++++++++++++++++++------------------ cli/src/plan/github.ts | 33 ++++++++++++---------------- cli/src/plan/types.ts | 4 ++-- 3 files changed, 41 insertions(+), 42 deletions(-) diff --git a/cli/src/plan/commands.ts b/cli/src/plan/commands.ts index 519dd306..20e32620 100644 --- a/cli/src/plan/commands.ts +++ b/cli/src/plan/commands.ts @@ -31,7 +31,7 @@ import { runGh, withBodyFile, writeIssueIfUnchanged, - type PullRequestRead, + type MergedPullRequest, type SnapshotOptions, } from "./github"; import { @@ -248,6 +248,13 @@ function describeCloser(closer: Closer | null | undefined): string { return "an unknown closer"; } +function sameCloseEvent(left: PlanIssue["closeEvent"], right: PlanIssue["closeEvent"]): boolean { + return ( + left?.createdAt === right?.createdAt && + describeCloser(left?.closer) === describeCloser(right?.closer) + ); +} + const exportPlan = Effect.fn("plan.export")(function* (args: ReadonlyArray) { if (args.length !== 1) return yield* refuse("export requires one issue"); const { issue } = yield* readPlanIssue(args[0]); @@ -328,8 +335,7 @@ const createPlan = Effect.fn("plan.new")(function* (args: ReadonlyArray) .join("\n"); const source = `## Goal\n${goalText}\n## Research\n${RESEARCH_PLACEHOLDER}\n## Steps\n${STEPS_HEADER}\n${STEPS_SEPARATOR}\n## Acceptance\n${ACCEPTANCE_HEADER}\n${ACCEPTANCE_SEPARATOR}`; const { body } = yield* attempt(() => normalizePlan(source, { mode })); - let linkByRest = false; - const url = yield* withBodyFile(body, (file) => + const { url, pendingParent } = yield* withBodyFile(body, (file) => Effect.gen(function* () { const argv = [ "issue", @@ -348,18 +354,20 @@ const createPlan = Effect.fn("plan.new")(function* (args: ReadonlyArray) "--repo", nameWithOwner, ]; - if (parent === undefined) return (yield* runGh(argv)).trim(); + if (parent === undefined) + return { url: (yield* runGh(argv)).trim(), pendingParent: undefined }; const withParent = [...argv, "--parent", String(parent)]; const result = yield* ghResult(withParent); // gh refuses an unknown flag before it creates anything, so the plain create runs once. - linkByRest = result.status !== 0 && /unknown flag: --parent\b/.test(result.stderr); - return (linkByRest ? yield* runGh(argv) : yield* ghOutput(withParent, result)).trim(); + if (result.status !== 0 && /unknown flag: --parent\b/.test(result.stderr)) + return { url: (yield* runGh(argv)).trim(), pendingParent: parent }; + return { url: (yield* ghOutput(withParent, result)).trim(), pendingParent: undefined }; }), ); const number = /\/issues\/([1-9]\d*)\/?$/.exec(url)?.[1]; if (!number) return yield* new GhError({ message: "gh issue create returned an invalid issue URL" }); - if (linkByRest && parent !== undefined) yield* linkSubIssue(parent, Number(number)); + if (pendingParent !== undefined) yield* linkSubIssue(pendingParent, Number(number)); yield* printLine(`plan created: #${number} ${url}`); yield* printAdvice(source, "drafting", [], { mode }); }); @@ -417,9 +425,9 @@ const showPlan = Effect.fn("plan.show")(function* (args: ReadonlyArray) // stuck (#90), so the advice names the helper's own paths: the step, when the merged work finished it; `reopen --pr` for // a v3 or v4 plan that a pull request closed; a new plan for a v5 plan, because `new --parent` refuses a closed parent. function unfinishedStepAdvice(issue: PlanIssue, step: Step): string { - const closed = `plan is closed as completed while step ${step.id} is ${step.status}; closed by ${describeCloser(issue.closer)}`; + const closer = issue.closeEvent?.closer; + const closed = `plan is closed as completed while step ${step.id} is ${step.status}; closed by ${describeCloser(closer)}`; const finish = `run step ${issue.number} ${step.id} done if the merged work finished it`; - const { closer } = issue; // `reopen --pr` also accepts a commit of a merged pull request that closes the plan (`closedByPullRequest`); it finds // and checks that pull request itself, so the advice names the condition and the way without that pull request. const rest = @@ -1051,15 +1059,13 @@ const retirePlan = Effect.fn("plan.retire")(function* (args: ReadonlyArray refuseStuck(issue)); - if ( - issue.closedEventAt === undefined || - Date.parse(issue.closedEventAt) < Date.parse(String(pullRequest.mergedAt)) - ) + const { closeEvent } = issue; + if (!closeEvent || Date.parse(closeEvent.createdAt) < Date.parse(pullRequest.mergedAt)) return false; - const { closer } = issue; + const { closer } = closeEvent; const { nameWithOwner } = yield* currentRepository(); const isPullRequest = (candidate: { readonly number: number; @@ -1129,8 +1135,7 @@ const writeReopen = Effect.fn("plan.writeReopen")(function* ( const foreign = settled.assignees.find((owner) => !known.has(owner.login)); if (foreign) return yield* refuse(`plan #${issue.number} is owned by ${foreign.login}`); if ( - settled.closedEventAt !== issue.closedEventAt || - describeCloser(settled.closer) !== describeCloser(issue.closer) || + !sameCloseEvent(settled.closeEvent, issue.closeEvent) || settled.state !== before.state || settled.stateReason !== (before.stateReason ?? null) || settled.body !== before.body || @@ -1294,7 +1299,7 @@ const postReopenComment = Effect.fn("plan.postReopenComment")(function* ( Effect.catch((error) => readSnapshot(issue.number, { comments: true }).pipe( Effect.flatMap(({ issue: now }) => { - const since = Date.parse(issue.closedEventAt ?? ""); + const since = Date.parse(issue.closeEvent?.createdAt ?? ""); const landed = trustedComments(now).some( (entry) => entry.body === comment && @@ -1334,8 +1339,7 @@ const settleAndReopen = Effect.fn("plan.settleAndReopen")(function* ({ const current = yield* read(); const sameClose = (yield* stillReopenable(current)) && - current.issue.closedEventAt === observed.issue.closedEventAt && - describeCloser(current.issue.closer) === describeCloser(observed.issue.closer); + sameCloseEvent(current.issue.closeEvent, observed.issue.closeEvent); if (isClosed(current.issue) && (current.status !== "finished" || !sameClose)) return yield* refuse( `plan #${current.issue.number} changed during the settle wait; run ${command} again`, @@ -1390,7 +1394,7 @@ const reopenPlan = Effect.fn("plan.reopen")(function* (args: ReadonlyArray 1) return yield* new GraphqlError({ message: "gh api graphql returned malformed latest closure" }); - if (nodes.length === 0) return { closer: undefined, closedEventAt: undefined }; + if (nodes.length === 0) return undefined; const event = yield* decodeClosedEvent(nodes[0]); const rawCloser = field(nodes[0], "closer"); let closer: Closer | null = null; @@ -392,7 +392,7 @@ const latestCloser = Effect.fn("plan.latestCloser")(function* (latestClosure: un else if (event.closer?.__typename === "Commit") closer = { __typename: "Commit", ...(yield* decodeCommit(rawCloser)) }; else if (event.closer) closer = { __typename: "Other" }; - return { closer, closedEventAt: event.createdAt }; + return { closer, createdAt: event.createdAt }; }); /** The viewer fields of a snapshot: none, the acting login, or the login and the node id that a write claims with. */ @@ -564,9 +564,9 @@ const snapshotIssue = Effect.fn("plan.snapshotIssue")(function* ( ), )).map((event) => event.label) : []; - const closure = options.closure + const closeEvent = options.closure ? yield* latestCloser(field(rawIssue, "latestClosure")) - : { closer: undefined, closedEventAt: undefined }; + : undefined; const children = options.children ? yield* issueSummaries( yield* issueNodes(number, field(rawIssue, "subIssues"), "subIssues", ISSUE_SUMMARY_FIELDS), @@ -587,8 +587,7 @@ const snapshotIssue = Effect.fn("plan.snapshotIssue")(function* ( assignees, comments, history, - closer: closure.closer, - closedEventAt: closure.closedEventAt, + closeEvent, children, parent, }; @@ -919,11 +918,11 @@ export const writeIssueIfUnchanged = Effect.fn("plan.writeIssueIfUnchanged")(fun return yield* new PlanRefusal({ message: "plan issue labels differ after edit" }); }); -export interface PullRequestRead { +export interface MergedPullRequest { readonly number: number; readonly url: string; - readonly merged: boolean; - readonly mergedAt: string | null; + readonly merged: true; + readonly mergedAt: string; readonly baseRefName: string; readonly body: string | null; readonly closesPlan: boolean; @@ -942,6 +941,7 @@ const MergeFields = Schema.Struct({ }); const decodeMerge = malformed(MergeFields, "pull request"); +const decodeMergedAt = malformed(ParsableTime, "pull request"); const decodePullRequest = malformed( Schema.Struct({ nameWithOwner: Schema.String, @@ -971,12 +971,7 @@ export const readPullRequest = Effect.fn("plan.readPullRequest")(function* ( const rawRepo = field(yield* graphql(query, { pr: number }), "repository"); const repo = yield* decodePullRequest(rawRepo); const { pullRequest } = repo; - const mergedAt = pullRequest.mergedAt; - if ( - pullRequest.merged && - !(Predicate.isString(mergedAt) && Number.isFinite(Date.parse(mergedAt))) - ) - return yield* new GraphqlError({ message: "gh api graphql returned malformed pull request" }); + const mergedAt = pullRequest.merged ? yield* decodeMergedAt(pullRequest.mergedAt) : undefined; const pageQuery = `query($owner:String!,$name:String!,$pr:Int!,$after:String!){repository(owner:$owner,name:$name){pullRequest(number:$pr){${references(true)}}}}`; const closed = yield* decodeClosingReferences( yield* connectionNodes( @@ -991,20 +986,20 @@ export const readPullRequest = Effect.fn("plan.readPullRequest")(function* ( ), ); const { headRefOid, mergeCommit } = yield* decodeMerge(field(rawRepo, "pullRequest")); + if (mergedAt === undefined) return { number, merged: false } as const; const isThis = (candidate: PullRequestNode): boolean => candidate.number === number && candidate.repository.nameWithOwner === repo.nameWithOwner; const landedByItself = - pullRequest.merged && mergeCommit !== null && mergeCommit.oid !== headRefOid && (yield* pullRequestNodes( yield* associatedNodes({ __typename: "Commit", ...mergeCommit }), )).some(isThis); - const read: PullRequestRead = { + const read: MergedPullRequest = { number, url: pullRequest.url, - merged: pullRequest.merged, - mergedAt: Predicate.isString(mergedAt) ? mergedAt : null, + merged: true, + mergedAt, baseRefName: pullRequest.baseRefName, body: pullRequest.body, closesPlan: closed.some( diff --git a/cli/src/plan/types.ts b/cli/src/plan/types.ts index 2ccd98fa..5a9688ca 100644 --- a/cli/src/plan/types.ts +++ b/cli/src/plan/types.ts @@ -148,8 +148,8 @@ export interface PlanIssue { readonly assignees: ReadonlyArray; readonly comments: ReadonlyArray; readonly history: ReadonlyArray; - readonly closer: Closer | null | undefined; - readonly closedEventAt: string | undefined; + /** No event and an event whose closer is unknown have different meanings. */ + readonly closeEvent: { readonly createdAt: string; readonly closer: Closer | null } | undefined; readonly children: ReadonlyArray; readonly parent: ParentLink | null | undefined; } From 4aaf78f74ea064e967c6e23758739d9622843ef0 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:46:11 -0300 Subject: [PATCH 4/5] Verify reopen ownership before posting the plan record - Carry the verified owner into comment recovery. Select label IDs explicitly for writes. - Exercise the final owner read, claim confirmation, malformed merge evidence, and creation without a parent. --- cli/src/plan/commands.ts | 34 ++++-- cli/src/plan/github.ts | 50 ++++---- cli/test/fixtures/gh-stub/ghStub.ts | 18 ++- cli/test/fixtures/gh-stub/state.ts | 5 + cli/test/unit/plan/children.test.ts | 24 +++- cli/test/unit/plan/reopen.test.ts | 107 ++++++++++++++++++ .../unit/plan/write-postconditions.test.ts | 42 +++++++ 7 files changed, 246 insertions(+), 34 deletions(-) diff --git a/cli/src/plan/commands.ts b/cli/src/plan/commands.ts index 20e32620..b0999ad2 100644 --- a/cli/src/plan/commands.ts +++ b/cli/src/plan/commands.ts @@ -32,7 +32,7 @@ import { withBodyFile, writeIssueIfUnchanged, type MergedPullRequest, - type SnapshotOptions, + type SnapshotConnections, } from "./github"; import { ACCEPTANCE_HEADER, @@ -179,7 +179,7 @@ const lacksPlanLabel = (number: number): string => const readPlanIssue = Effect.fn("plan.readPlanIssue")(function* ( value: string | undefined, - connections: SnapshotOptions = {}, + connections: SnapshotConnections = {}, ) { const number = yield* attempt(() => parseIssueNumber(value)); const { issue } = yield* readSnapshot(number, connections); @@ -197,7 +197,7 @@ const readPlanIssue = Effect.fn("plan.readPlanIssue")(function* ( // issue for the acting viewer. const readWritablePlan = Effect.fn("plan.readWritablePlan")(function* ( value: string | undefined, - connections: SnapshotOptions = {}, + connections: SnapshotConnections = {}, ) { const number = yield* attempt(() => parseIssueNumber(value)); const { issue, viewer, labelIds } = yield* readWriteSnapshot(number, connections); @@ -804,7 +804,7 @@ function openWork( } // The read of a plan for archive's recovery and close checks. -const archiveConnections: SnapshotOptions = { +const archiveConnections: SnapshotConnections = { comments: true, children: true, closure: true, @@ -1239,7 +1239,13 @@ const writeReopen = Effect.fn("plan.writeReopen")(function* ( return yield* refuse( `plan #${issue.number} ${isClosed(current) ? "closed again after the reopen" : `reopened, but it reads phase labels ${phaseList(current.labels)} and owners ${current.assignees.map((owner) => owner.login).join(", ") || "none"}`}; no comment was posted; ${reopenRecovery(current, login, expectedPhase, command, comment)}`, ); - yield* postReopenComment(issue, id, expectedPhase, comment, command); + const reopened = { + id, + number: current.number, + owner: current.assignees[0].login, + closeEvent: issue.closeEvent, + }; + yield* postReopenComment(reopened, expectedPhase, comment, command); yield* printLine(`plan #${issue.number} reopened: ${statusFromIssueOf(current)}`); }); @@ -1279,11 +1285,17 @@ const phaseList = (labels: ReadonlyArray<{ readonly name: string }>): string => .filter(isPhaseLabel) .join(", ") || "none"; +interface ReopenedPlan { + readonly id: string; + readonly number: number; + readonly owner: string; + readonly closeEvent: PlanIssue["closeEvent"]; +} + // The second write of a reopen. When it fails, the comments show whether it landed: a trusted comment with its text that // is newer than the close that this reopen observed belongs to this attempt. const postReopenComment = Effect.fn("plan.postReopenComment")(function* ( - issue: WritablePlanIssue, - id: string, + reopened: ReopenedPlan, expectedPhase: string, comment: string, command: string, @@ -1292,14 +1304,14 @@ const postReopenComment = Effect.fn("plan.postReopenComment")(function* ( "-f", "query=mutation($issue:ID!,$body:String!){addComment(input:{subjectId:$issue,body:$body}){clientMutationId}}", "-f", - `issue=${id}`, + `issue=${reopened.id}`, "-f", `body=${comment}`, ]).pipe( Effect.catch((error) => - readSnapshot(issue.number, { comments: true }).pipe( + readSnapshot(reopened.number, { comments: true }).pipe( Effect.flatMap(({ issue: now }) => { - const since = Date.parse(issue.closeEvent?.createdAt ?? ""); + const since = Date.parse(reopened.closeEvent?.createdAt ?? ""); const landed = trustedComments(now).some( (entry) => entry.body === comment && @@ -1308,7 +1320,7 @@ const postReopenComment = Effect.fn("plan.postReopenComment")(function* ( ); if (landed) return Effect.void; return refuse( - `plan #${issue.number} ${isClosed(now) ? "closed again after the reopen" : "is open again"}, but its reopen comment did not post (${error.message}); ${reopenRecovery(now, issue.viewer.login, expectedPhase, command, comment)}`, + `plan #${reopened.number} ${isClosed(now) ? "closed again after the reopen" : "is open again"}, but its reopen comment did not post (${error.message}); ${reopenRecovery(now, reopened.owner, expectedPhase, command, comment)}`, ); }), ), diff --git a/cli/src/plan/github.ts b/cli/src/plan/github.ts index 675811ec..25e90d2f 100644 --- a/cli/src/plan/github.ts +++ b/cli/src/plan/github.ts @@ -397,11 +397,13 @@ const latestCloser = Effect.fn("plan.latestCloser")(function* (latestClosure: un /** The viewer fields of a snapshot: none, the acting login, or the login and the node id that a write claims with. */ type ViewerFields = "" | "login" | "login id"; +type LabelSelection = "none" | "names" | "ids"; function snapshotQuery( number: number | undefined, - options: SnapshotOptions, + options: SnapshotConnections, viewerFields: ViewerFields, + labelSelection: LabelSelection, ): string { const issueFields = number === undefined @@ -424,8 +426,13 @@ function snapshotQuery( options.children ? issueConnectionSelection("subIssues", ISSUE_SUMMARY_FIELDS) : "", options.parent ? "parent{number repository{nameWithOwner}}" : "", ].join(" "); - const labels = options.namesOnly ? REPOSITORY_LABEL_NAMES : REPOSITORY_LABELS; - return `query($owner:String!,$name:String!${number === undefined ? "" : ",$number:Int!"}){${viewerFields ? `viewer{${viewerFields}}` : ""} repository(owner:$owner,name:$name){nameWithOwner visibility ${options.defaultBranch ? "defaultBranchRef{name}" : ""} ${options.labelLookup ? labels : ""} ${number === undefined ? "" : `issue(number:$number){${issueFields}}`}}}`; + const labels = + labelSelection === "ids" + ? REPOSITORY_LABELS + : labelSelection === "names" + ? REPOSITORY_LABEL_NAMES + : ""; + return `query($owner:String!,$name:String!${number === undefined ? "" : ",$number:Int!"}){${viewerFields ? `viewer{${viewerFields}}` : ""} repository(owner:$owner,name:$name){nameWithOwner visibility ${options.defaultBranch ? "defaultBranchRef{name}" : ""} ${labels} ${number === undefined ? "" : `issue(number:$number){${issueFields}}`}}}`; } const decodeRepository = malformed(RepositoryFields, "repository"); @@ -444,11 +451,12 @@ const decodeOptionalLabelName = malformed(Schema.NullOr(LabelName), "repository */ const queryRepository = Effect.fn("plan.queryRepository")(function* ( number: number | undefined, - options: SnapshotOptions, + options: SnapshotConnections, viewerFields: ViewerFields, + labelSelection: LabelSelection, ) { const data = yield* graphql( - snapshotQuery(number, options, viewerFields), + snapshotQuery(number, options, viewerFields, labelSelection), number === undefined ? {} : { number }, ); const repo = field(data, "repository"); @@ -470,21 +478,20 @@ const decodeViewer = Effect.fn("plan.decodeViewer")(function* (viewer: unknown) return decoded; }); -/** The plan labels of the repository `repo`, when `options` looks them up. */ +/** Decode the same repository label fields that the query selected. */ const repositoryLabels = Effect.fn("plan.repositoryLabels")(function* ( repo: unknown, - options: SnapshotOptions, + selection: LabelSelection, ) { let labelIds: Map | undefined; const missingLabels: Array = []; - if (options.labelLookup) { - if (!options.namesOnly) labelIds = new Map(); + if (selection !== "none") { + if (selection === "ids") labelIds = new Map(); for (const name of PLAN_LABELS) { const raw = field(repo, name.split(":").at(-1) ?? name); - const label = options.namesOnly ? null : yield* decodeOptionalLabel(raw); - const labelName = options.namesOnly - ? (yield* decodeOptionalLabelName(raw))?.name - : label?.name; + const label = selection === "ids" ? yield* decodeOptionalLabel(raw) : null; + const labelName = + selection === "names" ? (yield* decodeOptionalLabelName(raw))?.name : label?.name; if (labelName !== undefined && token(labelName) !== name) return yield* new GraphqlError({ message: "gh api graphql returned malformed repository labels", @@ -503,9 +510,13 @@ const readRepository = Effect.fn("plan.readRepository")(function* ( options: SnapshotOptions, ) { const viewerFields = options.acting ? "login" : ""; - const { repo, viewer } = yield* queryRepository(number, options, viewerFields); + const labelSelection = !options.labelLookup ? "none" : options.namesOnly ? "names" : "ids"; + const { repo, viewer } = yield* queryRepository(number, options, viewerFields, labelSelection); const login = options.acting ? yield* decodeLogin(field(viewer, "login")) : undefined; - const snapshot: RepositorySnapshot = { login, ...(yield* repositoryLabels(repo, options)) }; + const snapshot: RepositorySnapshot = { + login, + ...(yield* repositoryLabels(repo, labelSelection)), + }; return { repo, snapshot }; }); @@ -610,9 +621,10 @@ export const readWriteSnapshot = Effect.fn("plan.readWriteSnapshot")(function* ( number: number, connections: SnapshotConnections = {}, ) { - const { repo, viewer } = yield* queryRepository(number, connections, "login id"); + const labelSelection = connections.labelLookup ? "ids" : "none"; + const { repo, viewer } = yield* queryRepository(number, connections, "login id", labelSelection); const actor = yield* decodeViewer(viewer); - const labels = yield* repositoryLabels(repo, connections); + const labels = yield* repositoryLabels(repo, labelSelection); const result: WriteSnapshot = { ...labels, issue: yield* snapshotIssue(number, repo, connections), @@ -954,8 +966,8 @@ const decodeClosingReferences = malformed( "closing issue references", ); -// Pull request `number`: whether, when, and where it merged, its description, and whether GitHub lists plan -// `planNumber` of this repository among the issues that it closes. +// An unmerged pull request returns only its number and merge status. A merged one includes its timestamp, +// destination, description, closing references for this plan, and whether its own merge landed the change. export const readPullRequest = Effect.fn("plan.readPullRequest")(function* ( number: number, planNumber: number, diff --git a/cli/test/fixtures/gh-stub/ghStub.ts b/cli/test/fixtures/gh-stub/ghStub.ts index 5a41f518..7cf14280 100644 --- a/cli/test/fixtures/gh-stub/ghStub.ts +++ b/cli/test/fixtures/gh-stub/ghStub.ts @@ -1338,7 +1338,23 @@ if (group === "issue" && command === "view") { // Real gh reads `labels(first:100)` for `issue view` (cli/cli api/query_builder.go), so it never // returns a label past the first 100. const view = issueJson(issue); - emit(JSON.stringify(select({ ...view, labels: view.labels.slice(0, 100) }, value("--json")))); + // `issueViewOmitsViewerLoginOnce` shows the viewer assignee of one view with its node id alone, as an actor reply + // whose login is missing. + const viewer = state.viewerLogin; + const omitsLogin = + state.issueViewOmitsViewerLoginOnce === number && + viewer !== undefined && + (issue.assignees ?? []).includes(viewer); + if (omitsLogin) delete state.issueViewOmitsViewerLoginOnce; + const shown = omitsLogin + ? { + ...view, + assignees: (issue.assignees ?? []).map((login) => + login === viewer ? { id: userNodeId(login) } : { id: userNodeId(login), login }, + ), + } + : view; + emit(JSON.stringify(select({ ...shown, labels: view.labels.slice(0, 100) }, value("--json")))); // `afterIssueViewOnce` lands its change right after the view, such as a change between a pre-write read and a later // GraphQL read. const viewChange = state.afterIssueViewOnce; diff --git a/cli/test/fixtures/gh-stub/state.ts b/cli/test/fixtures/gh-stub/state.ts index 2b21d701..4f3e5540 100644 --- a/cli/test/fixtures/gh-stub/state.ts +++ b/cli/test/fixtures/gh-stub/state.ts @@ -176,6 +176,11 @@ export type StubState = { * view once the issue has served `afterReads` GraphQL reads. The view shows the issue before the change. */ afterIssueViewOnce?: StubChange & { issue: number }; + /** + * The issue whose next `gh issue view` that lists the viewer as an assignee shows that assignee with its node id and + * without its login. + */ + issueViewOmitsViewerLoginOnce?: number; /** A change, in the form of a scheduled change, that lands right after one GraphQL request that lists issues. */ afterListOnce?: StubChange & { issue: number }; ghLacksParentFlag?: boolean; diff --git a/cli/test/unit/plan/children.test.ts b/cli/test/unit/plan/children.test.ts index fb9b354d..43cc64b2 100644 --- a/cli/test/unit/plan/children.test.ts +++ b/cli/test/unit/plan/children.test.ts @@ -187,17 +187,35 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan child plans", () => { ); it( - "new writes the v5 marker", + "new without --parent writes the v5 marker and links the plan to no parent", () => { const context = planCliContext(); + // An open plan of the acting login that `new --parent` would accept, so a stray link has a parent to land on. + const possibleParent = context.createPlan("possible parent"); + const expected = context.loadState().nextIssue; const result = context.run("new", "--title", "plain plan", "--goal", "Fix the parser"); expectSuccess(result, "new"); const number = Number(/^plan created: #(\d+) /m.exec(result.stdout)?.[1]); + expect(number, "new prints the created plan").toBe(expected); expect(context.issue(number).body).toMatch(/^\n/); + expect(creates(context).at(-1), "the create names no parent").not.toContain("--parent"); expect( - context.issue(number).subIssues, - "a plan without --parent gets no parent", + context.issue(possibleParent).subIssues, + "the possible parent stores no sub-issue", ).toBeUndefined(); + expect( + context + .loadState() + .issues.filter((entry) => entry.subIssues?.includes(number)) + .map((entry) => entry.number), + "no issue stores the plan as its sub-issue", + ).toStrictEqual([]); + expect( + context + .loadState() + .calls.filter(([group, command]) => group === "api" && command !== "graphql"), + "no REST sub-issue link", + ).toStrictEqual([]); }, SPAWN_TIMEOUT_MS, ); diff --git a/cli/test/unit/plan/reopen.test.ts b/cli/test/unit/plan/reopen.test.ts index 694b5cc6..2456ea26 100644 --- a/cli/test/unit/plan/reopen.test.ts +++ b/cli/test/unit/plan/reopen.test.ts @@ -66,6 +66,43 @@ function stored({ issue }: PlanCliContext, number: number) { }; } +// The data of a pull request read for an unmerged `plan.pr` that closes the plan, as GitHub answers it, with the +// `pullRequest` fields of `replaced` in place of its own. `graphqlMissingData` serves it for the next page read. +function unmergedRead(plan: PartialMerge, replaced: Readonly>) { + return { + repository: { + nameWithOwner: "DocksDocks/fixture", + pullRequest: { + url: `https://github.com/DocksDocks/fixture/pull/${plan.pr}`, + merged: false, + mergedAt: null, + baseRefName: "main", + body: null, + headRefOid: `head${plan.pr}`, + mergeCommit: null, + closingIssuesReferences: { + nodes: [{ number: plan.number, repository: { nameWithOwner: "DocksDocks/fixture" } }], + pageInfo: { hasNextPage: false, endCursor: null }, + }, + ...replaced, + }, + }, + }; +} + +// A closing reference whose issue number is a string. +function malformedReferences(plan: PartialMerge) { + return { + closingIssuesReferences: { + nodes: [{ number: String(plan.number), repository: { nameWithOwner: "DocksDocks/fixture" } }], + pageInfo: { hasNextPage: false, endCursor: null }, + }, + }; +} + +const MALFORMED_REFERENCES = "gh api graphql returned malformed closing issue references"; +const MALFORMED_PULL_REQUEST = "gh api graphql returned malformed pull request"; + describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan reopen", () => { it( "reopen waits for the close by the pull request, then reopens with the contract comment and a claim", @@ -234,6 +271,52 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan reopen", () => { SPAWN_TIMEOUT_MS, ); + // The pull request read checks its closing references, then its merge fields, before it decides that the pull request + // has not merged; an unmerged pull request is no reason to skip a malformed field. + for (const [name, replaced, message] of [ + ["well-formed fields", () => ({}), (plan) => `pull request #${plan.pr} is not merged`], + ["malformed closing references", malformedReferences, () => MALFORMED_REFERENCES], + ["a head commit without an oid", () => ({ headRefOid: null }), () => MALFORMED_PULL_REQUEST], + [ + "a merge commit without an oid", + () => ({ mergeCommit: { oid: "", associatedPullRequests: null } }), + () => MALFORMED_PULL_REQUEST, + ], + [ + "malformed closing references and a head commit without an oid", + (plan) => ({ ...malformedReferences(plan), headRefOid: null }), + () => MALFORMED_REFERENCES, + ], + ] as const satisfies ReadonlyArray< + readonly [ + string, + (plan: PartialMerge) => Readonly>, + (plan: PartialMerge) => string, + ] + >) { + it( + `reopen answers an unmerged pull request read with ${name} from that read alone and writes nothing`, + () => { + const context = planCliContext(); + const plan = context.partialMerge(`unmerged pull request with ${name}`, { merged: false }); + context.updateState((state) => { + state.graphqlMissingData = { on: "page", data: unmergedRead(plan, replaced(plan)) }; + }); + refuse(reopen(context, plan), message(plan)); + const state = context.loadState(); + expect(state.graphqlMissingData, "the pull request read got the response").toBeUndefined(); + expect( + state.calls.filter(([group, command]) => group === "api" && command === "graphql"), + "the pull request read is the only GraphQL read", + ).toHaveLength(1); + expect(stored(context, plan.number)).toStrictEqual(ONGOING); + expect(context.writes()).toStrictEqual([]); + expect(context.waits()).toStrictEqual([]); + }, + SPAWN_TIMEOUT_MS, + ); + } + it( "reopen refuses a v5 plan before any wait or write, and names child plans", () => { @@ -821,6 +904,30 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan reopen", () => { SPAWN_TIMEOUT_MS, ); + it( + "reopen refuses an unassigned plan that only its last read before the write shows owned by the acting login", + () => { + const context = planCliContext(); + const plan = context.partialMerge("acting login claims after the pre-write read"); + context.schedule(plan.number, { afterReads: 0, ...closedBy(plan.closer) }); + // The pre-write read shows no owner, so the reopen would claim the plan. The acting login is no foreign owner, but + // the owners of the last read no longer match the owners that the claim was decided from. + context.updateState((state) => { + state.afterIssueViewOnce = { issue: plan.number, afterReads: 2, assignees: ["plan-agent"] }; + }); + refuse(reopen(context, plan), settleRefusal(plan.number)); + expect(context.waits()).toStrictEqual([SETTLE_WAIT]); + expect(stored(context, plan.number)).toStrictEqual({ + ...ONGOING, + state: "CLOSED", + stateReason: "COMPLETED", + assignees: ["plan-agent"], + }); + expect(context.writes(), "no reopen, no claim, and no comment").toStrictEqual([]); + }, + SPAWN_TIMEOUT_MS, + ); + it( "reopen reports a failed first request with the state that the plan reads after it", () => { diff --git a/cli/test/unit/plan/write-postconditions.test.ts b/cli/test/unit/plan/write-postconditions.test.ts index 3bf48ad2..4298f9e6 100644 --- a/cli/test/unit/plan/write-postconditions.test.ts +++ b/cli/test/unit/plan/write-postconditions.test.ts @@ -157,6 +157,48 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan write postconditions", () => { SPAWN_TIMEOUT_MS, ); + it( + "retire admits a pending claim by the viewer's node id and refuses a confirmed claim without the viewer's login", + () => { + const { run, issue, updateIssue, updateState, loadState, createPlan, schedule } = + planCliContext(); + // The viewer is assigned after the snapshot, and the pre-write read shows it by its node id alone. + const pending = createPlan("viewer by node id before the claim"); + updateIssue(pending, (entry) => { + entry.assignees = []; + }); + schedule(pending, { afterReads: 1, assignees: ["plan-agent"] }); + updateState((state) => { + state.issueViewOmitsViewerLoginOnce = pending; + }); + const retired = run("retire", String(pending), "--reason", "No longer needed"); + expectSuccess(retired, "retire with the viewer by node id"); + expect(loadState().issueViewOmitsViewerLoginOnce).toBeUndefined(); + expect(retired.stdout.trim()).toBe(`plan #${pending} retired`); + expect(issue(pending).state).toBe("CLOSED"); + expect(issue(pending).assignees).toStrictEqual(["plan-agent"]); + + // The claim lands, and the read right before the close shows the viewer by its node id alone. + const confirmed = createPlan("viewer by node id after the claim"); + updateIssue(confirmed, (entry) => { + entry.assignees = []; + }); + updateState((state) => { + state.issueViewOmitsViewerLoginOnce = confirmed; + }); + refuse( + run("retire", String(confirmed), "--reason", "No longer needed"), + `plan #${confirmed} is owned by undefined`, + ); + expect(loadState().issueViewOmitsViewerLoginOnce).toBeUndefined(); + expect(issue(confirmed).state).toBe("OPEN"); + expect(issue(confirmed).comments ?? []).toStrictEqual([]); + expect(issue(confirmed).assignees).toStrictEqual(["plan-agent"]); + expect(issue(confirmed).labels).toStrictEqual(["plan"]); + }, + SPAWN_TIMEOUT_MS, + ); + it( "retire reads the plan before the close even when it removes and claims nothing", () => { From dc3104a6bb3122a6c0991af4d70cb58cd8fb3b88 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:52:05 -0300 Subject: [PATCH 5/5] Preserve a one-time fixture response until the caller reads assignees - Cover the body-only reopen read before the guarded ownership read. - Document the Boolean closing decision rather than restating the pull request shape. --- cli/src/plan/github.ts | 3 +-- cli/test/fixtures/gh-stub/ghStub.ts | 8 +++++--- cli/test/unit/plan/reopen.test.ts | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/cli/src/plan/github.ts b/cli/src/plan/github.ts index 25e90d2f..9e9c5236 100644 --- a/cli/src/plan/github.ts +++ b/cli/src/plan/github.ts @@ -966,8 +966,7 @@ const decodeClosingReferences = malformed( "closing issue references", ); -// An unmerged pull request returns only its number and merge status. A merged one includes its timestamp, -// destination, description, closing references for this plan, and whether its own merge landed the change. +// `closesPlan` means GitHub lists this repository's plan among the issues closed by the merged pull request. export const readPullRequest = Effect.fn("plan.readPullRequest")(function* ( number: number, planNumber: number, diff --git a/cli/test/fixtures/gh-stub/ghStub.ts b/cli/test/fixtures/gh-stub/ghStub.ts index 7cf14280..8e6d5538 100644 --- a/cli/test/fixtures/gh-stub/ghStub.ts +++ b/cli/test/fixtures/gh-stub/ghStub.ts @@ -1338,23 +1338,25 @@ if (group === "issue" && command === "view") { // Real gh reads `labels(first:100)` for `issue view` (cli/cli api/query_builder.go), so it never // returns a label past the first 100. const view = issueJson(issue); + const selected = select({ ...view, labels: view.labels.slice(0, 100) }, value("--json")); // `issueViewOmitsViewerLoginOnce` shows the viewer assignee of one view with its node id alone, as an actor reply // whose login is missing. const viewer = state.viewerLogin; const omitsLogin = state.issueViewOmitsViewerLoginOnce === number && + Object.hasOwn(selected, "assignees") && viewer !== undefined && (issue.assignees ?? []).includes(viewer); if (omitsLogin) delete state.issueViewOmitsViewerLoginOnce; const shown = omitsLogin ? { - ...view, + ...selected, assignees: (issue.assignees ?? []).map((login) => login === viewer ? { id: userNodeId(login) } : { id: userNodeId(login), login }, ), } - : view; - emit(JSON.stringify(select({ ...shown, labels: view.labels.slice(0, 100) }, value("--json")))); + : selected; + emit(JSON.stringify(shown)); // `afterIssueViewOnce` lands its change right after the view, such as a change between a pre-write read and a later // GraphQL read. const viewChange = state.afterIssueViewOnce; diff --git a/cli/test/unit/plan/reopen.test.ts b/cli/test/unit/plan/reopen.test.ts index 2456ea26..b57eeb68 100644 --- a/cli/test/unit/plan/reopen.test.ts +++ b/cli/test/unit/plan/reopen.test.ts @@ -830,6 +830,24 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan reopen", () => { SPAWN_TIMEOUT_MS, ); + it( + "reopen refuses an assigned viewer without a login in its pre-write response", + () => { + const context = planCliContext(); + const plan = context.partialMerge("viewer login missing from guarded read", { + assignees: ["plan-agent"], + }); + context.schedule(plan.number, { afterReads: 0, ...closedBy(plan.closer) }); + context.updateState((state) => { + state.issueViewOmitsViewerLoginOnce = plan.number; + }); + refuse(reopen(context, plan), `plan #${plan.number} is owned by undefined`); + expect(context.issue(plan.number).state).toBe("CLOSED"); + expect(context.writes()).toStrictEqual([]); + }, + SPAWN_TIMEOUT_MS, + ); + it( "reopen refuses a plan that another login claims after the settle-wait read, right before the write", () => {