Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
PRD-8442: collect macOS DiagnosticReports into diagnostic bundles (#4040)
Andrew Mikofalvy477ae4b979aa
diff --git a/.changeset/rich-jars-shave.md b/.changeset/rich-jars-shave.mdnew file mode 100644index 000000000..01b63f071--- /dev/null+++ b/.changeset/rich-jars-shave.md@@ -0,0 +1,11 @@+---+'@inkeep/open-knowledge': patch+---++Detailed diagnostic bundles now collect the macOS crash reports the OS wrote for the app and its helpers, so an ending the app could not record itself can still be attributed.++When the operating system ends one of the app's processes, it writes its own report naming the cause: the signal or exception, the code-signing verdict, and whatever text the process left behind as it died. That record exists whether or not a crash handler ran to leave a dump, which is what makes it the only account of a whole class of endings, and those files were not being collected. A Detailed-level bundle now carries the matching ones under `diagnostic-reports/`, alongside a `state/diagnostic-reports-status.txt` record that says what the search found even when the answer is nothing, so a triage can tell "the OS recorded nothing" from "nobody looked".++Only this app's own reports are collected, never another application's, and they pass through the same redaction and secret-scrubbing as every other bundled file. macOS stores paths in these reports with every forward slash escaped, which the scrub cannot read, so a report is normalised as it enters a bundle rather than inside any one pass over it. The identifiers that link one machine's bundles to each other are replaced at the same point: measured over a year of real reports, `crashReporterKey` held one distinct value and `bootSessionUUID` two, so either re-identifies a user across every bundle they file. The per-incident id and the sleep/wake id are kept, since those are what correlating reports inside a bundle actually uses. The bug-report dialog's Detailed-diagnostics description, shown only on macOS, and the "What OpenKnowledge writes" reference both name the new category and what a report carries.++`ok diagnose bundle` collects them too, and prints what the search found before it writes the zip.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 214d1e208..437074fcb 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -44,6 +44,7 @@ On every platform the app writes app-level state and logs on launch. The table b| `~/.ok/mcp-status.json` | Records your first-launch MCP-setup consent choice | Outside-project (home dir) || `~/Library/Caches/@inkeepopen-knowledge-desktop-updater/` | Staged auto-update downloads (electron-updater) | Outside-project (home dir) || `~/Library/Caches/com.inkeep.open-knowledge.ShipIt/` | Install log of the macOS update helper (Squirrel's ShipIt), which swaps the app bundle after the app has quit. The only record of why an update failed to install, so a bug report you send collects it — only this app's, never those of other applications that use the same update mechanism | Outside-project (home dir) |+| `~/Library/Logs/DiagnosticReports/` | Not written by OpenKnowledge at all — this is macOS's own crash-report directory, shared by every application on the machine. When the OS ends one of this app's processes it records why there, which is sometimes the only account of a session that stopped without a crash dump, so a bug report you send at the **Detailed diagnostics** level collects the reports macOS wrote for this app and its helper processes — only ours, never those of any other application, and never at the standard level. A report also carries machine details macOS puts in every one of them — the account uid, the Mac model, and the name of the process that launched the app — while the identifiers that would link your bundles to each other, the crash-reporter key and the boot session, are replaced before bundling. `ok diagnose bundle` collects them too, on every run: that command produces the Detailed superset by design, and its summary tells you what the search found before it writes the zip | Outside-project (home dir) || `~/Library/Application Support/OpenKnowledge/Crashpad/` | Native crash minidumps, written by the OS crash handler (Electron's Crashpad) if the app ever crashes. Local-only: the crash reporter runs with `uploadToServer: false`, so no dump is ever uploaded automatically | Outside-project (home dir) || `~/Library/Application Support/OpenKnowledge/bug-report-dirty-shutdown.json` | Dirty-shutdown sentinel — written on **every** launch, refreshed as it runs, and removed on a clean quit. The next launch reads it to tell an app crash (prompts you) from the endings that are not a crash: a reboot, an OS shutdown, or dying asleep (all suppressed and logged instead), and an update install shutting the app down to replace its files (logged either way, and suppressed in almost every case: a shutdown the app had no chance to record, or one it cannot date because the previous session left no heartbeat, can still prompt so you are able to report it) | Outside-project (home dir) || `~/Library/Application Support/OpenKnowledge/bug-report-crash-acks.json` | Records which crash-report invitations you already answered or dismissed, so the same crash never re-prompts | Outside-project (home dir) |@@ -299,8 +300,8 @@ None of your content, by default. Everything above is written to your own disk.| What | When | Where it goes || --- | --- | --- |-| Diagnostic bundle | Only when you run `ok diagnose bundle` (you can inspect it first) | Wherever you send it |-| In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog, or the `Cmd+Shift+D` / `Ctrl+Shift+D` shortcut that opens the same dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. The zip carries a picture of the app window unless you uncheck **Screenshot** in that dialog, and the preview there is the picture that would be sent. A report reached through a surface you opened only to get to the reporter — the command palette, the Help popover, or the Windows and Linux menu bar — waits for that surface to close first, and carries no marker, because the row it would point at has already gone. Every other report you start yourself photographs the screen as it is, so an open menu or another person's document visible at the time is in the picture, and carries a marker drawn where your pointer was, since a screenshot never includes the cursor. No marker is drawn either if the pointer has not moved since the window loaded, or has since left the window. The invitation that appears on its own after a crash is the exception to all of this: it carries no picture at all. After a crash, the same dialog adds an **off-by-default** "Include crash dump" checkbox: a crash dump is a memory snapshot that can contain document content and can't be redacted, and it is only ever attached when you check that box. On macOS the zip also carries the update helper's install log (listed above), which is machine-wide rather than project-scoped; the zip's own README names it and says where it came from. The zip also carries a short send history of the bug reports previously generated on this machine — when each was generated and whether sending it succeeded — which is what makes a report that failed to send diagnosable at all. That history is machine-wide too, so it names the other projects you have filed reports from; it carries no document content, and the README names it the same way | By default, Send makes no network request — it opens a prefilled email draft to [email protected] that you send yourself, naming the zip to attach. Only when an operator has configured a bug-report intake endpoint ([`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables)) does Send upload the zip there, falling back to the same email draft if the upload fails |+| Diagnostic bundle | Only when you run `ok diagnose bundle` (you can inspect it first). On macOS it also carries the crash reports the OS recorded for this app and its helper processes (listed above), which are machine-wide rather than project-scoped; only this app's are collected, never another application's, and the summary printed before the zip is written says what that search found even when the answer is nothing | Wherever you send it |+| In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog, or the `Cmd+Shift+D` / `Ctrl+Shift+D` shortcut that opens the same dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. The zip carries a picture of the app window unless you uncheck **Screenshot** in that dialog, and the preview there is the picture that would be sent. A report reached through a surface you opened only to get to the reporter — the command palette, the Help popover, or the Windows and Linux menu bar — waits for that surface to close first, and carries no marker, because the row it would point at has already gone. Every other report you start yourself photographs the screen as it is, so an open menu or another person's document visible at the time is in the picture, and carries a marker drawn where your pointer was, since a screenshot never includes the cursor. No marker is drawn either if the pointer has not moved since the window loaded, or has since left the window. The invitation that appears on its own after a crash is the exception to all of this: it carries no picture at all. After a crash, the same dialog adds an **off-by-default** "Include crash dump" checkbox: a crash dump is a memory snapshot that can contain document content and can't be redacted, and it is only ever attached when you check that box. On macOS the zip also carries the update helper's install log (listed above), which is machine-wide rather than project-scoped; the zip's own README names it and says where it came from. At the **Detailed diagnostics** level — pre-checked on the invitation that follows a crash — it additionally carries the crash reports macOS itself recorded for this app and its helpers (also listed above), which are machine-wide for the same reason and named in the same README; only this app's are collected, never another application's, and the zip always says what that search found even when the answer is nothing. The zip also carries a short send history of the bug reports previously generated on this machine — when each was generated and whether sending it succeeded — which is what makes a report that failed to send diagnosable at all. That history is machine-wide too, so it names the other projects you have filed reports from; it carries no document content, and the README names it the same way | By default, Send makes no network request — it opens a prefilled email draft to [email protected] that you send yourself, naming the zip to attach. Only when an operator has configured a bug-report intake endpoint ([`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables)) does Send upload the zip there, falling back to the same email draft if the upload fails || Uninstall feedback | Only after an uninstall has already succeeded, and only if you pick a reason, type a note, or give an email address on the optional "Before you go" screen (desktop app) or prompt (`ok uninstall`). Skipping it, `--yes`, `--json`, and any non-interactive run send nothing | `openknowledge.ai/api/feedback` — the reason you picked, your note, your email address if you gave one, plus the app version and platform. It files one ticket for the team; nothing from your notes is included || Semantic search embeddings | Only when you enable [semantic search](./configuration.mdx#semantic-search) **and** set a key — off by default | Your configured embeddings provider (OpenAI by default) || GitHub sync / share | When you sync, clone, publish, or share | GitHub |diff --git a/packages/app/src/components/ReportBugDialog.dom.test.tsx b/packages/app/src/components/ReportBugDialog.dom.test.tsxindex cb38e2ccb..f5bef625a 100644--- a/packages/app/src/components/ReportBugDialog.dom.test.tsx+++ b/packages/app/src/components/ReportBugDialog.dom.test.tsx@@ -91,6 +91,7 @@ function installBridge(send?: (request: SendRequest) => Promise<OkBugReportSendResult>;captureScreenshot?: () => Promise<OkBugReportScreenshot | null>;crashDumpAvailability?: () => Promise<{ available: boolean }>;+ platform?: string;} = {},): BridgeLog {const log: BridgeLog = {@@ -103,6 +104,7 @@ function installBridge(crashDumpAvailabilityCalls: 0,};const bridge = {+ platform: handlers.platform ?? 'darwin',bugReport: {create: (request: CreateRequest) => {log.createCalls.push(request);@@ -285,6 +287,13 @@ describe('ReportBugDialog', () => {expect(screen.getByText('Adds telemetry, server state, and runtime info when available. Credentials are always removed; document names, if included, appear in cleartext (not redacted).',+ { exact: false },+ ),+ ).not.toBeNull();+ expect(+ screen.getByText(+ "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's.",+ { exact: false },),).not.toBeNull();@@ -296,6 +305,18 @@ describe('ReportBugDialog', () => {expect(screen.getByRole('button', { name: 'Create report' })).not.toBeNull();});+ test('omits the macOS crash-report sentence off macOS', async () => {+ installBridge({ platform: 'win32' });+ await renderDialog();++ expect(+ screen.getByText('Adds telemetry, server state, and runtime info when available.', {+ exact: false,+ }),+ ).not.toBeNull();+ expect(screen.queryByText(/crash reports macOS recorded/)).toBeNull();+ });+test('a system-wide report says up front that no project logs are included', async () => {installBridge();await renderDialog({ systemWide: true });diff --git a/packages/app/src/components/ReportBugDialogBody.tsx b/packages/app/src/components/ReportBugDialogBody.tsxindex b6a801d23..6165d42d6 100644--- a/packages/app/src/components/ReportBugDialogBody.tsx+++ b/packages/app/src/components/ReportBugDialogBody.tsx@@ -132,6 +132,8 @@ function ReportBugDialog({crashDumpAvailable: probedCrashDumpAvailable = false,}: ReportBugDialogProps) {const { t } = useLingui();+ const isMacOS =+ (typeof window !== 'undefined' ? window.okDesktop?.platform : undefined) === 'darwin';const [phase, setPhase] = useState<Phase>(COMPOSE_IDLE);const [note, setNote] = useState('');const [detailed, setDetailed] = useState(crashContext !== undefined || crashInvite !== undefined);@@ -376,7 +378,13 @@ function ReportBugDialog({Adds telemetry, server state, and runtime info when available. Credentialsare always removed; document names, if included, appear in cleartext (notredacted).- </Trans>+ </Trans>{' '}+ {isMacOS && (+ <Trans>+ It also adds the crash reports macOS recorded for OpenKnowledge and its+ helper processes, only ours and never another app's.+ </Trans>+ )}</p></div></div>diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex 4b37139df..f043e1327 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -4437,6 +4437,9 @@],"mPzgTS": ["فتح ", ["docName"]],"mR3uQg": ["تم حذف هذا الملف على الفرع الحالي (تعارض حذف/تعديل)."],+ "mRitpT": [+ "يضيف أيضًا تقارير الأعطال التي سجّلها macOS لـ OpenKnowledge وعملياتها المساعدة، تقاريرنا وحدها ولا تقارير أي تطبيق آخر أبدًا."+ ],"mToVM9": ["راسل ", ["agentName"]],"mU3j1b": ["إزالة العنصر ", ["0"]],"mVFyH-": [["accessibleLabel"], " (تعارض)"],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex e87ac3608..1046f8be2 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -7289,6 +7289,10 @@ msgstr "رابط المشاركة غير صالح."msgid "Invalid YAML"msgstr "YAML غير صالح"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "يضيف أيضًا تقارير الأعطال التي سجّلها macOS لـ OpenKnowledge وعملياتها المساعدة، تقاريرنا وحدها ولا تقارير أي تطبيق آخر أبدًا."+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex 5155a463f..3ee780c00 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -3821,6 +3821,9 @@],"mPzgTS": [["docName"], " খুলুন"],"mR3uQg": ["এই ফাইলটি বর্তমান ব্রাঞ্চে মুছে ফেলা হয়েছে (delete-modify দ্বন্দ্ব)।"],+ "mRitpT": [+ "এটি OpenKnowledge এবং এর সহায়ক প্রসেসগুলির জন্য macOS-এর রেকর্ড করা ক্র্যাশ রিপোর্টও যুক্ত করে, শুধু আমাদেরগুলি, কখনও অন্য কোনও অ্যাপের নয়।"+ ],"mToVM9": [["agentName"], "-কে বার্তা পাঠান"],"mU3j1b": ["আইটেম ", ["0"], " সরান"],"mVFyH-": [["accessibleLabel"], " (দ্বন্দ্ব)"],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex 6b8a4c51e..f44c976fc 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -7285,6 +7285,10 @@ msgstr "শেয়ার URL সঠিক নয়।"msgid "Invalid YAML"msgstr "অবৈধ YAML"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "এটি OpenKnowledge এবং এর সহায়ক প্রসেসগুলির জন্য macOS-এর রেকর্ড করা ক্র্যাশ রিপোর্টও যুক্ত করে, শুধু আমাদেরগুলি, কখনও অন্য কোনও অ্যাপের নয়।"+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex aec47cb98..576d6c6ae 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -3933,6 +3933,9 @@],"mPzgTS": ["Open ", ["docName"]],"mR3uQg": ["This file was deleted on the current branch (delete-modify conflict)."],+ "mRitpT": [+ "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+ ],"mToVM9": ["Message ", ["agentName"]],"mU3j1b": ["Remove item ", ["0"]],"mVFyH-": [["accessibleLabel"], " (conflict)"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 6113f39c3..3059d1f93 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -7289,6 +7289,10 @@ msgstr "Invalid share URL."msgid "Invalid YAML"msgstr "Invalid YAML"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex 6d41ab2a2..f0e90d7ba 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -4548,6 +4548,9 @@],"mPzgTS": ["Abrir ", ["docName"]],"mR3uQg": ["Este archivo se eliminó en la rama actual (conflicto delete-modify)."],+ "mRitpT": [+ "También añade los informes de fallos que macOS registró para OpenKnowledge y sus procesos auxiliares, solo los nuestros y nunca los de otra aplicación."+ ],"mToVM9": ["Escribir a ", ["agentName"]],"mU3j1b": ["Quitar el elemento ", ["0"]],"mVFyH-": [["accessibleLabel"], " (conflicto)"],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex f47ccc0c1..bb9a718a5 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -7289,6 +7289,10 @@ msgstr "URL para compartir no válida."msgid "Invalid YAML"msgstr "YAML no válido"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "También añade los informes de fallos que macOS registró para OpenKnowledge y sus procesos auxiliares, solo los nuestros y nunca los de otra aplicación."+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex 568fc3f51..b736c1468 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -4586,6 +4586,9 @@],"mPzgTS": ["Ouvrir ", ["docName"]],"mR3uQg": ["Ce fichier a été supprimé sur la branche actuelle (conflit delete-modify)."],+ "mRitpT": [+ "Il ajoute également les rapports de plantage que macOS a enregistrés pour OpenKnowledge et ses processus auxiliaires, uniquement les nôtres et jamais ceux d'une autre application."+ ],"mToVM9": ["Envoyer un message à ", ["agentName"]],"mU3j1b": ["Retirer l'élément ", ["0"]],"mVFyH-": [["accessibleLabel"], " (conflit)"],diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex bbd505604..9f23b5756 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -7289,6 +7289,10 @@ msgstr "URL de partage non valide."msgid "Invalid YAML"msgstr "YAML non valide"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "Il ajoute également les rapports de plantage que macOS a enregistrés pour OpenKnowledge et ses processus auxiliaires, uniquement les nôtres et jamais ceux d'une autre application."+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 4d8764cc7..35df32bee 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -3815,6 +3815,9 @@],"mPzgTS": [["docName"], " खोलें"],"mR3uQg": ["यह फ़ाइल वर्तमान ब्रांच पर हटा दी गई थी (delete-modify विरोध)।"],+ "mRitpT": [+ "यह OpenKnowledge और उसकी सहायक प्रक्रियाओं के लिए macOS द्वारा दर्ज की गई क्रैश रिपोर्ट भी जोड़ता है, केवल हमारी, कभी किसी अन्य ऐप की नहीं।"+ ],"mToVM9": [["agentName"], " को संदेश भेजें"],"mU3j1b": ["आइटम ", ["0"], " हटाएँ"],"mVFyH-": [["accessibleLabel"], " (टकराव)"],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 50e8e8e59..a89b6c23e 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -7285,6 +7285,10 @@ msgstr "साझा करने का URL अमान्य है।"msgid "Invalid YAML"msgstr "अमान्य YAML"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "यह OpenKnowledge और उसकी सहायक प्रक्रियाओं के लिए macOS द्वारा दर्ज की गई क्रैश रिपोर्ट भी जोड़ता है, केवल हमारी, कभी किसी अन्य ऐप की नहीं।"+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex 04988dc49..ba72ce45b 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -3970,6 +3970,9 @@],"mPzgTS": ["Buka ", ["docName"]],"mR3uQg": ["Berkas ini dihapus di cabang saat ini (konflik delete-modify)."],+ "mRitpT": [+ "Ini juga menambahkan laporan kerusakan yang direkam macOS untuk OpenKnowledge dan proses pembantunya, hanya milik kami dan tidak pernah milik aplikasi lain."+ ],"mToVM9": ["Kirim pesan ke ", ["agentName"]],"mU3j1b": ["Hapus item ", ["0"]],"mVFyH-": [["accessibleLabel"], " (konflik)"],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex ee7e2a2d1..ceada11dd 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -7285,6 +7285,10 @@ msgstr "URL berbagi tidak valid."msgid "Invalid YAML"msgstr "YAML tidak valid"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "Ini juga menambahkan laporan kerusakan yang direkam macOS untuk OpenKnowledge dan proses pembantunya, hanya milik kami dan tidak pernah milik aplikasi lain."+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex 765242180..815b8b228 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -3808,6 +3808,9 @@],"mPzgTS": [["docName"], " 열기"],"mR3uQg": ["이 파일은 현재 브랜치에서 삭제되었습니다 (delete-modify 충돌)."],+ "mRitpT": [+ "OpenKnowledge 및 해당 헬퍼 프로세스에 대해 macOS가 기록한 충돌 보고서도 추가합니다. 우리 것만 포함되며 다른 앱의 것은 절대 포함되지 않습니다."+ ],"mToVM9": [["agentName"], " 메시지"],"mU3j1b": ["항목 ", ["0"], " 제거"],"mVFyH-": [["accessibleLabel"], " (충돌)"],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 76c6887c8..c8c16d379 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -7289,6 +7289,10 @@ msgstr "잘못된 공유 URL입니다."msgid "Invalid YAML"msgstr "잘못된 YAML"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "OpenKnowledge 및 해당 헬퍼 프로세스에 대해 macOS가 기록한 충돌 보고서도 추가합니다. 우리 것만 포함되며 다른 앱의 것은 절대 포함되지 않습니다."+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex f969ace1b..16d2efb52 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -3933,6 +3933,9 @@],"mPzgTS": ["Ōƥēń ", ["docName"]],"mR3uQg": ["Ţĥĩś ƒĩĺē ŵàś ďēĺēţēď ōń ţĥē ćũŕŕēńţ ƀŕàńćĥ (ďēĺēţē-ḿōďĩƒŷ ćōńƒĺĩćţ)."],+ "mRitpT": [+ "Ĩţ àĺśō àďďś ţĥē ćŕàśĥ ŕēƥōŕţś ḿàćŌŚ ŕēćōŕďēď ƒōŕ ŌƥēńĶńōŵĺēďĝē àńď ĩţś ĥēĺƥēŕ ƥŕōćēśśēś, ōńĺŷ ōũŕś àńď ńēvēŕ àńōţĥēŕ àƥƥ'ś."+ ],"mToVM9": ["Ḿēśśàĝē ", ["agentName"]],"mU3j1b": ["Ŕēḿōvē ĩţēḿ ", ["0"]],"mVFyH-": [["accessibleLabel"], " (ćōńƒĺĩćţ)"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 7801c0fc3..ac45a11cb 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -7285,6 +7285,10 @@ msgstr ""msgid "Invalid YAML"msgstr ""+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr ""+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex e66a0e372..652f657a3 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -4454,6 +4454,9 @@],"mPzgTS": ["Abrir ", ["docName"]],"mR3uQg": ["Este arquivo foi excluído no ramo atual (conflito delete-modify)."],+ "mRitpT": [+ "Também adiciona os relatórios de falha que o macOS registrou para o OpenKnowledge e seus processos auxiliares, apenas os nossos e nunca os de outro aplicativo."+ ],"mToVM9": ["Enviar mensagem para ", ["agentName"]],"mU3j1b": ["Remover o item ", ["0"]],"mVFyH-": [["accessibleLabel"], " (conflito)"],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex afdffc1b0..a24d2f459 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -7285,6 +7285,10 @@ msgstr "URL de compartilhamento inválida."msgid "Invalid YAML"msgstr "YAML inválido"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "Também adiciona os relatórios de falha que o macOS registrou para o OpenKnowledge e seus processos auxiliares, apenas os nossos e nunca os de outro aplicativo."+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex 44d3c9e9b..7621d1b6f 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -4029,6 +4029,9 @@],"mPzgTS": [["docName"], " کھولیں"],"mR3uQg": ["یہ فائل موجودہ برانچ پر حذف کر دی گئی تھی (delete-modify تنازع)۔"],+ "mRitpT": [+ "یہ OpenKnowledge اور اس کے معاون پروسیسز کے لیے macOS کی ریکارڈ کردہ کریش رپورٹس بھی شامل کرتا ہے، صرف ہماری، کبھی کسی دوسری ایپ کی نہیں۔"+ ],"mToVM9": [["agentName"], " کو پیغام بھیجیں"],"mU3j1b": ["آئٹم ", ["0"], " ہٹائیں"],"mVFyH-": [["accessibleLabel"], " (تصادم)"],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex b8b4d0e21..b460585bd 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -7289,6 +7289,10 @@ msgstr "شیئر URL درست نہیں۔"msgid "Invalid YAML"msgstr "YAML درست نہیں"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "یہ OpenKnowledge اور اس کے معاون پروسیسز کے لیے macOS کی ریکارڈ کردہ کریش رپورٹس بھی شامل کرتا ہے، صرف ہماری، کبھی کسی دوسری ایپ کی نہیں۔"+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex d8dba2b55..7e82d6482 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -3472,6 +3472,9 @@"mPy9lS": ["把我现有的规格整理成一个按领域分组的链接索引,并标出与当前代码脱节的部分。"],"mPzgTS": ["打开 ", ["docName"]],"mR3uQg": ["此文件已在当前分支中删除(delete-modify 冲突)。"],+ "mRitpT": [+ "它还会添加 macOS 为 OpenKnowledge 及其辅助进程记录的崩溃报告,仅包含我们的报告,绝不包含其他应用的报告。"+ ],"mToVM9": ["给 ", ["agentName"], " 发消息"],"mU3j1b": ["移除项目 ", ["0"]],"mVFyH-": [["accessibleLabel"], "(冲突)"],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 77eb817be..0cbb073db 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -7289,6 +7289,10 @@ msgstr "共享链接无效。"msgid "Invalid YAML"msgstr "无效的 YAML"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "它还会添加 macOS 为 OpenKnowledge 及其辅助进程记录的崩溃报告,仅包含我们的报告,绝不包含其他应用的报告。"+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex 103010623..2f0b661d5 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -3496,6 +3496,9 @@"mPy9lS": ["把我現有的規格整理成一個依領域分組的連結索引,並標出和目前程式碼已經脫節的部分。"],"mPzgTS": ["開啟 ", ["docName"]],"mR3uQg": ["此檔案已在目前分支中刪除(delete-modify 衝突)。"],+ "mRitpT": [+ "它還會加入 macOS 為 OpenKnowledge 及其輔助程序記錄的當機報告,僅包含我們的報告,絕不包含其他應用程式的報告。"+ ],"mToVM9": ["傳訊息給 ", ["agentName"]],"mU3j1b": ["移除項目 ", ["0"]],"mVFyH-": [["accessibleLabel"], "(衝突)"],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 1da5ed4b2..a6af64070 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -7289,6 +7289,10 @@ msgstr "分享網址無效。"msgid "Invalid YAML"msgstr "無效的 YAML"+#: src/components/ReportBugDialogBody.tsx+msgid "It also adds the crash reports macOS recorded for OpenKnowledge and its helper processes, only ours and never another app's."+msgstr "它還會加入 macOS 為 OpenKnowledge 及其輔助程序記錄的當機報告,僅包含我們的報告,絕不包含其他應用程式的報告。"+#. placeholder {0}: prompt.cwd#. placeholder {1}: prompt.agentName#: src/components/acp/ThreadView.tsxdiff --git a/packages/cli/src/commands/bug-report-bundle.test.ts b/packages/cli/src/commands/bug-report-bundle.test.tsindex ca0a458df..af318f5df 100644--- a/packages/cli/src/commands/bug-report-bundle.test.ts+++ b/packages/cli/src/commands/bug-report-bundle.test.ts@@ -55,6 +55,38 @@ function makeProjectDir(slug = 'bundle-proj'): string {return projectDir;}+describe('collectStandardBundle — diagnostic-report staging count', () => {+ test('counts what reached the zip, not what the sweep selected', async () => {+ const projectDir = makeProjectDir();+ const reportsDir = makeTmpDir();+ const present = join(reportsDir, 'OpenKnowledge-present.ips');+ writeFileSync(+ present,+ `${JSON.stringify({ name: 'OpenKnowledge' })}\n{"procName":"OpenKnowledge"}\n`,+ );+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectStandardBundle({+ projectDir,+ redact: true,+ outputPath,+ diagnosticReports: {+ files: [present, join(reportsDir, 'OpenKnowledge-vanished.ips')],+ outcome: 'collected',+ foreignIgnored: 0,+ unparseable: 0,+ droppedOverCap: 0,+ windowDays: 7,+ },+ });++ expect(listZipEntries(zipPath)).toContain('diagnostic-reports/OpenKnowledge-present.ips');+ expect(readZipEntry(zipPath, 'state/diagnostic-reports-status.txt')).toBe(+ '1 collected (7d; 0 other-process report(s) ignored; 0 unparseable; 1 vanished before staging)\n',+ );+ });+});+describe('collectStandardBundle — project bundle', () => {test('packages lock/spawn-error, local sink logs, and sysinfo into the zip', async () => {const projectDir = makeProjectDir();diff --git a/packages/cli/src/commands/bug-report-bundle.ts b/packages/cli/src/commands/bug-report-bundle.tsindex 42f159a23..4339fd9f3 100644--- a/packages/cli/src/commands/bug-report-bundle.ts+++ b/packages/cli/src/commands/bug-report-bundle.ts@@ -13,6 +13,11 @@ import {import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';import type { ZipFile } from 'yazl';import type { DesktopMetadata } from '../diagnose/bundle.ts';+import {+ type DiagnosticReportCollection,+ prepareDiagnosticReportText,+ renderDiagnosticReportsStatus,+} from '../diagnose/diagnostic-reports.ts';import type { LanguageMetadata } from '../report-language.ts';import { redactContent, SECRET_PATTERN_NAMES } from './bug-report-redact.ts';import { DESKTOP_BUNDLE_ID } from './desktop-dispatch.ts';@@ -50,6 +55,7 @@ export interface CollectStandardBundleOptions {userLogsDir?: string;shipItLogFiles?: string[];bugReportLedgerFiles?: string[];+ diagnosticReports?: DiagnosticReportCollection;note?: string;extraFiles?: BundleExtraFile[];desktop?: DesktopMetadata | null;@@ -315,10 +321,11 @@ function addContentFiles(args: {}): void {for (const file of args.files) {try {+ const raw = readFileSync(file, 'utf8');addTextEntry({zipfile: args.zipfile,name: `${args.prefix}/${basename(file)}`,- content: readFileSync(file, 'utf8'),+ content: file.endsWith('.ips') ? prepareDiagnosticReportText(raw) : raw,redact: args.redact,revealDocNames: args.revealDocNames,bundleFiles: args.bundleFiles,@@ -354,6 +361,7 @@ export async function collectStandardBundle(? collectLocalSinkLogs(opts.projectDir): { files: [] };const shipItFiles = opts.shipItLogFiles ?? [];+ const diagnosticReportFiles = opts.diagnosticReports?.files ?? [];logger?.info({@@ -362,6 +370,7 @@ export async function collectStandardBundle(lockFileCount: lockFiles.length,localSinkFileCount: localSinkFiles.length,shipItLogFileCount: shipItFiles.length,+ diagnosticReportCount: diagnosticReportFiles.length,},'files collected',);@@ -413,6 +422,17 @@ export async function collectStandardBundle(logger,});+ addContentFiles({+ zipfile,+ files: diagnosticReportFiles,+ prefix: 'diagnostic-reports',+ redact,+ revealDocNames,+ bundleFiles,+ redactions,+ logger,+ });+for (const extra of opts.extraFiles ?? []) {try {const raw = readFileSync(extra.sourcePath);@@ -439,6 +459,20 @@ export async function collectStandardBundle(});}+ const diagnosticReportEntryNames = new Set(+ diagnosticReportFiles.map((f) => `diagnostic-reports/${basename(f)}`),+ );+ const diagnosticReportEntries = bundleFiles.filter((f) => diagnosticReportEntryNames.has(f));+ const diagnosticReportsStatus =+ opts.diagnosticReports === undefined+ ? 'not-collected (no collection attempted)'+ : renderDiagnosticReportsStatus(opts.diagnosticReports, diagnosticReportEntries.length);+ zipfile.addBuffer(+ Buffer.from(`${diagnosticReportsStatus}\n`, 'utf8'),+ 'state/diagnostic-reports-status.txt',+ );+ bundleFiles.push('state/diagnostic-reports-status.txt');+const sysinfoJson = JSON.stringify(sysinfo, null, 2);zipfile.addBuffer(Buffer.from(sysinfoJson, 'utf8'), 'sysinfo.json');bundleFiles.push('sysinfo.json');@@ -469,6 +503,26 @@ export async function collectStandardBundle(): [];+ const diagnosticReportCaveat =+ diagnosticReportEntries.length > 0+ ? [+ 'Crash reports under diagnostic-reports/ are rewritten on the way in,',+ 'independently of this setting: escaped path separators are normalised',+ 'so the scrub above can read them, and the identifiers that link this',+ "machine's bundles to each other are replaced. Nothing else is changed;",+ 'they are not byte-identical to the files macOS wrote.',+ ]+ : [];++ const noRedactDisclosure =+ diagnosticReportCaveat.length > 0+ ? [+ 'Redaction was disabled for this bundle; file contents are unmodified,',+ 'with one exception.',+ ...diagnosticReportCaveat,+ ]+ : ['Redaction was disabled for this bundle; file contents are unmodified.'];+const readme = ['# Bug Report Bundle','',@@ -503,6 +557,23 @@ export async function collectStandardBundle('',]: []),+ ...(diagnosticReportEntries.length > 0+ ? [+ 'Crash reports: written by macOS itself rather than by OpenKnowledge,',+ 'and machine-wide rather than scoped to any one project. They record',+ 'why the operating system ended a process of this app — the signal or',+ 'exception, the code-signing verdict, and whatever text the process',+ 'left behind as it died. They also carry machine details the OS puts',+ 'in every report: the account uid, the Mac model, and the name of the',+ 'process that launched this app, which on a managed machine can be',+ "internal tooling. The identifiers that would link this machine's",+ 'bundles to each other are replaced before bundling. Only this',+ "app's own reports are collected, never another application's, though",+ 'a report of ours still names the processes it ran alongside:',+ ...diagnosticReportEntries.map((f) => `- ${f}`),+ '',+ ]+ : []),...(ledgerEntries.length > 0? ['Send history: a small record for each bug report previously generated',@@ -523,10 +594,11 @@ export async function collectStandardBundle(? `${totalRedacted} line(s) were scrubbed across ${redactions.length} file(s).`: 'No redactions were needed.','See MANIFEST.json for the full redaction audit report.',+ ...diagnosticReportCaveat,'','This bundle is safe to attach to a GitHub issue.',]- : ['Redaction was disabled for this bundle; file contents are unmodified.']),+ : noRedactDisclosure),].join('\n');zipfile.addBuffer(Buffer.from(readme, 'utf8'), 'README.md');diff --git a/packages/cli/src/commands/diagnose-bundle.test.ts b/packages/cli/src/commands/diagnose-bundle.test.tsindex 974ac6b2a..792e0ebee 100644--- a/packages/cli/src/commands/diagnose-bundle.test.ts+++ b/packages/cli/src/commands/diagnose-bundle.test.ts@@ -55,6 +55,7 @@ function makeRunnerDeps(over: Partial<RunDiagnoseBundleDeps> = {}): {return 'y';},collectDeps: deterministicCollectDeps(),+ diagnosticReportsDir: makeTmpDir('ok-bundle-runner-reports-'),...over,};return { captured, deps };@@ -69,6 +70,77 @@ function readZipEntries(zipPath: string): string[] {.sort();}+describe('runDiagnoseBundle — macOS crash reports', () => {+ function writeReport(dir: string, fileName: string, name: string): void {+ const header = JSON.stringify({+ app_name: name,+ name,+ bug_type: '309',+ timestamp: '2026-05-28 14:00:00.00 +0000',+ });+ const body = JSON.stringify({ procName: name, asi: { [name]: ['abort() called'] } });+ writeAt(dir, fileName, `${header}\n${body}\n`.replaceAll('/', String.raw`\/`));+ }++ test('collects into the zip, and the summary says what it found', async () => {+ const contentDir = makeTmpDir();+ const reportsDir = makeTmpDir('ok-bundle-runner-reports-');+ writeReport(reportsDir, 'OpenKnowledge-2026-05-28-140000.ips', 'OpenKnowledge');+ writeReport(reportsDir, 'Slack-2026-05-28-140000.ips', 'Slack');+ const { deps, captured } = makeRunnerDeps({ diagnosticReportsDir: reportsDir });++ const result = await runDiagnoseBundle({ contentDir, yes: true }, deps);++ const entries = readZipEntries(result.outputPath ?? '');+ expect(entries).toContain('diagnostic-reports/OpenKnowledge-2026-05-28-140000.ips');+ expect(entries).not.toContain('diagnostic-reports/Slack-2026-05-28-140000.ips');+ expect(entries).toContain('state/diagnostic-reports-status.txt');+ const summaryLine = captured.logs.find((l) => l.includes('macOS crash reports:'));+ expect(summaryLine).toContain(+ '1 collected (7d; 1 other-process report(s) ignored; 0 unparseable)',+ );+ expect(summaryLine).not.toContain('not-collected');+ });++ test('reports an empty sweep rather than staying silent', async () => {+ const contentDir = makeTmpDir();+ const { deps, captured } = makeRunnerDeps();++ await runDiagnoseBundle({ contentDir, yes: true }, deps);++ expect(captured.logs.find((l) => l.includes('macOS crash reports:'))).toContain(+ 'none found in window',+ );+ });++ test('--no-redact names the crash-report rewrite as the exception', async () => {+ const contentDir = makeTmpDir();+ const reportsDir = makeTmpDir('ok-bundle-runner-reports-');+ writeReport(reportsDir, 'OpenKnowledge-2026-05-28-140000.ips', 'OpenKnowledge');+ const { deps, captured } = makeRunnerDeps({ diagnosticReportsDir: reportsDir });++ await runDiagnoseBundle({ contentDir, yes: true, redact: false }, deps);+ const allLogs = captured.logs.join('\n');++ expect(allLogs).toContain(+ 'NOT scrubbed (--no-redact): tokens and keys ship verbatim, crash reports excepted',+ );+ expect(allLogs).toContain('Not byte-identical to the files macOS wrote');+ });++ test('--no-redact promises no exception when no report was staged', async () => {+ const contentDir = makeTmpDir();+ const { deps, captured } = makeRunnerDeps();++ await runDiagnoseBundle({ contentDir, yes: true, redact: false }, deps);+ const allLogs = captured.logs.join('\n');++ expect(allLogs).toContain('NOT scrubbed (--no-redact): tokens and keys ship verbatim');+ expect(allLogs).not.toContain('crash reports excepted');+ expect(allLogs).not.toContain('Not byte-identical to the files macOS wrote');+ });+});+describe('runDiagnoseBundle — tracer bullet', () => {test('writes a zip to the default path with no server running and --yes', async () => {const contentDir = makeTmpDir();diff --git a/packages/cli/src/commands/diagnose.ts b/packages/cli/src/commands/diagnose.tsindex 81c4d5dc5..21c18a30a 100644--- a/packages/cli/src/commands/diagnose.ts+++ b/packages/cli/src/commands/diagnose.ts@@ -1,6 +1,6 @@import { spawn, spawnSync } from 'node:child_process';import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';+import { homedir, tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { createInterface } from 'node:readline/promises';import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';@@ -12,6 +12,11 @@ import {collectBundle,writeBundle,} from '../diagnose/bundle.ts';+import {+ collectDiagnosticReports,+ type DiagnosticReportCollection,+ renderDiagnosticReportsStatus,+} from '../diagnose/diagnostic-reports.ts';import {discoverLockDirs,type ProcessUsage,@@ -432,6 +437,7 @@ export interface RunDiagnoseBundleDeps {prompt?: (question: string) => Promise<string>;runProcessDiagnose?: (pid: number) => Promise<string>;collectDeps?: CollectBundleDeps;+ diagnosticReportsDir?: string;now?: () => Date;}@@ -476,10 +482,14 @@ function describeContentDirPath(collected: CollectedBundle): string {: 'not present';}-function describeCredentials(collected: CollectedBundle): string {+function describeCredentials(collected: CollectedBundle, stagedDiagnosticReports: number): string {const scrub = collected.manifest.redaction.secretScrub;if (scrub === undefined) {- return pc.yellow('NOT scrubbed (--no-redact): tokens and keys ship verbatim');+ return pc.yellow(+ stagedDiagnosticReports > 0+ ? 'NOT scrubbed (--no-redact): tokens and keys ship verbatim, crash reports excepted'+ : 'NOT scrubbed (--no-redact): tokens and keys ship verbatim',+ );}return `scrubbed known credential formats (${scrub.redactedLineCount} line(s) across ${scrub.redactions.length} file(s))`;}@@ -488,6 +498,7 @@ function printSummary(log: (msg: string) => void,collected: CollectedBundle,outputPath: string,+ diagnosticReports: DiagnosticReportCollection,): void {const { summary, manifest } = collected;log('');@@ -499,8 +510,17 @@ function printSummary(` Document names: included in cleartext (${summary.docNameCount} doc.name occurrence(s) in telemetry)`,);log(` Content-dir path: ${describeContentDirPath(collected)}`);- log(` Credentials: ${describeCredentials(collected)}`);+ log(` Credentials: ${describeCredentials(collected, summary.stagedDiagnosticReports)}`);log(` Server status: ${manifest.serverStatus}`);+ log(+ ` macOS crash reports: ${renderDiagnosticReportsStatus(diagnosticReports, summary.stagedDiagnosticReports)}`,+ );+ if (summary.stagedDiagnosticReports > 0) {+ log(' rewritten on the way in: escaped path separators normalised');+ log(' so the scrub can read them, and the per-device identifier');+ log(' replaced. Not byte-identical to the files macOS wrote, on');+ log(' any tier and regardless of --no-redact.');+ }log(` Output: ${outputPath}`);log('');}@@ -537,12 +557,17 @@ export async function runDiagnoseBundle(}const redact = opts.redact !== false;+ const diagnosticReports = collectDiagnosticReports(+ deps.diagnosticReportsDir ?? join(homedir(), 'Library', 'Logs', 'DiagnosticReports'),+ now(),+ );const collected = await collectBundle({contentDir: opts.contentDir,projectDir: opts.projectDir,processDir,redact,scrubSecrets: redact,+ diagnosticReports,deps: deps.collectDeps,});@@ -550,7 +575,7 @@ export async function runDiagnoseBundle(if (collected.manifest.serverStatus === 'not-running') {log(pc.yellow(' server not running — live state unavailable'));}- printSummary(log, collected, outputPath);+ printSummary(log, collected, outputPath, diagnosticReports);if (opts.yes !== true) {const answer = await prompt('Write bundle? [y/N]: ');diff --git a/packages/cli/src/diagnose/bundle-redact.test.ts b/packages/cli/src/diagnose/bundle-redact.test.tsindex fb2c229ba..1cb88adef 100644--- a/packages/cli/src/diagnose/bundle-redact.test.ts+++ b/packages/cli/src/diagnose/bundle-redact.test.ts@@ -139,6 +139,60 @@ describe('redactStagedBundle — contentDir masking', () => {expect(after).toContain('<CONTENT_DIR>');});+ test('masks contentDir in a diagnostic-reports/*.ips without re-serialising it', () => {+ const stagingDir = makeStagingDir();+ const contentDir = '/Users/test/notes';+ mkdirSync(join(stagingDir, 'diagnostic-reports'));+ const header = JSON.stringify({ app_name: 'OpenKnowledge', name: 'OpenKnowledge' });+ const body = [+ '{',+ ` "procPath" : "${contentDir}/OpenKnowledge.app/Contents/MacOS/OpenKnowledge",`,+ ` "asi" : {"OpenKnowledge":["loaded from ${contentDir}/plugins"]},`,+ ' "threads" : [{"threadState":{"x":[{"value":18446744072631617535}]}}],',+ ' "termination" : {"namespace":"SIGNAL","indicator":"Abort trap: 6"}',+ '}',+ ].join('\n');+ const raw = `${header}\n${body}\n`;+ writeStaged(stagingDir, 'diagnostic-reports/OpenKnowledge-2026-08-27.ips', raw);++ redactStagedBundle({ stagingDir, contentDir });++ const after = readStaged(stagingDir, 'diagnostic-reports/OpenKnowledge-2026-08-27.ips');+ expect(after).not.toContain(contentDir);+ expect(after).toContain('<CONTENT_DIR>/OpenKnowledge.app/Contents/MacOS/OpenKnowledge');+ expect(after).toContain('loaded from <CONTENT_DIR>/plugins');+ expect(after).toContain('"value":18446744072631617535');+ expect(after).toContain('"termination" : {');+ });++ test('leaves an .ips alone when the content dir does not appear in it', () => {+ const stagingDir = makeStagingDir();+ mkdirSync(join(stagingDir, 'diagnostic-reports'));+ const raw = `{"name":"OpenKnowledge"}\n{"threads":[{"x":[{"value":18446744072631617535}]}]}\n`;+ writeStaged(stagingDir, 'diagnostic-reports/OpenKnowledge-clean.ips', raw);++ redactStagedBundle({ stagingDir, contentDir: '/Users/nobody/no-such-dir' });++ expect(readStaged(stagingDir, 'diagnostic-reports/OpenKnowledge-clean.ips')).toBe(raw);+ });++ test('masks a truncated .ips that will not parse', () => {+ const stagingDir = makeStagingDir();+ const contentDir = '/Users/test/notes';+ mkdirSync(join(stagingDir, 'diagnostic-reports'));+ writeStaged(+ stagingDir,+ 'diagnostic-reports/OpenKnowledge-truncated.ips',+ `{"name":"OpenKnowledge"}\n{"procPath":"${contentDir}/bin`,+ );++ redactStagedBundle({ stagingDir, contentDir });++ const after = readStaged(stagingDir, 'diagnostic-reports/OpenKnowledge-truncated.ips');+ expect(after).not.toContain(contentDir);+ expect(after).toContain('<CONTENT_DIR>/bin');+ });+test('masks contentDir in a state/.txt plain file', () => {const stagingDir = makeStagingDir();const contentDir = '/Users/test/notes';diff --git a/packages/cli/src/diagnose/bundle-redact.ts b/packages/cli/src/diagnose/bundle-redact.tsindex fe1697930..b54d72fa8 100644--- a/packages/cli/src/diagnose/bundle-redact.ts+++ b/packages/cli/src/diagnose/bundle-redact.ts@@ -104,10 +104,17 @@ function isLineDelimitedJson(filePath: string): boolean {return filePath.endsWith('.jsonl') || filePath.endsWith('.log') || isRotatedLogPath(filePath);}+export const CONTENT_SUBDIRS_MASKED = [+ 'telemetry',+ 'logs',+ 'process',+ 'diagnostic-reports',+] as const;+export function redactStagedBundle(opts: RedactStagedBundleOpts): void {const ctx: RedactCtx = { contentDir: opts.contentDir };- for (const subdir of ['telemetry', 'logs', 'process']) {+ for (const subdir of CONTENT_SUBDIRS_MASKED) {for (const filePath of walkDirFiles(join(opts.stagingDir, subdir))) {if (isLineDelimitedJson(filePath)) {redactJsonlFile(filePath, ctx);diff --git a/packages/cli/src/diagnose/bundle.test.ts b/packages/cli/src/diagnose/bundle.test.tsindex d199a3b90..da077b534 100644--- a/packages/cli/src/diagnose/bundle.test.ts+++ b/packages/cli/src/diagnose/bundle.test.ts@@ -69,6 +69,39 @@ function writeAt(contentDir: string, relPath: string, body: string): void {writeFileSync(full, body);}+describe('collectBundle — diagnostic-report staging count', () => {+ test('counts what was staged, not what the sweep selected', async () => {+ const contentDir = makeTmpDir();+ const reportsDir = makeTmpDir();+ const present = join(reportsDir, 'OpenKnowledge-present.ips');+ writeFileSync(+ present,+ `${JSON.stringify({ name: 'OpenKnowledge' })}\n{"procName":"OpenKnowledge"}\n`,+ );++ const collected = await collectBundle({+ contentDir,+ deps: makeDeterministicDeps(),+ diagnosticReports: {+ files: [present, join(reportsDir, 'OpenKnowledge-vanished.ips')],+ outcome: 'collected',+ foreignIgnored: 0,+ unparseable: 0,+ droppedOverCap: 0,+ windowDays: 7,+ },+ });++ expect(+ readFileSync(join(collected.stagingDir, 'state', 'diagnostic-reports-status.txt'), 'utf-8'),+ ).toBe(+ '1 collected (7d; 0 other-process report(s) ignored; 0 unparseable; 1 vanished before staging)\n',+ );+ expect(collected.summary.stagedDiagnosticReports).toBe(1);+ collected.cleanup();+ });+});+describe('collectBundle — smoke', () => {test('produces a v2 manifest on a fresh content-dir with no server', async () => {const contentDir = makeTmpDir();diff --git a/packages/cli/src/diagnose/bundle.ts b/packages/cli/src/diagnose/bundle.tsindex 6f59578ae..99bed8635 100644--- a/packages/cli/src/diagnose/bundle.ts+++ b/packages/cli/src/diagnose/bundle.ts@@ -33,6 +33,11 @@ import { redactContent } from '../commands/bug-report-redact.ts';import { PACKAGE_VERSION } from '../constants.ts';import { defaultReadLanguage, type LanguageMetadata } from '../report-language.ts';import { isRotatedLogPath, redactStagedBundle } from './bundle-redact.ts';+import {+ type DiagnosticReportCollection,+ prepareDiagnosticReportText,+ renderDiagnosticReportsStatus,+} from './diagnostic-reports.ts';type BundleSchemaVersion = 2;@@ -100,6 +105,7 @@ export interface CollectBundleOpts {extraFiles?: BundleExtraFile[];userLogFiles?: string[];userStateFiles?: string[];+ diagnosticReports?: DiagnosticReportCollection;deps?: CollectBundleDeps;}@@ -122,6 +128,7 @@ interface BundleSummary {totalBytes: number;fileCount: number;docNameCount: number;+ stagedDiagnosticReports: number;contentDirVisible: boolean;redacted: boolean;}@@ -387,7 +394,11 @@ function stageFileIfPresent(srcPath: string, destPath: string): boolean {if (!existsSync(srcPath)) return false;try {mkdirSync(dirname(destPath), { recursive: true });- cpSync(srcPath, destPath);+ if (srcPath.endsWith('.ips')) {+ writeFileSync(destPath, prepareDiagnosticReportText(readFileSync(srcPath, 'utf-8')));+ } else {+ cpSync(srcPath, destPath);+ }return true;} catch {return false;@@ -419,7 +430,7 @@ function shouldCountLines(relPath: string): boolean {return LINE_COUNTED_EXTENSIONS.has(relPath.slice(lastDot));}-const SECRET_SCRUB_EXTENSIONS = new Set([+export const SECRET_SCRUB_EXTENSIONS = new Set(['.jsonl','.json','.txt',@@ -427,6 +438,7 @@ const SECRET_SCRUB_EXTENSIONS = new Set(['.lock','.yaml','.yml',+ '.ips',]);function isSecretScrubbable(relPath: string): boolean {@@ -494,6 +506,14 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedBjoin(stagingDir, REPORT_SIDECAR_BUNDLE_DIR, basename(userStatePath)),);}+ let stagedDiagnosticReports = 0;+ for (const reportPath of opts.diagnosticReports?.files ?? []) {+ if (+ stageFileIfPresent(reportPath, join(stagingDir, 'diagnostic-reports', basename(reportPath)))+ ) {+ stagedDiagnosticReports += 1;+ }+ }const lockDir = join(projectDir, '.ok', 'local');const lockPath = join(lockDir, 'server.lock');@@ -587,6 +607,15 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedBserverStatus === 'running' ? 'running\n' : `not-running (${serverStatusReason})\n`;writeFileSync(join(stagingDir, 'state', 'server-status.txt'), statusBody);+ const diagnosticReportsStatus =+ opts.diagnosticReports === undefined+ ? 'not-collected (no collection attempted)'+ : renderDiagnosticReportsStatus(opts.diagnosticReports, stagedDiagnosticReports);+ writeFileSync(+ join(stagingDir, 'state', 'diagnostic-reports-status.txt'),+ `${diagnosticReportsStatus}\n`,+ );+if (opts.processDir && existsSync(opts.processDir)) {const processDest = join(stagingDir, 'process');mkdirSync(processDest, { recursive: true });@@ -675,6 +704,7 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedB});const summary: BundleSummary = {+ stagedDiagnosticReports,totalBytes,fileCount: files.length,docNameCount,diff --git a/packages/cli/src/diagnose/diagnostic-reports.test.ts b/packages/cli/src/diagnose/diagnostic-reports.test.tsnew file mode 100644index 000000000..32cbc388f--- /dev/null+++ b/packages/cli/src/diagnose/diagnostic-reports.test.ts@@ -0,0 +1,438 @@+import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, join, resolve } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import {+ collectDiagnosticReports,+ prepareDiagnosticReportText,+ renderDiagnosticReportsStatus,+} from './diagnostic-reports.ts';++const tmpDirs: string[] = [];++function makeTmpDir(): string {+ const dir = mkdtempSync(resolve(tmpdir(), 'ok-diagnostic-reports-test-'));+ tmpDirs.push(dir);+ return dir;+}++afterEach(() => {+ for (const d of tmpDirs) {+ if (existsSync(d)) rmSync(d, { recursive: true, force: true });+ }+ tmpDirs.length = 0;+});++const NOW = new Date('2026-08-27T12:00:00.000Z');++function hoursBefore(hours: number): Date {+ return new Date(NOW.getTime() - hours * 60 * 60 * 1000);+}++function daysBefore(days: number): Date {+ return hoursBefore(days * 24);+}++function headerTimestamp(at: Date, offsetHours = 0): string {+ const shifted = new Date(at.getTime() + offsetHours * 60 * 60 * 1000);+ const sign = offsetHours < 0 ? '-' : '+';+ const abs = Math.abs(offsetHours);+ const offset = `${sign}${String(abs).padStart(2, '0')}00`;+ return `${shifted.toISOString().slice(0, 10)} ${shifted.toISOString().slice(11, 19)}.00 ${offset}`;+}++function writeReport(+ dir: string,+ fileName: string,+ opts: {+ name: string;+ at?: Date;+ incidentAt?: Date;+ incidentOffsetHours?: number;+ body?: Record<string, unknown>;+ raw?: string;+ },+): string {+ const path = join(dir, fileName);+ const at = opts.at ?? daysBefore(1);+ const header = JSON.stringify({+ app_name: opts.name,+ name: opts.name,+ bug_type: '309',+ timestamp: headerTimestamp(opts.incidentAt ?? at, opts.incidentOffsetHours ?? 0),+ os_version: 'macOS 26.6.2 (25G83)',+ });+ const body = JSON.stringify(+ opts.body ?? {+ procName: opts.name,+ termination: { namespace: 'SIGNAL', code: 6, indicator: 'Abort trap: 6' },+ },+ null,+ 2,+ );+ writeFileSync(path, opts.raw ?? `${header}\n${body}\n`);+ utimesSync(path, at, at);+ return path;+}++function collectedNames(dir: string): string[] {+ return collectDiagnosticReports(dir, NOW).files.map((f) => basename(f));+}++function statusOf(dir: string): string {+ const collected = collectDiagnosticReports(dir, NOW);+ return renderDiagnosticReportsStatus(collected, collected.files.length);+}++describe('prepareDiagnosticReportText', () => {+ test('rewrites the escaped solidus macOS writes', () => {+ expect(prepareDiagnosticReportText(String.raw`"\/Users\/test\/notes"`)).toBe(+ '"/Users/test/notes"',+ );+ });++ test('leaves an already-unescaped report byte-identical', () => {+ const plain = '{"name":"OpenKnowledge"}\n{"procPath":"/Applications/OpenKnowledge.app"}\n';+ expect(prepareDiagnosticReportText(plain)).toBe(plain);+ });++ test('preserves a literal backslash that precedes a solidus', () => {+ const encoded = String.raw`"C:\\/file"`;+ expect(JSON.parse(encoded)).toBe(String.raw`C:\/file`);+ expect(JSON.parse(prepareDiagnosticReportText(encoded))).toBe(String.raw`C:\/file`);+ });++ test('leaves 64-bit register values exactly as written', () => {+ const body = '{"threads":[{"threadState":{"x":[{"value":18446744072631617535}]}}]}';+ expect(prepareDiagnosticReportText(body)).toContain('18446744072631617535');+ expect(JSON.stringify(JSON.parse(body))).not.toContain('18446744072631617535');+ });+ test('replaces the linking identifiers, keeping the per-incident ones', () => {+ const raw = [+ '{',+ ' "crashReporterKey" : "03BEA1C8-0E42-2631-A65B-FB48F8C46739",',+ ' "bootSessionUUID" : "2C1A7E44-9B3D-4A02-8F55-1D0C6E9B7A31",',+ ' "sleepWakeUUID" : "7F2B9C10-4E5A-4B88-9C31-0A2D5E7F1B44",',+ ' "incident_id" : "9D5B0E6B-1F0A-4E77-9A6E-6C7B2E0A0B11"',+ '}',+ ].join('\n');++ const after = prepareDiagnosticReportText(raw);++ expect(after).not.toContain('03BEA1C8-0E42-2631-A65B-FB48F8C46739');+ expect(after).not.toContain('2C1A7E44-9B3D-4A02-8F55-1D0C6E9B7A31');+ expect(after).toContain('"crashReporterKey" : "[REDACTED-DEVICE-ID]"');+ expect(after).toContain('"bootSessionUUID" : "[REDACTED-DEVICE-ID]"');+ expect(after).toContain('7F2B9C10-4E5A-4B88-9C31-0A2D5E7F1B44');+ expect(after).toContain('9D5B0E6B-1F0A-4E77-9A6E-6C7B2E0A0B11');+ expect(() => JSON.parse(after)).not.toThrow();+ });++ test('does not backtrack on a long backslash run', () => {+ const run = `${'\\'.repeat(100_000)}x`;+ const started = Date.now();+ expect(prepareDiagnosticReportText(run)).toBe(run);+ expect(Date.now() - started).toBeLessThan(1_000);+ });+});++describe('collectDiagnosticReports', () => {+ test('collects a report for the app main process', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'OpenKnowledge-2026-08-27-045958.ips', { name: 'OpenKnowledge' });++ const result = collectDiagnosticReports(dir, NOW);++ expect(result.files.map((f) => basename(f))).toEqual(['OpenKnowledge-2026-08-27-045958.ips']);+ expect(result.outcome).toBe('collected');+ expect(renderDiagnosticReportsStatus(result, result.files.length)).toContain('1 collected');+ });++ test('collects every helper variant, including the one the detached server runs as', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'OpenKnowledge Helper-2026-08-27-045958.ips', {+ name: 'OpenKnowledge Helper',+ });+ writeReport(dir, 'OpenKnowledge Helper (GPU)-2026-08-27-045959.ips', {+ name: 'OpenKnowledge Helper (GPU)',+ });+ writeReport(dir, 'OpenKnowledge Helper (Renderer)-2026-08-27-050000.ips', {+ name: 'OpenKnowledge Helper (Renderer)',+ });++ expect(collectedNames(dir)).toHaveLength(3);+ });++ test('never harvests another application report', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'OpenKnowledge-2026-08-27-045958.ips', { name: 'OpenKnowledge' });+ writeReport(dir, 'Slack-2026-08-27-045958.ips', { name: 'Slack' });+ writeReport(dir, 'bash-2026-08-27-045958.ips', { name: 'bash' });+ writeReport(dir, 'node-2026-08-27-045958.ips', { name: 'node' });++ const result = collectDiagnosticReports(dir, NOW);++ expect(result.files.map((f) => basename(f))).toEqual(['OpenKnowledge-2026-08-27-045958.ips']);+ expect(result.foreignIgnored).toBe(3);+ expect(renderDiagnosticReportsStatus(result, result.files.length)).toContain(+ '3 other-process report(s) ignored',+ );+ });++ test('does not collect an unrelated app whose name shares the prefix', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'OpenKnowledgeBase-2026-08-27-045958.ips', { name: 'OpenKnowledgeBase' });++ expect(collectedNames(dir)).toEqual([]);+ });++ test('skips a directory even when its name ends in .ips', () => {+ const dir = makeTmpDir();+ mkdirSync(join(dir, 'Retired.ips'));+ writeReport(dir, 'OpenKnowledge-2026-08-27-045958.ips', { name: 'OpenKnowledge' });++ const result = collectDiagnosticReports(dir, NOW);++ expect(result.files.map((f) => basename(f))).toEqual(['OpenKnowledge-2026-08-27-045958.ips']);+ expect(result.unparseable).toBe(0);+ });++ test('ignores a valid owned report that does not carry the .ips extension', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'OpenKnowledge-2026-08-27-045958.diag', { name: 'OpenKnowledge' });++ const result = collectDiagnosticReports(dir, NOW);++ expect(result.files).toEqual([]);+ expect(result.foreignIgnored).toBe(0);+ expect(result.unparseable).toBe(0);+ });++ test('collects up to the seven-day boundary and no further', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'OpenKnowledge-inside.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(6 * 24 + 23),+ });+ writeReport(dir, 'OpenKnowledge-outside.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(7 * 24 + 1),+ });++ expect(collectedNames(dir)).toEqual(['OpenKnowledge-inside.ips']);+ });++ test('caps the collection and keeps the newest reports', () => {+ const dir = makeTmpDir();+ for (let i = 0; i < 30; i += 1) {+ writeReport(dir, `OpenKnowledge-${String(i).padStart(2, '0')}.ips`, {+ name: 'OpenKnowledge',+ at: new Date(NOW.getTime() - (30 - i) * 60 * 1000),+ });+ }++ const result = collectDiagnosticReports(dir, NOW);+ const names = result.files.map((f) => basename(f));++ expect(names).toHaveLength(25);+ expect(names[0]).toBe('OpenKnowledge-29.ips');+ expect(names).not.toContain('OpenKnowledge-00.ips');+ expect(result.droppedOverCap).toBe(5);+ expect(renderDiagnosticReportsStatus(result, result.files.length)).toContain(+ '5 older dropped over cap',+ );+ });++ test('orders by the incident time in the header, not by mtime', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'OpenKnowledge-stale-but-touched.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(1),+ incidentAt: hoursBefore(100),+ });+ writeReport(dir, 'OpenKnowledge-recent.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(50),+ incidentAt: hoursBefore(2),+ });++ expect(collectedNames(dir)).toEqual([+ 'OpenKnowledge-recent.ips',+ 'OpenKnowledge-stale-but-touched.ips',+ ]);+ });++ test('orders by the instant the offset denotes, not the printed wall clock', () => {+ const dir = makeTmpDir();+ const sameMtime = hoursBefore(1);+ writeReport(dir, 'OpenKnowledge-later-instant.ips', {+ name: 'OpenKnowledge',+ at: sameMtime,+ incidentAt: NOW,+ incidentOffsetHours: -7,+ });+ writeReport(dir, 'OpenKnowledge-earlier-instant.ips', {+ name: 'OpenKnowledge',+ at: sameMtime,+ incidentAt: hoursBefore(3),+ incidentOffsetHours: 0,+ });++ expect(collectedNames(dir)).toEqual([+ 'OpenKnowledge-later-instant.ips',+ 'OpenKnowledge-earlier-instant.ips',+ ]);+ });++ test('windows on mtime while ordering on the incident time', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'OpenKnowledge-old-incident-fresh-mtime.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(1),+ incidentAt: daysBefore(10),+ });+ writeReport(dir, 'OpenKnowledge-recent-incident.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(50),+ incidentAt: hoursBefore(2),+ });++ expect(collectedNames(dir)).toEqual([+ 'OpenKnowledge-recent-incident.ips',+ 'OpenKnowledge-old-incident-fresh-mtime.ips',+ ]);+ });++ test('falls back to mtime when the header timestamp does not parse', () => {+ const dir = makeTmpDir();+ const header = JSON.stringify({+ app_name: 'OpenKnowledge',+ name: 'OpenKnowledge',+ bug_type: '309',+ timestamp: 'Thu Aug 27 04:59:58 2026',+ });+ writeReport(dir, 'OpenKnowledge-odd-timestamp.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(1),+ raw: `${header}\n{"procName":"OpenKnowledge"}\n`,+ });+ writeReport(dir, 'OpenKnowledge-older.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(40),+ });++ expect(collectedNames(dir)).toEqual([+ 'OpenKnowledge-odd-timestamp.ips',+ 'OpenKnowledge-older.ips',+ ]);+ });++ test('falls back to mtime when the header carries no usable timestamp', () => {+ const dir = makeTmpDir();+ const header = JSON.stringify({ name: 'OpenKnowledge', bug_type: '309' });+ writeReport(dir, 'OpenKnowledge-no-timestamp.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(2),+ raw: `${header}\n{}\n`,+ });+ writeReport(dir, 'OpenKnowledge-older.ips', { name: 'OpenKnowledge', at: hoursBefore(3) });++ expect(collectedNames(dir)).toEqual([+ 'OpenKnowledge-no-timestamp.ips',+ 'OpenKnowledge-older.ips',+ ]);+ });++ describe('reports we cannot identify', () => {+ test('counts an unparseable header apart from another application report', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'garbled.ips', { name: 'OpenKnowledge', raw: 'not json at all\n{}\n' });+ writeReport(dir, 'Slack-2026-08-27-045958.ips', { name: 'Slack' });++ const result = collectDiagnosticReports(dir, NOW);++ expect(result.files).toEqual([]);+ expect(result.unparseable).toBe(1);+ expect(result.foreignIgnored).toBe(1);+ expect(renderDiagnosticReportsStatus(result, result.files.length)).toBe(+ 'none found in window (7d; 1 other-process report(s) ignored; 1 unparseable)',+ );+ });++ test('counts a header that parses but names no process', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'Nameless-2026-08-27.ips', {+ name: 'OpenKnowledge',+ at: hoursBefore(1),+ raw: `${JSON.stringify({ bug_type: '298', timestamp: '2026-08-27 04:59:58.00 +0000' })}\n{}\n`,+ });++ const result = collectDiagnosticReports(dir, NOW);++ expect(result.files).toEqual([]);+ expect(result.unparseable).toBe(1);+ expect(result.foreignIgnored).toBe(0);+ });++ test('reads a header that is the whole file, with no trailing newline', () => {+ const dir = makeTmpDir();+ const header = JSON.stringify({+ name: 'OpenKnowledge',+ bug_type: '309',+ timestamp: headerTimestamp(daysBefore(1)),+ });+ writeReport(dir, 'OpenKnowledge-partial.ips', { name: 'OpenKnowledge', raw: header });++ const result = collectDiagnosticReports(dir, NOW);++ expect(result.files.map((f) => basename(f))).toEqual(['OpenKnowledge-partial.ips']);+ expect(result.unparseable).toBe(0);+ });+ });++ describe('status when nothing is collected', () => {+ test('reports a missing directory as not-present', () => {+ const result = collectDiagnosticReports(join(makeTmpDir(), 'absent'), NOW);++ expect(result.files).toEqual([]);+ expect(result.outcome).toBe('not-present');+ expect(renderDiagnosticReportsStatus(result, result.files.length)).toBe(+ 'not-present (no DiagnosticReports directory)',+ );+ });++ test('reports a directory it could not read distinctly, naming the errno', () => {+ const dir = makeTmpDir();+ const notADirectory = join(dir, 'DiagnosticReports');+ writeFileSync(notADirectory, 'this is a file');++ const result = collectDiagnosticReports(notADirectory, NOW);++ expect(result.outcome).toBe('unreadable-directory');+ expect(renderDiagnosticReportsStatus(result, result.files.length)).toBe(+ 'unreadable (ENOTDIR reading DiagnosticReports)',+ );+ });++ test('reports an empty window distinctly from a missing directory', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'Slack-2026-08-27-045958.ips', { name: 'Slack' });++ expect(statusOf(dir)).toBe(+ 'none found in window (7d; 1 other-process report(s) ignored; 0 unparseable)',+ );+ });+ });++ test('renders the staged count when it falls short of what was selected', () => {+ const dir = makeTmpDir();+ writeReport(dir, 'OpenKnowledge-a.ips', { name: 'OpenKnowledge' });+ writeReport(dir, 'OpenKnowledge-b.ips', { name: 'OpenKnowledge' });++ const result = collectDiagnosticReports(dir, NOW);++ expect(renderDiagnosticReportsStatus(result, 1)).toBe(+ '1 collected (7d; 0 other-process report(s) ignored; 0 unparseable; 1 vanished before staging)',+ );+ });+});diff --git a/packages/cli/src/diagnose/diagnostic-reports.ts b/packages/cli/src/diagnose/diagnostic-reports.tsnew file mode 100644index 000000000..186b95383--- /dev/null+++ b/packages/cli/src/diagnose/diagnostic-reports.ts@@ -0,0 +1,176 @@+import { type Dirent, readdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { DESKTOP_PRODUCT_NAME } from '../integrations/desktop-state.ts';++const DIAGNOSTIC_REPORT_WINDOW_DAYS = 7;+const DIAGNOSTIC_REPORT_WINDOW_MS = DIAGNOSTIC_REPORT_WINDOW_DAYS * 24 * 60 * 60 * 1000;++const MAX_BUNDLED_DIAGNOSTIC_REPORTS = 25;++export interface DiagnosticReportCollection {+ files: string[];+ outcome: 'not-present' | 'unreadable-directory' | 'none-in-window' | 'collected';+ directoryErrorCode?: string;+ foreignIgnored: number;+ unparseable: number;+ droppedOverCap: number;+ windowDays: number;+}++export function renderDiagnosticReportsStatus(+ collection: DiagnosticReportCollection,+ stagedCount: number,+): string {+ if (collection.outcome === 'not-present') {+ return 'not-present (no DiagnosticReports directory)';+ }+ if (collection.outcome === 'unreadable-directory') {+ return `unreadable (${collection.directoryErrorCode ?? 'unknown'} reading DiagnosticReports)`;+ }+ const notes = [+ `${collection.windowDays}d`,+ `${collection.foreignIgnored} other-process report(s) ignored`,+ `${collection.unparseable} unparseable`,+ ];+ if (collection.droppedOverCap > 0) {+ notes.push(`${collection.droppedOverCap} older dropped over cap`);+ }+ const vanished = collection.files.length - stagedCount;+ if (vanished > 0) notes.push(`${vanished} vanished before staging`);+ if (collection.outcome === 'none-in-window') {+ return `none found in window (${notes.join('; ')})`;+ }+ return `${stagedCount} collected (${notes.join('; ')})`;+}++function normalizeSolidusEscapes(content: string): string {+ return content.replace(/\\+\/?/g, (run) => {+ if (!run.endsWith('/')) return run;+ const backslashes = run.length - 1;+ return '\\'.repeat(backslashes - (backslashes % 2)) + '/';+ });+}++const LINKING_IDENTIFIER_KEYS = ['crashReporterKey', 'bootSessionUUID'] as const;++const LINKING_IDENTIFIERS = new RegExp(+ `("(?:${LINKING_IDENTIFIER_KEYS.join('|')})"\\s*:\\s*)"[^"]*"`,+ 'g',+);++function stripLinkingIdentifiers(content: string): string {+ return content.replace(LINKING_IDENTIFIERS, '$1"[REDACTED-DEVICE-ID]"');+}++export function prepareDiagnosticReportText(content: string): string {+ return stripLinkingIdentifiers(normalizeSolidusEscapes(content));+}++type ReportHeader =+ | { readonly kind: 'named'; readonly name: string; readonly timestampMs: number | null }+ | { readonly kind: 'unreadable' };++const HEADER_TIMESTAMP = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;++function parseHeaderTimestamp(value: unknown): number | null {+ if (typeof value !== 'string') return null;+ const match = HEADER_TIMESTAMP.exec(value.trim());+ if (match === null) return null;+ const [, date, time, fraction = '', tzHours, tzMinutes] = match;+ const parsed = Date.parse(`${date}T${time}${fraction}${tzHours}:${tzMinutes}`);+ return Number.isNaN(parsed) ? null : parsed;+}++function readReportHeader(filePath: string): ReportHeader {+ try {+ const content = readFileSync(filePath, 'utf-8');+ const newline = content.indexOf('\n');+ const firstLine = newline === -1 ? content : content.slice(0, newline);+ const header: unknown = JSON.parse(firstLine);+ if (typeof header !== 'object' || header === null) return { kind: 'unreadable' };+ const {+ name,+ app_name: appName,+ timestamp,+ } = header as { name?: unknown; app_name?: unknown; timestamp?: unknown };+ const resolved = typeof name === 'string' ? name : typeof appName === 'string' ? appName : null;+ if (resolved === null) return { kind: 'unreadable' };+ return { kind: 'named', name: resolved, timestampMs: parseHeaderTimestamp(timestamp) };+ } catch {+ return { kind: 'unreadable' };+ }+}++function isOwnedProcessName(name: string): boolean {+ return name === DESKTOP_PRODUCT_NAME || name.startsWith(`${DESKTOP_PRODUCT_NAME} `);+}++export function collectDiagnosticReports(+ diagnosticReportsDir: string,+ now: Date,+): DiagnosticReportCollection {+ const empty: Omit<DiagnosticReportCollection, 'outcome'> = {+ files: [],+ foreignIgnored: 0,+ unparseable: 0,+ droppedOverCap: 0,+ windowDays: DIAGNOSTIC_REPORT_WINDOW_DAYS,+ };++ let entries: Dirent[];+ try {+ entries = readdirSync(diagnosticReportsDir, { withFileTypes: true });+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === 'ENOENT') return { ...empty, outcome: 'not-present' };+ return { ...empty, outcome: 'unreadable-directory', directoryErrorCode: code ?? 'unknown' };+ }++ const cutoffMs = now.getTime() - DIAGNOSTIC_REPORT_WINDOW_MS;+ const owned: { path: string; atMs: number }[] = [];+ let foreignIgnored = 0;+ let unparseable = 0;++ for (const entry of entries) {+ if (!entry.isFile()) continue;+ if (!entry.name.endsWith('.ips')) continue;++ const path = join(diagnosticReportsDir, entry.name);+ let mtimeMs: number;+ try {+ mtimeMs = statSync(path).mtimeMs;+ } catch {+ continue;+ }++ if (mtimeMs < cutoffMs) continue;++ const header = readReportHeader(path);+ const atMs =+ header.kind === 'named' && header.timestampMs !== null ? header.timestampMs : mtimeMs;++ if (header.kind === 'unreadable') {+ unparseable += 1;+ continue;+ }+ if (!isOwnedProcessName(header.name)) {+ foreignIgnored += 1;+ continue;+ }+ owned.push({ path, atMs });+ }++ owned.sort((a, b) => b.atMs - a.atMs);+ const kept = owned.slice(0, MAX_BUNDLED_DIAGNOSTIC_REPORTS);+ const counts = {+ foreignIgnored,+ unparseable,+ droppedOverCap: owned.length - kept.length,+ windowDays: DIAGNOSTIC_REPORT_WINDOW_DAYS,+ };++ if (kept.length === 0) {+ return { ...counts, files: [], outcome: 'none-in-window' };+ }+ return { ...counts, files: kept.map((r) => r.path), outcome: 'collected' };+}diff --git a/packages/cli/src/diagnose/staging-coverage.test.ts b/packages/cli/src/diagnose/staging-coverage.test.tsnew file mode 100644index 000000000..7ad686c8c--- /dev/null+++ b/packages/cli/src/diagnose/staging-coverage.test.ts@@ -0,0 +1,100 @@+import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { collectBundle, SECRET_SCRUB_EXTENSIONS } from './bundle.ts';+import { CONTENT_SUBDIRS_MASKED } from './bundle-redact.ts';++const tmpDirs: string[] = [];+afterEach(() => {+ for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });+ tmpDirs.length = 0;+});++describe('staged-content coverage', () => {+ const TOP_LEVEL = {+ telemetry: 'masked',+ logs: 'masked',+ process: 'masked',+ 'diagnostic-reports': 'masked',+ state: 'masked-separately',+ extra: 'raw-bytes-by-design',+ } as const;++ test('every masked subdir is declared, and every declared one is masked', () => {+ const declared = Object.entries(TOP_LEVEL)+ .filter(([, mode]) => mode === 'masked')+ .map(([dir]) => dir)+ .sort();+ expect([...CONTENT_SUBDIRS_MASKED].sort()).toEqual(declared);+ });++ test('the only unmasked staged directory is the declared binary exemption', () => {+ const unmasked = Object.entries(TOP_LEVEL)+ .filter(([, mode]) => mode === 'raw-bytes-by-design')+ .map(([dir]) => dir);+ expect(unmasked).toEqual(['extra']);+ });++ test('the secret-scrub extension set is exactly what is declared', () => {+ expect([...SECRET_SCRUB_EXTENSIONS].sort()).toEqual([+ '.ips',+ '.json',+ '.jsonl',+ '.lock',+ '.log',+ '.txt',+ '.yaml',+ '.yml',+ ]);+ });++ test('every text file family the masked subdirs stage is scrub-registered', () => {+ const stagedExtensions = {+ telemetry: ['.jsonl'],+ logs: ['.jsonl', '.log'],+ process: ['.json', '.txt'],+ 'diagnostic-reports': ['.ips'],+ } as const;+ expect(Object.keys(stagedExtensions).sort()).toEqual([...CONTENT_SUBDIRS_MASKED].sort());+ for (const [dir, exts] of Object.entries(stagedExtensions)) {+ for (const ext of exts) {+ expect(SECRET_SCRUB_EXTENSIONS.has(ext), `${dir} stages ${ext}`).toBe(true);+ }+ }+ });++ test('collectBundle produces no top-level directory this file does not declare', async () => {+ const contentDir = mkdtempSync(resolve(tmpdir(), 'ok-staging-coverage-'));+ tmpDirs.push(contentDir);+ writeFileSync(join(contentDir, 'note.md'), '# note\n');++ const collected = await collectBundle({+ contentDir,+ deps: {+ fetchAgentPresence: async () => null,+ fetchAgentEffects: async () => null,+ fetchWatcherRecent: async () => null,+ readShadowHead: () => null,+ readCheckpointRefs: () => null,+ now: () => new Date('2026-05-28T14:22:01.000Z'),+ okVersion: () => '0.7.99',+ readDesktopEnv: () => null,+ readRuntime: () => ({ nodeVersion: 'v24.18.0', platform: 'darwin', arch: 'arm64' }),+ isOtlpPushEnabled: () => false,+ },+ });++ try {+ const produced = readdirSync(collected.stagingDir, { withFileTypes: true })+ .filter((e) => e.isDirectory())+ .map((e) => e.name);+ expect(produced.length).toBeGreaterThan(0);+ for (const dir of produced) {+ expect(Object.keys(TOP_LEVEL), `staged directory "${dir}" is undeclared`).toContain(dir);+ }+ } finally {+ collected.cleanup();+ }+ });+});diff --git a/packages/cli/src/report-bundle.test.ts b/packages/cli/src/report-bundle.test.tsindex bd71ff354..41e1c3223 100644--- a/packages/cli/src/report-bundle.test.ts+++ b/packages/cli/src/report-bundle.test.ts@@ -365,6 +365,254 @@ describe('collectReportBundle — full level', () => {expect(shipIt).not.toContain(SECRET);});+ describe('macOS diagnostic reports', () => {+ const DEVICE_KEY = '03BEA1C8-0E42-2631-A65B-FB48F8C46739';+ const BOOT_SESSION = '2C1A7E44-9B3D-4A02-8F55-1D0C6E9B7A31';+ const SLEEP_WAKE = '7F2B9C10-4E5A-4B88-9C31-0A2D5E7F1B44';+ const INCIDENT_ID = '9D5B0E6B-1F0A-4E77-9A6E-6C7B2E0A0B11';++ function writeDiagnosticReport(+ dir: string,+ fileName: string,+ opts: { name: string; termination?: string; asi?: string },+ ): void {+ const header = JSON.stringify({+ app_name: opts.name,+ name: opts.name,+ bug_type: '309',+ timestamp: '2026-08-27 04:59:58.00 +0000',+ });+ const body = JSON.stringify({+ procName: opts.name,+ procPath: `/Users/test/Applications/${opts.name}.app/Contents/MacOS/${opts.name}`,+ crashReporterKey: DEVICE_KEY,+ bootSessionUUID: BOOT_SESSION,+ sleepWakeUUID: SLEEP_WAKE,+ incident_id: INCIDENT_ID,+ termination: {+ namespace: opts.termination ?? 'USER',+ code: 0,+ indicator: opts.termination ?? 'USER 0',+ },+ asi: { [opts.name]: [opts.asi ?? 'abort() called'] },+ });+ const raw = `${header}\n${body}\n`.replaceAll('/', String.raw`\/`);+ expect(raw).toContain(String.raw`\/Users\/test`);+ writeAt(dir, fileName, raw);+ }++ test('carries the app own report and names the cause', async () => {+ const diagnosticReportsDir = makeTmpDir();+ writeDiagnosticReport(diagnosticReportsDir, 'OpenKnowledge-2026-08-27-045958.ips', {+ name: 'OpenKnowledge',+ });+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'full',+ projectDir: makeFullProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ diagnosticReportsDir,+ });++ const entry = 'diagnostic-reports/OpenKnowledge-2026-08-27-045958.ips';+ expect(listZipEntries(zipPath)).toContain(entry);+ expect(readZipEntry(zipPath, entry)).toContain('USER 0');+ expect(readZipEntry(zipPath, 'state/diagnostic-reports-status.txt')).toBe(+ '1 collected (7d; 0 other-process report(s) ignored; 0 unparseable)\n',+ );+ });++ const URL_CREDENTIAL = 'https://svc:[email protected]/v1';++ test.each([+ ['with a project in scope', true],+ ['with no project in scope', false],+ ])('scrubs secrets out of a collected report, %s', async (_label, withProject) => {+ const diagnosticReportsDir = makeTmpDir();+ writeDiagnosticReport(diagnosticReportsDir, 'OpenKnowledge-2026-08-27-045958.ips', {+ name: 'OpenKnowledge',+ asi: `fetch failed for ${URL_CREDENTIAL}`,+ });+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'full',+ ...(withProject ? { projectDir: makeFullProjectDir() } : {}),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ diagnosticReportsDir,+ });++ const report = readZipEntry(+ zipPath,+ 'diagnostic-reports/OpenKnowledge-2026-08-27-045958.ips',+ );+ expect(report).toContain('USER 0');+ expect(report).not.toContain('s3cretpassword');+ expect(report).not.toContain('/Users/test');+ expect(report).not.toContain(DEVICE_KEY);+ expect(report).not.toContain(BOOT_SESSION);+ expect(report).toContain(INCIDENT_ID);+ expect(report).toContain(SLEEP_WAKE);+ });++ test('scrubs secrets out of a truncated report that will not parse', async () => {+ const diagnosticReportsDir = makeTmpDir();+ const header = JSON.stringify({ name: 'OpenKnowledge', bug_type: '309' });+ const torn = `{"procName":"OpenKnowledge","asi":"fetch failed for ${URL_CREDENTIAL}`;+ writeAt(+ diagnosticReportsDir,+ 'OpenKnowledge-torn.ips',+ `${header}\n${torn}`.replaceAll('/', String.raw`\/`),+ );+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'full',+ projectDir: makeFullProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ diagnosticReportsDir,+ });++ const report = readZipEntry(zipPath, 'diagnostic-reports/OpenKnowledge-torn.ips');+ expect(report).not.toContain('s3cretpassword');+ });++ test('says a report was rewritten even when redaction is disabled', async () => {+ const diagnosticReportsDir = makeTmpDir();+ writeDiagnosticReport(diagnosticReportsDir, 'OpenKnowledge-2026-08-27-045958.ips', {+ name: 'OpenKnowledge',+ });+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'full',+ redact: false,+ outputPath,+ userLogsDir: makeTmpDir(),+ diagnosticReportsDir,+ });++ const readme = readZipEntry(zipPath, 'README.md');+ expect(readme).toContain('Redaction was disabled for this bundle');+ expect(readme).toContain('rewritten on the way in');+ expect(readme).toContain('not byte-identical to the files macOS wrote');+ const report = readZipEntry(+ zipPath,+ 'diagnostic-reports/OpenKnowledge-2026-08-27-045958.ips',+ );+ expect(report).not.toContain(DEVICE_KEY);+ expect(report).not.toContain(String.raw`\/Users`);+ });++ test('claims no exception when no report was staged', async () => {+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'full',+ redact: false,+ outputPath,+ userLogsDir: makeTmpDir(),+ diagnosticReportsDir: makeTmpDir(),+ });++ const readme = readZipEntry(zipPath, 'README.md');+ expect(readme).toContain('Redaction was disabled for this bundle');+ expect(readme).not.toContain('exception');+ });++ test('does not carry another application report', async () => {+ const diagnosticReportsDir = makeTmpDir();+ writeDiagnosticReport(diagnosticReportsDir, 'Slack-2026-08-27-045958.ips', { name: 'Slack' });+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'full',+ projectDir: makeFullProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ diagnosticReportsDir,+ });++ expect(listZipEntries(zipPath).filter((e) => e.startsWith('diagnostic-reports/'))).toEqual(+ [],+ );+ });++ test('carries the reports and the record when full level has no project in scope', async () => {+ const diagnosticReportsDir = makeTmpDir();+ writeDiagnosticReport(diagnosticReportsDir, 'OpenKnowledge-2026-08-27-045958.ips', {+ name: 'OpenKnowledge',+ });+ writeDiagnosticReport(diagnosticReportsDir, 'Slack-2026-08-27-045958.ips', { name: 'Slack' });+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath, summary } = await collectReportBundle({+ level: 'full',+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ diagnosticReportsDir,+ });++ expect(summary.systemWide).toBe(true);+ const entries = listZipEntries(zipPath);+ expect(entries).toContain('diagnostic-reports/OpenKnowledge-2026-08-27-045958.ips');+ expect(entries).not.toContain('diagnostic-reports/Slack-2026-08-27-045958.ips');+ expect(readZipEntry(zipPath, 'state/diagnostic-reports-status.txt')).toBe(+ '1 collected (7d; 1 other-process report(s) ignored; 0 unparseable)\n',+ );+ expect(readZipEntry(zipPath, 'README.md')).toContain('Crash reports: written by macOS');+ });++ test('does not collect at standard level', async () => {+ const diagnosticReportsDir = makeTmpDir();+ writeDiagnosticReport(diagnosticReportsDir, 'OpenKnowledge-2026-08-27-045958.ips', {+ name: 'OpenKnowledge',+ });+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'standard',+ projectDir: makeFullProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ diagnosticReportsDir,+ });++ const entries = listZipEntries(zipPath);+ expect(entries.filter((e) => e.startsWith('diagnostic-reports/'))).toEqual([]);+ expect(readZipEntry(zipPath, 'state/diagnostic-reports-status.txt')).toBe(+ 'not-collected (no collection attempted)\n',+ );+ });++ test('records an empty window rather than staying silent', async () => {+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'full',+ projectDir: makeFullProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ diagnosticReportsDir: makeTmpDir(),+ });++ expect(readZipEntry(zipPath, 'state/diagnostic-reports-status.txt')).toBe(+ 'none found in window (7d; 0 other-process report(s) ignored; 0 unparseable)\n',+ );+ });+ });+test('scrubs ROTATED user logs too, whose counter suffix defeats an extension test', async () => {const projectDir = makeFullProjectDir();const userLogsDir = makeTmpDir();diff --git a/packages/cli/src/report-bundle.ts b/packages/cli/src/report-bundle.tsindex fd48a447d..faffd4748 100644--- a/packages/cli/src/report-bundle.ts+++ b/packages/cli/src/report-bundle.ts@@ -22,6 +22,10 @@ import {defaultReadDesktopEnv,writeBundle,} from './diagnose/bundle.ts';+import {+ collectDiagnosticReports,+ type DiagnosticReportCollection,+} from './diagnose/diagnostic-reports.ts';import { defaultReadLanguage, type LanguageMetadata } from './report-language.ts';import { isObject } from './utils/is-object.ts';@@ -37,6 +41,7 @@ export interface CollectReportBundleOptions {extraFiles?: BundleExtraFile[];userLogsDir?: string;cachesDir?: string;+ diagnosticReportsDir?: string;bugReportsDir?: string;logger?: BundleLogger;readDesktopEnv?: () => DesktopMetadata | null;@@ -73,6 +78,7 @@ async function collectFullBundle(projectDir: string,readDesktopEnv: () => DesktopMetadata | null,readLanguage: () => LanguageMetadata,+ diagnosticReports: DiagnosticReportCollection,): Promise<ReportBundleResult> {const projectSlug = resolveProjectSlug(projectDir, opts.logger);const collected = await collectBundle({@@ -87,6 +93,7 @@ async function collectFullBundle(...collectShipItLogFiles(opts.cachesDir ?? join(homedir(), 'Library', 'Caches')),],userStateFiles: collectBugReportLedgerFiles(opts.bugReportsDir ?? okBugReportsDir()),+ diagnosticReports,deps: { readDesktopEnv, readLanguage, logger: opts.logger },});try {@@ -116,8 +123,19 @@ export async function collectReportBundle(const { projectDir } = opts;const readDesktopEnv = opts.readDesktopEnv ?? defaultReadDesktopEnv;const readLanguage = opts.readLanguage ?? defaultReadLanguage;+ const resolveDiagnosticReports = (): DiagnosticReportCollection =>+ collectDiagnosticReports(+ opts.diagnosticReportsDir ?? join(homedir(), 'Library', 'Logs', 'DiagnosticReports'),+ new Date(),+ );if (opts.level === 'full' && projectDir !== undefined) {- return collectFullBundle(opts, projectDir, readDesktopEnv, readLanguage);+ return collectFullBundle(+ opts,+ projectDir,+ readDesktopEnv,+ readLanguage,+ resolveDiagnosticReports(),+ );}const { zipPath, summary } = await collectStandardBundle({projectDir,@@ -127,6 +145,7 @@ export async function collectReportBundle(userLogsDir: opts.userLogsDir,shipItLogFiles: collectShipItLogFiles(opts.cachesDir ?? join(homedir(), 'Library', 'Caches')),bugReportLedgerFiles: collectBugReportLedgerFiles(opts.bugReportsDir ?? okBugReportsDir()),+ diagnosticReports: opts.level === 'full' ? resolveDiagnosticReports() : undefined,logger: opts.logger,note: opts.note,extraFiles: opts.extraFiles,