Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): filter foreign crash dumps by ownership (PRD-7538) (#3137)
Andrew Mikofalvy31d7856b9be6
diff --git a/.changeset/crash-dump-ownership-filter.md b/.changeset/crash-dump-ownership-filter.mdnew file mode 100644index 000000000..710fafebc--- /dev/null+++ b/.changeset/crash-dump-ownership-filter.md@@ -0,0 +1,12 @@+---+"@inkeep/open-knowledge": patch+---++Crash reports no longer blame the app for a crash in some other program, and a bug report can no longer carry another application's process memory.++On macOS a task's Mach exception ports are inherited across fork and exec, so every descendant of the desktop app runs under the crash handler the app started: the in-app terminal's login shell, anything launched from that shell, MCP servers, agents, and unrelated GUI applications. When one of those aborted, the handler wrote its minidump into the app's own crash database and stamped it with the app's product name and version, and nothing downstream told the two apart.++- **A crash dump is now checked against the app bundle before it counts as ours.** Detection reads the dump's own module list to find the crashed process's main executable and requires it to resolve inside the app bundle. A dump from a foreign process no longer arms the "the previous session crashed" invitation, which previously fired after a perfectly clean quit whenever an unrelated app had crashed under the inherited handler.+- **A foreign dump can never be attached to a bug report.** This is the more serious half. The "include the crash dump" checkbox describes a memory snapshot of this app, and the collector copies the dump into the bundle byte for byte, so an unrelated application's raw process memory (plus its loaded-module inventory and library search paths) could be uploaded under a consent the reporter was never asked for. The attachment lookup now only returns dumps proved to belong to this app.+- **A dump too damaged to identify still prompts, but is never attached.** A dump truncated by the crash that produced it is most likely ours, and the invitation only asks a question the user can dismiss, so the prompt errs toward asking. Egress errs the other way: memory whose owner cannot be established is memory the consent dialog cannot honestly describe, so the checkbox is not offered.+- **Ignored dumps leave a log breadcrumb** naming how many were skipped, so a suppressed prompt is distinguishable from detection never running.diff --git a/knip.config.ts b/knip.config.tsindex 13582ee18..f004e6bc3 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -123,7 +123,9 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex d7a845280..dfd95ef49 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,3 +1,4 @@+import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 005627195..8bfdb40cd 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,3 +1,4 @@+import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex f4cc8a286..2a597ec3d 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,3 +1,4 @@+import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8890f6739..c18c086d5 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 9d9c244b0..463e89595 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,3 +1,4 @@+const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.tsindex c43fdd7e7..0939885bb 100644--- a/packages/core/src/bridge/intraline-predicate.ts+++ b/packages/core/src/bridge/intraline-predicate.ts@@ -1,3 +1,4 @@+export function rawLineCounts(doc: string): Map<string, number> {const counts = new Map<string, number>();for (const line of doc.split('\n')) {diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex 251560a35..c0dc65705 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,6 +65,7 @@ export function tryLineLevelCombine(return { clean: true, merged };}+export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex da41900cd..d35f6b455 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 754dc5cc2..0be5203e4 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;+interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}+/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}+export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex af20de1e2..dca644141 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,3 +1,4 @@+/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex 83d47404a..a363dfd54 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,3 +1,4 @@+import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.tsindex 9807a7e82..4499dbc92 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,3 +1,4 @@+export function selectFenceChar(info: string): '`' | '~' {return info.includes('`') ? '~' : '`';}diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 7415c474a..34704165b 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex ece5c02a1..b6299a948 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,3 +1,4 @@+import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex 54774764a..acd398aa6 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.tsindex 43ecdc709..ba9b56384 100644--- a/packages/core/src/markdown/div-align-promoter.ts+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex 6d3f3643e..4513da9bb 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,3 +1,4 @@+const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 00f5771ee..6931623c7 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}+interface GfmExample {section: string;markdown: string;@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}+interface MdxCrashEntry {id: string;input: string;@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}+export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}+export interface NgPinnedCase {id: string;name: string;@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}+export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex 8b1eb8519..daa3ef82b 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;+function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}+const WORDS = ['lorem','ipsum',@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}+type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}+function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 420dc0fe5..32c055c5b 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,6 +7,7 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';+export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 2653473da..283913255 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,3 +1,4 @@+export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex da0a81d23..5d1000cc4 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex 787315157..9681c0056 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,3 +1,4 @@+import type { Element as HastElement, Root as HastRoot } from 'hast';import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -128,7 +129,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified().use(rehypeParse, { fragment: true });+ const processor = unified()+ .use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 706fa9afb..994eb6917 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,3 +1,4 @@+import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex f49f4b64e..25bc43422 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -205,6 +206,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -253,6 +255,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -272,6 +275,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}+function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -340,6 +344,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -592,6 +597,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -672,6 +678,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -950,6 +957,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1075,6 +1083,7 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}+function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex fa0be9e86..b79e9aef7 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,3 +1,4 @@+import picomatch from 'picomatch';import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 312c9c74b..94b34dee1 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,3 +1,4 @@+const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex c94bfce20..a1dab6426 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -38,6 +38,7 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;+export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex d48eea5e4..a51f2ffb0 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};+export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex ef478e268..9c9542661 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,3 +1,4 @@+import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex 3871ccada..997f71794 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,3 +1,4 @@+import Ajv, { type ValidateFunction } from 'ajv';import Ajv2019 from 'ajv/dist/2019.js';import Ajv2020 from 'ajv/dist/2020.js';diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex 00d08265a..48d260ed6 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,3 +1,4 @@+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 5e832aa19..be5871ed9 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,3 +1,4 @@+import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -13,6 +14,7 @@ import {type MarkdownlintSlice,} from './types.ts';+const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex da6c477e9..772183427 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];@@ -69,6 +70,7 @@ export interface FrontmatterSlice {schemas: ResolvedFrontmatterSchemaEntry[];}+interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.tsindex 98238656e..437cc539a 100644--- a/packages/core/src/markdown/lint/validation-counts.ts+++ b/packages/core/src/markdown/lint/validation-counts.ts@@ -1,3 +1,4 @@+export interface ValidationSourceCounts {errorCount: number;warningCount: number;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex a5b511f25..bd79424c7 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex ed89371d0..00fbc0035 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex 8ce2b2492..df788a80d 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,3 +1,4 @@+import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 1a897fca8..17ed2b829 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 9864b3b60..7e4a9a48b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,6 +168,7 @@ export function parseRecursive(}}+interface VFilePlace {offset?: number;start?: { offset?: number };@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}+interface Region {start: number;end: number;@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}+export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}+interface SourceBlock {src: string;start: number;@@ -452,6 +456,7 @@ function tryPerBlockFallback(};}+function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex e6ab4fd57..43d420187 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,3 +1,4 @@+export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 4426ab46e..c21e1fdf1 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 91cdf658f..ccf06e94d 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,3 +1,4 @@+import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';import { isBlankLineParagraph } from './zero-emission-blocks.ts';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 0f399d34c..e5b4c9eba 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,3 +1,4 @@+import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- } else if (first === '[') {+ }+ else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex db10fa54b..ca225ce9b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,3 +1,4 @@+import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 34068d103..3a2524a9a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 93151d43b..2279a0189 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex 188f02d83..a0f467c42 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4ba2c3418..4e8542a21 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex 1a74b1272..a3c96b24a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex de35e7b79..e95cf43d6 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex b4be1b2ea..ffdb4d5b5 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex 3c8d88b7c..e2a96d1a7 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex cf2c9da8e..0389575ac 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,3 +1,4 @@+import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.tsindex 0dd54070e..96304e7a5 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,3 +1,4 @@+import type { JSONContent } from '@tiptap/core';import type { Nodes } from 'mdast';import { expect } from 'vitest';diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 46cc6a074..542204403 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,3 +1,4 @@+import type { Node as PmNode } from '@tiptap/pm/model';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { PropDef, SerializeContext } from '../registry/types.ts';diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex b012a5aff..8c08b7a04 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,3 +1,4 @@+import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex a41534404..20ce25dbe 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,3 +1,4 @@+import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.tsindex 0f1b0f27d..6e6d73400 100644--- a/packages/core/src/markdown/underline-promoter.ts+++ b/packages/core/src/markdown/underline-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex 1a082bda7..932d7d2a8 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,3 +1,4 @@+import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex d578476a7..ac9f5239b 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,3 +1,4 @@+const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex 6dad26200..afd9936fe 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {}}+const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {};}+function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};+const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/desktop/src/main/bundle-paths.test.ts b/packages/desktop/src/main/bundle-paths.test.tsindex 2d7fe1eae..826ef493e 100644--- a/packages/desktop/src/main/bundle-paths.test.ts+++ b/packages/desktop/src/main/bundle-paths.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'vitest';-import { wrapperPathInBundle } from './bundle-paths.ts';+import { appBundleRootFromExecutable, wrapperPathInBundle } from './bundle-paths.ts';describe('wrapperPathInBundle', () => {test('maps packaged executable path to bundled ok.sh wrapper', () => {@@ -11,3 +11,38 @@ describe('wrapperPathInBundle', () => {).toBe('/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh');});});++describe('appBundleRootFromExecutable', () => {+ test('darwin reduces the main binary to the .app root that also holds the helpers', () => {+ const root = appBundleRootFromExecutable(+ '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge',+ 'darwin',+ );++ expect(root).toBe('/Applications/OpenKnowledge.app');+ // The helper apps must land inside it — they are the processes that+ // actually crash most often.+ expect(+ '/Applications/OpenKnowledge.app/Contents/Frameworks/OpenKnowledge Helper.app/Contents/MacOS/OpenKnowledge Helper'.startsWith(+ `${root}/`,+ ),+ ).toBe(true);+ });++ test('a darwin binary run outside a bundle degrades to its own directory', () => {+ // Never the filesystem root: that would make every dump on the machine+ // read as ours.+ expect(appBundleRootFromExecutable('/opt/local/bin/openknowledge', 'darwin')).toBe(+ '/opt/local/bin',+ );+ });++ test('win32 and linux use the directory the helper binaries share', () => {+ expect(appBundleRootFromExecutable('C:\\Program Files\\OK\\OpenKnowledge.exe', 'win32')).toBe(+ 'C:\\Program Files\\OK',+ );+ expect(appBundleRootFromExecutable('/opt/OpenKnowledge/open-knowledge', 'linux')).toBe(+ '/opt/OpenKnowledge',+ );+ });+});diff --git a/packages/desktop/src/main/bundle-paths.ts b/packages/desktop/src/main/bundle-paths.tsindex 111f54871..f15b413cf 100644--- a/packages/desktop/src/main/bundle-paths.ts+++ b/packages/desktop/src/main/bundle-paths.ts@@ -25,3 +25,29 @@ export function wrapperPathInBundle(const bundleRoot = executablePath.replace(/\/Contents\/MacOS\/.*$/, '');return join(bundleRoot, 'Contents', 'Resources', 'cli', 'bin', 'ok.sh');}++/**+ * Root that every process of this app launches from, given the main+ * executable's path — the containment boundary for deciding whether a file on+ * disk belongs to us. Helper processes resolve inside it too: on darwin the+ * renderer/GPU/utility helpers live in `Contents/Frameworks/<Helper>.app`, and+ * elsewhere they sit beside the main binary.+ *+ * - darwin: `<Bundle>.app/Contents/MacOS/<bin>` → `<Bundle>.app`+ * - win32 / linux: the directory holding the executable+ *+ * Same layout arithmetic as `wrapperPathInBundle`, with no existence checks;+ * a darwin path that isn't bundle-shaped (an unpackaged binary run directly)+ * degrades to the executable's directory rather than to the filesystem root.+ */+export function appBundleRootFromExecutable(+ executablePath: string,+ platform: 'darwin' | 'win32' | 'linux' | string = process.platform,+): string {+ if (platform === 'win32') return win32.dirname(executablePath);+ if (platform === 'darwin') {+ const bundleRoot = executablePath.replace(/\/Contents\/MacOS\/[^/]+$/, '');+ if (bundleRoot !== executablePath) return bundleRoot;+ }+ return dirname(executablePath);+}diff --git a/packages/desktop/src/main/crash-detection.test.ts b/packages/desktop/src/main/crash-detection.test.tsindex fb5af1c22..f3c14ca71 100644--- a/packages/desktop/src/main/crash-detection.test.ts+++ b/packages/desktop/src/main/crash-detection.test.ts@@ -24,6 +24,7 @@ import {createCrashDetection,startLocalCrashReporter,} from './crash-detection.ts';+import { buildMinidump } from './minidump.test-helper.ts';const tmpDirs: string[] = [];@@ -38,9 +39,20 @@ const silentLogger = {warn: () => {},};+/** A third-party GUI app that inherited our exception handler and aborted. */+const FOREIGN_DUMP = buildMinidump([+ '/Applications/LibreOffice.app/Contents/MacOS/soffice',+ '/usr/lib/dyld',+]);++/** Truncated past the header — the shape a crash-during-dump-write leaves. */+const UNPARSEABLE_DUMP = Buffer.from('minidump-bytes-that-are-not-a-minidump');+interface Rig {deps: CrashDetectionDeps;emitted: OkBugReportCrashDetectedEvent[];+ /** A dump naming one of this rig's own executables as its main module. */+ ownDump: Buffer;/** Flip to false to simulate "no live renderer window can take the event". */setRendererAvailable(available: boolean): void;/** Swap the kernel boot-session identity, simulating a reboot between sessions. */@@ -57,9 +69,24 @@ function makeRig(): Rig {let rendererAvailable = true;let bootSessionUuid: string | null = 'boot-epoch-a';let clockMs = Date.parse('2026-07-10T00:00:00.000Z');+ const appBundleRoot = join(dir, 'Applications', 'OpenKnowledge.app');return {dir,emitted,+ // A helper process rather than the main binary: renderer/GPU/utility crashes+ // are the common case, and they must resolve inside the bundle root too.+ ownDump: buildMinidump([+ join(+ appBundleRoot,+ 'Contents',+ 'Frameworks',+ 'OpenKnowledge Helper (Renderer).app',+ 'Contents',+ 'MacOS',+ 'OpenKnowledge Helper (Renderer)',+ ),+ '/usr/lib/dyld',+ ]),setRendererAvailable(available: boolean) {rendererAvailable = available;},@@ -74,6 +101,7 @@ function makeRig(): Rig {sentinelPath: join(dir, 'user-data', 'bug-report-dirty-shutdown.json'),ackStorePath: join(dir, 'user-data', 'bug-report-crash-acks.json'),crashDumpsDir: join(dir, 'crash-dumps'),+ appBundleRoot,emit(event) {if (!rendererAvailable) return false;emitted.push(event);@@ -96,12 +124,17 @@ function readSentinel(rig: Rig): Record<string, string | undefined> {>;}-/** Seed a minidump whose mtime is pinned to the fake clock's timeline. */-function seedMinidump(rig: Rig, relPath: string, at: Date): void {+/**+ * Seed a minidump whose mtime is pinned to the fake clock's timeline. Defaults+ * to a dump owned by this rig's app bundle, so every pre-existing test keeps+ * meaning "a dump for one of our own processes is on disk".+ */+function seedMinidump(rig: Rig, relPath: string, at: Date, contents: Buffer = rig.ownDump): string {const dumpPath = join(rig.deps.crashDumpsDir, relPath);mkdirSync(dirname(dumpPath), { recursive: true });- writeFileSync(dumpPath, 'minidump-bytes');+ writeFileSync(dumpPath, contents);utimesSync(dumpPath, at, at);+ return dumpPath;}describe('runtime process-gone invitations', () => {@@ -375,6 +408,10 @@ describe('machine-level death suppression', () => {if (armed?.kind === 'boot') {expect(armed.context.dirtyShutdown).toBe(false);expect(armed.context.newMinidumps).toBe(1);+ // Ownership decides availability, and this is the one path that reaches+ // it across a boot-session boundary — a root that went stale between+ // sessions would show up here and nowhere else.+ expect(armed.minidumpAvailable).toBe(true);}});@@ -576,6 +613,232 @@ describe('newest un-acked minidump lookup', () => {});});+/**+ * macOS inherits Mach exception ports across fork/exec, so anything descended+ * from the app — the in-app terminal's shell, an MCP server, an unrelated GUI+ * app launched from that shell — writes its crash into OUR crash database under+ * OUR annotations. Two separate consequences are pinned here: a foreign dump+ * must not arm a report invitation, and (the serious one) it must never be+ * attachable to a bundle that leaves the machine carrying another program's+ * process memory.+ */+describe('crash-dump ownership filtering', () => {+ /** Boot with a clean previous session, so dumps are the only arming signal. */+ function bootAfterCleanQuit(rig: Rig) {+ const sessionA = createCrashDetection(rig.deps);+ sessionA.detectBootCrash();+ sessionA.markCleanQuit();+ }++ test('a dump from one of our own processes still arms and is still attachable', () => {+ const rig = makeRig();+ bootAfterCleanQuit(rig);+ const ownPath = seedMinidump(rig, 'pending/ours.dmp', rig.tick());++ const session = createCrashDetection(rig.deps);+ const armed = session.detectBootCrash();++ expect(armed?.kind).toBe('boot');+ if (armed?.kind === 'boot') {+ expect(armed.context.dirtyShutdown).toBe(false);+ expect(armed.context.newMinidumps).toBe(1);+ expect(armed.minidumpAvailable).toBe(true);+ }+ expect(session.newestMinidumpPath()).toBe(ownPath);+ });++ test('a dump from a foreign process neither arms nor is attachable', () => {+ const rig = makeRig();+ bootAfterCleanQuit(rig);+ seedMinidump(rig, 'pending/soffice.dmp', rig.tick(), FOREIGN_DUMP);++ const session = createCrashDetection(rig.deps);++ // The shape that misfires without the ownership gate: the app quit+ // cleanly, a third-party app the user launched from the in-app terminal+ // aborted, and the next boot claimed "the previous session crashed".+ expect(session.detectBootCrash()).toBeNull();+ session.notifyRendererReady();+ expect(rig.emitted).toHaveLength(0);+ expect(session.newestMinidumpPath()).toBeNull();+ });++ test('a bundle-root prefix collision does not read as ownership', () => {+ const rig = makeRig();+ bootAfterCleanQuit(rig);+ seedMinidump(+ rig,+ 'pending/lookalike.dmp',+ rig.tick(),+ buildMinidump([`${rig.deps.appBundleRoot}.malicious/Contents/MacOS/OpenKnowledge`]),+ );++ const session = createCrashDetection(rig.deps);++ expect(session.detectBootCrash()).toBeNull();+ expect(session.newestMinidumpPath()).toBeNull();+ });++ test('an unparseable dump still arms, but is never attachable', () => {+ const rig = makeRig();+ bootAfterCleanQuit(rig);+ seedMinidump(rig, 'pending/torn.dmp', rig.tick(), UNPARSEABLE_DUMP);++ const session = createCrashDetection(rig.deps);+ const armed = session.detectBootCrash();++ // Fail open on the prompt: a dump truncated by the very crash that wrote it+ // is probably ours, and a wrong guess costs one dismissible question.+ expect(armed?.kind).toBe('boot');+ if (armed?.kind === 'boot') {+ expect(armed.context.newMinidumps).toBe(1);+ // Fail closed on egress: memory whose owner we cannot establish is memory+ // the consent dialog cannot honestly describe.+ expect(armed.minidumpAvailable).toBe(false);+ }+ expect(session.newestMinidumpPath()).toBeNull();+ });++ test('a foreign dump does not override machine-level-death suppression', () => {+ const rig = makeRig();+ createCrashDetection(rig.deps).detectBootCrash();+ seedMinidump(rig, 'pending/soffice.dmp', rig.tick(), FOREIGN_DUMP);+ // The machine rebooted out from under the session. A dump written for some+ // other program is no evidence that this app native-crashed first, so the+ // fresh-dump override must not engage.++ rig.setBootSessionUuid('boot-epoch-b');+ const session = createCrashDetection(rig.deps);++ expect(session.detectBootCrash()).toBeNull();+ });++ test('a dirty shutdown still prompts when the only fresh dump is foreign', () => {+ const rig = makeRig();+ createCrashDetection(rig.deps).detectBootCrash();+ // Session A really did die (its sentinel survives) while an unrelated+ // descendant also crashed — same kernel session, so no reboot suppression.+ seedMinidump(rig, 'pending/soffice.dmp', rig.tick(), FOREIGN_DUMP);++ const armed = createCrashDetection(rig.deps).detectBootCrash();++ expect(armed?.kind).toBe('boot');+ if (armed?.kind === 'boot') {+ expect(armed.context.dirtyShutdown).toBe(true);+ expect(armed.context.newMinidumps).toBe(0);+ expect(armed.minidumpAvailable).toBe(false);+ }+ });++ test('the newest OWN dump is attachable even when a newer foreign dump exists', () => {+ const rig = makeRig();+ const detection = createCrashDetection(rig.deps);+ const ownPath = seedMinidump(rig, 'completed/ours.dmp', rig.tick());+ seedMinidump(rig, 'pending/soffice.dmp', rig.tick(), FOREIGN_DUMP);++ expect(detection.newestMinidumpPath()).toBe(ownPath);+ });++ test('a runtime crash offers no dump when only a foreign dump is on disk', () => {+ const rig = makeRig();+ const detection = createCrashDetection(rig.deps);+ seedMinidump(rig, 'completed/soffice.dmp', rig.tick(), FOREIGN_DUMP);++ detection.handleRenderProcessGone({ reason: 'crashed' });++ expect(rig.emitted[0]?.minidumpAvailable).toBe(false);+ expect(detection.newestMinidumpPath()).toBeNull();+ });++ test('a runtime crash says how many foreign dumps it walked past', () => {+ // "No checkbox" has two very different causes at runtime — Crashpad still+ // flushing our dump, or a descendant's dump being skipped — and only this+ // count tells an operator which one they are looking at.+ const rig = makeRig();+ const warnLines: Array<Record<string, unknown>> = [];+ rig.deps.logger = {+ info: () => {},+ warn: (payload: Record<string, unknown>) => {+ warnLines.push(payload);+ },+ };+ const detection = createCrashDetection(rig.deps);+ seedMinidump(rig, 'completed/soffice.dmp', rig.tick(), FOREIGN_DUMP);++ detection.handleRenderProcessGone({ reason: 'crashed' });++ expect(+ warnLines.find((line) => line.event === 'crash-detection.render-process-gone')+ ?.foreignDumpsIgnored,+ ).toBe(1);+ });++ test('a runtime crash counts unreadable dumps apart from foreign ones', () => {+ // The two mean different things to whoever reads the line: a foreign dump+ // is a descendant crashing, an unreadable one is a half-flushed dump or+ // the first sign the format drifted. Folded together they say neither.+ const rig = makeRig();+ const warnLines: Array<Record<string, unknown>> = [];+ rig.deps.logger = {+ info: () => {},+ warn: (payload: Record<string, unknown>) => {+ warnLines.push(payload);+ },+ };+ const detection = createCrashDetection(rig.deps);+ seedMinidump(rig, 'completed/torn.dmp', rig.tick(), UNPARSEABLE_DUMP);++ detection.handleRenderProcessGone({ reason: 'crashed' });++ const line = warnLines.find((l) => l.event === 'crash-detection.render-process-gone');+ expect(line?.unreadableDumpsSkipped).toBe(1);+ expect(line?.foreignDumpsIgnored).toBe(0);+ expect(rig.emitted[0]?.minidumpAvailable).toBe(false);+ });++ test('an own dump found first is not reported as foreign dumps ignored', () => {+ // The walk stops at the first owned dump, so the count only ever describes+ // what it actually rejected getting there.+ const rig = makeRig();+ const warnLines: Array<Record<string, unknown>> = [];+ rig.deps.logger = {+ info: () => {},+ warn: (payload: Record<string, unknown>) => {+ warnLines.push(payload);+ },+ };+ const detection = createCrashDetection(rig.deps);+ seedMinidump(rig, 'completed/ours.dmp', rig.tick());++ detection.handleChildProcessGone({ type: 'Utility', reason: 'crashed' });++ const line = warnLines.find((l) => l.event === 'crash-detection.child-process-gone');+ expect(line?.foreignDumpsIgnored).toBe(0);+ expect(rig.emitted[0]?.minidumpAvailable).toBe(true);+ });++ test('ignored foreign dumps leave a breadcrumb', () => {+ const rig = makeRig();+ const infoLines: Array<Record<string, unknown>> = [];+ rig.deps.logger = {+ info: (payload: Record<string, unknown>) => {+ infoLines.push(payload);+ },+ warn: () => {},+ };+ bootAfterCleanQuit(rig);+ seedMinidump(rig, 'pending/soffice.dmp', rig.tick(), FOREIGN_DUMP);++ createCrashDetection(rig.deps).detectBootCrash();++ // A silent suppression is indistinguishable from detection never running.+ const breadcrumb = infoLines.find(+ (line) => line.event === 'crash-detection.foreign-dumps-ignored',+ );+ expect(breadcrumb?.count).toBe(1);+ });+});+describe('process-level invariants', () => {test('crash detection registers no userland uncaughtException handler', () => {// Assert crash detection adds no NET uncaughtException listener rather than andiff --git a/packages/desktop/src/main/crash-detection.ts b/packages/desktop/src/main/crash-detection.tsindex 8585b7cbb..ccd259bd2 100644--- a/packages/desktop/src/main/crash-detection.ts+++ b/packages/desktop/src/main/crash-detection.ts@@ -27,6 +27,14 @@* overrides suppression: kernel panics never write app minidumps, so a dump* proves the app native-crashed before the machine went down.*+ * Not every dump in the crash database is ours. Crashpad's exception handler+ * is inherited by every descendant process, so the directory also collects+ * dumps for programs the app merely spawned. Both consumers of the dump scan+ * therefore classify by the dump's own main module (`minidump-ownership.ts`),+ * with deliberately opposite defaults for an unreadable dump: arming fails+ * open (a dismissible question), attachment fails closed (process memory+ * leaving the machine under a consent that describes THIS app).+ ** Deliberately absent: a userland `uncaughtException` handler. Electron* defers its main-process crash dialog to such a handler whenever one exists* (see `process-safety-net.ts`) — the boot-time sentinel/minidump scan is how@@ -47,6 +55,7 @@ import {} from 'node:fs';import { dirname, join } from 'node:path';import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';+import { classifyMinidumpOwnership, type MinidumpOwnership } from './minidump-ownership.ts';/*** Process-gone reasons that read as genuine crashes. `clean-exit` and@@ -120,6 +129,14 @@ export interface CrashDetectionDeps {ackStorePath: string;/** Electron's `app.getPath('crashDumps')`; scanned for fresh `.dmp` files. */crashDumpsDir: string;+ /**+ * Root that every process of this app launches from (`app.getPath('exe')`+ * reduced by `appBundleRootFromExecutable`). A dump in `crashDumpsDir` is+ * only ours when its main module resolves inside this root — Crashpad's+ * exception handler is inherited by every descendant process, so the crash+ * database also collects dumps for programs we merely spawned.+ */+ appBundleRoot: string;/*** Push one crash-detected event to a live renderer. Returns false when no* renderer could take it — the event stays armed and is re-offered on the@@ -176,13 +193,21 @@ export interface CrashDetection {ack(eventId: string): void;/*** Absolute path of the newest minidump not yet covered by an acknowledgment- * (strictly newer than the ack baseline) — 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 shutdown without a native crash) or every- * dump is already acked. Minidumps carry raw process memory that text- * redaction cannot scrub, so bundle inclusion stays behind the report- * dialog's crash-dump checkbox (pre-checked for a crash invite, opt-out)- * plus the review-before-send step that calls this — never a silent attach.+ * (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+ * 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.+ *+ * Minidumps carry raw process memory that text redaction cannot scrub, so+ * bundle inclusion stays behind the report dialog's crash-dump checkbox+ * (pre-checked for a crash invite, opt-out) plus the review-before-send step+ * that calls this — never a silent attach. Ownership is the same consent+ * question one level down: the dialog's copy describes THIS app's memory, so+ * a dump we cannot prove is ours must not be offered. This path therefore+ * fails CLOSED on an unreadable dump, unlike `detectBootCrash`, which only+ * asks a dismissible question and fails open.*/newestMinidumpPath(): string | null;}@@ -351,21 +376,48 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {return true;}- /**- * Newest minidump strictly newer than the ack baseline, or null. Shared by- * the report-time path lookup and the per-event availability signal so both- * answer from the same baseline-filtered scan of the crash-dumps dir.- */- function newestMinidumpEntry(): MinidumpEntry | null {+ function classifyDump(path: string): MinidumpOwnership {+ return classifyMinidumpOwnership(path, deps.appBundleRoot);+ }++ /** Baseline-filtered dumps from one scan of the crash-dumps dir, newest first. */+ function freshMinidumpEntries(): MinidumpEntry[] {const entries: MinidumpEntry[] = [];collectMinidumpEntries(deps.crashDumpsDir, MINIDUMP_SCAN_DEPTH, entries);const baselineMs = Date.parse(store.minidumpBaselineAt);- let newest: MinidumpEntry | null = null;- for (const entry of entries) {- if (entry.mtimeMs <= baselineMs) continue;- if (newest === null || entry.mtimeMs > newest.mtimeMs) newest = entry;+ return entries.filter((e) => e.mtimeMs > baselineMs).sort((a, b) => b.mtimeMs - a.mtimeMs);+ }++ /**+ * Newest un-acked minidump this app can prove it owns, or null. Shared by+ * the report-time path lookup and the per-event availability signal so the+ * checkbox is only offered when there is a dump the bundle may actually+ * carry. Walks newest-first and stops at the first owned dump, so a quiet+ * crash database costs one parse rather than one per file.+ *+ * The two skip counts report what the walk rejected on its way there, which+ * is what the runtime callers log. They are kept apart because they mean+ * different things to whoever reads that line: `foreignSkipped` is a+ * descendant process crashing, an ordinary event, while `unknownSkipped` is a+ * dump we could not read at all — a half-flushed one, or the first sign that+ * the format drifted out from under the parser. Counting as the walk goes+ * keeps the short-circuit intact; asking for totals afterwards would mean+ * classifying every fresh dump on every renderer crash.+ */+ function newestOwnedMinidump(): {+ entry: MinidumpEntry | null;+ foreignSkipped: number;+ unknownSkipped: number;+ } {+ let foreignSkipped = 0;+ let unknownSkipped = 0;+ for (const entry of freshMinidumpEntries()) {+ const ownership = classifyDump(entry.path);+ if (ownership === 'ours') return { entry, foreignSkipped, unknownSkipped };+ if (ownership === 'foreign') foreignSkipped += 1;+ else unknownSkipped += 1;}- return newest;+ return { entry: null, foreignSkipped, unknownSkipped };}return {@@ -418,10 +470,40 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {}}- const dumpEntries: MinidumpEntry[] = [];- collectMinidumpEntries(deps.crashDumpsDir, MINIDUMP_SCAN_DEPTH, dumpEntries);- const baselineMs = Date.parse(store.minidumpBaselineAt);- const newDumps = dumpEntries.filter((e) => e.mtimeMs > baselineMs).map((e) => e.mtimeMs);+ // Every fresh dump is classified before it can influence anything: the+ // crash database also collects dumps for descendant processes that+ // inherited our exception handler, and an unrelated program aborting is+ // not this app crashing. Without this the app prompts "the previous+ // session crashed" after a perfectly clean quit.+ const freshDumps = freshMinidumpEntries().map((entry) => ({+ entry,+ ownership: classifyDump(entry.path),+ }));+ const foreignDumpCount = freshDumps.filter((d) => d.ownership === 'foreign').length;+ const unreadableDumpCount = freshDumps.filter((d) => d.ownership === 'unknown').length;+ if (foreignDumpCount > 0 || unreadableDumpCount > 0) {+ // Otherwise a suppressed prompt and a detection pipeline that never+ // ran are indistinguishable in the logs. The unreadable count is the+ // one to watch: a dump we cannot parse at all is either half-flushed+ // or the first sign the format moved out from under the parser, and+ // unlike a foreign dump it leaves no other trace.+ deps.logger.info(+ {+ event: 'crash-detection.foreign-dumps-ignored',+ count: foreignDumpCount,+ unreadable: unreadableDumpCount,+ },+ 'ignored minidumps that this app could not claim',+ );+ }+ // Arming fails OPEN on an unparseable dump: a dump truncated by the very+ // crash that wrote it is more likely ours than not, and the cost of being+ // wrong is one prompt the user dismisses once. The attachment side takes+ // the opposite default, so an un-ownable dump can still never be sent.+ const newDumps = freshDumps+ .filter((d) => d.ownership !== 'foreign')+ .map((d) => d.entry.mtimeMs);+ const ownedDumpCount = freshDumps.filter((d) => d.ownership === 'ours').length;// A boot-session mismatch means the kernel rebooted after the previous// session was last alive; an os-shutdown marker means the OS killed the@@ -502,9 +584,11 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {eventId,kind: 'boot',context: { dirtyShutdown: !dumpDriven, newMinidumps: newDumps.length },- // A prior-session dump is already on disk, so the freshness scan- // that produced newDumps is the authoritative availability answer.- minidumpAvailable: newDumps.length > 0,+ // Availability is the stricter question — it decides whether the+ // dialog offers a checkbox that attaches process memory — so it+ // counts only dumps we proved are ours, never the fail-open set+ // that decided whether to prompt at all.+ minidumpAvailable: ownedDumpCount > 0,};if (armInvite(event)) {armed = event;@@ -590,11 +674,19 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {handleRenderProcessGone(details): void {if (!CRASH_REASONS.has(details.reason)) return;+ const owned = newestOwnedMinidump();deps.logger.warn({event: 'crash-detection.render-process-gone',reason: details.reason,exitCode: details.exitCode,+ // Otherwise an absent crash-dump checkbox is unreadable after the+ // fact: a dump Crashpad had not finished flushing and a dump written+ // for a descendant process both reach the operator as "no dump".+ // Carried on this line rather than the boot path's separate+ // breadcrumb so the counts sit with the crash they explain.+ foreignDumpsIgnored: owned.foreignSkipped,+ unreadableDumpsSkipped: owned.unknownSkipped,},'renderer process died abnormally',);@@ -609,7 +701,7 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {// Best-effort: Crashpad may still be flushing the dump when this// signal fires. A dump that lands just after reads as unavailable// here (no checkbox); the boot-time path is the reliable one.- minidumpAvailable: newestMinidumpEntry() !== null,+ minidumpAvailable: owned.entry !== null,})) {tryDeliver();@@ -618,12 +710,15 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {handleChildProcessGone(details): void {if (!CRASH_REASONS.has(details.reason)) return;+ const owned = newestOwnedMinidump();deps.logger.warn({event: 'crash-detection.child-process-gone',processType: details.type,reason: details.reason,exitCode: details.exitCode,+ foreignDumpsIgnored: owned.foreignSkipped,+ unreadableDumpsSkipped: owned.unknownSkipped,},'child process died abnormally',);@@ -637,7 +732,7 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {...(details.name !== undefined ? { name: details.name } : {}),...(details.exitCode !== undefined ? { exitCode: details.exitCode } : {}),},- minidumpAvailable: newestMinidumpEntry() !== null,+ minidumpAvailable: owned.entry !== null,})) {tryDeliver();@@ -665,7 +760,7 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {},newestMinidumpPath(): string | null {- return newestMinidumpEntry()?.path ?? null;+ return newestOwnedMinidump().entry?.path ?? null;},};}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex b2bff7dcf..7f9978adb 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -176,7 +176,7 @@ import {proxyShareTargetStatus,} from './branch-info-proxy.ts';import { createBugReportSidecarStore } from './bug-report-sidecar.ts';-import { wrapperPathInBundle } from './bundle-paths.ts';+import { appBundleRootFromExecutable, wrapperPathInBundle } from './bundle-paths.ts';import {type BundleReplaceWatcherHandle,startBundleReplaceWatcher,@@ -6099,6 +6099,12 @@ function bootPrimaryInstance(): void {sentinelPath: join(app.getPath('userData'), 'bug-report-dirty-shutdown.json'),ackStorePath: join(app.getPath('userData'), 'bug-report-crash-acks.json'),crashDumpsDir: app.getPath('crashDumps'),+ // macOS inherits Mach exception ports across fork/exec, so the crash+ // database above also collects dumps for anything a descendant process+ // launched (the in-app terminal's shell and whatever it starts). Detection+ // checks each dump's own main module against this root before treating it+ // as ours.+ appBundleRoot: appBundleRootFromExecutable(app.getPath('exe')),// Deliver to one live window — focused first — and report undeliverable// so the invitation waits for the next renderer-ready signal instead of// dropping (at boot, or when the only window is the one that crashed).diff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.tsindex 4372a2349..0c7208dfc 100644--- a/packages/desktop/src/main/ipc/bug-report.test.ts+++ b/packages/desktop/src/main/ipc/bug-report.test.ts@@ -1512,6 +1512,7 @@ describe('handleBugReportCrashAck', () => {sentinelPath: join(dir, 'sentinel.json'),ackStorePath: join(dir, 'crash-acks.json'),crashDumpsDir: join(dir, 'dumps'),+ appBundleRoot: join(dir, 'OpenKnowledge.app'),emit: () => true,now: () => {clockMs += 10_000;@@ -1522,6 +1523,9 @@ describe('handleBugReportCrashAck', () => {currentBootSessionUuid: () => 'boot-epoch-test',logger: { info: () => {}, warn: () => {} },};+ // Not a real minidump, so ownership reads as indeterminate — which the+ // boot scan deliberately treats as arm-worthy. That is what makes the ack+ // round-trip below observable; the dump itself is never attached.const seedMinidump = (relPath: string): void => {const dumpPath = join(deps.crashDumpsDir, relPath);mkdirSync(dirname(dumpPath), { recursive: true });diff --git a/packages/desktop/src/main/minidump-ownership.test.ts b/packages/desktop/src/main/minidump-ownership.test.tsnew file mode 100644index 000000000..c78e597a7--- /dev/null+++ b/packages/desktop/src/main/minidump-ownership.test.ts@@ -0,0 +1,233 @@+/**+ * Direct coverage for the minidump ownership parse.+ *+ * This module is the only thing standing between a third-party process's raw+ * memory and our bug-report uploads, and it reads attacker-shaped input: a+ * minidump we did not write, whose every length and offset is a `u32` we must+ * not trust. The tests below therefore drive the parser itself rather than+ * only its effect on crash detection.+ *+ * The security-relevant property is one-directional: NO malformed input may+ * ever be classified `'ours'`, and none may throw (a throw during the boot+ * scan would take out crash detection). `'unknown'` is the correct answer for+ * anything unreadable — callers pick their own default for it.+ */++import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { buildMinidump, type MinidumpPatch } from './minidump.test-helper.ts';+import { classifyMinidumpOwnership } from './minidump-ownership.ts';++const tmpDirs: string[] = [];++afterEach(() => {+ for (const dir of tmpDirs.splice(0)) {+ rmSync(dir, { recursive: true, force: true });+ }+});++function makeDir(): string {+ const dir = mkdtempSync(resolve(tmpdir(), 'ok-minidump-ownership-'));+ tmpDirs.push(dir);+ return dir;+}++/**+ * Write `bytes` as a dump and classify it against a bundle root under the same+ * temp dir. The builder receives that root so a case can name a module inside+ * it (ours) or anywhere else (foreign).+ */+function classifyBytes(bytes: (bundleRoot: string) => Buffer): string {+ const dir = makeDir();+ const bundleRoot = join(dir, 'Applications', 'OpenKnowledge.app');+ const dumpPath = join(dir, 'crash.dmp');+ writeFileSync(dumpPath, bytes(bundleRoot));+ return classifyMinidumpOwnership(dumpPath, bundleRoot);+}++/** The main binary of a packaged build living at `bundleRoot`. */+function ownModule(bundleRoot: string): string {+ return join(bundleRoot, 'Contents', 'MacOS', 'OpenKnowledge');+}++/** A helper process — the common crash case — inside the same bundle. */+function ownHelperModule(bundleRoot: string): string {+ return join(+ bundleRoot,+ 'Contents',+ 'Frameworks',+ 'OpenKnowledge Helper (Renderer).app',+ 'Contents',+ 'MacOS',+ 'OpenKnowledge Helper (Renderer)',+ );+}++const FOREIGN_MODULE = '/Applications/LibreOffice.app/Contents/MacOS/soffice';++describe('well-formed dumps', () => {+ test('a main-binary dump inside the bundle is ours', () => {+ expect(classifyBytes((root) => buildMinidump([ownModule(root), '/usr/lib/dyld']))).toBe('ours');+ });++ test('a helper-process dump inside the bundle is ours', () => {+ expect(classifyBytes((root) => buildMinidump([ownHelperModule(root)]))).toBe('ours');+ });++ test('a dump from an unrelated application is foreign', () => {+ expect(classifyBytes(() => buildMinidump([FOREIGN_MODULE, '/usr/lib/dyld']))).toBe('foreign');+ });++ test('only ModuleList[0] decides, not the modules loaded behind it', () => {+ // A foreign process that happens to have loaded one of our libraries must+ // not read as ours, and our own process is ours no matter what else it+ // loaded — the main executable is the whole question.+ expect(+ classifyBytes((root) => buildMinidump([FOREIGN_MODULE, join(root, 'Contents', 'lib.dylib')])),+ ).toBe('foreign');+ expect(classifyBytes((root) => buildMinidump([ownModule(root), FOREIGN_MODULE]))).toBe('ours');+ });++ test('a sibling path sharing the bundle-root prefix is foreign', () => {+ // `<root>.malicious/...` starts with the root string but is not inside it.+ expect(+ classifyBytes((root) => buildMinidump([`${root}.malicious/Contents/MacOS/OpenKnowledge`])),+ ).toBe('foreign');+ });++ test('a relative module name cannot resolve into the bundle', () => {+ expect(classifyBytes(() => buildMinidump(['Contents/MacOS/OpenKnowledge']))).toBe('foreign');+ });++ test('the ModuleList is found behind the streams a real dump puts first', () => {+ // Crashpad emits ThreadList, MemoryList, ExceptionStream and more ahead of+ // the ModuleList, so the directory search has to walk. A single-entry+ // fixture would pass even if the parser only ever read entry 0.+ expect(classifyBytes((root) => buildMinidump([ownModule(root)], { streamsBefore: 6 }))).toBe(+ 'ours',+ );+ expect(classifyBytes(() => buildMinidump([FOREIGN_MODULE], { streamsBefore: 6 }))).toBe(+ 'foreign',+ );+ });+});++/**+ * The two sides of the comparison do not spell paths the same way. Crashpad+ * records `ModuleList[0]` as the loader saw it — the path the process was+ * invoked through, symlinks intact — while the bundle root reaches us from+ * Electron's `app.getPath('exe')`, which Chromium resolves through `realpath`+ * before returning. Any symlink anywhere in the launch path therefore yields+ * two different spellings of one file, and comparing them as text alone reads+ * our own crash as somebody else's.+ *+ * Not hypothetical: a dev run launches Electron through pnpm's symlinked+ * `node_modules/electron`, and every own dump from such a run classifies+ * `'foreign'` under a purely lexical comparison.+ */+describe('symlinked launch paths', () => {+ /** Bundle at `<dir>/real/…`, reachable a second way via `<dir>/link/…`. */+ function makeLinkedBundle(): { realRoot: string; linkedExecutable: string; dir: string } {+ const dir = makeDir();+ const realRoot = join(dir, 'real', 'OpenKnowledge.app');+ mkdirSync(join(realRoot, 'Contents', 'MacOS'), { recursive: true });+ writeFileSync(join(realRoot, 'Contents', 'MacOS', 'OpenKnowledge'), '');+ symlinkSync(join(dir, 'real'), join(dir, 'link'));+ return {+ dir,+ realRoot,+ linkedExecutable: join(+ dir,+ 'link',+ 'OpenKnowledge.app',+ 'Contents',+ 'MacOS',+ 'OpenKnowledge',+ ),+ };+ }++ test('a dump recorded through a symlinked launch path is ours', () => {+ const { dir, realRoot, linkedExecutable } = makeLinkedBundle();+ const dumpPath = join(dir, 'crash.dmp');+ writeFileSync(dumpPath, buildMinidump([linkedExecutable, '/usr/lib/dyld']));++ expect(classifyMinidumpOwnership(dumpPath, realRoot)).toBe('ours');+ });++ test('resolving the link cannot launder a foreign dump into ours', () => {+ // The resolved form is what decides, so a foreign binary stays foreign no+ // matter which spelling of it the dump happens to carry.+ const { dir, realRoot } = makeLinkedBundle();+ const outsider = join(dir, 'Outsider.app', 'Contents', 'MacOS', 'Outsider');+ mkdirSync(join(dir, 'Outsider.app', 'Contents', 'MacOS'), { recursive: true });+ writeFileSync(outsider, '');+ symlinkSync(outsider, join(dir, 'outsider-link'));+ const dumpPath = join(dir, 'crash.dmp');+ writeFileSync(dumpPath, buildMinidump([join(dir, 'outsider-link')]));++ expect(classifyMinidumpOwnership(dumpPath, realRoot)).toBe('foreign');+ });+});++/**+ * Every case names a single lie the dump tells about its own layout, with the+ * rest of the structure left well-formed, so a failure points at one offset.+ */+const MALFORMED_CASES: Array<{ name: string; patch: MinidumpPatch }> = [+ { name: 'a wrong header magic', patch: { signature: 'XXXX' } },+ { name: 'a header truncated mid-field', patch: { truncateTo: 20 } },+ {+ name: 'a stream-directory RVA past the end of the file',+ patch: { streamDirectoryRva: 0xffff },+ },+ { name: 'a stream count beyond the parser cap', patch: { streamCount: 100_000 } },+ { name: 'a stream count of zero', patch: { streamCount: 0 } },+ { name: 'a directory holding no ModuleList stream', patch: { streamType: 7 } },+ { name: 'a ModuleList RVA past the end of the file', patch: { moduleListRva: 0xffff } },+ { name: 'a module count of zero', patch: { moduleCount: 0 } },+ // The ModuleList count sits at 44..48 and the first 108-byte record follows,+ // so cutting at 60 leaves the record short.+ { name: 'a first module record cut short by the file end', patch: { truncateTo: 60 } },+ { name: 'a module-name RVA past the end of the file', patch: { nameRva: 0xffff } },+ { name: 'a name byte length of zero', patch: { nameByteLength: 0 } },+ { name: 'an odd name byte length (never valid UTF-16)', patch: { nameByteLength: 9 } },+ { name: 'a name byte length beyond the parser cap', patch: { nameByteLength: 1_000_000 } },+ // Even and under the cap, but longer than the bytes actually present.+ { name: 'a name that overruns the end of the file', patch: { nameByteLength: 4096 } },+];++describe('malformed dumps are unreadable, never ours', () => {+ for (const { name, patch } of MALFORMED_CASES) {+ test(`${name} reads as unknown`, () => {+ expect(classifyBytes((root) => buildMinidump([ownModule(root)], patch))).toBe('unknown');+ });+ }++ test('a file that is not a minidump at all reads as unknown', () => {+ expect(classifyBytes(() => Buffer.from('minidump-bytes-that-are-not-a-minidump'))).toBe(+ 'unknown',+ );+ });++ test('an empty file reads as unknown', () => {+ expect(classifyBytes(() => Buffer.alloc(0))).toBe('unknown');+ });++ test('a dump that vanished before the scan reads as unknown', () => {+ // Crashpad rotates its own database, so a path can disappear between the+ // directory listing and this read.+ const dir = makeDir();+ expect(classifyMinidumpOwnership(join(dir, 'gone.dmp'), join(dir, 'OpenKnowledge.app'))).toBe(+ 'unknown',+ );+ });++ test('a directory where a dump should be reads as unknown', () => {+ // Opening succeeds on a directory; the first read is what fails.+ const dir = makeDir();+ expect(classifyMinidumpOwnership(dir, join(dir, 'OpenKnowledge.app'))).toBe('unknown');+ });+});diff --git a/packages/desktop/src/main/minidump-ownership.ts b/packages/desktop/src/main/minidump-ownership.tsnew file mode 100644index 000000000..bd4981a01--- /dev/null+++ b/packages/desktop/src/main/minidump-ownership.ts@@ -0,0 +1,189 @@+/**+ * Decide whether a minidump in our crash database was written for one of OUR+ * processes.+ *+ * The question is not rhetorical. On macOS a task's Mach exception ports are+ * inherited across fork/exec, so every descendant of the desktop process — the+ * in-app terminal's login shell, anything that shell launches, an MCP server, a+ * wholly unrelated GUI application started from that terminal — runs under the+ * Crashpad handler this app started. When such a process aborts, Crashpad+ * writes the dump into `app.getPath('crashDumps')` and stamps it with THIS+ * app's annotations (product name, version, `prod = Electron`). Nothing in the+ * dump's location or metadata distinguishes it from a real crash of ours.+ *+ * The dump's own module list does. `ModuleList[0]` is the crashed process's+ * main executable, recorded by the loader rather than by the annotation+ * pipeline, so it names the actual program that died. Resolving that path+ * against the app bundle root separates "we crashed" from "something we+ * happened to be the exception handler for crashed".+ *+ * Two Crashpad conventions carry that, and NEITHER is guaranteed by the+ * minidump format itself — they are behavior, not spec:+ *+ * 1. `ModuleList[0]` is the main executable, not just some loaded image.+ * 2. Its name is recorded as a full absolute path, not a basename.+ *+ * Both hold for Crashpad as shipped, and both were checked against real dumps+ * (one of ours, one from an unrelated app) when this was written. They are+ * written down here because the tests cannot check them: every test feeds this+ * parser bytes from a builder that assumes the same layout, so a future+ * Electron bump that reorders the module list or shortens the name would leave+ * the whole suite green. The failure is one-directional and quiet — nothing+ * leaks, but the attach-dump checkbox silently stops appearing.+ *+ * Drift surfaces in the crash-detection logs, and WHICH counter moves says+ * which kind it was. A reordered list or a shortened name still parses, so it+ * lands as `'foreign'`. Anything structural — record sizes, stream layout —+ * fails the parse instead and lands as `'unknown'`, which is why that count is+ * reported separately rather than folded in: on a crash that was plainly ours,+ * it is the only thing that moves.+ *+ * Reads only the handful of records it needs at explicit file offsets: a+ * minidump is raw process memory and can be hundreds of megabytes, so it must+ * never be slurped whole to answer a path question. No symbolizer, no Crashpad+ * tooling, no Electron.+ */++import { closeSync, openSync, readSync, realpathSync } from 'node:fs';+import { isPathWithinProject } from './path-containment.ts';++/**+ * `'unknown'` is a real third answer, not an error channel: a dump truncated by+ * the very crash that produced it, or written by a Crashpad revision whose+ * layout we don't recognize, has no honest owner. Callers choose their own+ * default for it, and the two callers here choose opposite ones.+ */+export type MinidumpOwnership = 'ours' | 'foreign' | 'unknown';++/** `MDMP` as a little-endian u32 — the minidump header signature. */+const MINIDUMP_SIGNATURE = 0x504d_444d;+const HEADER_BYTES = 32;+const NUMBER_OF_STREAMS_OFFSET = 8;+const STREAM_DIRECTORY_RVA_OFFSET = 12;+/** Directory entry: `(streamType u32, dataSize u32, rva u32)`. */+const DIRECTORY_ENTRY_BYTES = 12;+const DIRECTORY_ENTRY_RVA_OFFSET = 8;+/** `ModuleListStream` in the minidump stream-type enum. */+const MODULE_LIST_STREAM_TYPE = 4;+const MODULE_RECORD_BYTES = 108;+const MODULE_NAME_RVA_OFFSET = 20;++/**+ * Ceilings on the two counts read out of the file before any allocation. A+ * corrupt or hostile dump can name any u32 here, and a dump is untrusted input+ * for exactly the reason this module exists: it may have been written for a+ * process that is not ours.+ */+const MAX_STREAMS = 4096;+/** Byte length of the UTF-16 module name; real executable paths are far shorter. */+const MAX_MODULE_NAME_BYTES = 8192;++/** Exact positional read, or null when the file is shorter than the request. */+function readExactly(fd: number, length: number, position: number): Buffer | null {+ const buf = Buffer.alloc(length);+ return readSync(fd, buf, 0, length, position) === length ? buf : null;+}++/**+ * Path of `ModuleList[0]` — the crashed process's main executable — or null+ * when the file is not a minidump we can read that far into.+ */+function readMainModulePath(dumpPath: string): string | null {+ let fd: number | null = null;+ try {+ fd = openSync(dumpPath, 'r');+ const header = readExactly(fd, HEADER_BYTES, 0);+ if (header === null || header.readUInt32LE(0) !== MINIDUMP_SIGNATURE) return null;+ const streamCount = header.readUInt32LE(NUMBER_OF_STREAMS_OFFSET);+ if (streamCount === 0 || streamCount > MAX_STREAMS) return null;++ const directory = readExactly(+ fd,+ streamCount * DIRECTORY_ENTRY_BYTES,+ header.readUInt32LE(STREAM_DIRECTORY_RVA_OFFSET),+ );+ if (directory === null) return null;+ let moduleListRva: number | null = null;+ for (let i = 0; i < streamCount; i += 1) {+ const at = i * DIRECTORY_ENTRY_BYTES;+ if (directory.readUInt32LE(at) === MODULE_LIST_STREAM_TYPE) {+ moduleListRva = directory.readUInt32LE(at + DIRECTORY_ENTRY_RVA_OFFSET);+ break;+ }+ }+ if (moduleListRva === null) return null;++ const moduleCount = readExactly(fd, 4, moduleListRva);+ if (moduleCount === null || moduleCount.readUInt32LE(0) === 0) return null;+ const firstModule = readExactly(fd, MODULE_RECORD_BYTES, moduleListRva + 4);+ if (firstModule === null) return null;++ // A minidump string is a byte length followed by UTF-16LE units — the+ // length counts BYTES, not code units, so an odd value is malformed.+ const nameRva = firstModule.readUInt32LE(MODULE_NAME_RVA_OFFSET);+ const nameLength = readExactly(fd, 4, nameRva);+ if (nameLength === null) return null;+ const nameBytes = nameLength.readUInt32LE(0);+ if (nameBytes === 0 || nameBytes % 2 !== 0 || nameBytes > MAX_MODULE_NAME_BYTES) return null;+ const name = readExactly(fd, nameBytes, nameRva + 4);+ return name === null ? null : name.toString('utf16le');+ } catch {+ // Unopenable file, torn read, permissions change mid-scan, or a corrupt+ // dump — all mean the same thing to the caller.+ return null;+ } finally {+ if (fd !== null) {+ try {+ closeSync(fd);+ } catch {+ // Descriptor already reclaimed; nothing left to release.+ }+ }+ }+}++/**+ * Canonical spelling of `path`, or `path` unchanged when it resolves nowhere —+ * a dump routinely outlives the binary that wrote it (deleted app, replaced+ * bundle after an update, unreadable parent).+ */+function canonicalize(path: string): string {+ try {+ return realpathSync(path);+ } catch {+ return path;+ }+}++/**+ * Classify `dumpPath` against `appBundleRoot` — the root every process of this+ * app launches from, so helper processes (renderer, GPU, utility) all resolve+ * inside it alongside the main binary.+ *+ * Containment is asked twice because the two sides do not spell paths the same+ * way. Crashpad records the main module as the loader saw it, symlinks intact:+ * the path the process was actually invoked through. `appBundleRoot` descends+ * from Electron's `app.getPath('exe')`, which Chromium puts through `realpath`+ * before returning. One symlink anywhere in the launch path is enough to give a+ * single file two spellings, so the canonical forms are compared first; a dev+ * run reaching Electron through pnpm's linked `node_modules/electron` is the+ * everyday case, and under text comparison alone every own dump from one reads+ * as somebody else's. The raw comparison stays as the fallback for when either+ * side no longer resolves.+ *+ * Resolution can only ever widen `'ours'` to a module that physically sits+ * inside the bundle, which is what ownership means. A name that reads but lands+ * under neither spelling of the root is `'foreign'` — we learned what died and+ * it was not us.+ */+export function classifyMinidumpOwnership(+ dumpPath: string,+ appBundleRoot: string,+): MinidumpOwnership {+ const mainModule = readMainModulePath(dumpPath);+ if (mainModule === null) return 'unknown';+ const ours =+ isPathWithinProject(canonicalize(mainModule), canonicalize(appBundleRoot), process.platform) ||+ isPathWithinProject(mainModule, appBundleRoot, process.platform);+ return ours ? 'ours' : 'foreign';+}diff --git a/packages/desktop/src/main/minidump.test-helper.ts b/packages/desktop/src/main/minidump.test-helper.tsnew file mode 100644index 000000000..cb6be1615--- /dev/null+++ b/packages/desktop/src/main/minidump.test-helper.ts@@ -0,0 +1,104 @@+/**+ * Synthetic minidump builder shared by the ownership tests.+ *+ * Produces the smallest buffer the ownership parse can read: header, a+ * one-entry stream directory, a ModuleList, and the module-name strings. Real+ * dumps carry dozens of streams and hundreds of modules; ownership only reads+ * `ModuleList[0]`, so nothing else needs to exist.+ *+ * Built in-test rather than committed as a binary fixture — a blob nobody can+ * diff would hide which field the parse actually depends on, and the malformed+ * variants below are the point: every offset the parser trusts is reachable+ * here as a `patch` field, so a test can lie about exactly one of them and+ * leave the rest well-formed.+ */++const HEADER_BYTES = 32;+const DIRECTORY_ENTRY_BYTES = 12;+const MODULE_RECORD_BYTES = 108;+const MODULE_NAME_RVA_OFFSET = 20;+const MODULE_LIST_STREAM_TYPE = 4;++/** Per-field overrides; each one corrupts a single value the parser reads. */+export interface MinidumpPatch {+ /** Header magic. Anything but `MDMP` must be refused outright. */+ signature?: string;+ /** Header's claimed stream count, independent of what the directory holds. */+ streamCount?: number;+ /** Header's pointer to the stream directory. */+ streamDirectoryRva?: number;+ /** Directory entry's stream type; anything but 4 hides the ModuleList. */+ streamType?: number;+ /** Directory entry's pointer to the ModuleList. */+ moduleListRva?: number;+ /** ModuleList's claimed module count. */+ moduleCount?: number;+ /** `ModuleList[0]`'s pointer to its name block. */+ nameRva?: number;+ /** The name block's claimed BYTE length (not code units). */+ nameByteLength?: number;+ /** Cut the finished buffer here, simulating a dump the crash truncated. */+ truncateTo?: number;+ /**+ * Prepend this many non-ModuleList directory entries. Real Crashpad dumps+ * carry ThreadList, MemoryList, ExceptionStream and friends ahead of the+ * ModuleList, so the parser's search has to walk past them; with a+ * single-entry directory it would only ever be exercised at index 0.+ */+ streamsBefore?: number;+}++export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}): Buffer {+ const decoyStreams = patch.streamsBefore ?? 0;+ const directoryEntries = decoyStreams + 1;+ const directoryRva = HEADER_BYTES;+ const moduleListRva = directoryRva + directoryEntries * DIRECTORY_ENTRY_BYTES;+ const moduleListBytes = 4 + modulePaths.length * MODULE_RECORD_BYTES;++ // Names are laid out after the module records, so every record's name RVA+ // points forward into this block.+ const nameBlocks: Buffer[] = [];+ const nameRvas: number[] = [];+ let cursor = moduleListRva + moduleListBytes;+ for (const modulePath of modulePaths) {+ const encoded = Buffer.from(modulePath, 'utf16le');+ const block = Buffer.alloc(4 + encoded.length);+ block.writeUInt32LE(encoded.length, 0);+ encoded.copy(block, 4);+ nameBlocks.push(block);+ nameRvas.push(cursor);+ cursor += block.length;+ }+ const firstName = nameBlocks[0];+ if (patch.nameByteLength !== undefined && firstName !== undefined) {+ firstName.writeUInt32LE(patch.nameByteLength, 0);+ }++ const header = Buffer.alloc(HEADER_BYTES);+ header.write(patch.signature ?? 'MDMP', 0, 'ascii');+ header.writeUInt32LE(0xa793, 4); // version — unread by the ownership parse+ header.writeUInt32LE(patch.streamCount ?? directoryEntries, 8);+ header.writeUInt32LE(patch.streamDirectoryRva ?? directoryRva, 12);++ // Decoys first, ModuleList last, so a parser that only inspects entry 0+ // fails these fixtures instead of passing them by accident.+ const directory = Buffer.alloc(directoryEntries * DIRECTORY_ENTRY_BYTES);+ for (let i = 0; i < decoyStreams; i += 1) {+ // 3 = ThreadListStream; the type only has to not be ModuleList.+ directory.writeUInt32LE(3, i * DIRECTORY_ENTRY_BYTES);+ }+ const moduleListEntry = decoyStreams * DIRECTORY_ENTRY_BYTES;+ directory.writeUInt32LE(patch.streamType ?? MODULE_LIST_STREAM_TYPE, moduleListEntry);+ directory.writeUInt32LE(moduleListBytes, moduleListEntry + 4);+ directory.writeUInt32LE(patch.moduleListRva ?? moduleListRva, moduleListEntry + 8);++ const moduleList = Buffer.alloc(moduleListBytes);+ moduleList.writeUInt32LE(patch.moduleCount ?? modulePaths.length, 0);+ nameRvas.forEach((rva, index) => {+ const at = 4 + index * MODULE_RECORD_BYTES + MODULE_NAME_RVA_OFFSET;+ moduleList.writeUInt32LE(index === 0 ? (patch.nameRva ?? rva) : rva, at);+ });++ const dump = Buffer.concat([header, directory, moduleList, ...nameBlocks]);+ return patch.truncateTo === undefined ? dump : dump.subarray(0, patch.truncateTo);+}