Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): preserve an unreadable bug-report sidecar (PRD-8221) (#3770)
Andrew Mikofalvy1c098ac67db5
diff --git a/knip.config.ts b/knip.config.tsindex b61debe5e..8ad68f996 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -124,7 +124,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/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.tsindex 6b505314d..d979f4b39 100644--- a/packages/core/src/bridge/divergence-locate.ts+++ b/packages/core/src/bridge/divergence-locate.ts@@ -1,3 +1,4 @@+import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';export const BRIDGE_LINE_KINDS = [diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8fb428b90..01ef76a9f 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';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';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 01ac80099..dcc5b0690 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+import { stripFrontmatter } from '../extensions/frontmatter.ts';import { bodyEdgeEmpties } from './doc-boundary-space.ts';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 779e27500..ec1ac1b7e 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -206,6 +207,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -254,6 +256,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -276,6 +279,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 ?? [];@@ -344,6 +348,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -596,6 +601,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -676,6 +682,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -973,6 +980,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1098,6 +1106,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 1a81aa524..fbbd309df 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -52,6 +52,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 5f953d667..b0e7833fd 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 11b5abdfd..ffd277a90 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/okf-frontmatter/materialize.ts b/packages/core/src/markdown/lint/okf-frontmatter/materialize.tsindex 7a5af097e..f438f1b16 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts@@ -1,3 +1,4 @@+import type { OkfRuleId } from '../okf-rule-meta.ts';import { fileNameFor, OKF_SCHEMA_DIR, okfSchemaPathFor } from './paths.ts';import { OKF_FRONTMATTER_REGISTRY } from './registry.ts';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts b/packages/core/src/markdown/lint/okf-frontmatter/paths.tsindex 1ee913527..c290b6878 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts@@ -1,3 +1,4 @@+import type { OkfRuleId } from '../okf-rule-meta.ts';export const OKF_SCHEMA_DIR = '.ok/okf';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.tsindex f325fbbb4..53ecb619d 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts@@ -1,3 +1,4 @@+import { compileAppliesTo } from '../applies-to.ts';import { validateFrontmatterSource } from '../frontmatter-validate.ts';import {diff --git a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts b/packages/core/src/markdown/lint/okf-frontmatter/schemas.tsindex f1c37671b..89845d3d5 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts@@ -1,3 +1,4 @@+// file-level form is deliberate: the sibling `biome-ignore` must sit on the line// oxlint-disable unicorn/no-thenablediff --git a/packages/core/src/markdown/lint/okf-project/rules.ts b/packages/core/src/markdown/lint/okf-project/rules.tsindex 6d691ae2b..8b476332e 100644--- a/packages/core/src/markdown/lint/okf-project/rules.ts+++ b/packages/core/src/markdown/lint/okf-project/rules.ts@@ -1,3 +1,4 @@+import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';diff --git a/packages/core/src/markdown/lint/okf-rule-meta.ts b/packages/core/src/markdown/lint/okf-rule-meta.tsindex 4de50d79f..44913a9dc 100644--- a/packages/core/src/markdown/lint/okf-rule-meta.ts+++ b/packages/core/src/markdown/lint/okf-rule-meta.ts@@ -1,3 +1,4 @@+export const OKF_RULE_IDS = ['no-wiki-links','log-shape',diff --git a/packages/core/src/markdown/lint/okf-rules.ts b/packages/core/src/markdown/lint/okf-rules.tsindex 1d5538421..d0999b62e 100644--- a/packages/core/src/markdown/lint/okf-rules.ts+++ b/packages/core/src/markdown/lint/okf-rules.ts@@ -1,3 +1,4 @@+import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from './okf-rule-meta.ts';import type { OkfRule } from './okf-runner.ts';import { indexShape } from './rules/index-shape.ts';diff --git a/packages/core/src/markdown/lint/okf-runner.ts b/packages/core/src/markdown/lint/okf-runner.tsindex de130e3f4..fabb08d6e 100644--- a/packages/core/src/markdown/lint/okf-runner.ts+++ b/packages/core/src/markdown/lint/okf-runner.ts@@ -1,3 +1,4 @@+import type { Root } from 'mdast';import remarkFrontmatter from 'remark-frontmatter';import remarkGfm from 'remark-gfm';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 09c8450ee..0a089990e 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 {@@ -23,6 +24,7 @@ import {type OkfSlice,} from './types.ts';+const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/rules/index-shape.ts b/packages/core/src/markdown/lint/rules/index-shape.tsindex 59fe9b87d..fcbb1b56c 100644--- a/packages/core/src/markdown/lint/rules/index-shape.ts+++ b/packages/core/src/markdown/lint/rules/index-shape.ts@@ -1,3 +1,4 @@+import type { List, ListItem } from 'mdast';import { EXIT, visit } from 'unist-util-visit';import { defineScopedOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/rules/log-shape.ts b/packages/core/src/markdown/lint/rules/log-shape.tsindex e0159519f..431e4e9c8 100644--- a/packages/core/src/markdown/lint/rules/log-shape.ts+++ b/packages/core/src/markdown/lint/rules/log-shape.ts@@ -1,3 +1,4 @@+import type { Heading } from 'mdast';import { toString as headingText } from 'mdast-util-to-string';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/lint/rules/no-wiki-links.ts b/packages/core/src/markdown/lint/rules/no-wiki-links.tsindex 2123e977f..f75a04d15 100644--- a/packages/core/src/markdown/lint/rules/no-wiki-links.ts+++ b/packages/core/src/markdown/lint/rules/no-wiki-links.ts@@ -1,3 +1,4 @@+import type { Point } from 'unist';import { visit } from 'unist-util-visit';import { defineOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/rules/reserved-casing.ts b/packages/core/src/markdown/lint/rules/reserved-casing.tsindex 89ef3e4a9..c8b4d8f28 100644--- a/packages/core/src/markdown/lint/rules/reserved-casing.ts+++ b/packages/core/src/markdown/lint/rules/reserved-casing.ts@@ -1,3 +1,4 @@+import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';import { defineOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 6836b962d..c04fa4de0 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';import type { OkfRuleId } from './okf-rule-meta.ts';@@ -112,6 +113,7 @@ export interface OkfSlice {generate?: { index?: boolean };}+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 d988f4b8b..4aa0490c4 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 0e3224206..55736041c 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 7cac5b042..93798cf83 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,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 3e79f8cb6..959cc0bd2 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/bug-report-sidecar.test.ts b/packages/desktop/src/main/bug-report-sidecar.test.tsindex 1f71c4dcc..39391f571 100644--- a/packages/desktop/src/main/bug-report-sidecar.test.ts+++ b/packages/desktop/src/main/bug-report-sidecar.test.ts@@ -8,7 +8,17 @@* so the state machine and retention invariants are proven against real files.*/-import { existsSync, mkdtempSync, rmSync, truncateSync, utimesSync, writeFileSync } from 'node:fs';+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ truncateSync,+ utimesSync,+ writeFileSync,+} from 'node:fs';import { readFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';@@ -32,6 +42,16 @@ import {MAX_UNSENT_REPORT_COUNT,} from './ipc/bug-report.ts';+/**+ * Test projection: the sidecar's value, or `null` when it is absent or+ * unreadable. The tests below assert on stored VALUES; the absent-vs-unreadable+ * distinction is exercised directly against `readReportSidecar` instead.+ */+async function readSidecarValue(path: string) {+ const result = await readReportSidecar(path);+ return result.kind === 'ok' ? result.sidecar : null;+}+const tmpDirs: string[] = [];function makeTmpDir(): string {@@ -131,15 +151,15 @@ describe('writeReportSidecar / readReportSidecar', () => {// A YAML document, not JSON — the reader parses it back.expect(raw).toContain('state: generated');- const parsed = await readReportSidecar(sidecarPathForId(dir, id));+ const parsed = await readSidecarValue(sidecarPathForId(dir, id));expect(parsed?.id).toBe(id);expect(parsed?.state).toBe('generated');expect(parsed?.projectSlug).toBe('demo');});- test('reading an absent sidecar returns null (forgiving)', async () => {+ test('reading an absent sidecar reports `absent`, not a failure', async () => {const dir = makeTmpDir();- expect(await readReportSidecar(sidecarPathForId(dir, rid(1)))).toBeNull();+ expect(await readReportSidecar(sidecarPathForId(dir, rid(1)))).toEqual({ kind: 'absent' });});test('recordGenerated persists the note it was handed', async () => {@@ -157,7 +177,7 @@ describe('writeReportSidecar / readReportSidecar', () => {note: 'sync hung on a large repo',});- expect((await readReportSidecar(sidecarPathForId(dir, id)))?.note).toBe(+ expect((await readSidecarValue(sidecarPathForId(dir, id)))?.note).toBe('sync hung on a large repo',);});@@ -176,12 +196,85 @@ describe('writeReportSidecar / readReportSidecar', () => {projectSlug: 'demo',});- const sidecar = await readReportSidecar(sidecarPathForId(dir, id));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, id));expect(sidecar).not.toBeNull();expect(sidecar && 'note' in sidecar).toBe(false);});});+/**+ * A YAML alias bomb ("billion laughs"). `parseDocument` accepts it with an+ * EMPTY `doc.errors`, and the throw only lands on `doc.toJSON()`, so it is the+ * one input that can break a reader which trusts `doc.errors` alone.+ */+const ALIAS_BOMB_YAML = [+ 'a: &a ["x","x","x","x","x","x","x","x","x"]',+ 'b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]',+ 'c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]',+ 'd: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]',+ 'e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]',+ 'f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]',+ 'g: [*f,*f,*f,*f,*f,*f,*f,*f,*f]',+].join('\n');++describe('readReportSidecar — absent is not the same as unreadable', () => {+ test('a readable, valid sidecar reports `ok` with the parsed record', async () => {+ const dir = makeTmpDir();+ const id = rid(1);+ await writeReportSidecar(dir, makeSidecar({ id, state: 'generated' }));++ const read = await readReportSidecar(sidecarPathForId(dir, id));+ expect(read.kind).toBe('ok');+ expect(read.kind === 'ok' && read.sidecar.id).toBe(id);+ });++ test('a real IO error reports `unreadable`, and never throws', async () => {+ const dir = makeTmpDir();+ const id = rid(1);+ // A directory where the sidecar file should be: reading it fails with+ // EISDIR — a genuine non-ENOENT IO error. Unlike chmod, this is not ignored+ // when the suite runs as root and behaves the same on Windows.+ mkdirSync(sidecarPathForId(dir, id));++ const read = await readReportSidecar(sidecarPathForId(dir, id));+ expect(read.kind).toBe('unreadable');+ expect(read.kind === 'unreadable' && read.reason).toBe('io-error');+ // The cause is carried, not discarded — the silence was the worst part.+ expect(read.kind === 'unreadable' && read.err).toBeDefined();+ });++ test('malformed YAML reports `unreadable`, distinguishing it from absent', async () => {+ const dir = makeTmpDir();+ const id = rid(1);+ writeFileSync(sidecarPathForId(dir, id), 'state: [unclosed\n bad: : :\n');++ const read = await readReportSidecar(sidecarPathForId(dir, id));+ expect(read.kind).toBe('unreadable');+ expect(read.kind === 'unreadable' && read.reason).toBe('parse-error');+ });++ test('valid YAML of the wrong shape reports `unreadable`', async () => {+ const dir = makeTmpDir();+ const id = rid(1);+ writeFileSync(sidecarPathForId(dir, id), 'version: 1\nnot: a sidecar\n');++ const read = await readReportSidecar(sidecarPathForId(dir, id));+ expect(read.kind).toBe('unreadable');+ expect(read.kind === 'unreadable' && read.reason).toBe('schema-invalid');+ });++ test('a YAML alias bomb reports `unreadable` rather than throwing', async () => {+ const dir = makeTmpDir();+ const id = rid(1);+ writeFileSync(sidecarPathForId(dir, id), ALIAS_BOMB_YAML);++ // `doc.errors` is empty here; the failure only surfaces from `toJSON()`.+ const read = await readReportSidecar(sidecarPathForId(dir, id));+ expect(read.kind).toBe('unreadable');+ expect(read.kind === 'unreadable' && read.reason).toBe('parse-error');+ });+});+describe('listReports — states and ordering', () => {test('returns rows newest-first with the right state, retryability and reference', async () => {const dir = makeTmpDir();@@ -320,6 +413,87 @@ describe('deleteReport — containment and in-flight', () => {});});+describe('listReports — one bad file must never break the list', () => {+ test('an alias-bomb sidecar degrades its own row and leaves the rest listable', async () => {+ const dir = makeTmpDir();+ const goodId = await seedReport(dir, 1, { state: 'generated', note: 'a real report' });+ const bombId = rid(2);+ seedZip(dir, bombId);+ writeFileSync(sidecarPathForId(dir, bombId), ALIAS_BOMB_YAML);++ const result = await listReports(dir);++ // The whole point: the scan survives. Before the `toJSON` guard this+ // rejected `scanReports`'s `Promise.all` and took the entire history with+ // it, which is the invariant the module header states.+ expect(result.ok).toBe(true);+ const rows = result.ok ? result.reports : [];+ expect(rows.map((r) => r.id).sort()).toEqual([goodId, bombId].sort());+ expect(rows.find((r) => r.id === goodId)?.note).toBe('a real report');+ const bombRow = rows.find((r) => r.id === bombId);+ expect(bombRow?.state).toBe('unknown');+ expect(bombRow?.degraded).toBe(true);+ });++ test('retention still does its work with an alias-bomb sidecar present', async () => {+ const dir = makeTmpDir();+ // An orphan sidecar (no zip) the sweep is supposed to reclaim...+ const orphanId = rid(1);+ writeFileSync(sidecarPathForId(dir, orphanId), 'id: [unterminated\n : : :');+ const liveId = await seedReport(dir, 2, { state: 'generated' });+ // ...and an alias bomb sharing the directory with it.+ const bombId = rid(3);+ seedZip(dir, bombId);+ writeFileSync(sidecarPathForId(dir, bombId), ALIAS_BOMB_YAML);++ await runRetentionSweep(dir, createInFlightRegistry());++ // Asserting the sweep still ACTS, not merely that it resolved: a rejected+ // scan makes it bail early, which is silent and would pass a+ // does-not-throw assertion.+ expect(existsSync(sidecarPathForId(dir, orphanId))).toBe(false);+ expect(existsSync(zipPathForId(dir, liveId))).toBe(true);+ expect(existsSync(zipPathForId(dir, bombId))).toBe(true);+ });+});++describe('retention — a momentarily unreadable sidecar is not reclaimed', () => {+ // chmod is the fixture here rather than a directory: the file has to stay+ // genuinely UNLINKABLE-but-unreadable, or the assertion passes for the wrong+ // reason (unlink of a directory fails regardless of the predicate).+ test.skipIf(process.getuid?.() === 0 || process.platform === 'win32')(+ 'a sent tombstone whose sidecar hits EACCES survives the orphan sweep',+ async () => {+ const dir = makeTmpDir();+ const id = rid(1);+ // A sent tombstone: zip already reclaimed, sidecar holds the state, the+ // reference and the reporter's note.+ await writeReportSidecar(+ dir,+ makeSidecar({+ id,+ state: 'sent',+ reference: 'REF-TOMBSTONE',+ note: 'the editor froze after a paste',+ zipDeleted: true,+ }),+ );+ const path = sidecarPathForId(dir, id);+ chmodSync(path, 0o000);++ await runRetentionSweep(dir, createInFlightRegistry());++ const survived = existsSync(path);+ chmodSync(path, 0o644);+ expect(survived).toBe(true);+ // And the record is intact once it is readable again.+ const restored = await readSidecarValue(path);+ expect(restored?.reference).toBe('REF-TOMBSTONE');+ expect(restored?.note).toBe('the editor froze after a paste');+ },+ );+});+describe('send hooks — state transitions and in-flight lock', () => {test('onSendStart marks uploading and blocks a second concurrent send', async () => {const dir = makeTmpDir();@@ -327,7 +501,7 @@ describe('send hooks — state transitions and in-flight lock', () => {const store = createBugReportSidecarStore({ dir });expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: true });- expect((await readReportSidecar(sidecarPathForId(dir, id)))?.state).toBe('uploading');+ expect((await readSidecarValue(sidecarPathForId(dir, id)))?.state).toBe('uploading');// A second retry while the first is in flight is refused.expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: false });});@@ -345,7 +519,7 @@ describe('send hooks — state transitions and in-flight lock', () => {expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: true });- const synthesized = await readReportSidecar(sidecarPathForId(dir, id));+ const synthesized = await readSidecarValue(sidecarPathForId(dir, id));expect(synthesized).not.toBeNull();expect(synthesized?.projectSlug ?? null).toBeNull();expect(synthesized && 'note' in synthesized).toBe(false);@@ -362,7 +536,7 @@ describe('send hooks — state transitions and in-flight lock', () => {await store.sendHooks.onSendStart(id);await store.sendHooks.onSendResult(id, { kind: 'sent', reference: 'OK-777' });- const sidecar = await readReportSidecar(sidecarPathForId(dir, id));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, id));expect(sidecar?.state).toBe('sent');expect(sidecar?.reference).toBe('OK-777');expect(sidecar?.zipDeleted).toBe(true);@@ -389,7 +563,7 @@ describe('send hooks — state transitions and in-flight lock', () => {reason: 'complete-rejected: 503',});- const sidecar = await readReportSidecar(sidecarPathForId(dir, id));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, id));expect(sidecar?.state).toBe('upload-failed');expect(sidecar?.lastError?.reason).toBe('complete-rejected: 503');expect(sidecar?.attempts?.at(-1)).toMatchObject({ transport: 'upload', outcome: 'failed' });@@ -407,7 +581,7 @@ describe('send hooks — state transitions and in-flight lock', () => {await store.sendHooks.onSendResult(id, { kind: 'email-drafted' });- const sidecar = await readReportSidecar(sidecarPathForId(dir, id));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, id));expect(sidecar?.state).toBe('email-drafted');expect(sidecar?.attempts?.at(-1)).toMatchObject({ transport: 'email' });expect(sidecar?.note).toBe('the editor froze after a paste');@@ -423,7 +597,7 @@ describe('runRetentionSweep', () => {await runRetentionSweep(dir, createInFlightRegistry());expect(existsSync(zipPathForId(dir, id))).toBe(false);- expect((await readReportSidecar(sidecarPathForId(dir, id)))?.zipDeleted).toBe(true);+ expect((await readSidecarValue(sidecarPathForId(dir, id)))?.zipDeleted).toBe(true);});test('the tombstone write keeps the note after the zip is reclaimed', async () => {@@ -436,7 +610,7 @@ describe('runRetentionSweep', () => {// The zip that held the reporter's words is gone, so the sidecar is now the// only local copy. A tombstone that dropped it would leave the row that// most needs a title permanently unable to have one.- const sidecar = await readReportSidecar(sidecarPathForId(dir, id));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, id));expect(sidecar?.zipDeleted).toBe(true);expect(sidecar?.note).toBe(note);});@@ -597,13 +771,116 @@ describe('reconcileStaleUploading', () => {const reconciled = await reconcileStaleUploading(dir);expect(reconciled).toBe(1);- const stale = await readReportSidecar(sidecarPathForId(dir, staleId));+ const stale = await readSidecarValue(sidecarPathForId(dir, staleId));expect(stale?.state).toBe('upload-failed');expect(stale?.lastError?.reason).toBe('interrupted-by-restart');expect(stale?.note).toBe('the editor froze after a paste');// A non-uploading sidecar is untouched.- expect((await readReportSidecar(sidecarPathForId(dir, okId)))?.state).toBe('generated');+ expect((await readSidecarValue(sidecarPathForId(dir, okId)))?.state).toBe('generated');+ });+});++describe('send hooks — an unreadable sidecar is preserved, not overwritten', () => {+ /** Collects the store's warn calls so a skipped write can be shown to be loud. */+ function makeWarnRecorder() {+ const warns: { data: unknown; message: string }[] = [];+ return {+ warns,+ logger: {+ warn: (data: unknown, message: string) => {+ warns.push({ data, message });+ },+ },+ };+ }++ /** Seed a real note-bearing report, then make its sidecar unreadable in place. */+ async function seedUnreadable(dir: string, note: string): Promise<string> {+ const id = await seedReport(dir, 1, { state: 'generated', note });+ writeFileSync(sidecarPathForId(dir, id), 'state: [unclosed\n bad: : :\n');+ return id;+ }++ test('onSendStart still proceeds, and leaves the sidecar byte-identical', async () => {+ const dir = makeTmpDir();+ const id = await seedUnreadable(dir, 'the editor froze after a paste');+ const before = readFileSync(sidecarPathForId(dir, id));+ const { logger, warns } = makeWarnRecorder();+ const store = createBugReportSidecarStore({ dir, logger });++ // The send is not blocked — refusing a concurrent retry is the in-flight+ // registry's job, not the sidecar's.+ expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: true });+ expect(readFileSync(sidecarPathForId(dir, id))).toEqual(before);+ expect(warns.some((w) => w.message.includes('sidecar unreadable'))).toBe(true);});++ test('onSendResult leaves the record alone and logs the outcome it could not store', async () => {+ const dir = makeTmpDir();+ const id = await seedUnreadable(dir, 'sync hung on a large repo');+ const before = readFileSync(sidecarPathForId(dir, id));+ const { logger, warns } = makeWarnRecorder();+ const store = createBugReportSidecarStore({ dir, logger });++ await store.sendHooks.onSendResult(id, { kind: 'sent', reference: 'REF-8221' });++ expect(readFileSync(sidecarPathForId(dir, id))).toEqual(before);+ // A confirmed send's reference is the reporter's only handle on the report+ // with support. If it cannot be stored it has to be recoverable from the+ // log, or the send becomes untraceable.+ const skipped = warns.find((w) => w.message.includes('send outcome not recorded'));+ expect(skipped).toBeDefined();+ expect(JSON.stringify(skipped?.data)).toContain('REF-8221');+ });++ test('the in-flight lock is released even when the write is skipped', async () => {+ const dir = makeTmpDir();+ const id = await seedUnreadable(dir, 'a note behind a corrupt file');+ const store = createBugReportSidecarStore({ dir });++ expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: true });+ // Mid-send the lock is held, so a second retry is refused.+ expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: false });++ await store.sendHooks.onSendResult(id, { kind: 'upload-failed', reason: 'offline' });++ // The `finally` still runs on the skipped-write branch. Moving the release+ // into the `else` would compile and pass every other test while stranding+ // the report in flight forever.+ expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: true });+ });++ test('an ABSENT sidecar still synthesizes, so a legacy zip is not stranded', async () => {+ const dir = makeTmpDir();+ const id = rid(1);+ // No sidecar at all, as the CLI writes it: nothing to preserve, so the+ // first retry is still free to build a record.+ seedZip(dir, id);+ const store = createBugReportSidecarStore({ dir });++ expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: true });+ expect((await readSidecarValue(sidecarPathForId(dir, id)))?.state).toBe('uploading');+ });++ // chmod is the only fixture that keeps a PARSEABLE note behind a read failure,+ // which is what makes this the end-to-end proof. It is also the one fixture+ // root ignores, hence the guard.+ test.skipIf(process.getuid?.() === 0 || process.platform === 'win32')(+ 'a valid note survives an EACCES read rather than being erased',+ async () => {+ const dir = makeTmpDir();+ const note = 'crashed while renaming a folder';+ const id = await seedReport(dir, 1, { state: 'generated', note });+ const path = sidecarPathForId(dir, id);+ chmodSync(path, 0o000);+ const store = createBugReportSidecarStore({ dir });++ await store.sendHooks.onSendResult(id, { kind: 'sent', reference: 'REF-EACCES' });++ chmodSync(path, 0o644);+ expect((await readSidecarValue(path))?.note).toBe(note);+ },+ );});describe('legacy zip mtime ordering', () => {diff --git a/packages/desktop/src/main/bug-report-sidecar.ts b/packages/desktop/src/main/bug-report-sidecar.tsindex 6e83383d9..9b3664b12 100644--- a/packages/desktop/src/main/bug-report-sidecar.ts+++ b/packages/desktop/src/main/bug-report-sidecar.ts@@ -22,6 +22,14 @@* never break the list, and a pre-feature zip with no sidecar must still appear.* Writes are atomic; a write failure never loses the newest unsent bundle. The* state machine is enforced by these writers, not by the schema.+ *+ * Reading and writing are forgiving in *different* ways, and the difference is+ * load-bearing. The list tolerates an unreadable sidecar by degrading the row.+ * The send-path writers refuse to REWRITE one: only a genuinely absent record+ * is synthesized over, because since the note is persisted the file holds the+ * reporter's own prose, and a transient EACCES must not be allowed to erase it.+ * Retention is the deliberate exception — it still unlinks an unreadable+ * sidecar whose bundle is already gone, and one evicted by the unsent caps.*/import { readdir, readFile, realpath, stat, unlink } from 'node:fs/promises';@@ -115,27 +123,76 @@ export async function writeReportSidecar(dir: string, sidecar: ReportSidecar): P}/**- * Read + validate a sidecar. Returns `null` on ENOENT, YAML parse error, or- * schema violation — the forgiving-read contract (the caller synthesizes a- * degraded row). Only a genuine non-ENOENT IO error propagates.+ * Why a sidecar could be read but not used — diagnostic only; all three+ * preserve. Deliberately not exported: it is reachable through+ * `SidecarReadResult`, and knip fails the drift gate on an export nothing+ * outside this module consumes.+ */+type SidecarUnreadableReason = 'io-error' | 'parse-error' | 'schema-invalid';++/**+ * The outcome of reading one sidecar. `absent` and `unreadable` are separate+ * arms on purpose: a missing file means this report has no record, an+ * unreadable one means we could not tell what its record says. Collapsing them+ * into a single nullish channel is what let a transient EACCES be mistaken for+ * "never had a sidecar" and overwritten.*/-export async function readReportSidecar(sidecarPath: string): Promise<ReportSidecar | null> {+export type SidecarReadResult =+ | { kind: 'ok'; sidecar: ReportSidecar }+ | { kind: 'absent' }+ | { kind: 'unreadable'; reason: SidecarUnreadableReason; err?: unknown };++/**+ * Read + validate a sidecar. Never throws: every failure is a value, so no+ * caller has to wrap this in a `.catch` that flattens the distinction back out.+ */+export async function readReportSidecar(sidecarPath: string): Promise<SidecarReadResult> {let content: string;try {content = await readFile(sidecarPath, 'utf-8');} catch (err) {- if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;- throw err;+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'absent' };+ return { kind: 'unreadable', reason: 'io-error', err };}- const doc = parseDocument(content);- if (doc.errors.length > 0) return null;- const parsed = ReportSidecarSchema.safeParse(doc.toJSON());- return parsed.success ? parsed.data : null;+ let doc: ReturnType<typeof parseDocument>;+ try {+ // Guarded for the same reason as `toJSON` below: the composer is recursive+ // descent, so deeply nested input can exhaust the stack and throw rather+ // than fill `doc.errors`. `scanReports` no longer has a `.catch`, so any+ // escape here would take the whole history list with it.+ doc = parseDocument(content);+ } catch (err) {+ return { kind: 'unreadable', reason: 'parse-error', err };+ }+ if (doc.errors.length > 0) {+ return { kind: 'unreadable', reason: 'parse-error', err: doc.errors[0] };+ }+ let value: unknown;+ try {+ // `toJSON` throws rather than filling `doc.errors` on an alias bomb+ // (`ReferenceError: Excessive alias count indicates a resource exhaustion+ // attack`). The never-throws contract has to cover that too: `scanReports`+ // no longer wraps this call, so one such file would otherwise reject its+ // `Promise.all` and fail the whole history list.+ value = doc.toJSON();+ } catch (err) {+ return { kind: 'unreadable', reason: 'parse-error', err };+ }+ const parsed = ReportSidecarSchema.safeParse(value);+ return parsed.success+ ? { kind: 'ok', sidecar: parsed.data }+ : { kind: 'unreadable', reason: 'schema-invalid', err: parsed.error };}interface ScannedReport {id: string;sidecar: ReportSidecar | null;+ /**+ * The full read outcome. Kept alongside the flattened `sidecar` so consumers+ * that must not treat a momentary IO failure as durable corruption (the+ * retention orphan sweep) can tell the two apart.+ */+ sidecarRead: SidecarReadResult;/** A sidecar FILE was present (even if unreadable/corrupt). */sidecarPresent: boolean;zipExists: boolean;@@ -167,12 +224,17 @@ async function scanReports(dir: string): Promise<ScannedReport[]> {[...ids].map(async (id): Promise<ScannedReport> => {const zipStat = await stat(zipPathForId(dir, id)).catch(() => null);const sidecarPresent = sidecarIds.has(id);- const sidecar = sidecarPresent- ? await readReportSidecar(sidecarPathForId(dir, id)).catch(() => null)- : null;+ // The list stays forgiving: an unreadable sidecar renders as a degraded+ // `unknown` row rather than failing the scan. `sidecarPresent` is what+ // keeps it from being mistaken for a sidecar-less legacy zip.+ const read = sidecarPresent+ ? await readReportSidecar(sidecarPathForId(dir, id))+ : ({ kind: 'absent' } as const);+ const sidecar = read.kind === 'ok' ? read.sidecar : null;return {id,sidecar,+ sidecarRead: read,sidecarPresent,zipExists: zipStat !== null,zipBytes: zipStat?.size ?? sidecar?.zipBytes ?? 0,@@ -302,7 +364,7 @@ export async function deleteReport(return zipOk && sidecarOk ? { ok: true } : { ok: false, reason: 'io-error' };}-/** Build a minimal `generated` sidecar for a report with no readable record (a retried legacy zip). */+/** Build a minimal `generated` sidecar for a report with no record at all (a retried legacy zip). */async function synthesizeSidecar(dir: string, id: string): Promise<ReportSidecar> {const zipStat = await stat(zipPathForId(dir, id)).catch(() => null);return {@@ -317,6 +379,34 @@ async function synthesizeSidecar(dir: string, id: string): Promise<ReportSidecar};}+/**+ * Resolve the record a state transition should be built on, or `null` when the+ * existing record must not be overwritten.+ *+ * `absent` is the only outcome it is safe to synthesize for: there is no record+ * to lose, which is exactly the sidecar-less legacy zip being retried for the+ * first time. An `unreadable` sidecar is a file we failed to read, not a report+ * without a record — and since the note is persisted it holds the reporter's+ * own prose, so synthesizing over it destroys the text the row is titled by and+ * a retry would have resent. A transient EACCES, EIO or Windows AV lock would+ * erase it permanently and silently, so the send proceeds and the file is left+ * exactly as it is.+ */+async function readSidecarForTransition(+ dir: string,+ id: string,+ logger?: SidecarLogger,+): Promise<ReportSidecar | null> {+ const read = await readReportSidecar(sidecarPathForId(dir, id));+ if (read.kind === 'ok') return read.sidecar;+ if (read.kind === 'absent') return await synthesizeSidecar(dir, id);+ logger?.warn(+ { id, reason: read.reason, err: read.err },+ 'bug-report: sidecar unreadable, preserving the existing record and skipping the update',+ );+ return null;+}+/*** Mark a report `uploading` and acquire the in-flight lock (the `onSendStart`* hook). Returns `{ proceed: false }` when the report's send is already in@@ -333,10 +423,13 @@ async function markUploading(if (inFlight.has(id)) return { proceed: false };inFlight.add(id);try {- const base =- (await readReportSidecar(sidecarPathForId(dir, id)).catch(() => null)) ??- (await synthesizeSidecar(dir, id));- await writeReportSidecar(dir, { ...base, state: 'uploading' });+ const base = await readSidecarForTransition(dir, id, logger);+ // A skipped mark is not a blocked send: the in-flight registry, not the+ // sidecar, is what refuses a second concurrent retry, and leaving the prior+ // state also spares the row a poison `uploading` a crash could strand.+ if (base !== null) {+ await writeReportSidecar(dir, { ...base, state: 'uploading' });+ }} catch (err) {logger?.warn({ id, err }, 'bug-report: failed to mark report uploading');}@@ -347,7 +440,9 @@ async function markUploading(* Record a send's terminal outcome (the `onSendResult` hook): write the* `sent`/`upload-failed`/`email-drafted` state, append a bounded attempt,* release the in-flight lock, and run retention (which reclaims the zip on a- * confirmed send). Never throws.+ * confirmed send). Never throws. The state write is SKIPPED when the existing+ * sidecar could not be read — the outcome is logged instead of overwriting a+ * record whose contents are unknown, so the report stays retryable.*/async function recordSendResult(dir: string,@@ -358,43 +453,53 @@ async function recordSendResult(): Promise<void> {const at = new Date().toISOString();try {- const base =- (await readReportSidecar(sidecarPathForId(dir, id)).catch(() => null)) ??- (await synthesizeSidecar(dir, id));- const attempt =- outcome.kind === 'sent'- ? { at, transport: 'upload', outcome: 'success', reference: outcome.reference }- : outcome.kind === 'upload-failed'- ? {- at,- transport: 'upload',- outcome: 'failed',- error: outcome.reason,- ...(outcome.errorCode === undefined ? {} : { errorCode: outcome.errorCode }),- }- : { at, transport: 'email', outcome: 'success' };- const attempts = [...(base.attempts ?? []), attempt].slice(-MAX_REPORT_ATTEMPTS);- // Rebuild without a stale lastError, then set the new terminal fields.- const { lastError: _priorError, reference: _priorRef, ...rest } = base;- let next: ReportSidecar = { ...rest, attempts };- if (outcome.kind === 'sent') {- next = { ...next, state: 'sent', reference: outcome.reference };- } else if (outcome.kind === 'upload-failed') {- next = {- ...next,- state: 'upload-failed',- lastError: {- reason: outcome.reason,- at,- ...(outcome.errorCode === undefined ? {} : { errorCode: outcome.errorCode }),- },- };+ const base = await readSidecarForTransition(dir, id, logger);+ if (base === null) {+ // The outcome cannot be persisted without erasing a record we could+ // not read. Log it instead: a confirmed send's reference is the+ // reporter's only handle on the report with support, so losing it+ // silently is worse than the missed state write. The row keeps its+ // prior state, which leaves the report retryable rather than stranded.+ logger?.warn({ id, outcome }, 'bug-report: send outcome not recorded, sidecar unreadable');} else {- next = { ...next, state: 'email-drafted' };+ const attempt =+ outcome.kind === 'sent'+ ? { at, transport: 'upload', outcome: 'success', reference: outcome.reference }+ : outcome.kind === 'upload-failed'+ ? {+ at,+ transport: 'upload',+ outcome: 'failed',+ error: outcome.reason,+ ...(outcome.errorCode === undefined ? {} : { errorCode: outcome.errorCode }),+ }+ : { at, transport: 'email', outcome: 'success' };+ const attempts = [...(base.attempts ?? []), attempt].slice(-MAX_REPORT_ATTEMPTS);+ // Rebuild without a stale lastError, then set the new terminal fields.+ const { lastError: _priorError, reference: _priorRef, ...rest } = base;+ let next: ReportSidecar = { ...rest, attempts };+ if (outcome.kind === 'sent') {+ next = { ...next, state: 'sent', reference: outcome.reference };+ } else if (outcome.kind === 'upload-failed') {+ next = {+ ...next,+ state: 'upload-failed',+ lastError: {+ reason: outcome.reason,+ at,+ ...(outcome.errorCode === undefined ? {} : { errorCode: outcome.errorCode }),+ },+ };+ } else {+ next = { ...next, state: 'email-drafted' };+ }+ await writeReportSidecar(dir, next);}- await writeReportSidecar(dir, next);} catch (err) {- logger?.warn({ id, err }, 'bug-report: failed to record send result');+ // `outcome` rides along for the same reason the `base === null` branch logs+ // it: on a `sent` whose write failed, this is the only surviving copy of+ // the reference.+ logger?.warn({ id, err, outcome }, 'bug-report: failed to record send result');} finally {inFlight.delete(id);}@@ -510,10 +615,25 @@ export async function runRetentionSweep(// sidecar written by a newer app with a state this build doesn't recognize// still parses, and reclaiming it would make the open-enum forward// compatibility the schema exists for a lie.+ //+ // `io-error` is excluded for the same reason the send-path writers preserve:+ // it means we could not READ the file, not that the file is junk. A sent+ // tombstone is exactly this shape (zip reclaimed, sidecar holding the state,+ // the reference and the reporter's note), so unlinking one that is merely+ // locked or momentarily unreadable would destroy the record outright — a+ // harder version of the overwrite this fix exists to prevent.for (const r of scanned) {- if (r.sidecarPresent && r.sidecar === null && !r.zipExists && !inFlight.has(r.id)) {+ const durablyCorrupt =+ r.sidecarRead.kind === 'unreadable' && r.sidecarRead.reason !== 'io-error';+ if (durablyCorrupt && !r.zipExists && !inFlight.has(r.id)) {await unlinkIfPresent(sidecarPathForId(dir, r.id));- logger?.warn({ id: r.id }, 'bug-report: reclaimed an unreadable sidecar with no bundle');+ logger?.warn(+ {+ id: r.id,+ reason: r.sidecarRead.kind === 'unreadable' ? r.sidecarRead.reason : undefined,+ },+ 'bug-report: reclaimed an unreadable sidecar with no bundle',+ );}}diff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.tsindex 4d903c440..982a00b45 100644--- a/packages/desktop/src/main/ipc/bug-report.test.ts+++ b/packages/desktop/src/main/ipc/bug-report.test.ts@@ -89,6 +89,16 @@ import {resolveMinidumpIntent,} from './bug-report.ts';+/**+ * Test projection: the sidecar's value, or `null` when it is absent or+ * unreadable. The tests below assert on stored VALUES; the absent-vs-unreadable+ * distinction is exercised directly against `readReportSidecar` instead.+ */+async function readSidecarValue(path: string) {+ const result = await readReportSidecar(path);+ return result.kind === 'ok' ? result.sidecar : null;+}+const tmpDirs: string[] = [];function makeTmpDir(prefix = 'ok-bugreport-ipc-'): string {@@ -2684,7 +2694,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks stif (!result.ok) throw new Error(`expected ok, got: ${result.error}`);expect(result.zipPath).toBe(zipPath);- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar?.id).toBe(REPORT_ID);expect(sidecar?.state).toBe('generated');expect(sidecar?.bundleLevel).toBe('standard');@@ -2701,7 +2711,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st});if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar?.note).toBe('The editor froze after I pasted a large table');});@@ -2716,7 +2726,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st});if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar?.note).toBe(note);expect(readZipEntry(zipPath, 'note.txt')).toContain(note);});@@ -2727,7 +2737,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks stconst result = await handleBugReportCreate(createDeps, { kind: 'create', level: 'standard' });if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar).not.toBeNull();expect(sidecar && 'note' in sidecar).toBe(false);});@@ -2745,7 +2755,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st});if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar).not.toBeNull();expect(sidecar && 'note' in sidecar).toBe(false);});@@ -2764,7 +2774,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks stexpect(result.ok).toBe(true);// No sidecar landed, and that is the accepted cost — the report itself did.- expect(await readReportSidecar(sidecarPathForId(dir, REPORT_ID))).toBeNull();+ expect(await readSidecarValue(sidecarPathForId(dir, REPORT_ID))).toBeNull();});test('a whitespace-only note is stored as no note', async () => {@@ -2780,7 +2790,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st// The row would title itself by the fallback either way, but a stored blank// still reads as "has a note", so a retry would send whitespace to the// intake as the reporter's own words.- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar).not.toBeNull();expect(sidecar && 'note' in sidecar).toBe(false);});@@ -2799,7 +2809,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st// is empty, so it derives no title from this. If the writer disagreed and// stored it, the row would fall back while the sidecar claimed a note and// a retry would put the controls on the wire.- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar).not.toBeNull();expect(sidecar && 'note' in sidecar).toBe(false);});@@ -2818,7 +2828,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st// case that made the writer and the renderer disagree: the row derived no// title while the sidecar still claimed to hold a note, and a retry put it// on the wire as the reporter's words.- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar).not.toBeNull();expect(sidecar && 'note' in sidecar).toBe(false);});@@ -2840,7 +2850,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st});if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);- const stored = (await readReportSidecar(sidecarPathForId(dir, REPORT_ID)))?.note;+ const stored = (await readSidecarValue(sidecarPathForId(dir, REPORT_ID)))?.note;expect(stored?.length).toBe(32_768);expect(stored?.endsWith('\u{1F600}')).toBe(true);});@@ -2856,7 +2866,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st});if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar?.note).toBe('auth broke with [REDACTED-ANTHROPIC] in the header');// Nothing on the durable path may carry the raw secret, YAML included.const raw = readFileSync(sidecarPathForId(dir, REPORT_ID), 'utf-8');@@ -2876,7 +2886,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st});if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar?.note).toBe('db at postgres://[REDACTED]@localhost timed out');expect(sidecar?.note?.length).toBeGreaterThan(note.length);});@@ -2900,7 +2910,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st// Clamped at the ceiling with the orphaned high surrogate dropped, so the// stored copy ends on the filler rather than half an emoji.- const stored = (await readReportSidecar(sidecarPathForId(dir, REPORT_ID)))?.note;+ const stored = (await readSidecarValue(sidecarPathForId(dir, REPORT_ID)))?.note;expect(stored).toBe(`://[REDACTED]@${filler}`);// The property that matters: send re-validates the note against the same@@ -2929,7 +2939,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st);expect(result).toEqual({ ok: true, reference: 'OK-1042' });- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar?.state).toBe('sent');expect(sidecar?.reference).toBe('OK-1042');expect(sidecar?.zipDeleted).toBe(true);@@ -2949,7 +2959,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st);expect(result.ok).toBe(false);- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar?.state).toBe('upload-failed');expect(sidecar?.lastError?.reason).toContain('mint-rejected');expect(existsSync(zipPath)).toBe(true);@@ -2984,7 +2994,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st);expect(result.ok).toBe(false);- const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ const sidecar = await readSidecarValue(sidecarPathForId(dir, REPORT_ID));expect(sidecar?.lastError).toMatchObject({reason: 'mint-network-error',errorCode: 'ENOTFOUND',@@ -3025,7 +3035,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks st// The owning send still holds the report: the refusal returned before the// terminal hook, so it wrote no state and released no lock the owner is// still relying on.- expect((await readReportSidecar(sidecarPathForId(dir, REPORT_ID)))?.state).toBe('uploading');+ expect((await readSidecarValue(sidecarPathForId(dir, REPORT_ID)))?.state).toBe('uploading');expect((await store.sendHooks.onSendStart(REPORT_ID)).proceed).toBe(false);});@@ -3059,9 +3069,7 @@ describe('bug-report sidecar wiring — create writes the record, send tracks stexpect(result.ok).toBe(false);if (result.ok) throw new Error('expected fallback');expect(result.reason).toBe('email-draft');- expect((await readReportSidecar(sidecarPathForId(dir, REPORT_ID)))?.state).toBe(- 'email-drafted',- );+ expect((await readSidecarValue(sidecarPathForId(dir, REPORT_ID)))?.state).toBe('email-drafted');});});