diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 187d1e9b..03d8b47f 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -14690,6 +14690,19 @@ describe("the stand-up (BB-300)", () => { return { ...t, project, steward }; } + /** A bound ticket with one linked, gate-met pull request and its approve-pr need (BB-309). */ + async function adoptedWithPull() { + const t = await setup(); + const head = "aaaaaaa1"; + const marker = comment({ id: "m1", author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); + t.entities.set("uuid-12", issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + await t.flush(); + const [project, steward] = t.spawns.map((x) => x.id) as [string, string]; + return { ...t, project, steward }; + } + it("reports a stand-up as available on the board when the voice plugin is ready", async () => { const t = await adopted(); const board = (await t.harness.callRpc("stewardsBoard", { projectId: "p1" })) as { board: { standup?: { available: boolean; message: string | null } } }; @@ -14792,6 +14805,34 @@ describe("the stand-up (BB-300)", () => { expect(retracted).toContain("No note"); }); + it("resolves a pull request key to the ticket binding that holds its gate need (BB-309)", async () => { + const t = await adoptedWithPull(); + const b = t.hooks.store.find("ENG-12")!; + const need = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "approve-pr"); + expect(need, "the ticket should hold an approve-pr need").toBeDefined(); + const started = (await t.harness.callRpc("stewardsStandupStart", { projectId: "p1" }, client)) as { sessionId: string; standupId: string }; + // steward_status by the pull key the brief shows resolves to the ticket. + const status = (await t.harness.callRpc("stewardsStandupTool", { sessionId: started.sessionId, name: "steward_status", arguments: JSON.stringify({ key: "acme/web#7" }) }, voice)) as string; + expect(status).toContain("ENG-12"); + expect(status).not.toContain("No steward"); + // entity_snapshot by the pull URL renders the pull's own snapshot. + const entity = (await t.harness.callRpc("stewardsStandupTool", { sessionId: started.sessionId, name: "entity_snapshot", arguments: JSON.stringify({ key: "https://github.com/acme/web/pull/7" }) }, voice)) as string; + expect(entity).toContain("Add login retry"); + expect(entity).not.toContain("No steward"); + // take_note by the pull key binds to the open need, recording the resolved + // ticket key so the confirmation path's `store.find` finds it later. + await t.harness.callRpc("stewardsStandupTool", { sessionId: started.sessionId, name: "take_note", arguments: JSON.stringify({ type: "gate", text: "Looks good", binding: "acme/web#7", action: "approve" }) }, voice); + const note = t.hooks.store.standup(started.standupId)!.notes[0]!; + expect(note).toMatchObject({ binding: "ENG-12", need: need!.id }); + // Confirming applies it through the need-action path, exactly as the page does. + const confirmed = await t.harness.callRpc("stewardsStandupConfirm", { standupId: started.standupId, noteId: note.id }, client); + expect(confirmed).toMatchObject({ ok: true, applied: true }); + expect(t.hooks.store.need(need!.id)!.status).toBe("done"); + // A pull key with no open gate item still answers "No steward". + const unknown = (await t.harness.callRpc("stewardsStandupTool", { sessionId: started.sessionId, name: "steward_status", arguments: JSON.stringify({ key: "acme/web#999" }) }, voice)) as string; + expect(unknown).toContain("No steward for acme/web#999"); + }); + it("scrubs a pasted credential from a tool result before it reaches the model", async () => { const t = await adopted(); // A ticket body can carry a pasted token; it must not reach OpenAI. @@ -15384,6 +15425,8 @@ describe("the stand-up (BB-300)", () => { const prompt = String(delegate.prompt); expect(prompt).toContain("Read only"); expect(prompt).toContain("one-line verdict first"); + // BB-309: the answer is spoken, so the standing instructions ask for plain prose. + expect(prompt).toContain("Write plain prose only"); expect(prompt).toContain("Are the bb-server builds still stalling?"); expect(prompt).toContain("ENG-12"); await t.idle(delegate.id, "Yes, the builds are still stalling."); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 2839540f..9b6157fb 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -94,7 +94,7 @@ import { MULTI_REPO_ENVIRONMENT_PROVIDER_ID, MULTI_REPO_PLUGIN_ID, multiRepoEnvi import { KUBECTL_VERBS, createKubectlReader, kubectlRefusal, type KubectlResult, type OpsAccess, type OpsReader } from "./kubectl.js"; import { HOOKS_URL_ENV, createHooksLoop, type Lease, type Rejection } from "./hooks-client.js"; import { createBriefing, nightlyDue, stillNight, toDigestRecords } from "./nightly.js"; -import { STANDUP_TOOLS, buildStandupInstructions, readbackLine, runStandupTool, STANDUP_DELEGATE_ANSWER_MAX_CHARS, type StandupAskOutcome, type StandupDelegation, type StandupEndOutcome, type StandupNote, type StandupNoteType, type StandupRecord, type StandupToolReply } from "./standup.js"; +import { STANDUP_TOOLS, buildStandupInstructions, readbackLine, runStandupTool, samePullRef, STANDUP_DELEGATE_ANSWER_MAX_CHARS, type StandupAskOutcome, type StandupDelegation, type StandupEndOutcome, type StandupNote, type StandupNoteType, type StandupRecord, type StandupToolReply } from "./standup.js"; import { classify, hasFingerprintLine, lookChanges, opsTargetKey, parseOpsTargetKey, redactLine, scrubCredentials, ticketResolved, type DependabotTarget, type FingerprintRow, type K8sTarget, type OpsLook, type OpsTarget, type SentryTarget, type Sighting, type TicketState } from "./ops.js"; import { EVENTS_PER_LOOK, NO_TOKEN, RECENT_PER_LOOK, SENTRY_API_URL, TOKEN_SCOPES, createSentryReader, emptySentryLook, issueInOrg, recentLine, sentryChanges, sentryResolveTargets, sentrySightings, sentrySummary, type SentryFinding, type SentryLook, type SentryReader } from "./sentry.js"; import { advanced, answerDiffers, anyWorkerInFlight, asksForOpenApproval, commentDiffersFromRecommendation, compactDue, deploymentSettled, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, hasLabel, IDLE_WAKE_TEXT, idleInActiveStage, isCommentNews, isOwnStageChange, lifecycle, mechanicalStatus, namesUserAsBlocker, newHumanComments, newestCommentAt, openUserFacingItems, ownChecksFinished, ownPullClosed, ownPullMerged, phaseAndStage, productGateOptions, runningWorkerReason, newestEditComment, specDiff, specHash, specText, stuckDue, unheardWait, workerInFlight, workerReportedTerminal, type Change, type MechanicalEvent, type OpenUserItem } from "./reconcile.js"; @@ -1543,6 +1543,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P "Do not comment on any ticket or pull request, and do not run `bb stewards done`, `escalate` or `merge`, or make any Linear write.", "", "Reply with a one-line verdict first, then the evidence, under 200 words.", + "Write plain prose only: no Markdown, no headings, no bullet points, no bold or italics, no code fences. Your answer is read aloud.", ].join("\n"); /** `bb stewards show ` output for the delegate's context, or null when the key has no steward here. */ @@ -1719,6 +1720,23 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await wakeProject(row.projectId, "the owner held a stand-up", { digestDue: false, notes: lines }); } + /** + * BB-309: the stand-up's key reader. A ticket key resolves as before; a + * pull-request key or URL that names no binding of its own resolves to the + * open binding holding an open approve-pr or merge need for it, so the key + * the brief shows works in every read tool, gate note and confirmation. + */ + function standupBindingFor(projectId: string, key: string): Binding | null { + const direct = store.find(key, projectId); + if (direct !== null) return direct; + if (parsePullRef(key) === null) return null; + for (const b of store.open(projectId)) { + const held = store.openNeeds(b.id).some((n) => (n.kind === "approve-pr" || n.kind === "merge") && samePullRef(n.url, key)); + if (held) return b; + } + return null; + } + /** * Apply one confirmed note through the path its shape already uses: a gate * item through the need-action RPC the Approve and Decline buttons use, @@ -1731,7 +1749,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P async function applyStandupNote(standup: StandupRow, note: StandupNoteRow): Promise<{ ok: boolean; applied: boolean; message: string }> { const type = note.type as StandupNoteType; const text = scrubCredentials(note.text); - const binding = note.binding === null ? null : store.find(note.binding, standup.projectId); + const binding = note.binding === null ? null : standupBindingFor(standup.projectId, note.binding); let applied = false; let message = "Confirmed."; @@ -9622,7 +9640,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const result = await runStandupTool(name, args, { projectId: standupProjectId, now, - binding: (key) => store.find(key, standupProjectId), + binding: (key) => standupBindingFor(standupProjectId, key), openEscalations: (bindingId) => store.openEscalations(bindingId), escalation: (id) => store.escalation(id), lessons: (bindingId) => store.allLessons(standupProjectId).filter((l) => l.bindingId === bindingId), diff --git a/plugins/stewards/standup.test.ts b/plugins/stewards/standup.test.ts index 84018a78..43631ab7 100644 --- a/plugins/stewards/standup.test.ts +++ b/plugins/stewards/standup.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { STANDUP_CONTEXT_MAX_CHARS, STANDUP_DELEGATE_ANSWER_MAX_CHARS, + STANDUP_ENTITY_DESCRIPTION_MAX_CHARS, STANDUP_MAX_INSTRUCTIONS_CHARS, STANDUP_NOTE_TYPES, STANDUP_STALE_DAYS, @@ -15,6 +16,7 @@ import { readbackLine, readbackLines, runStandupTool, + stripMarkdown, type StandupNote, type StandupRecord, type StandupToolContext, @@ -22,7 +24,7 @@ import { import type { Briefing } from "./nightly.js"; import type { Binding, Escalation, Lesson } from "./store.js"; import type { GuidanceUnit } from "./guidance.js"; -import { comment, issue } from "./fixtures.js"; +import { comment, issue, pull } from "./fixtures.js"; const binding = (over: Partial = {}): Binding => ({ @@ -164,6 +166,57 @@ describe("runStandupTool (BB-300)", () => { expect(out).toContain("Children: acme/web#13 Sub-task (open)"); }); + it("renders a linked pull request with its title and state, and a pull key's own snapshot (BB-309)", async () => { + const linked = pull({ + id: "acme/web#7", + key: "acme/web#7", + url: "https://github.com/acme/web/pull/7", + title: "Add login retry", + state: "open", + author: "sam", + description: "Retries login.", + comments: [comment({ id: "c1", author: "Jane", did: "approved", body: "Looks good to me.", createdAt: "2026-10-03T00:00:00Z" })], + }); + const ticketEntity = issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }); + const b = binding({ lastSnapshot: { entity: ticketEntity, pulls: [linked] } }); + const ctx = context({ snapshot: async () => ticketEntity, binding: (key) => (key === "ENG-12" || key === "acme/web#7" || key === "https://github.com/acme/web/pull/7" ? b : null) }); + // The ticket lists the linked pull with the title and state the binding holds. + const ticket = (await runStandupTool("entity_snapshot", { key: "ENG-12" }, ctx)) as string; + expect(ticket).toContain("Linked pull requests: acme/web#7 Add login retry (open)"); + // A pull key that resolves to the ticket renders the pull, not the ticket. + const pr = (await runStandupTool("entity_snapshot", { key: "acme/web#7" }, ctx)) as string; + expect(pr).toContain("acme/web#7: Add login retry"); + expect(pr).toContain("State: open"); + expect(pr).toContain("Author: sam"); + expect(pr).toContain("Retries login."); + expect(pr).toContain("2026-10-03T00:00:00Z Jane approved: Looks good to me."); + expect(pr).not.toContain("No steward"); + // A pull URL resolves the same way. + const byUrl = (await runStandupTool("entity_snapshot", { key: "https://github.com/acme/web/pull/7" }, ctx)) as string; + expect(byUrl).toContain("acme/web#7: Add login retry"); + }); + + it("clips a long entity body without flattening it (BB-309)", async () => { + const long = pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", description: `first line\n\n${"y".repeat(STANDUP_ENTITY_DESCRIPTION_MAX_CHARS + 50)}` }); + const b = binding({ lastSnapshot: { entity: issue(), pulls: [long] } }); + const ctx = context({ binding: (key) => (key === "acme/web#8" ? b : null) }); + const out = (await runStandupTool("entity_snapshot", { key: "acme/web#8" }, ctx)) as string; + expect(out).toContain("first line"); + // The body keeps its line breaks and is clipped at the cap. + expect(out).toContain("first line\n\ny"); + expect(out).not.toContain("y".repeat(STANDUP_ENTITY_DESCRIPTION_MAX_CHARS + 1)); + expect(out).toContain("…"); + }); + + it("renders a ticket body as written, without the pull clip (BB-309)", async () => { + const long = "z".repeat(STANDUP_ENTITY_DESCRIPTION_MAX_CHARS + 50); + const entity = issue({ description: long }); + const b = binding({ lastSnapshot: { entity, pulls: [] } }); + const ctx = context({ snapshot: async () => entity, binding: (key) => (key === "ENG-12" ? b : null) }); + const out = (await runStandupTool("entity_snapshot", { key: "ENG-12" }, ctx)) as string; + expect(out).toContain(long); + }); + it("reads the lessons behind a decision", async () => { const out = await runStandupTool("decision_rationale", { key: "ENG-12" }, context()); expect(out).toContain("Prefer the smaller change."); @@ -257,6 +310,41 @@ describe("runStandupTool (BB-300)", () => { await runStandupTool("take_note", { type: "gate", text: "Looks good", binding: "ENG-12", action: "approve", need: "need_2" }, named); expect(named.record.notes[0]).toMatchObject({ need: "need_2" }); }); + + it("matches a gate need by the pull request key the brief shows (BB-309)", async () => { + const need = { id: "need_1", kind: "approve-pr", what: "Approve acme/web#7 on GitHub", url: "https://github.com/acme/web/pull/7" } as never; + const byKey = context({ needs: () => [need] }); + await runStandupTool("take_note", { type: "gate", text: "Looks good", binding: "ENG-12", action: "approve", need: "acme/web#7" }, byKey); + expect(byKey.record.notes[0]).toMatchObject({ need: "need_1", needLabel: "Approve acme/web#7 on GitHub" }); + const byUrl = context({ needs: () => [need] }); + await runStandupTool("take_note", { type: "gate", text: "Looks good", binding: "ENG-12", action: "approve", need: "https://github.com/acme/web/pull/7" }, byUrl); + expect(byUrl.record.notes[0]).toMatchObject({ need: "need_1" }); + const noMatch = context({ needs: () => [need] }); + await expect(runStandupTool("take_note", { type: "gate", text: "Looks good", binding: "ENG-12", action: "approve", need: "acme/web#9" }, noMatch)).rejects.toThrow(/matches/u); + }); + + it("records the resolved binding key for a gate note taken by pull key (BB-309)", async () => { + const need = { id: "need_1", kind: "approve-pr", what: "Approve acme/web#7 on GitHub", url: "https://github.com/acme/web/pull/7" } as never; + const ctx = context({ binding: (key) => (key === "ENG-12" || key === "acme/web#7" ? binding() : null), needs: () => [need] }); + await runStandupTool("take_note", { type: "gate", text: "Looks good", binding: "acme/web#7", action: "approve" }, ctx); + // The confirmation path's `store.find` needs the binding's own key, not the pull key. + expect(ctx.record.notes[0]).toMatchObject({ binding: "ENG-12", need: "need_1" }); + }); + + it("uses a pull-key binding to pick the exact gate item, and keeps a ticket key ambiguous (BB-309)", async () => { + const approve7 = { id: "need_7", kind: "approve-pr", what: "Approve acme/web#7 on GitHub", url: "https://github.com/acme/web/pull/7" } as never; + const merge8 = { id: "need_8", kind: "merge", what: "Merge acme/web#8 on GitHub", url: "https://github.com/acme/web/pull/8" } as never; + const resolve = (key: string) => (key === "ENG-12" || key === "acme/web#7" || key === "acme/web#8" ? binding() : null); + // The pull key names #8, which has no approve item: refuse, never bind #7. + await expect(runStandupTool("take_note", { type: "gate", text: "Looks good", binding: "acme/web#8", action: "approve" }, context({ binding: resolve, needs: () => [approve7, merge8] }))).rejects.toThrow(/matches/u); + // The pull key with the matching action binds that pull's item, not the first of the kind. + const mergeCtx = context({ binding: resolve, needs: () => [approve7, merge8] }); + await runStandupTool("take_note", { type: "gate", text: "Ship it", binding: "acme/web#8", action: "merge" }, mergeCtx); + expect(mergeCtx.record.notes[0]).toMatchObject({ binding: "ENG-12", need: "need_8" }); + // A ticket key with two items of the action's kind is still ambiguous. + const approve7b = { id: "need_7b", kind: "approve-pr", what: "Approve acme/web#7b on GitHub", url: "https://github.com/acme/web/pull/7b" } as never; + await expect(runStandupTool("take_note", { type: "gate", text: "Looks good", binding: "ENG-12", action: "approve" }, context({ needs: () => [approve7, approve7b] }))).rejects.toThrow(/several open gate items/u); + }); }); describe("ask_a_thread (BB-307)", () => { @@ -314,6 +402,20 @@ describe("ask_a_thread (BB-307)", () => { it("requires a question", async () => { await expect(runStandupTool("ask_a_thread", {}, context())).rejects.toThrow(/question is required/u); }); + + it("strips Markdown from a delegate answer before logging or returning it (BB-309)", async () => { + const answer = "**Verdict:** the build is fine.\n\n# Details\n\n- item one\n- item two\n\nUse `retry`."; + const ctx = context({ askThread: async () => ({ outcome: "success", answer, startedAt: 1, finishedAt: 2, error: null }) }); + const out = (await runStandupTool("ask_a_thread", { question: "q" }, ctx)) as string; + expect(out).toContain("Verdict: the build is fine."); + expect(out).toContain("item one"); + expect(out).not.toContain("**"); + expect(out).not.toMatch(/^#/mu); + expect(out).not.toMatch(/^- /mu); + expect(out).not.toContain("`"); + // The logged answer is the stripped one, so the record carries no markers either. + expect(ctx.record.delegations[0]!.answer).toBe(out); + }); }); const briefing = (over: Partial = {}): Briefing => ({ @@ -423,6 +525,30 @@ describe("buildStandupInstructions (BB-300)", () => { expect(line).not.toContain("days"); }); + it("carries a gate item's pull title, steward summary and review verdict (BB-309)", () => { + const need = { what: "Approve acme/web#7 on GitHub", kind: "approve-pr", createdAt: 1, url: "https://github.com/acme/web/pull/7" } as never; + const linked = pull({ comments: [comment({ id: "m1", author: "trotterdylan", body: "", signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" })] }); + const b = binding({ entityKey: "ENG-12", status: { actor: "steward", nextAction: "review", summary: "In review, waiting on the owner", waitingOn: "the approval", at: 1 } as never, lastSnapshot: { entity: issue(), pulls: [linked] } }); + const text = buildStandupInstructions(briefing({ decisions: { needs: [{ need, binding: b }], withUser: [] } }), "Acme", 10_000); + expect(text).toContain("Add login retry"); + expect(text).toContain("In review, waiting on the owner"); + expect(text).toContain("review approved, lane owner-reviewed, approver owner"); + }); + + it("clips a long steward summary in a gate item's line (BB-309)", () => { + const need = { what: "Approve acme/web#7 on GitHub", kind: "approve-pr", createdAt: 1, url: "https://github.com/acme/web/pull/7" } as never; + const longSummary = `In review ${"x".repeat(STANDUP_CONTEXT_MAX_CHARS + 50)}`; + const b = binding({ entityKey: "ENG-12", status: { summary: longSummary, actor: "steward", nextAction: "review", waitingOn: "the approval", at: 1 } as never, lastSnapshot: { entity: issue(), pulls: [pull()] } }); + const text = buildStandupInstructions(briefing({ decisions: { needs: [{ need, binding: b }], withUser: [] } }), "Acme", 10_000); + expect(text).not.toContain("x".repeat(STANDUP_CONTEXT_MAX_CHARS + 1)); + }); + + it("tells the model a gate note's binding is the ticket key and need is the pull request (BB-309)", () => { + const text = buildStandupInstructions(briefing(), "Acme", 10_000); + expect(text).toContain("the binding is the ticket key before the colon on the brief line"); + expect(text).toContain("need is the pull request named on it"); + }); + it("says no digest yet, and the last digest date once there is one (BB-306)", () => { expect(buildStandupInstructions(briefing(), "Acme", 10_000)).toContain("has not filed a digest yet"); const at = Date.parse("2026-11-10T00:00:00Z"); @@ -493,3 +619,15 @@ describe("buildStandupInstructions (BB-300)", () => { expect(text).not.toMatch(/## Done since\n- \(none\)/u); }); }); + +describe("stripMarkdown (BB-309)", () => { + it("keeps the words and drops headings, bullets, emphasis and code", () => { + expect(stripMarkdown("**Bold** and `code`.")).toBe("Bold and code."); + expect(stripMarkdown("keep snake_case and 2 * 3 * 4")).toBe("keep snake_case and 2 * 3 * 4"); + expect(stripMarkdown("# Heading\n## Two")).toBe("Heading\nTwo"); + expect(stripMarkdown("- one\n- two")).toBe("one\ntwo"); + expect(stripMarkdown("1. one\n2. two")).toBe("one\ntwo"); + expect(stripMarkdown("```\nblock\n```")).toBe("\nblock\n"); + expect(stripMarkdown("plain text")).toBe("plain text"); + }); +}); diff --git a/plugins/stewards/standup.ts b/plugins/stewards/standup.ts index b5be0899..d3bf74eb 100644 --- a/plugins/stewards/standup.ts +++ b/plugins/stewards/standup.ts @@ -14,6 +14,8 @@ import type { Briefing } from "./nightly.js"; import type { Binding, Escalation, Lesson, Need } from "./store.js"; import type { EntitySnapshot } from "./source-contract.js"; import type { GuidanceUnit } from "./guidance.js"; +import { parsePullRef } from "./github.js"; +import { latestReviewMarker } from "./gate.js"; import { redactLine } from "./ops.js"; /** One function tool, shaped the way the Realtime API's `realtime.open` expects. */ @@ -100,6 +102,8 @@ export const STANDUP_ENTITY_COMMENTS_MAX = 5; export const STANDUP_ENTITY_COMMENT_MAX_CHARS = 300; /** The most children `entity_snapshot` lists before it says how many were left out (BB-306). */ export const STANDUP_ENTITY_CHILDREN_MAX = 10; +/** How much of an entity's body `entity_snapshot` carries (BB-309). */ +export const STANDUP_ENTITY_DESCRIPTION_MAX_CHARS = 1_000; const DAY_MS = 86_400_000; /** The only tools that write, and they write only to the stand-up record. */ @@ -404,12 +408,20 @@ function escalationTool(ctx: StandupToolContext, args: Record): async function entityTool(ctx: StandupToolContext, key: string): Promise { const b = ctx.binding(key); if (b === null) return `No steward for ${key} in this project.`; - const entity = (await ctx.snapshot(b).catch(() => null)) ?? b.lastSnapshot?.entity ?? null; + // BB-309: a pull-request key resolves to the ticket binding that holds its + // gate need. Render that pull's own snapshot from what the binding already + // holds, never the ticket's snapshot or a "No steward" line. The binding's + // own key is the entity even when it parses as a pull reference (a GitHub + // issue key has the same shape). + const linked = key === b.entityKey ? null : pullFromKey(b, key); + const entity = linked ?? (await ctx.snapshot(b).catch(() => null)) ?? b.lastSnapshot?.entity ?? null; if (entity === null) return `No snapshot is available for ${key}.`; const lines = [`${entity.key}: ${entity.title ?? "(no title)"}`]; lines.push(`State: ${entity.state ?? "unknown"}${entity.labels.length === 0 ? "" : ` · labels: ${entity.labels.join(", ")}`}`); if (entity.author !== null) lines.push(`Author: ${entity.author}`); - if (entity.description !== null && entity.description.trim() !== "") lines.push(entity.description.trim()); + // BB-309: a pull request's body is clipped for the spoken answer; a ticket's + // body is rendered as written, as before. + if (entity.description !== null && entity.description.trim() !== "") lines.push(entity.kind === "pull" ? clipBlock(entity.description, STANDUP_ENTITY_DESCRIPTION_MAX_CHARS) : entity.description.trim()); // BB-306: the snapshot already fetched these; render them so the model does // not have to spend a lookup on what the tool already has. const comments = entity.comments.slice(-STANDUP_ENTITY_COMMENTS_MAX); @@ -417,7 +429,19 @@ async function entityTool(ctx: StandupToolContext, key: string): Promise lines.push(`Comments (last ${comments.length} of ${entity.comments.length}):`); for (const c of comments) lines.push(` ${c.createdAt} ${c.author} ${c.did}: ${clipText(c.body, STANDUP_ENTITY_COMMENT_MAX_CHARS)}`); } - if (entity.linkedPulls.length > 0) lines.push(`Linked pull requests: ${entity.linkedPulls.map((p) => p.key ?? p.url).join(", ")}`); + if (entity.linkedPulls.length > 0) { + // BB-309: a ticket's linked pull requests render with the title and state + // the binding already read for them, not the key alone. + lines.push( + `Linked pull requests: ${entity.linkedPulls + .map((p) => { + const linkKey = p.key ?? p.url; + const pull = linkedPullFor(b, p); + return pull === null ? linkKey : `${linkKey} ${pull.title ?? "(no title)"} (${pull.state ?? "unknown"})`; + }) + .join(", ")}`, + ); + } if (entity.children.length > 0) { const shown = entity.children.slice(0, STANDUP_ENTITY_CHILDREN_MAX); const more = (entity.childrenTotal ?? entity.children.length) - shown.length; @@ -472,7 +496,10 @@ function gateNeed(ctx: StandupToolContext, binding: Binding, action: string | nu const candidates = ctx.needs(binding.id).filter((n) => gateKinds(action).includes(n.kind)); if (candidates.length === 0) throw new Error(`No open ${action ?? "gate"} item on ${binding.entityKey}`); if (wanted !== null) { - const match = candidates.find((n) => n.id === wanted || n.url === wanted || n.what === wanted); + // BB-309: the brief names a gate item by its pull request key + // (`owner/repo#N`); match it against the need's URL too, not only the id, + // the exact URL or the description. + const match = candidates.find((n) => n.id === wanted || n.url === wanted || n.what === wanted || samePullRef(n.url, wanted)); if (match === undefined) throw new Error(`No open gate item on ${binding.entityKey} matches ${JSON.stringify(wanted)}`); return match; } @@ -492,11 +519,19 @@ function takeNote(ctx: StandupToolContext, args: Record): strin // binding with several open items can never apply the wrong one later. let need: string | null = null; let needLabel: string | null = null; + // BB-309: the binding may be a pull-request key the brief shows. Record the + // resolved binding's own key so the confirmation path's `store.find` finds + // it later, and use the pull key to pick the exact item when the caller did + // not name one. + let bindingValue = bindingKey; if (type === "gate") { if (bindingKey === null) throw new Error("a gate note needs a binding"); const binding = ctx.binding(bindingKey); if (binding === null) throw new Error(`No steward for ${bindingKey}`); - const item = gateNeed(ctx, binding, action, optionalString(args, "need")); + bindingValue = binding.entityKey; + const explicit = optionalString(args, "need"); + const wanted = explicit ?? (bindingKey !== binding.entityKey && parsePullRef(bindingKey) !== null ? bindingKey : null); + const item = gateNeed(ctx, binding, action, wanted); need = item.id; needLabel = item.what; } @@ -504,7 +539,7 @@ function takeNote(ctx: StandupToolContext, args: Record): strin id: `note_${crypto.randomUUID()}`, type: type as StandupNoteType, text, - binding: bindingKey, + binding: bindingValue, escalation: optionalString(args, "escalationId"), action: action as StandupNote["action"], need, @@ -583,7 +618,9 @@ async function askThreadTool(ctx: StandupToolContext, args: Record samePullRef(p.key, key) || (p.url !== null && samePullRef(p.url, key))) ?? null; +} + +/** The binding's snapshot of a linked pull, by its link key or url, or null when it was not read. */ +function linkedPullFor(binding: Binding, link: { url: string; key: string | null }): EntitySnapshot | null { + return (binding.lastSnapshot?.pulls ?? []).find((p) => (link.key !== null && samePullRef(p.key, link.key)) || samePullRef(p.url ?? "", link.url)) ?? null; +} + +/** + * BB-309: the facts a gate need's brief line carries, read only from what the + * binding already holds: the pull's title, the steward's status summary and + * the last `bb-review` verdict with its lane and approver. No source call. + */ +function gateNeedFacts(binding: Binding, need: Need): string[] { + const facts: string[] = []; + const pull = pullFromKey(binding, need.url); + if (pull !== null && pull.title !== null && pull.title.trim() !== "") facts.push(`"${pull.title.trim()}"`); + const summary = binding.status?.summary; + if (summary !== null && summary !== undefined && summary.trim() !== "") facts.push(clipText(summary, STANDUP_CONTEXT_MAX_CHARS)); + if (pull !== null) { + const marker = latestReviewMarker(pull.comments); + if (marker !== null) { + const lane = marker.lane === null ? "" : `, lane ${marker.lane}`; + const approver = marker.approver === undefined ? "" : `, approver ${marker.approver}`; + facts.push(`review ${marker.verdict}${lane}${approver}`); + } + } + return facts; +} + +/** + * BB-309: strip the Markdown a delegate reaches for even when asked for plain + * prose, so the spoken answer carries no markers. Headings, bullets, numbered + * lists, blockquotes, bold, strikethrough, code fences and inline code all keep + * their words and lose their punctuation. Single `*`/`_` emphasis is left + * alone: it is not a marker a voice model reads, and stripping it would mangle + * `snake_case` identifiers and arithmetic. + */ +export function stripMarkdown(text: string): string { + return text + .replace(/^```[^\n]*$/gmu, "") + .replace(/^~~~[^\n]*$/gmu, "") + .replace(/^\s{0,3}#{1,6}\s+/gmu, "") + .replace(/^\s{0,3}[-*+]\s+/gmu, "") + .replace(/^\s{0,3}\d+[.)]\s+/gmu, "") + .replace(/^\s{0,3}>\s?/gmu, "") + .replace(/\*\*\*(.+?)\*\*\*/gsu, "$1") + .replace(/\*\*(.+?)\*\*/gsu, "$1") + .replace(/~~(.+?)~~/gsu, "$1") + .replace(/`([^`\n]+)`/gu, "$1"); +} + /** An open question put to the owner, with the binding it attaches to resolved to a key. */ export type StandupOpenQuestion = { key: string | null; question: string; choices: string[]; createdAt: number; context: string | null }; /** The owner's decisions, as one line each: needs, forwarded escalations and open questions. */ function decisionLines(briefing: Briefing, questions: readonly StandupOpenQuestion[], now: number): string[] { const out: string[] = []; - for (const { need, binding } of briefing.decisions.needs) out.push(withAge(`${binding.entityKey}: ${need.what} (${need.kind})`, now, need.createdAt)); + for (const { need, binding } of briefing.decisions.needs) { + const base = `${binding.entityKey}: ${need.what} (${need.kind})`; + // BB-309: a gate item's line carries the pull's substance from what the + // binding already holds, so describing it needs no lookup. + const facts = need.kind === "approve-pr" || need.kind === "merge" ? gateNeedFacts(binding, need) : []; + out.push(withAge(facts.length === 0 ? base : `${base} — ${facts.join(" · ")}`, now, need.createdAt)); + } for (const { escalation, from } of briefing.decisions.withUser) out.push(withAge(`${from.entityKey}: ${escalation.question}${escalation.recommendation === null ? "" : ` — recommendation: ${escalation.recommendation}`}`, now, escalation.createdAt)); // The briefing's `withUser` leaves questions to the digest's own section // (slice 1); the stand-up is exactly where the owner answers them, so they are @@ -719,6 +834,8 @@ export function buildStandupInstructions(briefing: Briefing, projectName: string : "Lead with the things only the owner can unblock for this steward, then what is stuck or held. If nothing is waiting on the owner and nothing is stuck, say so plainly and ask what is on their mind.", "You may read state with the tools you have been given, and you may take or retract notes. You cannot act on a steward, merge, resolve or change anything; the owner confirms notes after the stand-up.", "When the owner decides something, take a note in the matching shape (resolve an escalation, a gate item, guidance for a binding, direction for the project, or a standing rule) and read it back in their words. A remark that is not a decision is a free note.", + "For a gate note, the binding is the ticket key before the colon on the brief line, and need is the pull request named on it (for example owner/repo#34).", + "For a gate note on a pull request, binding may also be the pull request key itself (owner/repo#34) when the brief names it that way.", "To close: call readback and read every line aloud in the server's own words, then ask the owner to confirm. Retract any note they reject, read the changed list back again, and only then call end_standup with the ids they clearly agreed to. Never end without a readback, and treat anything short of a clear yes as no confirmation.", "A merge gate item is never applied by end_standup: read it aloud on its own and tell the owner it stays for the page's Confirm button.", "An item's text is what was true when it was raised, not what is true now; its age says how much to trust it, so verify a stale claim before repeating it.",