Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): record whether the crash dump reached the bundle (PRD-7769) (#3161)
Andrew Mikofalvy5ebdfbc5e10e
diff --git a/.changeset/crash-dump-attach-decision-record.md b/.changeset/crash-dump-attach-decision-record.mdnew file mode 100644index 000000000..4e130f09e--- /dev/null+++ b/.changeset/crash-dump-attach-decision-record.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++A crash report that arrives without its crash dump now explains itself. Until now, a bug report whose crash dump was missing looked identical whether you had unchecked the box on purpose, the app had found no crash dump it could prove was its own, or the dump had been cleaned up in the moment between choosing to send it and the report being packed. All three arrived as an empty slot, and there was no way to tell them apart afterwards, so a report that should have carried the most useful evidence about a crash could not even be shown to be missing it. The app now writes a line into its own log recording which of those actually happened, and, when a dump was looked for, how many crash dumps were skipped because they belonged to a helper process or could not be read at all. The line is written before the report is packed, so it travels inside the very report it explains rather than turning up in the next one.++A dump that was on hand is the one case that line cannot settle by itself, since whether it survived being packed is only known once packing is done. The report answers that on its own: the line says a dump was going in, and the report either carries it or it does not. Relatedly, a dump cleaned up mid-pack used to abort the whole detailed report; it is now recorded as a dump that did not make it, and the rest of the report is still produced.++This changes nothing about what gets attached. The crash-dump checkbox behaves exactly as before: it appears only when a crash dump for that crash is on disk, comes pre-checked because that dump is the evidence the report exists to carry, and can be unchecked. This only observes the choice already being made. The record names no file: a crash dump is raw program memory that cannot be scrubbed, and its filename identifies the individual crash, so the line carries only the outcome, the counts, and a size in bytes.diff --git a/packages/cli/src/diagnose/bundle.ts b/packages/cli/src/diagnose/bundle.tsindex 571f45a2c..1c65b2cba 100644--- a/packages/cli/src/diagnose/bundle.ts+++ b/packages/cli/src/diagnose/bundle.ts@@ -618,9 +618,17 @@ function countDocNameOccurrences(filePath: string): number {function stageFileIfPresent(srcPath: string, destPath: string): boolean {if (!existsSync(srcPath)) return false;- mkdirSync(dirname(destPath), { recursive: true });- cpSync(srcPath, destPath);- return true;+ try {+ mkdirSync(dirname(destPath), { recursive: true });+ cpSync(srcPath, destPath);+ return true;+ } catch {+ // A source can vanish or turn unreadable between the check and the copy —+ // crash-dump cleanup and log rotation both run on their own schedule. Report+ // it as absent, which every caller already handles, rather than letting one+ // artifact that went away mid-collection fail the whole bundle.+ return false;+ }}function walkStagedFiles(stagingDir: string): string[] {diff --git a/packages/desktop/src/main/crash-detection.test.ts b/packages/desktop/src/main/crash-detection.test.tsindex 210a30512..de35b5fbe 100644--- a/packages/desktop/src/main/crash-detection.test.ts+++ b/packages/desktop/src/main/crash-detection.test.ts@@ -623,12 +623,12 @@ describe('newest un-acked minidump lookup', () => {seedMinidump(rig, 'pending/older.dmp', older);seedMinidump(rig, 'completed/newer.dmp', newer);- expect(detection.newestMinidumpPath()).toBe(+ expect(detection.newestMinidumpForReport().path).toBe(join(rig.deps.crashDumpsDir, 'completed', 'newer.dmp'),);detection.ack('boot:some-earlier-event');- expect(detection.newestMinidumpPath()).toBeNull();+ expect(detection.newestMinidumpForReport().path).toBeNull();});test('dumps already covered by the fresh-install baseline never surface', () => {@@ -636,14 +636,14 @@ describe('newest un-acked minidump lookup', () => {seedMinidump(rig, 'pending/historic.dmp', new Date(Date.parse('2026-07-09T00:00:00.000Z')));const detection = createCrashDetection(rig.deps);- expect(detection.newestMinidumpPath()).toBeNull();+ expect(detection.newestMinidumpForReport().path).toBeNull();});test('a crash-dumps dir Crashpad has not created yet reads as no dump', () => {const rig = makeRig();const detection = createCrashDetection(rig.deps);- expect(detection.newestMinidumpPath()).toBeNull();+ expect(detection.newestMinidumpForReport().path).toBeNull();});});@@ -678,7 +678,7 @@ describe('crash-dump ownership filtering', () => {expect(armed.context.newMinidumps).toBe(1);expect(armed.minidumpAvailable).toBe(true);}- expect(session.newestMinidumpPath()).toBe(ownPath);+ expect(session.newestMinidumpForReport().path).toBe(ownPath);});test('a dump from a foreign process neither arms nor is attachable', () => {@@ -694,7 +694,7 @@ describe('crash-dump ownership filtering', () => {expect(session.detectBootCrash()).toBeNull();session.notifyRendererReady();expect(rig.emitted).toHaveLength(0);- expect(session.newestMinidumpPath()).toBeNull();+ expect(session.newestMinidumpForReport().path).toBeNull();});test('a bundle-root prefix collision does not read as ownership', () => {@@ -710,7 +710,7 @@ describe('crash-dump ownership filtering', () => {const session = createCrashDetection(rig.deps);expect(session.detectBootCrash()).toBeNull();- expect(session.newestMinidumpPath()).toBeNull();+ expect(session.newestMinidumpForReport().path).toBeNull();});test('an unparseable dump still arms, but is never attachable', () => {@@ -730,7 +730,7 @@ describe('crash-dump ownership filtering', () => {// the consent dialog cannot honestly describe.expect(armed.minidumpAvailable).toBe(false);}- expect(session.newestMinidumpPath()).toBeNull();+ expect(session.newestMinidumpForReport().path).toBeNull();});test('a foreign dump does not override machine-level-death suppression', () => {@@ -770,7 +770,7 @@ describe('crash-dump ownership filtering', () => {const ownPath = seedMinidump(rig, 'completed/ours.dmp', rig.tick());seedMinidump(rig, 'pending/soffice.dmp', rig.tick(), FOREIGN_DUMP);- expect(detection.newestMinidumpPath()).toBe(ownPath);+ expect(detection.newestMinidumpForReport().path).toBe(ownPath);});test('a runtime crash offers no dump when only a foreign dump is on disk', () => {@@ -781,7 +781,58 @@ describe('crash-dump ownership filtering', () => {detection.handleRenderProcessGone({ reason: 'crashed' });expect(rig.emitted[0]?.minidumpAvailable).toBe(false);- expect(detection.newestMinidumpPath()).toBeNull();+ expect(detection.newestMinidumpForReport().path).toBeNull();+ });++ test('the report lookup carries the skip counts alongside the dump it found', () => {+ // The report path needs its own copy of these: the boot-time breadcrumb+ // only fires at boot, so a report composed later has no other record of+ // what the ownership walk rejected.+ const rig = makeRig();+ const detection = createCrashDetection(rig.deps);+ seedMinidump(rig, 'completed/soffice.dmp', rig.tick(), FOREIGN_DUMP);+ seedMinidump(rig, 'completed/torn.dmp', rig.tick(), UNPARSEABLE_DUMP);+ const ownPath = seedMinidump(rig, 'completed/ours.dmp', rig.tick());++ // Newest-first, so the owned dump seeded last is reached first and the+ // older rejects are never classified — nothing to count.+ expect(detection.newestMinidumpForReport()).toEqual({+ path: ownPath,+ foreignSkipped: 0,+ unknownSkipped: 0,+ });+ });++ test('an empty-handed report lookup says what it walked past to get there', () => {+ const rig = makeRig();+ const detection = createCrashDetection(rig.deps);+ seedMinidump(rig, 'completed/soffice.dmp', rig.tick(), FOREIGN_DUMP);+ seedMinidump(rig, 'completed/torn.dmp', rig.tick(), UNPARSEABLE_DUMP);++ // Without the split, "a descendant crashed" and "we could not read the+ // dump at all" both reach the report as a bare absent dump.+ expect(detection.newestMinidumpForReport()).toEqual({+ path: null,+ foreignSkipped: 1,+ unknownSkipped: 1,+ });+ });++ test('the report lookup still stops at the first owned dump', () => {+ const rig = makeRig();+ const detection = createCrashDetection(rig.deps);+ seedMinidump(rig, 'completed/soffice.dmp', rig.tick(), FOREIGN_DUMP);+ const ownPath = seedMinidump(rig, 'completed/ours.dmp', rig.tick());+ seedMinidump(rig, 'completed/newer-soffice.dmp', rig.tick(), FOREIGN_DUMP);++ // One newer foreign dump gets classified on the way to ours; the older one+ // is never reached. Counting every fresh dump instead would mean parsing+ // the whole crash database on each lookup.+ expect(detection.newestMinidumpForReport()).toEqual({+ path: ownPath,+ foreignSkipped: 1,+ unknownSkipped: 0,+ });});test('a runtime crash says how many foreign dumps it walked past', () => {diff --git a/packages/desktop/src/main/crash-detection.ts b/packages/desktop/src/main/crash-detection.tsindex c8b3577f6..57db5e9fd 100644--- a/packages/desktop/src/main/crash-detection.ts+++ b/packages/desktop/src/main/crash-detection.ts@@ -212,13 +212,15 @@ export interface CrashDetection {/** Persist an acknowledgment so the event never re-prompts, and disarm it. */ack(eventId: string): void;/**- * Absolute path of the newest minidump not yet covered by an acknowledgment- * (strictly newer than the ack baseline) AND provably written for one of our- * own processes — the dump belonging to whatever crash the user is currently- * invited to report. Null when the un-acked crash left no dump (e.g. dirty+ * The newest minidump not yet covered by an acknowledgment (strictly newer+ * than the ack baseline) AND provably written for one of our own processes —+ * the dump belonging to whatever crash the user is currently invited to+ * report. `path` is null when the un-acked crash left no dump (e.g. dirty* shutdown without a native crash), when every dump is already acked, or* when the only fresh dumps belong to descendant processes that inherited- * our crash handler.+ * our crash handler. The two skip counts say which of those it was, which is+ * the difference between a bundle that arrived without a dump for a knowable+ * reason and one that is a mystery after the fact.** Minidumps carry raw process memory that text redaction cannot scrub, so* bundle inclusion stays behind the report dialog's crash-dump checkbox@@ -229,7 +231,22 @@ export interface CrashDetection {* fails CLOSED on an unreadable dump, unlike `detectBootCrash`, which only* asks a dismissible question and fails open.*/- newestMinidumpPath(): string | null;+ newestMinidumpForReport(): MinidumpReportLookup;+}++/**+ * What one report-time minidump lookup found. The skip counts are what the+ * ownership walk rejected on its way to the answer, carried alongside the path+ * so a caller that logs the outcome can say WHY there was no dump without+ * running a second classification pass.+ */+export interface MinidumpReportLookup {+ /** Absolute path of the attachable dump, or null when there is none. */+ path: string | null;+ /** Fresh dumps skipped because they belong to a descendant process. */+ foreignSkipped: number;+ /** Fresh dumps skipped because they could not be parsed at all. */+ unknownSkipped: number;}/**@@ -826,8 +843,13 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {}},- newestMinidumpPath(): string | null {- return newestOwnedMinidump().entry?.path ?? null;+ newestMinidumpForReport(): MinidumpReportLookup {+ const owned = newestOwnedMinidump();+ return {+ path: owned.entry?.path ?? null,+ foreignSkipped: owned.foreignSkipped,+ unknownSkipped: owned.unknownSkipped,+ };},};}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex a436e244b..adad41dcd 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -4916,7 +4916,12 @@ function registerIpcHandlers() {packaged: app.isPackaged,channel: channelFromVersion(app.getVersion()),},- newestMinidumpPath: () => crashDetection?.newestMinidumpPath() ?? null,+ newestMinidumpForReport: () =>+ crashDetection?.newestMinidumpForReport() ?? {+ path: null,+ foreignSkipped: 0,+ unknownSkipped: 0,+ },// Main-owned bytes captured for this exact window; `create` stages them// only when the renderer opted in via `includeScreenshot`.screenshotPngBytes: () => bugReportScreenshots.get(event.sender.id)?.png ?? null,@@ -4924,6 +4929,7 @@ function registerIpcHandlers() {// once the bundle is written, so it survives dialog close + restart.onReportGenerated: (meta) => bugReportSidecar.recordGenerated(meta),logger: getLogger('bug-report'),+ flushLogger: flushDesktopLogger,},request,);@@ -6011,14 +6017,14 @@ trustSystemCertificates();// to a named sibling dir gives each instance its own lock + isolated storage.//// The instance name is `OK_INSTANCE` when set, else auto-derived from the git-// checkout (branch name, or worktree dir on detached HEAD) so two `bun run dev`+// checkout (branch name, or worktree dir on detached HEAD) so two `pnpm dev`// launches from different worktrees isolate automatically — no env needed. The// repo default branch (main/master) is skipped so plain dev on main keeps the// classic shared `userData`; `OK_AUTO_INSTANCE=0` disables auto-derivation.// Must run before `requestSingleInstanceLock()` and any `userData` read;// packaged builds ignore it so releases are never affected.if (!app.isPackaged) {- // Auto-derivation is for humans running `bun run dev` from a worktree; keep it+ // Auto-derivation is for humans running `pnpm dev` from a worktree; keep it// out of the E2E desktop smoke, which drives an unpackaged build on a feature// branch. Deriving there would run git on the launch path and relocate// `userData` on every smoke launch. Explicit `OK_INSTANCE` still wins, so adiff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.tsindex 0c7208dfc..eeff94ab3 100644--- a/packages/desktop/src/main/ipc/bug-report.test.ts+++ b/packages/desktop/src/main/ipc/bug-report.test.ts@@ -7,13 +7,16 @@* call whose ctx-resolution behavior is shared with every project-scoped IPC* and covered by the existing main-side siblings.*- * HOME and the `OK_DESKTOP_*` block are snapshot/restored around every test:- * bun runs all test files in one process, so an unrestored env mutation here- * becomes a load-order-dependent failure in another suite.+ * HOME and the `OK_DESKTOP_*` block are snapshot/restored around every test.+ * Vitest forks a worker per test file, so the blast radius stops at this file+ * — but every test inside it shares that one process, and these are exactly+ * the variables the bundle collector reads, so an unrestored mutation makes a+ * later test here depend on which test ran before it.*/import { execFileSync, execSync } from 'node:child_process';import {+ appendFileSync,existsSync,mkdirSync,mkdtempSync,@@ -48,8 +51,12 @@ import {handleBugReportCreate,handleBugReportSend,MAX_UPLOAD_ZIP_BYTES,+ type MinidumpIntent,+ type OkBugReportCreateRequest,parseTransportSafeUrl,resolveBugReportIntakeUrl,+ resolveMinidumpAttachment,+ resolveMinidumpIntent,} from './bug-report.ts';const tmpDirs: string[] = [];@@ -131,6 +138,48 @@ function makeDeps(overrides: Partial<BugReportCreateDeps> = {}): BugReportCreate};}+/** One report-time minidump lookup result, defaulting to "nothing was skipped". */+function dumpLookup(path: string | null, foreignSkipped = 0, unknownSkipped = 0) {+ return { path, foreignSkipped, unknownSkipped };+}++/**+ * Records what the handler logged, so the crash-dump decision lines can be+ * asserted on. The real desktop logger is level-silent under NODE_ENV=test and+ * writes async, so the injected sink is the only observable.+ */+function makeLogRecorder() {+ const lines: Array<{+ level: 'info' | 'warn';+ payload: Record<string, unknown>;+ message: string;+ }> = [];+ const ofPhase = (phase: 'intent' | 'outcome') => {+ const found = lines.filter(+ (l) => l.payload.event === 'bug-report.minidump-decision' && l.payload.phase === phase,+ );+ if (found.length > 1) throw new Error(`expected at most one ${phase}, got ${found.length}`);+ return found[0];+ };+ return {+ lines,+ logger: {+ info: (payload: Record<string, unknown>, message: string) => {+ lines.push({ level: 'info', payload, message });+ },+ warn: (payload: Record<string, unknown>, message: string) => {+ lines.push({ level: 'warn', payload, message });+ },+ },+ /** The pre-collection record — the one that can reach the bundle it describes. */+ intent: () => ofPhase('intent'),+ /** The post-collection confirmation, emitted only for a dump that was on hand. */+ outcome: () => ofPhase('outcome'),+ /** Every decision line, whichever phase, for exhaustive payload sweeps. */+ decisions: () => lines.filter((l) => l.payload.event === 'bug-report.minidump-decision'),+ };+}+describe('handleBugReportCreate — project bundle', () => {test('builds the zip at the returned path with the project content set and the note', async () => {const projectDir = makeProjectDir();@@ -264,10 +313,10 @@ describe('handleBugReportCreate — no project (system-wide)', () => {});test('defaults the destination to ~/.ok/bug-reports/<timestamp>-bugreport.zip', () => {- // Bun resolves `os.homedir()` at process launch, so the default path can- // only be steered hermetically by a subprocess launched with a fake HOME- // (mutating `process.env.HOME` in this process would not take, and the- // real `~/.ok` must never be touched by tests).+ // The default path resolves through `homedir()`, so steering it means+ // steering HOME. A subprocess with a fake HOME keeps that mutation out of+ // this process entirely — every other test in this file shares it — while+ // still proving the real `~/.ok` is never where a test writes.const fakeHome = makeTmpDir('ok-bugreport-home-');const userLogsDir = makeTmpDir();const driverDir = makeTmpDir('ok-bugreport-driver-');@@ -1195,7 +1244,7 @@ describe('handleBugReportCreate — crash-dump opt-in', () => {Buffer.from([0x00, 0x9c]),]);writeFileSync(dumpPath, dumpBytes);- const deps = makeDeps({ newestMinidumpPath: () => dumpPath });+ const deps = makeDeps({ newestMinidumpForReport: () => dumpLookup(dumpPath) });const result = await handleBugReportCreate(deps, {kind: 'create',@@ -1213,7 +1262,7 @@ describe('handleBugReportCreate — crash-dump opt-in', () => {test('without the opt-in no minidump is included even when one exists', async () => {const dumpPath = join(makeTmpDir(), 'renderer-crash.dmp');writeFileSync(dumpPath, 'dump-bytes');- const deps = makeDeps({ newestMinidumpPath: () => dumpPath });+ const deps = makeDeps({ newestMinidumpForReport: () => dumpLookup(dumpPath) });const result = await handleBugReportCreate(deps, { kind: 'create', level: 'standard' });@@ -1222,7 +1271,7 @@ describe('handleBugReportCreate — crash-dump opt-in', () => {});test('opting in with no relevant dump on disk still builds the bundle', async () => {- const deps = makeDeps({ newestMinidumpPath: () => null });+ const deps = makeDeps({ newestMinidumpForReport: () => dumpLookup(null) });const result = await handleBugReportCreate(deps, {kind: 'create',@@ -1236,15 +1285,10 @@ describe('handleBugReportCreate — crash-dump opt-in', () => {test('an opted-in dump that vanished before staging is warned about, never dropped silently', async () => {const vanishedDump = join(makeTmpDir(), 'already-cleaned.dmp');- const warnings: Array<{ payload: Record<string, unknown>; message: string }> = [];+ const recorder = makeLogRecorder();const deps = makeDeps({- newestMinidumpPath: () => vanishedDump,- logger: {- info: () => {},- warn: (payload, message) => {- warnings.push({ payload, message });- },- },+ newestMinidumpForReport: () => dumpLookup(vanishedDump),+ logger: recorder.logger,});const result = await handleBugReportCreate(deps, {@@ -1255,12 +1299,17 @@ describe('handleBugReportCreate — crash-dump opt-in', () => {if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);expect(listZipEntries(result.zipPath).some((e) => e.startsWith('extra/'))).toBe(false);- expect(warnings).toHaveLength(1);- expect(warnings[0]?.payload.sourcePath).toBe(vanishedDump);+ // Two independent lines, and both must survive: the collector reports the+ // unreadable source, the handler reports that the decision came out as a+ // failure. Collapsing them would put the record back at the mercy of the+ // collector happening to log.+ const collectorWarn = recorder.lines.find((l) => l.payload.sourcePath !== undefined);+ expect(collectorWarn?.payload.sourcePath).toBe(vanishedDump);+ expect(recorder.outcome()?.payload.reason).toBe('stage-failed');});test('a non-boolean includeCrashDump is refused as invalid-request', async () => {- const deps = makeDeps({ newestMinidumpPath: () => '/never-read.dmp' });+ const deps = makeDeps({ newestMinidumpForReport: () => dumpLookup('/never-read.dmp') });const result = await handleBugReportCreate(deps, {kind: 'create',@@ -1272,6 +1321,588 @@ describe('handleBugReportCreate — crash-dump opt-in', () => {});});+/**+ * A bundle that arrives with no crash dump has several very different causes,+ * and before this record they were indistinguishable in triage. Each test here+ * pins one cause to one enum value.+ */+describe('handleBugReportCreate — crash-dump decision record', () => {+ function seedDump(name = 'renderer-crash.dmp', bytes = Buffer.from([0x4d, 0x44, 0x4d, 0x50])) {+ const dumpPath = join(makeTmpDir(), name);+ writeFileSync(dumpPath, bytes);+ return dumpPath;+ }++ /**+ * Writes where the real desktop logger writes — into the user-logs dir the+ * collector snapshots — and does it synchronously, standing in for the+ * production destination plus its flush. The only way to prove the record+ * reaches the bundle rather than merely getting emitted.+ */+ function makeFileLogger(userLogsDir: string) {+ const logPath = join(userLogsDir, 'desktop.2026-01-01.log');+ const write = (level: 'info' | 'warn') => (payload: object, message: string) => {+ appendFileSync(logPath, `${JSON.stringify({ level, ...payload, msg: message })}\n`);+ };+ return { info: write('info'), warn: write('warn') };+ }++ /**+ * The file-logger's asynchronous sibling: lines sit in memory until+ * `flushLogger` drains them, which is how the production destination+ * (`pino.destination({ sync: false })`) behaves. Writing the record before+ * collection is necessary but not sufficient against that destination — only+ * the drain makes the bytes visible to the collector's read.+ *+ * The log file is seeded the way a running app's already is, so a record that+ * never got drained fails as a missing LINE rather than a missing file.+ */+ function makeDeferredFileLogger(userLogsDir: string) {+ const logPath = join(userLogsDir, 'desktop.2026-01-01.log');+ writeFileSync(logPath, `${JSON.stringify({ level: 'info', msg: 'app ready' })}\n`);+ const buffered: string[] = [];+ const write = (level: 'info' | 'warn') => (payload: object, message: string) => {+ buffered.push(`${JSON.stringify({ level, ...payload, msg: message })}\n`);+ };+ return {+ logger: { info: write('info'), warn: write('warn') },+ flush: () => {+ appendFileSync(logPath, buffered.join(''));+ buffered.length = 0;+ },+ };+ }++ /** The decision records the bundle itself carries, parsed out of its log entry. */+ function decisionsInBundle(zipPath: string): Record<string, unknown>[] {+ return readZipEntry(zipPath, 'logs/desktop.2026-01-01.log')+ .split('\n')+ .filter((l) => l.includes('bug-report.minidump-decision'))+ .map((l) => JSON.parse(l) as Record<string, unknown>);+ }++ test('the intent record is inside the bundle it explains, not some later one', async () => {+ const userLogsDir = makeTmpDir();+ const deps = makeDeps({+ userLogsDir,+ logger: makeFileLogger(userLogsDir),+ newestMinidumpForReport: () => dumpLookup(null, 1, 0),+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ // The collector reads the log file's bytes as it runs, so a record written+ // after it returns can only ever reach triage in the NEXT report. This is+ // the whole point of the split: the terminal reasons land in the bundle.+ expect(decisionsInBundle(result.zipPath)).toEqual([+ expect.objectContaining({ phase: 'intent', reason: 'none-available', requested: true }),+ ]);+ });++ test('against a buffering destination only the drain gets the intent into the bundle', async () => {+ const userLogsDir = makeTmpDir();+ const deferred = makeDeferredFileLogger(userLogsDir);+ const deps = makeDeps({+ userLogsDir,+ logger: deferred.logger,+ flushLogger: deferred.flush,+ newestMinidumpForReport: () => dumpLookup(null, 1, 0),+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ // The sibling test above proves the record is written before collection; a+ // synchronous writer would land it there whether or not anything drained.+ // Here ordering alone buys nothing: drop the `flushLogger` call, or move it+ // after `collectReportBundle`, and the line is still in memory when the+ // collector snapshots the file — the bundle comes back with the seed line+ // and no decision record.+ expect(decisionsInBundle(result.zipPath)).toEqual([+ expect.objectContaining({ phase: 'intent', reason: 'none-available', requested: true }),+ ]);+ });++ test('an on-hand dump leaves an intent record the bundle can be read against', async () => {+ const userLogsDir = makeTmpDir();+ const deps = makeDeps({+ userLogsDir,+ logger: makeFileLogger(userLogsDir),+ newestMinidumpForReport: () => dumpLookup(seedDump()),+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ // `staging` plus the bundle's own `extra/` is the pairing: the outcome+ // record cannot be in here, so the entry has to be readable as the answer.+ expect(decisionsInBundle(result.zipPath)).toEqual([+ expect.objectContaining({ phase: 'intent', reason: 'staging' }),+ ]);+ expect(listZipEntries(result.zipPath)).toContain('extra/renderer-crash.dmp');+ });++ test('the full level puts the intent in the bundle and leaves the outcome out', async () => {+ const userLogsDir = makeTmpDir();+ const deps = makeDeps({+ projectDir: makeProjectDir(),+ userLogsDir,+ logger: makeFileLogger(userLogsDir),+ newestMinidumpForReport: () => dumpLookup(seedDump()),+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'full',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ // The in-memory recorder cannot tell "written before collection" from+ // "written after and recorded anyway", and the full level is the one a+ // crash invite actually sends. Read against the finished zip instead: the+ // intent is in it, and the outcome — which lands after the bytes are+ // snapshotted — provably is not.+ expect(decisionsInBundle(result.zipPath)).toEqual([+ expect.objectContaining({ phase: 'intent', reason: 'staging' }),+ ]);+ // The full level names its entries by walking the staging dir rather than+ // by the standard level's literal push. The `attached` inference is only+ // sound while both spell the entry the same way, so pin the name in the+ // inventory the inference reads AND in the zip a triager opens.+ expect(result.summary.files).toContain('extra/renderer-crash.dmp');+ expect(listZipEntries(result.zipPath)).toContain('extra/renderer-crash.dmp');+ });++ test('a staged dump records attached at outcome, with the size read up front', async () => {+ const dumpPath = seedDump();+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(dumpPath),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(recorder.intent()?.payload).toMatchObject({+ event: 'bug-report.minidump-decision',+ phase: 'intent',+ requested: true,+ reason: 'staging',+ minidumpAvailable: true,+ sizeBytes: 4,+ });+ // Nothing is settled yet, so the intent record must not claim it is.+ expect(recorder.intent()?.payload).not.toHaveProperty('attached');+ expect(recorder.outcome()?.level).toBe('info');+ expect(recorder.outcome()?.payload).toMatchObject({+ phase: 'outcome',+ attached: true,+ reason: 'attached',+ sizeBytes: 4,+ });+ });++ test('the production level — a crash invite sends full — still infers attached', async () => {+ // The full level builds its inventory through a completely separate+ // implementation (a staging-dir walk) from the standard level's literal+ // push, and a crash invite always sends `full`. The inference depends on+ // the two agreeing on the entry name.+ const dumpPath = seedDump();+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ projectDir: makeProjectDir(),+ newestMinidumpForReport: () => dumpLookup(dumpPath),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'full',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(listZipEntries(result.zipPath)).toContain('extra/renderer-crash.dmp');+ expect(recorder.outcome()?.payload).toMatchObject({ attached: true, reason: 'attached' });+ });++ test('the full level records stage-failed rather than failing the whole report', async () => {+ // The full-level collector tests for existence and then copies, so a dump+ // cleaned up in between used to throw out of collection and lose the report+ // along with any account of why.+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ projectDir: makeProjectDir(),+ newestMinidumpForReport: () => dumpLookup(join(makeTmpDir(), 'already-cleaned.dmp')),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'full',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(recorder.outcome()?.level).toBe('warn');+ expect(recorder.outcome()?.payload).toMatchObject({ reason: 'stage-failed' });+ });++ test('unchecking the offered box records declined without consulting the lookup', async () => {+ const recorder = makeLogRecorder();+ let lookupCalls = 0;+ const deps = makeDeps({+ newestMinidumpForReport: () => {+ lookupCalls += 1;+ return dumpLookup(seedDump());+ },+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: false,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(recorder.intent()?.payload).toMatchObject({+ requested: false,+ reason: 'declined',+ });+ // Settled before collection, so there is nothing left for an outcome to say.+ expect(recorder.outcome()).toBeUndefined();+ // The lookup walks the crash-dumps dir and parses dump headers. Hoisting it+ // out of the opt-in guard would charge every ordinary bug report for that.+ expect(lookupCalls).toBe(0);+ expect(recorder.intent()?.payload).not.toHaveProperty('minidumpAvailable');+ });++ test('a report with no crash checkbox in play records not-offered', async () => {+ const recorder = makeLogRecorder();+ let lookupCalls = 0;+ const deps = makeDeps({+ newestMinidumpForReport: () => {+ lookupCalls += 1;+ return dumpLookup(null);+ },+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'standard' });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(recorder.intent()?.payload).toMatchObject({+ requested: false,+ reason: 'not-offered',+ });+ expect(recorder.outcome()).toBeUndefined();+ expect(lookupCalls).toBe(0);+ });++ test('opting in with nothing attachable records none-available plus what was skipped', async () => {+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(null, 2, 1),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ // Without the counts this case reads the same as a crash that genuinely+ // wrote no dump, which is the shape that made a real report undiagnosable.+ expect(recorder.intent()?.payload).toMatchObject({+ requested: true,+ reason: 'none-available',+ minidumpAvailable: false,+ foreignDumpsIgnored: 2,+ unreadableDumpsSkipped: 1,+ });+ expect(recorder.intent()?.payload).not.toHaveProperty('sizeBytes');+ expect(recorder.outcome()).toBeUndefined();+ });++ test('a dump that never reached the bundle records stage-failed at warn level', async () => {+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(join(makeTmpDir(), 'already-cleaned.dmp')),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(recorder.intent()?.payload).toMatchObject({ reason: 'staging' });+ expect(recorder.outcome()?.level).toBe('warn');+ expect(recorder.outcome()?.payload).toMatchObject({+ requested: true,+ attached: false,+ reason: 'stage-failed',+ minidumpAvailable: true,+ });+ });++ test('a screenshot riding along in extra/ does not make an absent dump read as attached', async () => {+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(join(makeTmpDir(), 'already-cleaned.dmp')),+ screenshotPngBytes: () => Buffer.from([0x89, 0x50, 0x4e, 0x47]),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ includeScreenshot: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ // `extra/` is shared, so a prefix test would call this attached.+ expect(listZipEntries(result.zipPath)).toContain('extra/screenshot.png');+ expect(recorder.outcome()?.payload.reason).toBe('stage-failed');+ });++ test('a dump and a screenshot both staged still records attached', async () => {+ const dumpPath = seedDump();+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(dumpPath),+ screenshotPngBytes: () => Buffer.from([0x89, 0x50, 0x4e, 0x47]),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ includeScreenshot: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(listZipEntries(result.zipPath)).toContain('extra/screenshot.png');+ expect(recorder.outcome()?.payload.reason).toBe('attached');+ });++ test('a rejected request records nothing — no decision was ever made', async () => {+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup('/never-read.dmp'),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: 'yes',+ } as unknown as Parameters<typeof handleBugReportCreate>[1]);++ expect(result.ok).toBe(false);+ expect(recorder.decisions()).toEqual([]);+ });++ test('a bundle that failed to build still records the intent, but no outcome', async () => {+ const recorder = makeLogRecorder();+ // The collector creates its destination directory, so block it with a+ // regular file where that directory would go.+ const blockedRoot = makeTmpDir();+ writeFileSync(join(blockedRoot, 'blocker'), 'not-a-directory');+ const deps = makeDeps({+ outputPath: join(blockedRoot, 'blocker', 'report.zip'),+ newestMinidumpForReport: () => dumpLookup(seedDump()),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ expect(result.ok).toBe(false);+ // The intent was real even though the bundle was not; the outcome has no+ // inventory to read, so it stays silent rather than guessing.+ expect(recorder.intent()?.payload).toMatchObject({ reason: 'staging' });+ expect(recorder.outcome()).toBeUndefined();+ });++ test('a sink that throws on the decision records never fails the report', async () => {+ // Scoped to the decision records on purpose. The collector's own logging+ // is not fail-soft against a throwing sink and is governed separately; a+ // logger that threw on everything would abort inside collection and prove+ // nothing about these two calls.+ let thrown = 0;+ const throwOnDecision = (payload: Record<string, unknown>) => {+ if (payload.event !== 'bug-report.minidump-decision') return;+ thrown += 1;+ throw new Error('log sink is down');+ };+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(seedDump()),+ logger: { info: throwOnDecision, warn: throwOnDecision },+ flushLogger: () => {+ throw new Error('drain failed');+ },+ });++ // Observation is not the product: a broken sink loses the record, not the+ // bundle the user is trying to send.+ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(listZipEntries(result.zipPath)).toContain('extra/renderer-crash.dmp');+ // Both records, and the drain between them, were attempted and swallowed.+ expect(thrown).toBe(2);+ });++ test('no decision record on any branch names the dump', async () => {+ const dumpName = 'renderer-crash-0BADF00D.dmp';+ // Every branch that emits: each terminal intent, and both outcomes. A path+ // added to any one of them has to fail here — the bytes are unredactable+ // process memory and Crashpad names each dump per crash.+ const branches: Array<{+ lookupPath: string | null;+ request: Partial<OkBugReportCreateRequest>;+ }> = [+ { lookupPath: null, request: {} },+ { lookupPath: seedDump(dumpName), request: { includeCrashDump: false } },+ { lookupPath: null, request: { includeCrashDump: true } },+ { lookupPath: seedDump(dumpName), request: { includeCrashDump: true } },+ { lookupPath: join(makeTmpDir(), dumpName), request: { includeCrashDump: true } },+ ];++ const seen = new Set<string>();+ for (const branch of branches) {+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(branch.lookupPath),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ ...branch.request,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ const records = recorder.decisions();+ expect(records.length).toBeGreaterThan(0);+ for (const record of records) {+ seen.add(String(record.payload.reason));+ // The message is a fixed string today, but it rides the same sink,+ // so sweep both halves of the record together.+ const serialized = `${JSON.stringify(record.payload)} ${record.message}`;+ if (branch.lookupPath !== null) {+ expect(serialized).not.toContain(branch.lookupPath);+ expect(serialized).not.toContain(dirname(branch.lookupPath));+ }+ expect(serialized).not.toContain(dumpName);+ expect(serialized).not.toContain('renderer-crash');+ expect(serialized).not.toContain('.dmp');+ expect(serialized).not.toContain('extra/');+ }+ }+ // Pins the sweep to the full vocabulary: a sixth reason with a fresh+ // payload shape has to be added above rather than silently skipped.+ expect([...seen].sort()).toEqual(+ ['attached', 'declined', 'none-available', 'not-offered', 'staging', 'stage-failed'].sort(),+ );+ });+});++describe('resolveMinidumpIntent', () => {+ const cases: Array<{+ name: string;+ input: Parameters<typeof resolveMinidumpIntent>[0];+ expected: MinidumpIntent;+ }> = [+ {+ name: 'never offered',+ input: { requested: undefined, minidumpPath: '/dumps/a.dmp' },+ expected: { reason: 'not-offered' },+ },+ {+ name: 'offered and unchecked',+ input: { requested: false, minidumpPath: '/dumps/a.dmp' },+ expected: { reason: 'declined' },+ },+ {+ name: 'opted in, nothing the app can prove it owns',+ input: { requested: true, minidumpPath: null },+ expected: { reason: 'none-available' },+ },+ {+ name: 'opted in with a dump on hand',+ input: { requested: true, minidumpPath: '/dumps/a.dmp' },+ expected: { reason: 'staging', zipEntry: 'extra/a.dmp' },+ },+ ];++ for (const { name, input, expected } of cases) {+ test(name, () => {+ expect(resolveMinidumpIntent(input)).toEqual(expected);+ });+ }+});++describe('resolveMinidumpAttachment', () => {+ const staging = { reason: 'staging', zipEntry: 'extra/a.dmp' } as const;++ test('the entry the dump was staged under is in the inventory', () => {+ expect(resolveMinidumpAttachment(staging, ['sysinfo.json', 'extra/a.dmp'])).toEqual({+ attached: true,+ reason: 'attached',+ });+ });++ test('another extra/ entry is not the dump', () => {+ expect(resolveMinidumpAttachment(staging, ['sysinfo.json', 'extra/screenshot.png'])).toEqual({+ attached: false,+ reason: 'stage-failed',+ });+ });++ test('an empty inventory is a staging failure, not an attach', () => {+ expect(resolveMinidumpAttachment(staging, [])).toEqual({+ attached: false,+ reason: 'stage-failed',+ });+ });+});+describe('handleBugReportCreate — screenshot opt-in', () => {// A PNG signature wrapping a would-be-redacted token: the screenshot must// arrive byte-identical — images ride the `extra/` seam raw, never scrubbed.@@ -1322,7 +1953,7 @@ describe('handleBugReportCreate — screenshot opt-in', () => {const dumpBytes = Buffer.from([0x4d, 0x44, 0x4d, 0x50, 0x00, 0xff]);writeFileSync(dumpPath, dumpBytes);const deps = makeDeps({- newestMinidumpPath: () => dumpPath,+ newestMinidumpForReport: () => dumpLookup(dumpPath),screenshotPngBytes: () => pngBytes,});diff --git a/packages/desktop/src/main/ipc/bug-report.ts b/packages/desktop/src/main/ipc/bug-report.tsindex 8d4897d56..91a627ea2 100644--- a/packages/desktop/src/main/ipc/bug-report.ts+++ b/packages/desktop/src/main/ipc/bug-report.ts@@ -37,6 +37,7 @@ import {type ReportBundleLevel,} from '@inkeep/open-knowledge-core';import type { OkBugReportSendInput } from '@inkeep/open-knowledge-core/desktop-bridge';+import type { MinidumpReportLookup } from '../crash-detection.ts';import { logIpcError } from '../ipc-log.ts';import { isPathWithinProject } from '../path-containment.ts';import type { UpdateChannel } from '../state-store.ts';@@ -123,11 +124,13 @@ export interface BugReportCreateDeps {userLogsDir?: string;/*** Crash-detection lookup for the newest un-acked minidump (wired from- * `CrashDetection.newestMinidumpPath`). Only consulted when the renderer- * opted in via `includeCrashDump`; absent or returning null simply omits- * the dump.+ * `CrashDetection.newestMinidumpForReport`). Only consulted when the renderer+ * opted in via `includeCrashDump` — the lookup walks the crash-dumps dir and+ * parses dump headers, so calling it on every report would charge an ordinary+ * bug report for a crash artifact it never wanted. Absent, or returning a null+ * path, simply omits the dump; the lookup's skip counts explain which.*/- newestMinidumpPath?: () => string | null;+ newestMinidumpForReport?: () => MinidumpReportLookup;/*** Main-owned PNG bytes of the screenshot captured when the report dialog* opened, consulted only when the renderer opted in via `includeScreenshot`.@@ -142,6 +145,14 @@ export interface BugReportCreateDeps {* silent omission from the bundle.*/logger?: BundleLogger;+ /**+ * Drain `logger`'s buffer to disk. The desktop destination is asynchronous,+ * so a line emitted moments before the collector reads the log file can+ * still be in memory when those bytes are snapshotted — which would keep the+ * crash-dump record out of the very bundle it explains. Absent in tests,+ * where the logger is a synchronous in-memory recorder.+ */+ flushLogger?: () => void;/*** Persist the report's `generated` sidecar (and run the retention sweep)* after a bundle is written. Injected so the durable-record write is exercised@@ -152,10 +163,6 @@ export interface BugReportCreateDeps {onReportGenerated?: (meta: GeneratedReportMeta) => Promise<void>;}-/**- * `createHandler` casts renderer args without runtime enforcement, so the- * payload is re-validated here before any filesystem work.- *//*** Ceiling on the free-text note the renderer may hand to `create`/`send`. A* genuine "what happened?" note is a sentence or two; this refuses an abusive@@ -169,6 +176,10 @@ function isValidNote(note: unknown): boolean {return note === undefined || (typeof note === 'string' && note.length <= MAX_NOTE_LENGTH);}+/**+ * `createHandler` casts renderer args without runtime enforcement, so the+ * payload is re-validated here before any filesystem work.+ */function isCreateRequest(request: unknown): request is OkBugReportCreateRequest {if (typeof request !== 'object' || request === null) return false;const r = request as Record<string, unknown>;@@ -181,6 +192,113 @@ function isCreateRequest(request: unknown): request is OkBugReportCreateRequest);}+/**+ * Why a bundle did or did not carry a crash minidump. A bundle that arrives+ * without one is otherwise unexplainable after the fact: the reporter having+ * unchecked the box, no attachable dump existing, and a staging failure all+ * reach triage as the same empty `extra/`.+ *+ * Deliberately five values, not more. `foreign-only` and `unreadable-only`+ * would leave a mixed walk with no home, so what the ownership walk rejected+ * rides as two counts instead. `read-failed` and `disappeared` collapse into+ * `stage-failed` because neither collector distinguishes them: the standard+ * level catches every read error in one branch and the full level only tests+ * for existence, so both surface identically as an entry that never appeared.+ */+type MinidumpAttachReason =+ /** The dump was opted into and is in the bundle. */+ | 'attached'+ /** The checkbox was shown and the reporter unchecked it. */+ | 'declined'+ /** No checkbox was shown, so no dump was ever in play. */+ | 'not-offered'+ /** Opted in, but the lookup found no dump this app can prove it owns. */+ | 'none-available'+ /** Opted in with a dump on hand, but it never reached the bundle. */+ | 'stage-failed';++/** No lookup ran, so nothing was found and nothing was skipped. */+const NO_MINIDUMP_LOOKUP: MinidumpReportLookup = {+ path: null,+ foreignSkipped: 0,+ unknownSkipped: 0,+};++/** The one intent whose outcome only the finished bundle can settle. */+export interface StagingMinidumpIntent {+ reason: 'staging';+ /** Zip entry the dump will occupy if the collector places it. */+ zipEntry: string;+}++/**+ * What is knowable about the crash dump before the bundle is built. Three of+ * the five outcomes are already final here — they turn on the opt-in and the+ * lookup alone — and `staging` covers the one that still depends on whether+ * the collector managed to place the file. `Exclude` rather than a re-listed+ * union so a sixth reason cannot be added without deciding which side of+ * collection settles it.+ */+export type MinidumpIntent =+ | { reason: Exclude<MinidumpAttachReason, 'attached' | 'stage-failed'> }+ | StagingMinidumpIntent;++/**+ * Decide everything about the crash dump that does not require a finished+ * bundle. Owns the zip entry name too, so the name the dump is looked for+ * under is by construction the name it was staged under.+ */+export function resolveMinidumpIntent(input: {+ /** The renderer's opt-in, tri-state: unchecked, checked, or never offered. */+ requested: boolean | undefined;+ /** Absolute path the lookup found, or null when it found nothing attachable. */+ minidumpPath: string | null;+}): MinidumpIntent {+ if (input.requested === undefined) return { reason: 'not-offered' };+ if (input.requested === false) return { reason: 'declined' };+ if (input.minidumpPath === null) return { reason: 'none-available' };+ return { reason: 'staging', zipEntry: `extra/${basename(input.minidumpPath)}` };+}++/**+ * Settle a staged dump against the bundle's own inventory rather than against+ * the intent to stage, so a dump the collector silently dropped cannot report+ * as attached.+ *+ * The boolean is fully determined by the reason, so the return type pairs them+ * rather than leaving `{ attached: true, reason: 'stage-failed' }` expressible+ * — the same discriminated encoding `MinidumpIntent` uses.+ */+export function resolveMinidumpAttachment(+ intent: StagingMinidumpIntent,+ /** The bundle's captured entry names. */+ bundledFiles: readonly string[],+): { attached: true; reason: 'attached' } | { attached: false; reason: 'stage-failed' } {+ // Match the exact entry: `extra/` is shared with the opted-in screenshot, so+ // a prefix test reports a dump whenever a screenshot rode along.+ if (bundledFiles.includes(intent.zipEntry)) return { attached: true, reason: 'attached' };+ return { attached: false, reason: 'stage-failed' };+}++/**+ * Emit one crash-dump decision record. Observing the report must never be able+ * to fail a report that otherwise succeeded, so a logger that throws is+ * swallowed here — the same fail-soft posture as the sidecar write.+ */+function recordMinidumpDecision(+ deps: BugReportCreateDeps,+ level: 'info' | 'warn',+ payload: Record<string, unknown>,+ message: string,+): void {+ try {+ if (level === 'warn') deps.logger?.warn(payload, message);+ else deps.logger?.info(payload, message);+ } catch {+ // The logger is the thing that failed; there is nowhere left to report it.+ }+}+/*** Build the redacted bug-report bundle for the `create` operation. Never* throws — every failure mode maps to the discriminated `{ok: false}` result@@ -199,8 +317,15 @@ export async function handleBugReportCreate(});return { ok: false, error: 'invalid-request' };}- const minidumpPath =- request.includeCrashDump === true ? (deps.newestMinidumpPath?.() ?? null) : null;+ const minidumpLookup =+ request.includeCrashDump === true+ ? (deps.newestMinidumpForReport?.() ?? NO_MINIDUMP_LOOKUP)+ : NO_MINIDUMP_LOOKUP;+ const minidumpPath = minidumpLookup.path;+ const intent = resolveMinidumpIntent({+ requested: request.includeCrashDump,+ minidumpPath,+ });const screenshotBytes =request.includeScreenshot === true ? (deps.screenshotPngBytes?.() ?? null) : null;@@ -210,6 +335,52 @@ export async function handleBugReportCreate(// a picture of the user's screen must not linger in tmp once it is zipped.const extraFiles: { sourcePath: string; zipName?: string }[] = [];if (minidumpPath !== null) extraFiles.push({ sourcePath: minidumpPath });++ // Size is read here, not after collection, so it describes the dump as it+ // was when the decision was taken.+ const dumpSizeBytes =+ minidumpPath === null+ ? undefined+ : await stat(minidumpPath)+ .then((s) => s.size)+ .catch(() => undefined);+ // Deliberately says nothing about WHICH dump: a minidump is unredactable+ // process memory and its filename is a per-crash identifier, so the record+ // carries a size at most.+ const decisionFacts = {+ event: 'bug-report.minidump-decision',+ requested: request.includeCrashDump === true,+ ...(request.includeCrashDump === true+ ? {+ minidumpAvailable: minidumpPath !== null,+ // Counts ride the opted-in branch only, so they never appear on a+ // report where no dump was ever in play — a zero there would read as+ // "we walked the crash database and found it clean".+ foreignDumpsIgnored: minidumpLookup.foreignSkipped,+ unreadableDumpsSkipped: minidumpLookup.unknownSkipped,+ }+ : {}),+ ...(dumpSizeBytes !== undefined ? { sizeBytes: dumpSizeBytes } : {}),+ };++ // Written BEFORE the bundle is collected, because the collector snapshots+ // the log file's bytes as it runs: a line emitted afterwards can only reach+ // triage in some later report, which is the undiagnosable shape this record+ // exists to remove. Every terminal reason is already settled here, so a+ // bundle carrying only this line still explains itself; `staging` is the one+ // reason left open, and then the bundle's own `extra/` is the answer.+ recordMinidumpDecision(+ deps,+ 'info',+ { ...decisionFacts, phase: 'intent', reason: intent.reason },+ 'bug-report: crash-dump decision recorded before collection',+ );+ try {+ deps.flushLogger?.();+ } catch {+ // A failed drain costs the line its place in this bundle, nothing more.+ }+let screenshotTmpPath: string | null = null;try {if (screenshotBytes !== null) {@@ -257,6 +428,21 @@ export async function handleBugReportCreate();});}+ // Only a dump that was actually on hand has anything left to settle; the+ // other reasons were final before collection and said so. This line lands+ // in the NEXT report's logs, never this bundle — for this one, the pairing+ // is the intent line above plus whether `extra/` holds the dump.+ if (intent.reason === 'staging') {+ const { attached, reason } = resolveMinidumpAttachment(intent, summary.files);+ recordMinidumpDecision(+ deps,+ attached ? 'info' : 'warn',+ { ...decisionFacts, phase: 'outcome', attached, reason },+ attached+ ? 'bug-report: opted-in crash dump reached the bundle'+ : 'bug-report: opted-in crash dump did not reach the bundle',+ );+ }return { ok: true, zipPath, zipSizeBytes, summary };} catch (err) {// Environmental failure at the fs boundary (unwritable destination, disk