mirror of
https://github.com/storytold/autocraft.git
synced 2026-11-24 16:31:06 +01:00
Merge app-user-lane
This commit is contained in:
commit
dc57337320
28 files changed
+577
-45
No files matched your search
@@ -20,6 +20,10 @@ export type GroupIo = {
|
||||
/** Returns the comment's URL. */
|
||||
comment(live: GroupLive, body: string, at: { number: number; decision: string }): Promise<string>;
|
||||
close(live: GroupLive, at: { number: number; decision: string }): Promise<void>;
|
||||
/** Called before a decision's writes: a string says why the decision waits (its operator has no token or no access), and it is left for a later run. */
|
||||
begin?(decision: string): Promise<string | null>;
|
||||
/** A write of the decision failed with `why`; true when that is a wait for the operator's access, not a failure to count. */
|
||||
failed?(decision: string, why: string): boolean;
|
||||
};
|
||||
export type GroupRun = {
|
||||
repo: string; io: GroupIo; at: () => string; log: (line: string) => void;
|
||||
@@ -70,6 +74,8 @@ export async function actOnGroups(db: DatabaseSync, run: GroupRun): Promise<Grou
|
||||
for (const c of closers) if (!posted.get(dec.id, c.number, "close")) run.log(` would comment and close ${ref(c.number)} (${dec.id})`);
|
||||
continue;
|
||||
}
|
||||
const waits = await run.io.begin?.(dec.id);
|
||||
if (waits) { run.log(` ${dec.id}: waiting: ${waits}`); continue; }
|
||||
const skip = (n: number, step: string, reason: string, release = false) => {
|
||||
record(dec.id, n, step, null);
|
||||
if (release) {
|
||||
@@ -152,6 +158,7 @@ export async function actOnGroups(db: DatabaseSync, run: GroupRun): Promise<Grou
|
||||
}
|
||||
} catch (e) {
|
||||
const why = (e as Error).message.replace(/\s+/g, " ").slice(0, 300);
|
||||
if (run.io.failed?.(dec.id, why)) { run.log(` ${dec.id}: waiting: ${why}`); continue; }
|
||||
res.failed.push({ ref: cur ? ref(cur.item.number) : dec.id, reason: why });
|
||||
run.log(` ${dec.id}: failed: ${why}`);
|
||||
if (!cur) return res;
|
||||
|
||||
+51
-9
@@ -31,12 +31,13 @@ import { fillEmbedHashes } from "../itemhash.ts";
|
||||
import { applyDuplicateAnswers } from "../dupes/decide.ts";
|
||||
import { commentApprovalOf } from "./approval.ts";
|
||||
import { CLI_BY, type By } from "../core/gates.ts";
|
||||
import { guardItem, guardRepo } from "../core/guard.ts";
|
||||
import { guardItem, guardRepo, type GuardedRepo } from "../core/guard.ts";
|
||||
import { actOnGroups, type GroupIo } from "./dupe-groups.ts";
|
||||
import { cleanReason, duplicateComment, prCloseComment, scopeCloseComment } from "./templates.ts";
|
||||
import { plannedItems } from "../core/select-items.ts";
|
||||
import { jobItem } from "../runner/job-items.ts";
|
||||
import { ownerOf } from "../owners.ts";
|
||||
import { authFailure, laneForDecision, markExecDone, noWriteReason, setExecState, SIGN_IN_REASON, type LaneDeps, type Lane } from "../github/user-lane.ts";
|
||||
|
||||
const ACTOR = "act";
|
||||
const NO_IO: GroupIo = { live: async () => null, comment: async () => "", close: async () => {} };
|
||||
@@ -44,7 +45,7 @@ const KIND = "comment-close";
|
||||
const DUP_FACT = "duplicate of ";
|
||||
const REASON_FACT = "review reason: ";
|
||||
|
||||
export type ActDeps = { querier: Querier; now: () => Date };
|
||||
export type ActDeps = { querier: Querier; now: () => Date; /** The user lane's token source and transports; default: the secrets file's app. */ lane?: LaneDeps };
|
||||
export const defaultDeps = (): ActDeps => ({ querier: new Client(1000), now: () => new Date() });
|
||||
|
||||
export type ActParams = {
|
||||
@@ -260,8 +261,17 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st
|
||||
handled++;
|
||||
params.onHandled?.(handled);
|
||||
const prev = rowOf(db, t);
|
||||
// An answer in a repo on the app's identity is carried out as the operator who gave it, with their token; it waits when there is none.
|
||||
const lr = await laneForDecision(db, d.lane, t.decisionId, [t.repo]);
|
||||
if (lr && !("lane" in lr)) {
|
||||
if ("transient" in lr) jobItem(db, t.repo, t.number, `not closed yet: ${lr.transient}`, log);
|
||||
else { setExecState(db, t.decisionId, lr.state, lr.reason); jobItem(db, t.repo, t.number, `waiting: ${lr.reason}`, log); }
|
||||
continue;
|
||||
}
|
||||
if (lr) setExecState(db, t.decisionId, "pending");
|
||||
const q = lr ? lr.lane.querier : d.querier;
|
||||
try {
|
||||
const live = await readLive(d.querier, t.repo, t.number);
|
||||
const live = await readLive(q, t.repo, t.number);
|
||||
if (!live) { skip(t, "GitHub returned no such item"); continue; }
|
||||
if (live.state !== "OPEN") { skip(t, `already ${live.state.toLowerCase()} on GitHub`); continue; }
|
||||
if (t.kind === "close" || t.kind === "merge") {
|
||||
@@ -276,15 +286,15 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st
|
||||
if (t.kind === "duplicate") {
|
||||
const orig = /^([\w.-]+)#(\d+)$/.exec(factValue(dec, DUP_FACT) ?? "");
|
||||
if (!orig || orig[1] !== t.repo || Number(orig[2]) === t.number) { skip(t, "the decision names no other item of this repo as the original"); continue; }
|
||||
const o = await readLive(d.querier, t.repo, Number(orig[2]));
|
||||
const o = await readLive(q, t.repo, Number(orig[2]));
|
||||
if (!o) { skip(t, "GitHub returned no such original"); continue; }
|
||||
body = duplicateComment({ repo: t.repo, original: `${orig[1]}#${orig[2]}`, closed: o.state !== "OPEN" });
|
||||
} else body = commentFor(dec, t);
|
||||
url = await commentOn(w, g, d.querier, "act-comment", { repo: t.repo, number: t.number, id: live.id }, decisionNote(dec), body, { decision: t.decisionId });
|
||||
url = await commentOn(w, g, q, "act-comment", { repo: t.repo, number: t.number, id: live.id }, decisionNote(dec), body, { decision: t.decisionId });
|
||||
// Saved before the close so a retry after a failed close does not comment twice.
|
||||
save(t, "failed", "comment posted; close not done yet", url);
|
||||
}
|
||||
await closeItem(w, g, d.querier, { repo: t.repo, number: t.number, id: live.id, pr: live.type === "PullRequest" }, { decision: t.decisionId, head: live.head });
|
||||
await closeItem(w, g, q, { repo: t.repo, number: t.number, id: live.id, pr: live.type === "PullRequest" }, { decision: t.decisionId, head: live.head });
|
||||
save(t, "done", null, url);
|
||||
db.prepare("INSERT INTO stages (repo, number, stage, at, actor, note) VALUES (?, ?, 'closed', ?, ?, ?)").run(t.repo, t.number, at(), ACTOR, `closed after ${t.kind} decision ${t.decisionId}`);
|
||||
summary.done.push(refOf(t));
|
||||
@@ -292,6 +302,14 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st
|
||||
settle(t);
|
||||
} catch (e) {
|
||||
const why = (e as Error).message.replace(/\s+/g, " ").slice(0, 300);
|
||||
const denied = lr ? authFailure(why) : null;
|
||||
if (denied) {
|
||||
// The user's token may not do this write: wait for access instead of failing, and write nothing as anyone else.
|
||||
setExecState(db, t.decisionId, denied, denied === "waiting-token" ? SIGN_IN_REASON : noWriteReason(t.repo));
|
||||
jobItem(db, t.repo, t.number, `waiting: ${why}`, log);
|
||||
continue;
|
||||
}
|
||||
if (lr) setExecState(db, t.decisionId, "failed", why);
|
||||
const row = rowOf(db, t);
|
||||
save(t, "failed", why, row?.comment_url ?? null);
|
||||
summary.failed.push({ ref: refOf(t), reason: why });
|
||||
@@ -303,10 +321,33 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st
|
||||
const groupGrant = summary.failed.length ? null : guardRepo(db, repo, "comment", params.by ?? CLI_BY);
|
||||
if (groupGrant && "refused" in groupGrant) log(` duplicate groups: not applied: ${groupGrant.refused}`);
|
||||
else if (groupGrant) {
|
||||
// Each group decision is carried out as the operator who answered it; `begin` picks that operator's lane.
|
||||
let lane: Lane | null = null;
|
||||
const q = (): Querier => lane?.querier ?? d.querier;
|
||||
const asAnswerer = (decision: string): GuardedRepo => {
|
||||
const g = guardRepo(db, repo, "comment", params.by ?? CLI_BY, decision);
|
||||
if ("refused" in g) throw new Error(g.refused);
|
||||
return g;
|
||||
};
|
||||
const io: GroupIo = {
|
||||
live: (n) => readLive(d.querier, repo, n),
|
||||
comment: (live, body, at) => commentOn(w, groupGrant, d.querier, "act-comment", { repo, number: at.number, id: live.id }, decisionNote(getDecision(db, at.decision)!), body, { decision: at.decision }),
|
||||
close: (live, at) => closeItem(w, groupGrant, d.querier, { repo, number: at.number, id: live.id, pr: live.type === "PullRequest" }, { decision: at.decision, head: live.head }),
|
||||
async begin(decision) {
|
||||
lane = null;
|
||||
const lr = await laneForDecision(db, d.lane, decision, [repo]);
|
||||
if (!lr) return null;
|
||||
if ("lane" in lr) { lane = lr.lane; setExecState(db, decision, "pending"); return null; }
|
||||
if ("transient" in lr) return lr.transient;
|
||||
setExecState(db, decision, lr.state, lr.reason);
|
||||
return lr.reason;
|
||||
},
|
||||
failed(decision, why) {
|
||||
const denied = lane ? authFailure(why) : null;
|
||||
if (denied) { setExecState(db, decision, denied, denied === "waiting-token" ? SIGN_IN_REASON : noWriteReason(repo)); return true; }
|
||||
if (lane) setExecState(db, decision, "failed", why);
|
||||
return false;
|
||||
},
|
||||
live: (n) => readLive(q(), repo, n),
|
||||
comment: (live, body, at) => commentOn(w, asAnswerer(at.decision), q(), "act-comment", { repo, number: at.number, id: live.id }, decisionNote(getDecision(db, at.decision)!), body, { decision: at.decision }),
|
||||
close: (live, at) => closeItem(w, asAnswerer(at.decision), q(), { repo, number: at.number, id: live.id, pr: live.type === "PullRequest" }, { decision: at.decision, head: live.head }),
|
||||
};
|
||||
const g = await actOnGroups(db, {
|
||||
repo, io, at, log, dryRun: false,
|
||||
@@ -317,6 +358,7 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st
|
||||
summary.skipped.push(...g.skipped);
|
||||
summary.failed.push(...g.failed);
|
||||
}
|
||||
markExecDone(db);
|
||||
log(`act ${repo}: ${summary.done.length} closed, ${summary.skipped.length} skipped, ${summary.failed.length} failed, ${summary.asked.length} asked`);
|
||||
return summary;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Runs one action card once through the existing write paths (src/github/write.ts, the decision answer,
|
||||
// the per-repo approvals) with the operator's login on every audit row. Cards never run on their own.
|
||||
import { guardRepo } from "../core/guard.ts";
|
||||
import { initExecState, laneForOperator, type LaneDeps } from "../github/user-lane.ts";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import { readLive } from "../act/index.ts";
|
||||
import { readLive, writeEffect } from "../act/index.ts";
|
||||
import { duplicateComment } from "../act/templates.ts";
|
||||
import { audit } from "../dash/audit.ts";
|
||||
import { optionsOf, BACKLOG, HANDLED, getDecision, reposOf, replaceProposedCards } from "../decisions.ts";
|
||||
@@ -26,7 +27,7 @@ export type CardRow = {
|
||||
};
|
||||
|
||||
/** `canWrite` is the signed-in operator's write access to a repo; the shell has none to check. */
|
||||
export type ActDeps = StoreDeps & { querier?: Querier; /** Runs `gh` for the open_issue step. */ exec?: Exec; canWrite?: (repo: string) => Promise<boolean>; /** Indexes into a resolution's steps the operator removed. */ skip?: number[]; /** The operator's note with the choice. */ note?: string };
|
||||
export type ActDeps = StoreDeps & { querier?: Querier; /** Runs `gh` for the open_issue step. */ exec?: Exec; canWrite?: (repo: string) => Promise<boolean>; /** Indexes into a resolution's steps the operator removed. */ skip?: number[]; /** The user lane's token source and transports; default: the secrets file's app. */ lane?: LaneDeps; /** The operator's note with the choice. */ note?: string };
|
||||
|
||||
export const cardOf = (db: DatabaseSync, id: number): CardRow | undefined =>
|
||||
db.prepare("SELECT * FROM conversation_cards WHERE id = ?").get(id) as CardRow | undefined;
|
||||
@@ -115,6 +116,7 @@ async function answerDecision(db: DatabaseSync, c: CardRow, decisionId: string |
|
||||
replaceProposedCards(db, d.repo, d.number);
|
||||
audit(db, by, "answer", d.id, { answer: key, source: "conversation" });
|
||||
db.exec("COMMIT");
|
||||
if (writeEffect(d.kind, key)) initExecState(db, d.id);
|
||||
return { result: `Answered the decision with "${o.label}"`, url: null };
|
||||
} catch (e) {
|
||||
db.exec("ROLLBACK");
|
||||
@@ -235,7 +237,8 @@ function actRoom(db: DatabaseSync): void {
|
||||
|
||||
/** The Act approval of `repo` for the operator's write, and room under the daily limit. */
|
||||
function actGrant(db: DatabaseSync, repo: string, by: string, need: "comment" | "labels" = "comment") {
|
||||
const g = guardRepo(db, repo, need, { operator: by });
|
||||
// The operator who presses the button acts as themselves (as `user:<login>` once the repo is on the app's identity).
|
||||
const g = guardRepo(db, repo, need, { operator: by }, undefined, by);
|
||||
if ("refused" in g) throw new Error(g.refused);
|
||||
actRoom(db);
|
||||
return g;
|
||||
@@ -465,12 +468,18 @@ export async function doCard(db: DatabaseSync, id: number, by: string, deps: Act
|
||||
noteIsSummary = true;
|
||||
}
|
||||
}
|
||||
// A card's GitHub writes are the pressing operator's own: on a repo with the app's identity they use that operator's token, and a card that cannot stays proposed.
|
||||
const repos = [c.repo, ...(params.kind === "resolution" ? params.steps.flatMap((x) => (x.kind === "transfer" ? [x.to] : x.kind === "open_issue" ? [x.repo] : [])) : [])];
|
||||
const writes = params.kind === "comment" || params.kind === "label" || params.kind === "close" || params.kind === "duplicate"
|
||||
|| (params.kind === "resolution" && params.steps.some((x) => x.kind !== "review" && x.kind !== "fixup"));
|
||||
const lr = writes ? await laneForOperator(db, deps.lane, by, repos) : null;
|
||||
if (lr && !("lane" in lr)) throw new ConversationError("transient" in lr ? 503 : 409, "transient" in lr ? `GitHub could not be reached to check your access: ${lr.transient}` : lr.reason);
|
||||
const at = (deps.now?.() ?? new Date()).toISOString();
|
||||
const claim = db.prepare("UPDATE conversation_cards SET state = 'running', acted_by = ?, acted_at = ? WHERE id = ? AND state = 'proposed'").run(by, at, id);
|
||||
if (claim.changes !== 1) return { card: c, ran: false };
|
||||
let out: Outcome | null = null, error: string | null = null, posted = false;
|
||||
try {
|
||||
out = await run(db, c, params, by, deps.querier ?? new Client(1000), at, deps.canWrite, noteIsSummary ? undefined : note, deps.exec);
|
||||
out = await run(db, c, params, by, lr ? lr.lane.querier : deps.querier ?? new Client(1000), at, deps.canWrite, noteIsSummary ? undefined : note, lr ? lr.lane.exec : deps.exec);
|
||||
} catch (e) {
|
||||
error = oneLine(String((e as Error).message ?? e));
|
||||
posted = e instanceof StepError && e.posted;
|
||||
|
||||
+5
-4
@@ -119,7 +119,7 @@ export async function guardBatchMerge(db: DatabaseSync, batch: Ref & { head: str
|
||||
}
|
||||
|
||||
/** Lets an issue or PR write of the item steps through while decideItem still has the action for the item. No GitHub read: the caller reads what it needs. */
|
||||
export async function guardItem(db: DatabaseSync, ref: Ref, action: ItemWant, by: By): Promise<GuardedItem | Refused> {
|
||||
export async function guardItem(db: DatabaseSync, ref: Ref, action: ItemWant, by: By, asDecision?: string): Promise<GuardedItem | Refused> {
|
||||
const name = `${ref.repo}#${ref.number}`;
|
||||
const f = loadItemFact(db, ref.repo, ref.number);
|
||||
if (!f) return { refused: `${name}: not an open item the pipeline tracks` };
|
||||
@@ -134,7 +134,7 @@ export async function guardItem(db: DatabaseSync, ref: Ref, action: ItemWant, by
|
||||
const now = plan.actions.map((x) => x.kind + (typeof x.params?.bucket === "string" ? `:${x.params.bucket}` : "")).join(", ") || "none";
|
||||
return { refused: `${name}: the plan no longer has ${action.kind}${action.bucket ? `:${action.bucket}` : ""} (state ${plan.state}, actions: ${now})` };
|
||||
}
|
||||
return { scope: "item", action, repo: ref.repo, number: ref.number, as: identityOfDecision(db, action.decisionId) } as unknown as GuardedItem;
|
||||
return { scope: "item", action, repo: ref.repo, number: ref.number, as: identityOfDecision(db, asDecision ?? action.decisionId) } as unknown as GuardedItem;
|
||||
}
|
||||
|
||||
/** The approvals of a repo and the global switch, read now. */
|
||||
@@ -147,7 +147,8 @@ export function repoApprovals(db: DatabaseSync, repo: string): Parameters<typeof
|
||||
}
|
||||
|
||||
/** Lets a repo-level write through (no item behind it): the repo approval it needs (null: none) and, for the pipeline's own writes, the global switch. */
|
||||
export function guardRepo(db: DatabaseSync, repo: string, need: Approval | null, by: By, decisionId?: string): GuardedRepo | Refused {
|
||||
export function guardRepo(db: DatabaseSync, repo: string, need: Approval | null, by: By, decisionId?: string, login?: string): GuardedRepo | Refused {
|
||||
const why = gateRepo(repoApprovals(db, repo), need, by, repo);
|
||||
return why ? { refused: `${repo}: ${why}` } : ({ scope: "repo", need, repo, as: identityOfDecision(db, decisionId) } as unknown as GuardedRepo);
|
||||
// `login`: the operator pressing the button right now (a conversation card), who acts as themselves with no answered decision yet.
|
||||
return why ? { refused: `${repo}: ${why}` } : ({ scope: "repo", need, repo, as: login ? `user:${login}` : identityOfDecision(db, decisionId) } as unknown as GuardedRepo);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { preparing } from "../../decide/prepared.ts";
|
||||
import { priorityOf } from "../../priority/read.ts";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import type {
|
||||
Claim, Classification, Decision, DecisionComment, DecisionKind, DecisionList, DuplicateMember, ItemState, Opinion, QueueSlot, RelatedItem, Relation,
|
||||
Claim, Classification, Decision, ExecState, DecisionComment, DecisionKind, DecisionList, DuplicateMember, ItemState, Opinion, QueueSlot, RelatedItem, Relation,
|
||||
} from "../../../web/src/api/types.ts";
|
||||
import { resetGroupAnswer } from "../../dupes/decide.ts";
|
||||
import { NOTE_MAX } from "../../conversations/types.ts";
|
||||
@@ -15,6 +15,7 @@ import { BACKLOG, HANDLED, SNOOZED_SQL, replaceProposedCards, WITHDRAWN_OPTION,
|
||||
import { commentPreview, writeEffect } from "../../act/index.ts";
|
||||
import { optionTextsOf, textsFor, textsHash } from "../../dupes/texts.ts";
|
||||
import { audit } from "../audit.ts";
|
||||
import { initExecState, retryDecision } from "../../github/user-lane.ts";
|
||||
import { randomToken } from "../server/crypto.ts";
|
||||
import { HttpError, type RateLimiter } from "../server/util.ts";
|
||||
import type { Req } from "../types.ts";
|
||||
@@ -224,6 +225,7 @@ export function toDecision(db: DatabaseSync, d: DecisionRow, viewer: Viewer): De
|
||||
answer: d.answer,
|
||||
answerNote: viewer.staff ? d.answer_note : null,
|
||||
answeredBy: d.answered_by, answeredAt: d.answered_at, appliedAt: d.applied_at,
|
||||
exec: d.answer && !d.applied_at && d.exec_state && d.exec_state !== "done" ? { state: d.exec_state as ExecState, reason: d.exec_reason ?? null } : null,
|
||||
adoptedOpinion: adopted ? toOpinion(adopted) : null,
|
||||
opinions,
|
||||
exceptions: exceptionsOf(d),
|
||||
@@ -427,6 +429,7 @@ export async function answer(db: DatabaseSync, req: Req, via?: "mcp"): Promise<D
|
||||
if (r.changes !== 1) throw new HttpError(409, "someone answered this a moment ago");
|
||||
replaceProposedCards(db, d.repo, d.number);
|
||||
});
|
||||
if (writeEffect(d.kind, ans)) initExecState(db, d.id);
|
||||
audit(db, req.user.login, "answer", d.id, { answer: ans, source: "dashboard", ...(via ? { via } : {}), exceptions: exceptions?.length ? exceptions : undefined, note: note ? true : undefined });
|
||||
// The thread keeps the choice (and the note) when the item has a conversation.
|
||||
if (d.repo && d.number !== null && conversationOf(db, d.repo, d.number)) {
|
||||
@@ -458,7 +461,7 @@ export async function undo(db: DatabaseSync, req: Req, via?: "mcp"): Promise<Dec
|
||||
if (d.applied_at && !directHandled(db, d)) throw new HttpError(409, "the pipeline already acted on this answer");
|
||||
inTransaction(db, () => {
|
||||
if (!canUndo(db, d)) throw new HttpError(409, "the pipeline already wrote to GitHub for this answer");
|
||||
const r = db.prepare(`UPDATE main.decisions SET answer = NULL, answer_note = NULL, exceptions = NULL, answered_by = NULL, answered_at = NULL, applied_at = NULL, adopted_opinion = NULL, snoozed_by = NULL, snoozed_at = NULL
|
||||
const r = db.prepare(`UPDATE main.decisions SET answer = NULL, answer_note = NULL, exceptions = NULL, answered_by = NULL, answered_at = NULL, applied_at = NULL, adopted_opinion = NULL, snoozed_by = NULL, snoozed_at = NULL, exec_state = NULL, exec_reason = NULL
|
||||
WHERE id = ? AND answer IS NOT NULL AND (applied_at IS NULL OR answer = '${HANDLED.key}')`).run(d.id);
|
||||
if (r.changes !== 1) throw new HttpError(409, "the pipeline acted on this a moment ago");
|
||||
resetGroupAnswer(db, d.id);
|
||||
@@ -467,6 +470,16 @@ export async function undo(db: DatabaseSync, req: Req, via?: "mcp"): Promise<Dec
|
||||
return toDecision(db, getDecision(db, d.id)!, await viewerWith(db, req));
|
||||
}
|
||||
|
||||
/** Operator: tries the GitHub write of a waiting or failed answer again. It is still made as the operator who answered. */
|
||||
export async function retry(db: DatabaseSync, req: Req): Promise<Decision> {
|
||||
const d = await needDecision(db, req, req.params.id!);
|
||||
await requireOperator(req, d);
|
||||
if (!d.answer || d.applied_at) throw new HttpError(409, "that decision has nothing waiting to run");
|
||||
if (!retryDecision(db, d.id)) throw new HttpError(409, "that decision is not waiting or failed");
|
||||
audit(db, req.user.login, "retry", d.id, { answer: d.answer });
|
||||
return toDecision(db, getDecision(db, d.id)!, await viewerWith(db, req));
|
||||
}
|
||||
|
||||
export async function reopen(db: DatabaseSync, req: Req): Promise<Decision> {
|
||||
const d = await needDecision(db, req, req.params.id!);
|
||||
await requireOperator(req, d);
|
||||
@@ -509,6 +522,7 @@ export async function adopt(db: DatabaseSync, req: Req): Promise<Decision> {
|
||||
WHERE id = ? AND answer IS NULL`).run(option, isBatch(d) ? "[]" : null, req.user.login, new Date().toISOString(), o.id, d.id);
|
||||
if (r.changes !== 1) throw new HttpError(409, "someone answered this a moment ago");
|
||||
});
|
||||
if (writeEffect(d.kind, option)) initExecState(db, d.id);
|
||||
audit(db, req.user.login, "adopt", d.id, { answer: o.option, opinion: o.id, of: o.login });
|
||||
return await settled(db, req, d.id);
|
||||
}
|
||||
|
||||
@@ -381,6 +381,7 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] {
|
||||
get("/api/decisions/:id/thread", dec.thread),
|
||||
post("/api/decisions/:id/answer", dec.answer),
|
||||
post("/api/decisions/:id/undo", dec.undo),
|
||||
post("/api/decisions/:id/retry", dec.retry),
|
||||
{ method: "POST", pattern: "/api/decisions/:id/snooze", operator: true, handler: ok(dec.snooze) },
|
||||
post("/api/decisions/:id/reopen", dec.reopen),
|
||||
{ method: "POST", pattern: "/api/decisions/backlog", operator: true, handler: ok(dec.backlogBulk) },
|
||||
|
||||
@@ -24,7 +24,14 @@ export const publicBase = (config: Config, req: IncomingMessage): string => conf
|
||||
export function githubAppRoutes(config: Config, deps: AppDeps): Route[] {
|
||||
return [{
|
||||
method: "GET", pattern: "/api/admin/github-app", operator: true,
|
||||
handler: async (db, r): Promise<Res> => ({ json: { ...(await githubAppStatus(db, config, deps)), csrf: r.csrf } }),
|
||||
handler: async (db, r): Promise<Res> => ({
|
||||
json: {
|
||||
...(await githubAppStatus(db, config, deps)),
|
||||
csrf: r.csrf,
|
||||
// Whether the signed-in operator has let the app act as them (their user token is stored and still good).
|
||||
authorized: config.secrets.app ? !!db.prepare("SELECT 1 FROM user_tokens WHERE login = ? AND status = 'ok'").get(r.user.login) : null,
|
||||
},
|
||||
}),
|
||||
}, {
|
||||
// Forgets the registered app's keys so another app can be registered; the operator deletes the app on GitHub.
|
||||
method: "POST", pattern: "/api/admin/github-app/remove", operator: true,
|
||||
@@ -61,9 +68,9 @@ export function githubAppRoutes(config: Config, deps: AppDeps): Route[] {
|
||||
}];
|
||||
}
|
||||
|
||||
export async function githubAppStatus(db: DatabaseSync, config: Config, deps: AppDeps): Promise<Omit<GithubAppStatus, "csrf">> {
|
||||
export async function githubAppStatus(db: DatabaseSync, config: Config, deps: AppDeps): Promise<Omit<GithubAppStatus, "csrf" | "authorized">> {
|
||||
const app = config.secrets.app;
|
||||
const status: Omit<GithubAppStatus, "csrf"> = {
|
||||
const status: Omit<GithubAppStatus, "csrf" | "authorized"> = {
|
||||
configured: !!app, loginMode: config.loginApp, canRegister: !!config.secretsFile,
|
||||
defaultName: envVar("GITHUB_APP_NAME") ?? DEFAULT_APP_NAME, app: null, installations: [], links: openLinks(db), error: null,
|
||||
};
|
||||
|
||||
@@ -20,13 +20,16 @@ import { auditLoginMode, finishRegistration, githubAppRoutes, startRegistration
|
||||
import { OrgSetup } from "./github-setup.ts";
|
||||
import { Vault } from "../../github/vault.ts";
|
||||
import { saveUserTokens } from "./user-tokens.ts";
|
||||
import { FakeProvider, oauthProviderFor, providerFor, type GithubUser, type Provider, type Tokens } from "./provider.ts";
|
||||
import { FakeProvider, GitHubProvider, oauthProviderFor, providerFor, type GithubUser, type Provider, type Tokens } from "./provider.ts";
|
||||
import { retryWaiting } from "../../github/user-lane.ts";
|
||||
import { createSession, deleteSession, loadSession, makeUser, pruneExpired, SESSION_TTL, userForLogin, type Session } from "./sessions.ts";
|
||||
import { answering, handleMcp, writes as mcpWrites, type Msg as McpMsg } from "../mcp/index.ts";
|
||||
import { loadToken, pruneTokens } from "../mcp/tokens.ts";
|
||||
import { esc, HttpError, parseCookies, plainPage, RateLimiter, safeReturnTo } from "./util.ts";
|
||||
|
||||
export const SESSION_COOKIE = "__Host-craft_session";
|
||||
/** `oauth_states.return_to` of an "act as you" authorization, which the shared sign-in callback tells apart from a sign-in by this prefix. */
|
||||
const AUTHORIZE_PREFIX = "authorize:";
|
||||
const STATE_COOKIE = "__Host-craft_oauth";
|
||||
const BODY_LIMIT = 64 * 1024;
|
||||
const FILE_TYPES: Record<string, string> = {
|
||||
@@ -145,7 +148,10 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
// The org setup link signs in with the OAuth App even when dashboard sign-in uses the GitHub App.
|
||||
const setupProvider = opts.provider ?? (config.devAuth ? provider : oauthProviderFor(config));
|
||||
const box = new TokenBox(config.secrets.sessionKey);
|
||||
const vault = new Vault(db, box, provider);
|
||||
// The GitHub App's own provider: it signs users in under login=github-app, and always makes and refreshes their user tokens (the "act as you" authorization).
|
||||
const appKeys = config.secrets.app;
|
||||
const appProvider: Provider | null = opts.provider ?? (config.devAuth ? provider : appKeys ? new GitHubProvider(appKeys.clientId, appKeys.clientSecret) : null);
|
||||
const vault = new Vault(db, box, appProvider ?? provider);
|
||||
const appDeps = { apiBase: opts.githubApi };
|
||||
const routes = compile([...opts.routes, ...githubAppRoutes(config, appDeps)]);
|
||||
auditLoginMode(db, config);
|
||||
@@ -321,6 +327,15 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
if (loadSession(db, cookies.get(SESSION_COOKIE))) return { r: { redirect: returnTo } };
|
||||
return startOAuth(returnTo, url.searchParams.get("select") === "1");
|
||||
}
|
||||
if (req.method === "GET" && path === "/auth/authorize-app") {
|
||||
if (!signinLimit.allow(ip)) return { r: errorPage(nonce, 429, "Too many attempts", "Wait a few minutes and try again.") };
|
||||
const returnTo = safeReturnTo(url.searchParams.get("return_to"));
|
||||
const s = loadSession(db, cookies.get(SESSION_COOKIE));
|
||||
if (!s) return { r: { redirect: `/auth/signin?${new URLSearchParams({ return_to: `/auth/authorize-app?${new URLSearchParams({ return_to: returnTo })}` })}` } };
|
||||
if (s.role !== "operator") return { r: errorPage(nonce, 403, "Not authorised", "Only operators authorize AutoCraft to act as them.") };
|
||||
if (!appProvider) return { r: errorPage(nonce, 409, "No GitHub App", "No GitHub App is registered, so there is nothing to authorize.") };
|
||||
return startOAuth(`${AUTHORIZE_PREFIX}${returnTo}`, false, undefined, appProvider);
|
||||
}
|
||||
if (req.method === "GET" && path === "/auth/callback") {
|
||||
if (!signinLimit.allow(ip)) return { r: errorPage(nonce, 429, "Too many attempts", "Wait a few minutes and try again.") };
|
||||
const clear = [cookie(STATE_COOKIE, "", 0)];
|
||||
@@ -337,7 +352,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
}
|
||||
let tokens: Tokens | null, who: GithubUser | null;
|
||||
try {
|
||||
const p = row.return_to?.startsWith("setup:") ? setupProvider : provider;
|
||||
const p = row.return_to?.startsWith("setup:") ? setupProvider : row.return_to?.startsWith(AUTHORIZE_PREFIX) ? (appProvider ?? provider) : provider;
|
||||
tokens = await p.exchange(code, row.verifier, callbackUrl);
|
||||
who = tokens ? await p.identity(tokens.access) : null;
|
||||
} catch (e) {
|
||||
@@ -351,6 +366,17 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
const out = await setup.signedIn(row.return_to, tokens, who, nonce, cookies);
|
||||
return { r: out.r, cookies: [...clear, ...(out.cookies ?? [])] };
|
||||
}
|
||||
if (row.return_to?.startsWith(AUTHORIZE_PREFIX)) {
|
||||
// "Act as you": only the user token is stored. The session and the sign-in are untouched.
|
||||
const s = loadSession(db, cookies.get(SESSION_COOKIE));
|
||||
if (!s || s.role !== "operator" || s.login.toLowerCase() !== who.login.toLowerCase() || checkGithubId(db, s.login, who.id) === "mismatch") {
|
||||
return { r: errorPage(nonce, 403, "Not authorised", "Sign in to the dashboard as the GitHub account you authorize, then try again."), cookies: clear };
|
||||
}
|
||||
saveUserTokens(db, box, s.login, who.id, tokens);
|
||||
retryWaiting(db, s.login);
|
||||
audit(db, s.login, "github-app-authorize", s.login, { ip });
|
||||
return { r: { redirect: safeReturnTo(row.return_to.slice(AUTHORIZE_PREFIX.length)) }, cookies: clear };
|
||||
}
|
||||
const login = who.login;
|
||||
const access = getAccess(db, login);
|
||||
if (!access) {
|
||||
@@ -362,7 +388,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
return { r: errorPage(nonce, 403, "Not authorised", `The GitHub account ${login} is not the account that was added to this dashboard's access list.`), cookies: clear };
|
||||
}
|
||||
const id = createSession(db, box, access.login, tokens, req.headers["user-agent"]);
|
||||
if (config.loginApp === "github-app") saveUserTokens(db, box, access.login, who.id, tokens);
|
||||
if (config.loginApp === "github-app") { saveUserTokens(db, box, access.login, who.id, tokens); retryWaiting(db, access.login); }
|
||||
audit(db, access.login, "sign-in", access.login, { ip });
|
||||
return {
|
||||
r: { redirect: safeReturnTo(row.return_to) },
|
||||
|
||||
@@ -55,6 +55,9 @@ const ADDED_COLUMNS: [table: string, column: string, type: string][] = [
|
||||
// What Opus had seen of the item when it proposed the card: JSON {head, last_comment}; null for cards stored before this.
|
||||
["conversation_cards", "seen", "TEXT"],
|
||||
["decisions", "snoozed_at", "TEXT"],
|
||||
// Where the GitHub write of an answer stands under repo_identity=app (src/github/user-lane.ts): pending | waiting-token | waiting-permission | done | failed; null before any attempt.
|
||||
["decisions", "exec_state", "TEXT"],
|
||||
["decisions", "exec_reason", "TEXT"],
|
||||
["classifications", "probs", "TEXT"],
|
||||
["token_usage", "cost_usd", "REAL"],
|
||||
["classifications", "input_hash", "TEXT"],
|
||||
|
||||
@@ -12,6 +12,7 @@ import { audit } from "./dash/audit.ts";
|
||||
import { actionable, getDecision } from "./decisions.ts";
|
||||
import { PLUGIN_LABEL } from "./labels/plan.ts";
|
||||
import { sameLabel } from "./labels/set.ts";
|
||||
import { markExecDone } from "./github/user-lane.ts";
|
||||
|
||||
const ACTOR = "pipeline";
|
||||
|
||||
@@ -43,6 +44,7 @@ export function applyUsedAnswers(db: DatabaseSync, at: string = new Date().toISO
|
||||
audit(db, ACTOR, "answer-used", a.id, { answer: a.answer });
|
||||
n++;
|
||||
}
|
||||
markExecDone(db);
|
||||
return n;
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ export type DecisionRow = {
|
||||
answered_by: string | null; answered_at: string | null; applied_at: string | null;
|
||||
prepared_at?: string | null; prepared_head?: string | null; prepare_failed_head?: string | null; recommend_failures?: number | null; recommend_failed_at?: string | null;
|
||||
summary: string | null; summary_by: string | null; summary_at: string | null; adopted_opinion: string | null; snoozed_by: string | null; snoozed_at: string | null;
|
||||
exec_state?: string | null; exec_reason?: string | null;
|
||||
};
|
||||
|
||||
const j = <T>(s: string | null, d: T): T => {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
// The user lane: a GitHub write that carries out an operator's answer is made as that operator, with the operator's
|
||||
// GitHub App user token (src/github/vault.ts), never as the box account or the app. Only repos whose `repo_identity`
|
||||
// is `app` use it; under `legacy` nothing here runs and the box account writes as before.
|
||||
//
|
||||
// A decision whose operator has no usable token, or no write access on the repo, does not fail: it waits
|
||||
// (`decisions.exec_state` waiting-token / waiting-permission, with a plain reason) and runs again after that operator
|
||||
// signs in or authorizes again, or when someone presses Retry.
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import { AppError, call, GITHUB_API } from "./app.ts";
|
||||
import { identityOfDecision, repoIdentity } from "./identity.ts";
|
||||
import { openVault, type Vault } from "./vault.ts";
|
||||
import { withIdentityEnv } from "./install-token.ts";
|
||||
import { exec as defaultExec, type Exec } from "../fixup/git.ts";
|
||||
import { Client, type Querier } from "../mirror.ts";
|
||||
import { slugOf } from "../owners.ts";
|
||||
|
||||
export type ExecState = "pending" | "waiting-token" | "waiting-permission" | "done" | "failed";
|
||||
export const WAITING: readonly ExecState[] = ["waiting-token", "waiting-permission"];
|
||||
|
||||
export const SIGN_IN_REASON = "Sign in to let AutoCraft finish this as you";
|
||||
export const noWriteReason = (repo: string): string => `You have no write access to ${slugOf(repo)}`;
|
||||
|
||||
/** Sets the state shown on the decision. Writes nothing when it is already that, so the planner is not woken for nothing. */
|
||||
export function setExecState(db: DatabaseSync, id: string, state: ExecState, reason: string | null = null): void {
|
||||
db.prepare("UPDATE main.decisions SET exec_state = ?, exec_reason = ? WHERE id = ? AND (exec_state IS NOT ? OR exec_reason IS NOT ?)").run(state, reason, id, state, reason);
|
||||
}
|
||||
|
||||
/** Decisions the pipeline applied are done. */
|
||||
export function markExecDone(db: DatabaseSync): void {
|
||||
db.prepare("UPDATE main.decisions SET exec_state = 'done', exec_reason = NULL WHERE applied_at IS NOT NULL AND exec_state IS NOT NULL AND exec_state <> 'done'").run();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a decision answered under an app repo to pending, or to waiting-token when its operator has no stored token set
|
||||
* (a database read only: the network checks happen when the write runs).
|
||||
*/
|
||||
export function initExecState(db: DatabaseSync, id: string): void {
|
||||
const d = db.prepare("SELECT repo, answered_by FROM main.decisions WHERE id = ? AND answer IS NOT NULL AND applied_at IS NULL").get(id) as { repo: string | null; answered_by: string | null } | undefined;
|
||||
if (!d?.repo || !d.answered_by || repoIdentity(db, d.repo) !== "app") return;
|
||||
const has = db.prepare("SELECT 1 FROM main.user_tokens WHERE login = ? AND status = 'ok'").get(d.answered_by);
|
||||
if (has) setExecState(db, id, "pending");
|
||||
else setExecState(db, id, "waiting-token", SIGN_IN_REASON);
|
||||
}
|
||||
|
||||
/** Puts the waiting (and, for one decision, failed) decisions back to pending so the stages take them up again. Returns how many changed. */
|
||||
export function retryWaiting(db: DatabaseSync, login?: string): number {
|
||||
const r = db.prepare(`UPDATE main.decisions SET exec_state = 'pending', exec_reason = NULL
|
||||
WHERE exec_state IN ('waiting-token', 'waiting-permission') AND applied_at IS NULL AND answer IS NOT NULL AND (? IS NULL OR answered_by = ? COLLATE NOCASE)`).run(login ?? null, login ?? null);
|
||||
return Number(r.changes);
|
||||
}
|
||||
|
||||
export function retryDecision(db: DatabaseSync, id: string): boolean {
|
||||
const r = db.prepare(`UPDATE main.decisions SET exec_state = 'pending', exec_reason = NULL
|
||||
WHERE id = ? AND exec_state IN ('waiting-token', 'waiting-permission', 'failed') AND applied_at IS NULL AND answer IS NOT NULL`).run(id);
|
||||
return Number(r.changes) > 0;
|
||||
}
|
||||
|
||||
// ---- the lane ----------------------------------------------------------------------
|
||||
|
||||
/** What a write made as a user needs: the user's name for the audit row, and the transports that carry the token. */
|
||||
export type Lane = {
|
||||
login: string;
|
||||
/** The whole environment of the child: the user's token as GH_TOKEN, and none of the box's own tokens. */
|
||||
env: Record<string, string>;
|
||||
querier: Querier;
|
||||
exec: Exec;
|
||||
};
|
||||
|
||||
export type Permission = "write" | "none" | "rejected";
|
||||
|
||||
export type LaneDeps = {
|
||||
vault: Pick<Vault, "userToken"> | null;
|
||||
/** The user's permission on the repo, read with the user's token. Throws when GitHub cannot answer. */
|
||||
permission?: (token: string, repo: string) => Promise<Permission>;
|
||||
/** Tests replace the transports. */
|
||||
transports?: (env: Record<string, string>) => { querier: Querier; exec: Exec };
|
||||
};
|
||||
|
||||
export type Waiting = { state: "waiting-token" | "waiting-permission"; reason: string };
|
||||
/** `transient`: GitHub or the token refresh could not answer now; nothing is recorded and the next run tries again. */
|
||||
export type LaneResult = { lane: Lane } | Waiting | { transient: string };
|
||||
|
||||
/** The repo's permission for the token, from GitHub's `permissions` field of the repository. */
|
||||
export async function githubPermission(token: string, repo: string, apiBase = GITHUB_API): Promise<Permission> {
|
||||
try {
|
||||
const r = (await call(apiBase, `/repos/${slugOf(repo)}`, token)) as { permissions?: { admin?: boolean; maintain?: boolean; push?: boolean } };
|
||||
const p = r.permissions;
|
||||
return p?.push || p?.maintain || p?.admin ? "write" : "none";
|
||||
} catch (e) {
|
||||
if (e instanceof AppError) {
|
||||
if (e.status === 401) return "rejected";
|
||||
if (e.status === 403 || e.status === 404) return "none";
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
const memo = new WeakMap<DatabaseSync, LaneDeps>();
|
||||
/** The vault of the secrets file (null without a registered app) and GitHub's own permission read. */
|
||||
export function defaultLaneDeps(db: DatabaseSync): LaneDeps {
|
||||
let d = memo.get(db);
|
||||
if (!d) {
|
||||
let vault: Vault | null = null;
|
||||
try { vault = openVault(db); } catch { /* no readable secrets: no token can be had */ }
|
||||
d = { vault };
|
||||
memo.set(db, d);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
export function laneOf(deps: LaneDeps, login: string, token: string): Lane {
|
||||
const env = withIdentityEnv({ kind: "app", token });
|
||||
const t = deps.transports?.(env);
|
||||
return {
|
||||
login, env,
|
||||
querier: t?.querier ?? new Client(1000, env),
|
||||
exec: t?.exec ?? ((cmd, args, opts) => defaultExec(cmd, args, { ...opts, env: { ...env, ...opts?.env }, replaceEnv: true })),
|
||||
};
|
||||
}
|
||||
|
||||
/** A usable token for the login and write access on every repo, or the reason it waits. */
|
||||
export async function resolveLane(deps: LaneDeps, login: string, repos: string[]): Promise<LaneResult> {
|
||||
if (!deps.vault) return { state: "waiting-token", reason: SIGN_IN_REASON };
|
||||
const permission = deps.permission ?? githubPermission;
|
||||
let t = await deps.vault.userToken(login);
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
if (!t.ok) return t.needsSignIn ? { state: "waiting-token", reason: SIGN_IN_REASON } : { transient: "the user token could not be refreshed now" };
|
||||
let rejected = false;
|
||||
for (const repo of repos) {
|
||||
let p: Permission;
|
||||
try {
|
||||
p = await permission(t.access, repo);
|
||||
} catch (e) {
|
||||
return { transient: String((e as Error).message ?? e).replace(/\s+/g, " ").slice(0, 200) };
|
||||
}
|
||||
if (p === "none") return { state: "waiting-permission", reason: noWriteReason(repo) };
|
||||
if (p === "rejected") { rejected = true; break; }
|
||||
}
|
||||
if (!rejected) return { lane: laneOf(deps, login, t.access) };
|
||||
// GitHub refused the access token as expired or revoked: one refresh, then the person has to sign in again.
|
||||
if (attempt > 0) return { state: "waiting-token", reason: SIGN_IN_REASON };
|
||||
t = await deps.vault.userToken(login, t.access);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lane for the operator who answered `decisionId`, or null when every repo is on the box account (`legacy`): the
|
||||
* caller then uses its own transports and nothing changes. Only the repos on `app` are checked.
|
||||
*/
|
||||
export async function laneForDecision(db: DatabaseSync, deps: LaneDeps | undefined, decisionId: string, repos: string[]): Promise<LaneResult | null> {
|
||||
const app = repos.filter((r) => repoIdentity(db, r) === "app");
|
||||
if (!app.length) return null;
|
||||
// A decision that waits stays put until its operator signs in or someone retries it: no network call per run.
|
||||
const row = db.prepare("SELECT exec_state, exec_reason FROM main.decisions WHERE id = ?").get(decisionId) as { exec_state: string | null; exec_reason: string | null } | undefined;
|
||||
if (row && (row.exec_state === "waiting-token" || row.exec_state === "waiting-permission")) return { state: row.exec_state, reason: row.exec_reason ?? SIGN_IN_REASON };
|
||||
const who = identityOfDecision(db, decisionId);
|
||||
if (who === "app") return { state: "waiting-token", reason: SIGN_IN_REASON };
|
||||
return resolveLane(deps ?? defaultLaneDeps(db), who.slice("user:".length), app);
|
||||
}
|
||||
|
||||
/** The lane for an operator acting right now (a conversation card), or null when every repo is on the box account. */
|
||||
export async function laneForOperator(db: DatabaseSync, deps: LaneDeps | undefined, login: string, repos: string[]): Promise<LaneResult | null> {
|
||||
const app = repos.filter((r) => repoIdentity(db, r) === "app");
|
||||
return app.length ? resolveLane(deps ?? defaultLaneDeps(db), login, app) : null;
|
||||
}
|
||||
|
||||
/** What GitHub says when the user's token may not do the write: 401, 403 or 404, or an integration without access. */
|
||||
export function authFailure(message: string): "waiting-token" | "waiting-permission" | null {
|
||||
if (/\b401\b|bad credentials/i.test(message)) return "waiting-token";
|
||||
if (/\b(403|404)\b|not accessible by integration|must have (admin|write)|resource not accessible|could not resolve to a repository/i.test(message)) return "waiting-permission";
|
||||
return null;
|
||||
}
|
||||
+5
-4
@@ -26,7 +26,7 @@ export { GITHUB_ACTIONS } from "./actions.ts";
|
||||
export type { Note } from "./note.ts";
|
||||
|
||||
/** Who writes (the audit login: the stage name, or the operator for manual actions) and where the row goes. */
|
||||
export type Writer = { db: DatabaseSync; login: string; /** Replaces the installation-token minter (tests). */ mint?: (owner: string, repo: string) => Promise<string> };
|
||||
export type Writer = { db: DatabaseSync; login: string; /** Replaces the installation-token minter (tests). */ mint?: (owner: string, repo: string) => Promise<string>; /** Replaces the app lane's GraphQL client (tests). */ appClient?: (env: Record<string, string>) => Pick<Querier, "query"> };
|
||||
type Details = Record<string, unknown>;
|
||||
type Retry = <T>(f: () => Promise<T>) => Promise<T>;
|
||||
|
||||
@@ -96,7 +96,7 @@ function laneGit(w: Writer, g: Guarded | Grant, git: Pick<Git, "git">): Pick<Git
|
||||
function laneQuery(w: Writer, g: Guarded | Grant, q: Querier): Querier {
|
||||
if (!inAppLane(w, g)) return q;
|
||||
return {
|
||||
query: async (query, variables) => new Client(0, await appEnv(w, g)).query(query, variables),
|
||||
query: async (query, variables) => (w.appClient ?? ((env) => new Client(0, env)))(await appEnv(w, g)).query(query, variables),
|
||||
get spent() { return q.spent; },
|
||||
get remaining() { return q.remaining; },
|
||||
};
|
||||
@@ -546,8 +546,9 @@ export const MERGE_RECORDED_ENV = "AUTOCRAFT_MERGE_RECORDED";
|
||||
* Runs the merge command for the guarded PR and records the merge or the refusal. The command gets
|
||||
* `OWNER/REPO PR --squash|--merge <extra> --head <guarded head>`, and must refuse when GitHub's head
|
||||
* differs from that head. Every merge command, the built-in safe-merge and any `$AUTOCRAFT_MERGE_CMD`, takes `--head` as part of this contract.
|
||||
* `env`, when given, is the command's whole environment (a user's token replaces the box's).
|
||||
*/
|
||||
export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string[], appEnv?: Record<string, string>) => Promise<CommandResult>, cmd: string, g: Guarded<"merge">, o: { method: "squash" | "merge"; extra?: string[] }, details: Details = {}, landed?: () => Promise<boolean>): Promise<CommandResult> {
|
||||
export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string[], env?: Record<string, string>) => Promise<CommandResult>, cmd: string, g: Guarded<"merge">, o: { method: "squash" | "merge"; extra?: string[] }, details: Details = {}, landed?: () => Promise<boolean>, env?: Record<string, string>): Promise<CommandResult> {
|
||||
const args = [`${slugOf(g.repo)}`, String(g.number), `--${o.method}`, ...(o.extra ?? []), "--head", g.head];
|
||||
const repo = g.repo;
|
||||
const method: string = o.method;
|
||||
@@ -559,7 +560,7 @@ export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string
|
||||
if (inAppLane(w, g)) {
|
||||
// The merge command runs with the installation token as its whole environment.
|
||||
try { r = await run(cmd, args, await appEnv(w, g)); } catch (e) { if (!String((e as Error).message).startsWith("app identity:")) throw e; r = failedResult(e); }
|
||||
} else r = await run(cmd, args);
|
||||
} else r = await run(cmd, args, env);
|
||||
} catch (e) {
|
||||
finish(w, id, base, oneLine(String((e as Error).message ?? e)));
|
||||
throw e;
|
||||
|
||||
+39
-4
@@ -11,6 +11,8 @@ import { plannedItems } from "../core/select-items.ts";
|
||||
import { ALL_LABELS, type LabelDef } from "./set.ts";
|
||||
import { jobItem } from "../runner/job-items.ts";
|
||||
import { ownerOf } from "../owners.ts";
|
||||
import { repoIdentity } from "../github/identity.ts";
|
||||
import { authFailure, laneForDecision, noWriteReason, setExecState, SIGN_IN_REASON, type LaneDeps } from "../github/user-lane.ts";
|
||||
|
||||
export const BATCH = 10; // mutations per request
|
||||
export const WRITES_PER_MIN = 60; // GitHub asks integrators to stay near this for content-creating writes
|
||||
@@ -65,7 +67,15 @@ export async function ensureLabels(client: Querier, repo: string, apply: boolean
|
||||
export type ApplyResult = { planned: number; labeled: number; failed: number[]; skipped: number; batches: number; dryRun: boolean };
|
||||
export type ApplyOpts = { runId: string; limit?: number; apply: boolean; login?: string; /** Who asked; default: an operator at the command line. */ by?: By; wait?: Wait; log?: (s: string) => void;
|
||||
/** Called with the running count of items labelled, after each batch. */
|
||||
onLabeled?: (labeled: number) => void };
|
||||
onLabeled?: (labeled: number) => void;
|
||||
/** The user lane's token source and transports; default: the secrets file's app. */
|
||||
lane?: LaneDeps };
|
||||
|
||||
/** The scope decision an operator answered "plugin" for this item: its answer is what adds the plugin candidate label, so its operator writes it. */
|
||||
export function pluginDecisionOf(db: DatabaseSync, repo: string, number: number): string | undefined {
|
||||
return (db.prepare(`SELECT id FROM main.decisions WHERE kind = 'scope' AND repo = ? AND number = ? AND answer = 'plugin' AND answered_by IN (SELECT login FROM main.access WHERE role = 'operator')
|
||||
ORDER BY answered_at DESC LIMIT 1`).get(repo, number) as { id: string } | undefined)?.id;
|
||||
}
|
||||
|
||||
/** An item the Plans give labels to, and the labels to add. */
|
||||
type Todo = { number: number; add: string[] };
|
||||
@@ -106,12 +116,37 @@ export async function applyLabels(db: DatabaseSync, client: Querier, repo: strin
|
||||
const idMap = new Map([...ids].map(([n, v]) => [n, v.id] as [number, string | null]));
|
||||
// Each item is guarded right before its labels are written: the Plan must still add them.
|
||||
const grants = new Map<number, GuardedItem>();
|
||||
// A label an operator's answer adds (plugin candidate) is written as that operator in a repo on the app's identity; the rest stay with the stage's own account.
|
||||
const asUser = new Map<number, string>();
|
||||
for (const r of writable) {
|
||||
const g = await guardItem(db, { repo, number: r.number }, { kind: "label" }, o.by ?? CLI_BY);
|
||||
if ("refused" in g) { log(`${repo}#${r.number}: not labelled: ${g.refused}`); res.skipped++; } else grants.set(r.number, g);
|
||||
const dec = repoIdentity(db, repo) === "app" ? pluginDecisionOf(db, repo, r.number) : undefined;
|
||||
const g = await guardItem(db, { repo, number: r.number }, { kind: "label" }, o.by ?? CLI_BY, dec);
|
||||
if ("refused" in g) { log(`${repo}#${r.number}: not labelled: ${g.refused}`); res.skipped++; } else { grants.set(r.number, g); if (dec) asUser.set(r.number, dec); }
|
||||
}
|
||||
const guarded = writable.filter((r) => grants.has(r.number));
|
||||
const done = guarded.length ? await mutate(w, client, repo, guarded, idMap, have, wait, o.runId, grants) : [];
|
||||
const done: number[] = [];
|
||||
const plain = guarded.filter((r) => !asUser.has(r.number));
|
||||
if (plain.length) done.push(...await mutate(w, client, repo, plain, idMap, have, wait, o.runId, grants));
|
||||
for (const r of guarded.filter((x) => asUser.has(x.number))) {
|
||||
const dec = asUser.get(r.number)!;
|
||||
const lr = await laneForDecision(db, o.lane, dec, [repo]);
|
||||
if (lr && !("lane" in lr)) {
|
||||
if (!("transient" in lr)) { setExecState(db, dec, lr.state, lr.reason); log(`${repo}#${r.number}: waiting: ${lr.reason}`); }
|
||||
res.skipped++;
|
||||
continue;
|
||||
}
|
||||
if (lr) setExecState(db, dec, "pending");
|
||||
try {
|
||||
done.push(...await addLabels(w, lr ? lr.lane.querier : client, repo,
|
||||
[{ number: r.number, id: idMap.get(r.number)!, labelIds: r.add.map((a) => have.labels.get(a.toLowerCase())!), names: r.add, g: grants.get(r.number)! }], (f) => retrying(f, wait), { run: o.runId }));
|
||||
} catch (e) {
|
||||
const why = String((e as Error).message ?? e).replace(/\s+/g, " ").slice(0, 300);
|
||||
const denied = lr ? authFailure(why) : null;
|
||||
if (denied) { setExecState(db, dec, denied, denied === "waiting-token" ? SIGN_IN_REASON : noWriteReason(repo)); res.skipped++; continue; }
|
||||
if (lr) setExecState(db, dec, "failed", why);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
for (const r of guarded) if (!done.includes(r.number)) res.failed.push(r.number);
|
||||
const ok = guarded.filter((r) => done.includes(r.number));
|
||||
if (ok.length) {
|
||||
|
||||
+30
-7
@@ -37,6 +37,7 @@ export { buildQueue, countStates, QUEUE_STATES, type QueueEntry, type QueueState
|
||||
import { envVar } from "../env.ts";
|
||||
import { effectiveCi, optionalChecks } from "../optional-checks.ts";
|
||||
import { jobItem } from "../runner/job-items.ts";
|
||||
import { authFailure, laneForDecision, markExecDone, noWriteReason, setExecState, SIGN_IN_REASON, type Lane, type LaneDeps } from "../github/user-lane.ts";
|
||||
import { ownerOf } from "../owners.ts";
|
||||
|
||||
/** Name of the built-in guarded merge (`autocraft safe-merge`); any other `$AUTOCRAFT_MERGE_CMD` is run as an external command that must accept `--head <sha>` and refuse when the PR head differs. */
|
||||
@@ -53,8 +54,10 @@ export type CommandResult = { code: number; stdout: string; stderr: string };
|
||||
export type MergeDeps = {
|
||||
querier: Querier;
|
||||
/** Runs the merge command; throws only when it can't be started. */
|
||||
run: (cmd: string, args: string[], appEnv?: Record<string, string>) => Promise<CommandResult>;
|
||||
run: (cmd: string, args: string[], env?: Record<string, string>) => Promise<CommandResult>;
|
||||
now: () => Date;
|
||||
/** The user lane's token source and transports; default: the secrets file's app. */
|
||||
lane?: LaneDeps;
|
||||
/** `$AUTOCRAFT_MERGE_CMD`, default the built-in `safe-merge`. */
|
||||
mergeCommand: string;
|
||||
};
|
||||
@@ -88,7 +91,7 @@ export type MergeSummary = {
|
||||
|
||||
export function spawnRun(cmd: string, args: string[], env?: Record<string, string>, replaceEnv = false): Promise<CommandResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const p = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], env: replaceEnv ? env : env ? { ...process.env, ...env } : process.env });
|
||||
const p = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], env: env ? (replaceEnv ? env : { ...process.env, ...env }) : process.env });
|
||||
let stdout = "", stderr = "";
|
||||
p.stdout.on("data", (d) => (stdout += d));
|
||||
p.stderr.on("data", (d) => (stderr += d));
|
||||
@@ -98,10 +101,9 @@ export function spawnRun(cmd: string, args: string[], env?: Record<string, strin
|
||||
}
|
||||
|
||||
/** Runs the merge command; the built-in name runs `autocraft safe-merge` from this checkout. */
|
||||
export function mergeRun(cmd: string, args: string[], appEnv?: Record<string, string>): Promise<CommandResult> {
|
||||
// `appEnv` is the app lane's whole child environment: the merge runs with the installation token only.
|
||||
if (appEnv) return cmd === DEFAULT_MERGE_COMMAND ? spawnRun(process.execPath, ["--no-warnings", CLI, "safe-merge", ...args], { ...appEnv, [MERGE_RECORDED_ENV]: "1" }, true) : spawnRun(cmd, args, appEnv, true);
|
||||
return cmd === DEFAULT_MERGE_COMMAND ? spawnRun(process.execPath, ["--no-warnings", CLI, "safe-merge", ...args], { [MERGE_RECORDED_ENV]: "1" }) : spawnRun(cmd, args);
|
||||
export function mergeRun(cmd: string, args: string[], env?: Record<string, string>): Promise<CommandResult> {
|
||||
// With `env` (a user's token set) the child gets exactly that environment: no box token is left in it.
|
||||
return cmd === DEFAULT_MERGE_COMMAND ? spawnRun(process.execPath, ["--no-warnings", CLI, "safe-merge", ...args], { ...env, [MERGE_RECORDED_ENV]: "1" }, !!env) : spawnRun(cmd, args, env, !!env);
|
||||
}
|
||||
|
||||
export function defaultDeps(): MergeDeps {
|
||||
@@ -315,6 +317,17 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line
|
||||
if (!mergeApprovalOf(db, repo)) { log(` merging in ${repo} is no longer approved; stopping`); break; }
|
||||
if (mergeHeld(db, repo, e.number)) { log(` ${refOf(e)}: merge held since the queue was read; skipped`); continue; }
|
||||
if (backlogHeld(db, repo, e.number) || duplicateHeld(db, repo, e.number)) { log(` ${refOf(e)}: held since the queue was read; skipped`); continue; }
|
||||
// An operator's Merge answer in a repo on the app's identity is carried out as that operator, with their token.
|
||||
let lane: Lane | null = null;
|
||||
if (e.path === "operator" && e.decisionId) {
|
||||
const lr = await laneForDecision(db, d.lane, e.decisionId, [repo]);
|
||||
if (lr && !("lane" in lr)) {
|
||||
if (!("transient" in lr)) setExecState(db, e.decisionId, lr.state, lr.reason);
|
||||
log(` ${refOf(e)}: ${"transient" in lr ? `not merged yet: ${lr.transient}` : `waiting: ${lr.reason}`}`);
|
||||
continue;
|
||||
}
|
||||
if (lr) { lane = lr.lane; setExecState(db, e.decisionId, "pending"); }
|
||||
}
|
||||
summary.attempted.push(refOf(e));
|
||||
seen = null;
|
||||
const [ch] = await refreshChecks(db, d.querier, repo, [e.number]);
|
||||
@@ -363,9 +376,18 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line
|
||||
log(` ${refOf(e)}: not merged: ${g.refused}`);
|
||||
continue;
|
||||
}
|
||||
const r = await mergeViaCommand(w, d.run, d.mergeCommand, g, { method, extra: allowFailedArgs(db, repo, d.mergeCommand) }, { run: runId, head: e.head, path: e.path });
|
||||
const r = await mergeViaCommand(w, d.run, d.mergeCommand, g, { method, extra: allowFailedArgs(db, repo, d.mergeCommand) }, { run: runId, head: e.head, path: e.path }, undefined, lane?.env);
|
||||
if (r.code !== 0) {
|
||||
const why = oneLine(r.stderr) || oneLine(r.stdout) || `exit code ${r.code}`;
|
||||
const denied = lane && e.decisionId ? authFailure(why) : null;
|
||||
if (denied) {
|
||||
// The user's token may not merge: wait for their access. No refusal is recorded, so the PR stays queued.
|
||||
setExecState(db, e.decisionId!, denied, denied === "waiting-token" ? SIGN_IN_REASON : noWriteReason(repo));
|
||||
log(` ${refOf(e)}: waiting: ${why}`);
|
||||
summary.attempted.pop();
|
||||
continue;
|
||||
}
|
||||
if (lane && e.decisionId) setExecState(db, e.decisionId, "failed", why);
|
||||
refuse(e, method, `${d.mergeCommand}: ${why}`);
|
||||
continue;
|
||||
}
|
||||
@@ -379,6 +401,7 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line
|
||||
params.onMerged?.(summary.merged.length);
|
||||
log(` ${refOf(e)}: merged (${method})`);
|
||||
}
|
||||
markExecDone(db);
|
||||
log(`merge ${repo}: ${summary.merged.length} merged, ${summary.refused.length} refused, ${summary.asked.length} asked; run ${runId}`);
|
||||
return summary;
|
||||
}
|
||||
|
||||
+2
-1
@@ -153,7 +153,8 @@ CREATE TABLE IF NOT EXISTS decisions (
|
||||
summary TEXT, summary_by TEXT, summary_at TEXT, -- AI summary of the item or batch, by which model, when
|
||||
adopted_opinion TEXT, -- decision_opinions.id when the answer adopted an opinion
|
||||
snoozed_by TEXT, -- operator who snoozed the open question
|
||||
snoozed_at TEXT -- the question is snoozed while the item has no activity after this (SNOOZED_SQL)
|
||||
snoozed_at TEXT, -- the question is snoozed while the item has no activity after this (SNOOZED_SQL)
|
||||
exec_state TEXT, exec_reason TEXT -- the answer's GitHub write: pending | waiting-token | waiting-permission | done | failed, and why it waits or failed
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS decisions_open ON decisions(answer, kind, repo);
|
||||
CREATE INDEX IF NOT EXISTS decisions_asked ON decisions(answer, asked_at);
|
||||
|
||||
@@ -31,7 +31,7 @@ test("the audit row records legacy until the repo is switched, then the grant's
|
||||
mkdirSync(SCRATCH, { recursive: true });
|
||||
const db = connect(join(SCRATCH, `identity-audit-${process.pid}.db`));
|
||||
db.prepare("INSERT OR IGNORE INTO tracked_repos (name) VALUES ('app')").run();
|
||||
const w = { db, login: "act" };
|
||||
const w = { db, login: "act", mint: async () => "ghs_test", appClient: () => q };
|
||||
const item = { repo: "app", number: 7, id: "I_1", pr: false };
|
||||
const last = () => JSON.parse((db.prepare("SELECT details FROM audit WHERE action = 'act-close' ORDER BY rowid DESC LIMIT 1").get() as { details: string }).details) as { identity: string };
|
||||
assert.equal(repoIdentity(db, "app"), "legacy");
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// The user lane: an answered close in a repo on the app's identity is written as the answering operator with their
|
||||
// token; without a token it waits and writes nothing. Under the default (legacy) setting nothing changes.
|
||||
import assert from "node:assert/strict";
|
||||
import { afterEach, test } from "node:test";
|
||||
import { runAct } from "../src/act/index.ts";
|
||||
import { setRepoIdentity } from "../src/github/identity.ts";
|
||||
import { retryWaiting, type LaneDeps } from "../src/github/user-lane.ts";
|
||||
import { OPERATOR, world, type World } from "./world-db.ts";
|
||||
|
||||
const quiet = () => {};
|
||||
let current: World | null = null;
|
||||
const fresh = (): World => (current = world().repo());
|
||||
afterEach(() => current?.close());
|
||||
|
||||
const askedAndAnswered = async (w: World) => {
|
||||
const asked = await runAct(w.db, { repo: "app", dryRun: false }, quiet, w.gh.actDeps());
|
||||
w.answerDecision(asked.asked[0]!, "close");
|
||||
return asked.asked[0]!;
|
||||
};
|
||||
const execOf = (w: World, id: string) => w.rows("SELECT exec_state AS s, exec_reason AS r FROM decisions WHERE id = ?", id)[0] as { s: string | null; r: string | null };
|
||||
|
||||
test("legacy repos close as before; an app repo without the operator's token waits and writes nothing, then closes as the operator after a sign-in", async () => {
|
||||
// legacy: the box transports close it and no state is recorded
|
||||
const a = fresh().pr(1).review(1, { verdict: "close", reason: "Does not match the reference app" });
|
||||
const idA = await askedAndAnswered(a);
|
||||
assert.deepEqual((await runAct(a.db, { repo: "app", dryRun: false }, quiet, a.gh.actDeps())).done, ["app#1"]);
|
||||
assert.deepEqual(a.gh.writes.map((x) => x.kind), ["comment", "close"]);
|
||||
assert.deepEqual(execOf(a, idA), { s: null, r: null });
|
||||
a.close();
|
||||
|
||||
// app: no token for the answering operator
|
||||
const w = fresh().pr(1).review(1, { verdict: "close", reason: "Does not match the reference app" });
|
||||
setRepoIdentity(w.db, "op", "app", "app");
|
||||
const id = await askedAndAnswered(w);
|
||||
const userQuerier = { query: async (_q: string, _v?: object): Promise<Record<string, unknown>> => ({}), spent: 0, remaining: null as number | null };
|
||||
let token: string | null = null;
|
||||
const lane: LaneDeps = {
|
||||
vault: { userToken: async () => (token ? { ok: true, access: token } : { ok: false, needsSignIn: true, why: "no-token" }) },
|
||||
permission: async () => "write",
|
||||
transports: () => ({ querier: userQuerier, exec: async () => ({ code: 0, stdout: "", stderr: "" }) }),
|
||||
};
|
||||
const deps = { ...w.gh.actDeps(), lane };
|
||||
const waiting = await runAct(w.db, { repo: "app", dryRun: false }, quiet, deps);
|
||||
assert.deepEqual(waiting.done, []);
|
||||
assert.equal(w.gh.writes.length, 0, "the box account writes nothing in a repo on the app's identity");
|
||||
assert.deepEqual(execOf(w, id), { s: "waiting-token", r: "Sign in to let AutoCraft finish this as you" });
|
||||
|
||||
// The operator authorizes: the decision is pending again and the next run uses their lane (its own querier, not the box's).
|
||||
token = "user-token";
|
||||
assert.equal(retryWaiting(w.db, OPERATOR), 1);
|
||||
assert.deepEqual(execOf(w, id), { s: "pending", r: null });
|
||||
const queries: string[] = [];
|
||||
userQuerier.query = async (q: string) => { queries.push(q.includes("closeIssue") || q.includes("closePullRequest") ? "close" : q.includes("addComment") ? "comment" : "read"); return q.includes("issueOrPullRequest") ? { repository: { issueOrPullRequest: { __typename: "PullRequest", id: "PR_1", state: "OPEN", headRefOid: (w.rows("SELECT head_oid FROM items WHERE number = 1")[0] as { head_oid: string }).head_oid } } } : {}; };
|
||||
await runAct(w.db, { repo: "app", dryRun: false }, quiet, deps);
|
||||
assert.equal(w.gh.writes.length, 0, "still nothing through the box's transports");
|
||||
assert.ok(queries.includes("comment") && queries.includes("close"), `the user's transports made the writes: ${queries.join(",")}`);
|
||||
const row = w.rows("SELECT details FROM audit WHERE action = 'act-close'")[0] as { details: string };
|
||||
assert.equal((JSON.parse(row.details) as { identity: string }).identity, `user:${OPERATOR}`);
|
||||
});
|
||||
@@ -108,6 +108,8 @@ export interface Api {
|
||||
forItem(repo: RepoName, number: number, kind?: DecisionKind): Promise<Decision | null>;
|
||||
answer(id: string, input: AnswerInput): Promise<Decision>;
|
||||
undo(id: string): Promise<Decision>;
|
||||
/** Operator: runs the GitHub write of a waiting or failed answer again. */
|
||||
retry(id: string): Promise<Decision>;
|
||||
/** Operator: clear a Backlog answer so the decision is open again. */
|
||||
reopen(id: string): Promise<Decision>;
|
||||
/** Operator: snooze (`on`) or wake an open decision. */
|
||||
|
||||
@@ -115,6 +115,7 @@ export function createHttpApi(): Api {
|
||||
forItem: (repo, number, kind) => get(`/api/items/${encodeURIComponent(repo)}/${encodeURIComponent(String(number))}/decision${qs({ kind })}`),
|
||||
answer: (id, input) => post(dec(id, "/answer"), input),
|
||||
undo: (id) => post(dec(id, "/undo")),
|
||||
retry: (id) => post(dec(id, "/retry")),
|
||||
snooze: (id, on) => post(dec(id, "/snooze"), { on }),
|
||||
reopen: (id) => post(dec(id, "/reopen")),
|
||||
feedback: (id, input) => post(dec(id, "/feedback"), input),
|
||||
|
||||
@@ -180,7 +180,7 @@ export function createAdminMock(me: User, changed: () => void): AdminApi {
|
||||
const appStatus = (): GithubAppStatus => {
|
||||
const registered = !appRemoved && (typeof location === "undefined" || !location.search.includes("unregistered"));
|
||||
return {
|
||||
configured: registered, loginMode: "oauth", canRegister: true, defaultName: "AutoCraft", csrf: "mock",
|
||||
configured: registered, loginMode: "oauth", canRegister: true, defaultName: "AutoCraft", csrf: "mock", authorized: registered ? false : null,
|
||||
app: registered ? { id: "1234567", slug: "autocraft-demo", name: "AutoCraft", installUrl: "https://github.com/apps/autocraft-demo/installations/new", transferUrl: "https://github.com/settings/apps/autocraft-demo/advanced" } : null,
|
||||
links: [...setupLinks],
|
||||
installations: registered ? [
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
DecisionKind,
|
||||
Preapproval,
|
||||
DecisionOption,
|
||||
ExecState,
|
||||
Item,
|
||||
Progress,
|
||||
RelatedItem,
|
||||
@@ -157,6 +158,8 @@ interface Seed {
|
||||
answer?: [string, string, number, boolean, string?, number?]; // answer, by, hoursAgo, applied, note, index of the adopted opinion
|
||||
opinions?: [string, string | null, string | null, number][]; // login, option, note, minutes ago
|
||||
docket?: string;
|
||||
/** An answer whose GitHub write has not run: where it stands and why. */
|
||||
exec?: [ExecState, string | null];
|
||||
}
|
||||
|
||||
const SEEDS: Seed[] = [
|
||||
@@ -549,6 +552,59 @@ const SEEDS: Seed[] = [
|
||||
size: [344, 61, 5],
|
||||
cls: [["haiku", "missing feature", "yes"], ["jev", "missing feature", "yes"]],
|
||||
},
|
||||
// answered, the GitHub write waits or failed
|
||||
{
|
||||
kind: "close",
|
||||
repo: "texturecraft",
|
||||
number: 230,
|
||||
title: "Replace the brush engine with a shader pipeline",
|
||||
question: "Close this PR?",
|
||||
context: [],
|
||||
facts: ["+3,120 −2,004 · 22 files", "author: 0 merged"],
|
||||
options: [
|
||||
{ key: "close", label: "Close with note" },
|
||||
{ key: "hold", label: "Hold" },
|
||||
{ key: "keep", label: "Keep open" },
|
||||
],
|
||||
recommended: "close",
|
||||
publicText: "Thanks for the work here. A replacement of the whole brush engine is more than we can review as one PR.",
|
||||
ageH: 5,
|
||||
author: "gridlock-9",
|
||||
answer: ["close", "ochre-fox", 1, false],
|
||||
exec: ["waiting-token", "Sign in to let AutoCraft finish this as you"],
|
||||
},
|
||||
{
|
||||
kind: "merge",
|
||||
repo: "filmcraft",
|
||||
number: 3362,
|
||||
title: "Show the frame counter while scrubbing",
|
||||
question: "Merge now?",
|
||||
context: [],
|
||||
facts: ["+64 −9 · 3 files", "CI passing · mergeable"],
|
||||
options: [
|
||||
{ key: "merge", label: "Merge" },
|
||||
{ key: "hold", label: "Hold" },
|
||||
],
|
||||
recommended: "merge",
|
||||
ageH: 8,
|
||||
author: "larkspur-dev",
|
||||
answer: ["merge", "kiri-n", 2, false],
|
||||
exec: ["waiting-permission", "You have no write access to storytold/filmcraft"],
|
||||
},
|
||||
{
|
||||
kind: "scope",
|
||||
repo: "designcraft",
|
||||
number: 2251,
|
||||
title: "Export artboards as animated SVG",
|
||||
question: "Is animated SVG export in scope?",
|
||||
context: [],
|
||||
facts: ["+410 −12 · 6 files"],
|
||||
...spread(scopeOpts("close")),
|
||||
ageH: 12,
|
||||
author: "kiln-and-reed",
|
||||
answer: ["close", "ochre-fox", 3, false],
|
||||
exec: ["failed", "GitHub answered 502 while closing the item"],
|
||||
},
|
||||
// answered
|
||||
{
|
||||
kind: "scope",
|
||||
@@ -771,6 +827,7 @@ function toDecision(s: Seed): Decision {
|
||||
answeredBy: s.answer?.[1] ?? null,
|
||||
answeredAt: s.answer ? iso(s.answer[2] * H) : null,
|
||||
appliedAt: s.answer?.[3] ? iso(s.answer[2] * H - 20 * M) : null,
|
||||
exec: s.exec ? { state: s.exec[0], reason: s.exec[1] } : null,
|
||||
opinions,
|
||||
adoptedOpinion: s.answer?.[5] !== undefined ? opinions[s.answer[5]] : null,
|
||||
exceptions: [],
|
||||
|
||||
@@ -96,7 +96,7 @@ export function createMockApi(): Api {
|
||||
};
|
||||
|
||||
const settle = (d: Decision, answer: string, note: string | null, adoptedOpinion: Decision["adoptedOpinion"], exceptions: Decision["exceptions"] = []) =>
|
||||
Object.assign(d, { answer, answerNote: note, exceptions, answeredBy: me.login, answeredAt: nowIso(), adoptedOpinion, claim: null, undoable: true });
|
||||
Object.assign(d, { answer, answerNote: note, exceptions, answeredBy: me.login, answeredAt: nowIso(), adoptedOpinion, claim: null, undoable: true, exec: null });
|
||||
|
||||
return {
|
||||
me: () => wait(me, 10),
|
||||
@@ -125,6 +125,13 @@ export function createMockApi(): Api {
|
||||
changed();
|
||||
return wait(d, 30);
|
||||
},
|
||||
async retry(id) {
|
||||
const d = find(id);
|
||||
requireOperator(d);
|
||||
if (d.exec) Object.assign(d, { exec: { state: "pending", reason: null } });
|
||||
changed();
|
||||
return wait(d, 30);
|
||||
},
|
||||
async undo(id) {
|
||||
const d = find(id);
|
||||
requireOperator(d);
|
||||
|
||||
@@ -94,6 +94,8 @@ export interface DuplicateMember {
|
||||
adds: string[];
|
||||
}
|
||||
|
||||
export type ExecState = "pending" | "waiting-token" | "waiting-permission" | "done" | "failed";
|
||||
|
||||
export interface Decision {
|
||||
id: string;
|
||||
kind: DecisionKind;
|
||||
@@ -138,6 +140,8 @@ export interface Decision {
|
||||
answeredBy: string | null;
|
||||
answeredAt: string | null;
|
||||
appliedAt: string | null;
|
||||
/** The GitHub write of the answer while it is not done (repos on the app's identity only): waiting for the answering operator's sign-in or access, failed, or pending. null otherwise. */
|
||||
exec: { state: ExecState; reason: string | null } | null;
|
||||
/** The opinion the operator adopted as the answer, if any. */
|
||||
adoptedOpinion: Opinion | null;
|
||||
opinions: Opinion[];
|
||||
@@ -859,6 +863,8 @@ export interface GithubAppStatus {
|
||||
defaultName: string;
|
||||
/** The session's CSRF token, for the registration form. */
|
||||
csrf: string;
|
||||
/** The signed-in operator has let the app act as them; null when no app is registered. */
|
||||
authorized: boolean | null;
|
||||
app: { id: string; slug: string; name: string | null; installUrl: string; transferUrl: string } | null;
|
||||
/** Each account the app is installed on, with the repos it covers. */
|
||||
installations: { owner: string; selection: "all" | "selected"; repos: string[] }[];
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Block } from "../../ui/molecules/Block";
|
||||
import { ConfirmButton } from "../../ui/molecules/ConfirmButton";
|
||||
import { Facts } from "../../ui/molecules/Facts";
|
||||
import { Page } from "../../ui/organisms/Page";
|
||||
import { authorizeHref } from "../decisions/ExecLine";
|
||||
|
||||
const LOGIN_MODE = { oauth: "OAuth App", "github-app": "GitHub App" } as const;
|
||||
|
||||
@@ -60,9 +61,13 @@ function AppBlock({ s, onChange }: { s: GithubAppStatus; onChange: () => void })
|
||||
["Slug", <code key="slug">{s.app.slug}</code>],
|
||||
["App id", <code key="id">{s.app.id}</code>],
|
||||
["Sign-in", LOGIN_MODE[s.loginMode]],
|
||||
["Acts as you", s.authorized ? "Authorized" : "Not authorized"],
|
||||
]}
|
||||
/>
|
||||
<div className="mt-3 flex flex-wrap gap-x-5 gap-y-2 text-sm">
|
||||
<a href={authorizeHref()} className="text-accent-ink hover:underline">
|
||||
{s.authorized ? "Authorize again" : "Authorize AutoCraft to act as you"}
|
||||
</a>
|
||||
<TextLink href={s.app.installUrl}>Install</TextLink>
|
||||
<TextLink href={s.app.transferUrl}>Transfer</TextLink>
|
||||
<ConfirmButton className="ml-auto" label="Remove" confirmLabel="Remove app" loading={busy} onConfirm={() => void remove()} />
|
||||
|
||||
@@ -16,6 +16,7 @@ import { } from "../../lib/format";
|
||||
import { TimeAgo } from "../../ui/atoms/TimeAgo";
|
||||
import { ClaimPill, ClassifierLines, Disclosure, Facts, KindTag, RelatedList } from "./parts";
|
||||
import { Refs } from "./Refs";
|
||||
import { ExecLine } from "./ExecLine";
|
||||
import { AnswerNotice } from "./AnswerNotice";
|
||||
import { DuplicateGroup, RiskList } from "./Group";
|
||||
import { localActions, ordered, refOf, useDecisionFilter, useDecisionList, useLocal, usePinned, useSelection, useUndo, type AnswerEntry } from "./state";
|
||||
@@ -348,6 +349,7 @@ export function AnsweredState({ d, canUndo }: { d: Decision; canUndo: boolean })
|
||||
{d.adoptedOpinion ? `, using ${d.adoptedOpinion.login}'s answer` : ""} · <TimeAgo iso={d.answeredAt!} />{closed ? "" : ` · ${d.appliedAt ? "applied" : "not applied yet"}`}
|
||||
</span>
|
||||
{d.answerNote && <span className="w-full text-sm text-ink/70">“{d.answerNote}”</span>}
|
||||
<ExecLine d={d} canRetry={canUndo} />
|
||||
{backlog && canUndo && (
|
||||
<span className="ml-auto flex items-center gap-2">
|
||||
{write.error && <span className="text-xs text-bad">{write.error}</span>}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { ArrowClockwiseIcon, HourglassIcon, KeyIcon, WarningCircleIcon } from "@phosphor-icons/react";
|
||||
import { useApi } from "../../api/client";
|
||||
import type { Decision } from "../../api/types";
|
||||
import { Button } from "../../ui/atoms/Button";
|
||||
import { cn } from "../../ui/cn";
|
||||
import { useWrite } from "../../lib/hooks";
|
||||
import { useUser } from "../../shell/UserContext";
|
||||
|
||||
/** Starts the GitHub App user authorization for the signed-in operator and returns to this page. The session is not touched. */
|
||||
export const authorizeHref = (): string => `/auth/authorize-app?${new URLSearchParams({ return_to: window.location.pathname + window.location.search })}`;
|
||||
|
||||
const TONE = { pending: "text-ink/55", "waiting-token": "text-warn", "waiting-permission": "text-warn", failed: "text-bad", done: "text-ink/55" } as const;
|
||||
|
||||
/**
|
||||
* Where the GitHub write of an answer stands while it is not done: why it waits, with the actions that unblock it.
|
||||
* Shown under the answer on the decision and the item, and under the row in the answered list.
|
||||
*/
|
||||
export function ExecLine({ d, canRetry, compact }: { d: Decision; canRetry: boolean; compact?: boolean }) {
|
||||
const api = useApi();
|
||||
const write = useWrite();
|
||||
const operator = useUser().role === "operator";
|
||||
const exec = d.exec;
|
||||
if (!exec || exec.state === "done") return null;
|
||||
const Icon = exec.state === "pending" ? HourglassIcon : WarningCircleIcon;
|
||||
const text = exec.reason ?? "Waiting to run";
|
||||
return (
|
||||
<div className={cn("flex flex-wrap items-center gap-x-3 gap-y-1", compact ? "mt-1 text-xs" : "w-full text-sm", TONE[exec.state])} onClick={(e) => e.stopPropagation()}>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<Icon className="shrink-0" />
|
||||
<span>{text}</span>
|
||||
</span>
|
||||
{operator && exec.state === "waiting-token" && (
|
||||
<a href={authorizeHref()} className="inline-flex items-center gap-1 text-accent-ink hover:underline">
|
||||
<KeyIcon />
|
||||
Authorize AutoCraft to act as you
|
||||
</a>
|
||||
)}
|
||||
{canRetry && exec.state !== "pending" && (
|
||||
<Button size="sm" variant="ghost" icon={ArrowClockwiseIcon} loading={write.busy === "retry"} onClick={() => void write.run("retry", () => api.decisions.retry(d.id))}>
|
||||
Retry
|
||||
</Button>
|
||||
)}
|
||||
{write.error && <span className="text-bad">{write.error}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { ItemRef } from "../../ui/molecules/ItemRef";
|
||||
import { ClaimPill, KIND_ICON } from "./parts";
|
||||
import { canActOn } from "./DecisionDetail";
|
||||
import { AnswerNotice } from "./AnswerNotice";
|
||||
import { ExecLine } from "./ExecLine";
|
||||
import { KIND_LABEL, KINDS, localActions, ordered, useDecisionFilter, useDecisionList, useLocal, useSelection, useUndo } from "./state";
|
||||
import { useNow } from "../../lib/useNow";
|
||||
import { itemPath } from "../../lib/links";
|
||||
@@ -164,6 +165,7 @@ function Row({ d, canUndo, active, checked, mine, onOpen, activeRef }: { d: Deci
|
||||
{d.answer && d.undoable && canUndo && <RowUndo id={d.id} />}
|
||||
</span>
|
||||
</div>
|
||||
<ExecLine d={d} canRetry={canUndo} compact />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user