Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): make project-scope Fix all fast and interruptible (#3125)
serafin-garciae8f3c21b3fb6
diff --git a/.changeset/fix-all-sweep-performance.md b/.changeset/fix-all-sweep-performance.mdnew file mode 100644index 000000000..35a8de6e9--- /dev/null+++ b/.changeset/fix-all-sweep-performance.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Make project-wide Fix all fast and keep the app usable while it runs. On a 2,400-document knowledge base the Problems panel took several seconds to open in project scope and a full sweep took minutes with the app locked up for most of it; the panel now opens in well under a second and the same sweep finishes in around a minute, with the window on screen, and the app stays responsive throughout. File groups start collapsed, so the panel shows a list of files and their problem counts instead of mounting every problem in the project at once — a new control next to Refresh expands or collapses them all in one click. Progress now advances in batches rather than on every file, which also stops screen readers announcing thousands of updates during a sweep. The sweep paces itself and retries when the server is briefly at capacity, so it no longer starves other work happening in the project and no longer reports files as unfixable when they were only refused. A running sweep can now be stopped: previously the only way out of a Fix all started by mistake was reloading the page. Files already fixed stay fixed, and the panel re-checks the project so the remaining count is accurate.diff --git a/package.json b/package.jsonindex 204c2f36f..596a6abad 100644--- a/package.json+++ b/package.json@@ -33,6 +33,7 @@"tier3": "STRESS_FIDELITY=1 pnpm run tier2","measure:fuzz": "cd packages/app && pnpm run measure:fuzz","measure:stress": "cd packages/app && pnpm run measure:stress",+ "measure:sweep": "cd packages/app && pnpm run measure:sweep","prepare": "bash scripts/husky-prepare.sh","changeset": "changeset",diff --git a/packages/app/package.json b/packages/app/package.jsonindex fc42581e3..b2e9b9e28 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -25,6 +25,7 @@"test:stress:api": "tsx tests/stress/stress-api.ts","measure:fuzz": "bash scripts/measure-fuzz.sh","measure:stress": "bash scripts/measure-stress.sh",+ "measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh","test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox",diff --git a/packages/app/scripts/_measure-lib.sh b/packages/app/scripts/_measure-lib.shindex ac9b75295..cb45775d3 100755--- a/packages/app/scripts/_measure-lib.sh+++ b/packages/app/scripts/_measure-lib.sh@@ -1,11 +1,11 @@#!/usr/bin/env bash#-# _measure-lib.sh — shared helpers for measure-fuzz.sh + measure-stress.sh+# _measure-lib.sh — shared helpers for the measure-*.sh / perf-*.sh producer scripts#-# Source this from both producer scripts after `set -euo pipefail` to pick+# Source this from any producer script after `set -euo pipefail` to pick# up the functions below. Keeps host detection, epoch-ms resolution, JSONL# append serialization, and numeric-flag validation in one place so a-# future schema change or portability fix touches one file, not two.+# future schema change or portability fix touches one file, not each consumer.## **This file is not directly invokable.** Source it. `bash _measure-lib.sh`# exits 1 with a diagnostic.diff --git a/packages/app/scripts/make-sweep-fixture.mjs b/packages/app/scripts/make-sweep-fixture.mjsnew file mode 100644index 000000000..2bb5f1baa--- /dev/null+++ b/packages/app/scripts/make-sweep-fixture.mjs@@ -0,0 +1,364 @@+#!/usr/bin/env node+//+// make-sweep-fixture.mjs — generate the content fixtures the sweep measurement+// and manual QA run against.+//+// Why this exists+// ---------------+// `measure-sweep.sh` and the Fix-all QA scenarios both need a large corpus with+// a known number of fixable lint findings. Those corpora used to be hand-built+// outside the repo, which made `pnpm run measure:sweep` reproducible only on the+// machine that happened to still have them. This script makes the fixture a+// derived artifact: same seed in, same corpus out, on any machine.+//+// Output is a plain content directory — no `.ok/`, no git. The consumer copies+// it to a scratch dir and points a server at the copy.+//+// Usage+// -----+// node scripts/make-sweep-fixture.mjs --preset realistic --out ~/ok-validation/realistic+// node scripts/make-sweep-fixture.mjs --preset small --out ~/ok-validation/small+// node scripts/make-sweep-fixture.mjs --preset subchunk --out ~/ok-validation/subchunk+//+// Flags+// -----+// --preset NAME realistic | small | subchunk (required unless --docs given)+// --out DIR destination directory (required). Refuses a non-empty dir+// unless --force.+// --docs N override the preset's document count.+// --seed N PRNG seed (default 7714) — same seed, same corpus.+// --force replace a non-empty directory. Refuses unless the target+// carries this script's `.ok-sweep-fixture` marker and has no+// `.git` — a mistyped --out must not delete real work.+// --quiet suppress the per-preset summary.+//+// Presets+// -------+// realistic 2,400 docs shaped to match the corpus the spec's §7 numbers were+// measured on: ~2,341 docs carrying at least one finding, ~2,083 of+// those carrying at least one FIXABLE finding, ~8,300 findings total.+// small 36 docs, 6 of them fixable — the "small project" QA fixture.+// subchunk 45 docs, all fixable, deliberately long so a sub-chunk sweep still+// takes multiple seconds (the progress-visibility scenario).+//+// No wiki-links are emitted. The corpus is intentionally link-free: the doc-scoped+// audit walks the backward link index, so a link-dense corpus measures the link+// graph rather than the sweep.+//+// Calibration+// -----------+// `realistic` was tuned against a real `GET /api/audit` rather than by reasoning+// about which rules fire. Measured at seed 7714:+//+// docs scanned 2400 · groups 2341 · fixable files 2083 · findings 8734 · 2.31 MB+//+// The first three are exact (they follow from role assignment) and are what drive+// render cost; the finding total runs ~5% above the 8,304 of the corpus the spec's+// §7 numbers came from, and the response size matches its stated 2.3 MB.+//+// Two calibration findings are baked into the emitters below, both of which had+// silently inflated an earlier draft of this corpus:+// - a frontmatter `title:` makes MD025 fire on EVERY document, so no document is+// ever genuinely clean (see buildDoc);+// - a heading block deeper than the document's h1 trips MD001 as collateral.++import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { join, resolve } from 'node:path';++// ── PRNG (mulberry32) — deterministic across platforms/Node versions ─────────+function makeRng(seed) {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++// ── Violation blocks ────────────────────────────────────────────────────────+// Each block is written to yield exactly ONE finding, and is separated from its+// neighbours by blank lines so heading/list spacing rules (MD022/MD031/MD032)+// do not fire as collateral and inflate the count. The `fixable` flag records+// whether markdownlint ships an autofix for that rule — the sweep only acts on+// findings that carry one, so the two groups are what make a doc land in the+// "fixable" bucket or merely the "has problems" bucket.++const FIXABLE_BLOCKS = [+ // MD009 — trailing spaces (one trailing space; br_spaces default of 2 makes a+ // 2-space line a legal hard break, so one space is the unambiguous violation).+ (i) => `Paragraph ${i} carries a single trailing space. `,+ // MD010 — hard tabs.+ (i) => `Paragraph ${i}\tcontains a hard tab character.`,+ // MD018 — no space after hash in an ATX heading. Level 2, so it does not trip+ // MD001 (heading-increment) against the document's h1.+ (i) => `##Section ${i} heading without a space after the hash`,+ // MD019 — multiple spaces after hash. Level 2 for the same reason.+ (i) => `## Section ${i} heading with two spaces after the hash`,+];++const NON_FIXABLE_BLOCKS = [+ // MD040 — fenced code block without a language.+ (i) => `\`\`\`\nplain fenced block ${i} with no language\n\`\`\``,+ // MD042 — empty link.+ (i) => `Paragraph ${i} links to [nothing here]().`,+ // MD045 — image with no alternate text.+ (i) => `Paragraph ${i} shows  inline.`,+];++const FILLER = [+ 'This paragraph is ordinary prose and carries no lint findings at all.',+ 'It exists so the document has enough body to look like real content.',+ 'Nothing here should trip a rule; it is deliberately unremarkable text.',+ 'The corpus needs bulk so the audit walk and the render both do real work.',+];++/**+ * Build one document.+ *+ * @param index doc number, used for stable titles/paths+ * @param fixableCount how many fixable-rule blocks to inject+ * @param brokenCount how many non-fixable-rule blocks to inject+ * @param fillerParas how many clean paragraphs to pad with+ * @param rng seeded PRNG+ */+function buildDoc(index, fixableCount, brokenCount, fillerParas, rng) {+ const lines = [];+ // No `title:` key: MD025's front_matter_title default treats a frontmatter+ // title as the document's top-level heading, which would make the `# ...`+ // below a second h1 and fire MD025 on EVERY doc — including the ones this+ // fixture needs to be genuinely clean.+ lines.push('---');+ lines.push(`index: ${index}`);+ lines.push('---');+ lines.push('');+ lines.push(`# Document ${index}`);+ lines.push('');+ lines.push(FILLER[index % FILLER.length]);+ lines.push('');++ const blocks = [];+ for (let i = 0; i < fixableCount; i++) {+ const pick = FIXABLE_BLOCKS[Math.floor(rng() * FIXABLE_BLOCKS.length)];+ blocks.push(pick(index * 100 + i));+ }+ for (let i = 0; i < brokenCount; i++) {+ const pick = NON_FIXABLE_BLOCKS[Math.floor(rng() * NON_FIXABLE_BLOCKS.length)];+ blocks.push(pick(index * 100 + i));+ }+ for (let i = 0; i < fillerParas; i++) {+ blocks.push(FILLER[(index + i) % FILLER.length]);+ }++ // Shuffle so violations are not all clustered at the top of every doc.+ for (let i = blocks.length - 1; i > 0; i--) {+ const j = Math.floor(rng() * (i + 1));+ [blocks[i], blocks[j]] = [blocks[j], blocks[i]];+ }++ for (const block of blocks) {+ lines.push(block);+ lines.push('');+ }++ // Trailing newline is present, so MD047 does not fire as an uncounted extra.+ return lines.join('\n').replace(/\n+$/, '\n');+}++// ── Presets ─────────────────────────────────────────────────────────────────+// `fixablePerDoc` / `brokenPerDoc` are ranges [min, max] inclusive.+const PRESETS = {+ realistic: {+ docs: 2400,+ cleanDocs: 59, // 2400 - 2341 docs-with-problems+ fixableDocs: 2083, // of the 2,341 with problems, these carry an autofixable one+ // Calibrated against the real audit: each block yields ~1 finding, so+ // 2,083 × ~2.5 + 2,341 × ~1.5 lands near the 8,304 the spec's §7 corpus had.+ fixablePerDoc: [1, 4],+ brokenPerDoc: [1, 2],+ fillerParas: [3, 8],+ },+ small: {+ docs: 36,+ cleanDocs: 24,+ fixableDocs: 6,+ fixablePerDoc: [1, 4],+ brokenPerDoc: [1, 2],+ fillerParas: [2, 5],+ },+ subchunk: {+ docs: 45,+ cleanDocs: 0,+ fixableDocs: 45,+ fixablePerDoc: [18, 26],+ brokenPerDoc: [0, 1],+ fillerParas: [40, 60],+ },+};++// ── Arg parsing ─────────────────────────────────────────────────────────────++/**+ * Reject a non-numeric or non-positive flag value instead of letting it become+ * NaN. `Number('abc')` is NaN, which silently degrades two different ways: as+ * `--docs` it makes the generation loop never iterate, so the script writes only+ * `.ok/config.yml` and still exits 0; as `--seed` it becomes 0 via `NaN >>> 0`,+ * quietly breaking the same-seed-same-corpus contract this file promises. The+ * shell siblings reject the same shape (`assert_numeric_flag` in _measure-lib.sh).+ */+function numericFlag(name, raw) {+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) {+ console.error(`error: ${name} must be a positive number (got: ${JSON.stringify(raw)})`);+ process.exit(2);+ }+ return n;+}++const argv = process.argv.slice(2);+let preset = null;+let outDir = null;+let docsOverride = null;+let seed = 7714;+let force = false;+let quiet = false;++for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--preset') preset = argv[++i];+ else if (arg === '--out') outDir = argv[++i];+ else if (arg === '--docs') docsOverride = numericFlag('--docs', argv[++i]);+ else if (arg === '--seed') seed = numericFlag('--seed', argv[++i]);+ else if (arg === '--force') force = true;+ else if (arg === '--quiet') quiet = true;+ else if (arg === '-h' || arg === '--help') {+ console.log(+ 'usage: make-sweep-fixture.mjs --preset <realistic|small|subchunk> --out <dir> [--seed N] [--force]',+ );+ process.exit(0);+ } else {+ console.error(`error: unknown flag: ${arg}`);+ process.exit(2);+ }+}++if (!preset || !PRESETS[preset]) {+ console.error(`error: --preset must be one of: ${Object.keys(PRESETS).join(', ')}`);+ process.exit(2);+}+if (!outDir) {+ console.error('error: --out <dir> is required');+ process.exit(2);+}++outDir = resolve(outDir.replace(/^~(?=$|\/)/, homedir()));++// Marker this script drops into every corpus it generates. `--force` will only+// delete a directory carrying it, so a mistyped --out (the parent+// ~/ok-validation, or `.` from inside a checkout) fails loudly instead of+// recursively destroying someone's work. The documented invocations re-target+// directories this script itself produced, so they keep working unchanged.+const FIXTURE_MARKER = '.ok-sweep-fixture';++if (existsSync(outDir) && readdirSync(outDir).length > 0) {+ if (!force) {+ console.error(`error: ${outDir} exists and is not empty (pass --force to overwrite)`);+ process.exit(2);+ }+ if (existsSync(join(outDir, '.git'))) {+ console.error(+ `error: refusing --force on ${outDir} — it contains a .git directory.\n` ++ ' This script deletes its target recursively; that looks like a real checkout.',+ );+ process.exit(2);+ }+ if (!existsSync(join(outDir, FIXTURE_MARKER))) {+ console.error(+ `error: refusing --force on ${outDir} — no ${FIXTURE_MARKER} marker found.\n` ++ ' --force only overwrites corpora this script generated. Delete the\n' ++ ' directory by hand if you really mean to replace it.',+ );+ process.exit(2);+ }+ rmSync(outDir, { recursive: true, force: true });+}+mkdirSync(outDir, { recursive: true });+writeFileSync(+ join(outDir, FIXTURE_MARKER),+ 'Generated by packages/app/scripts/make-sweep-fixture.mjs. Safe for --force to replace.\n',+ 'utf8',+);++// ── Generate ────────────────────────────────────────────────────────────────+const cfg = { ...PRESETS[preset] };+if (docsOverride !== null) cfg.docs = docsOverride;++const rng = makeRng(seed);+const pickRange = ([lo, hi]) => lo + Math.floor(rng() * (hi - lo + 1));++// Assign each doc a role up front, then shuffle so the roles are not contiguous+// (a contiguous block of clean docs would sort to one end of the panel).+const roles = [];+for (let i = 0; i < cfg.docs; i++) {+ if (i < cfg.cleanDocs) roles.push('clean');+ else if (i < cfg.cleanDocs + cfg.fixableDocs) roles.push('fixable');+ else roles.push('broken-only');+}+for (let i = roles.length - 1; i > 0; i--) {+ const j = Math.floor(rng() * (i + 1));+ [roles[i], roles[j]] = [roles[j], roles[i]];+}++// Spread docs over subdirectories so the tree resembles a real KB rather than+// one flat directory of several thousand entries.+const PER_DIR = 50;+let written = 0;++for (let i = 0; i < cfg.docs; i++) {+ const role = roles[i];+ const fixableCount = role === 'fixable' ? pickRange(cfg.fixablePerDoc) : 0;+ const brokenCount = role === 'clean' ? 0 : pickRange(cfg.brokenPerDoc);+ const fillerParas = pickRange(cfg.fillerParas);++ const body = buildDoc(i, fixableCount, brokenCount, fillerParas, rng);++ const bucket = `section-${String(Math.floor(i / PER_DIR)).padStart(3, '0')}`;+ const dir = join(outDir, bucket);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, `doc-${String(i).padStart(5, '0')}.md`), body, 'utf8');+ written++;+}++// A fixture is only usable if a server will actually lint it. `ok init` writes a+// config whose keys are all commented out, and the markdownlint plugin defaults+// to disabled — so a fixture without this file audits to zero findings and looks+// like a passing sweep of nothing.+mkdirSync(join(outDir, '.ok'), { recursive: true });+writeFileSync(+ join(outDir, '.ok', 'config.yml'),+ [+ '# Generated by make-sweep-fixture.mjs — do not hand-edit.',+ 'contentRules:',+ ' markdownlint:',+ ' enabled: true',+ '',+ ].join('\n'),+ 'utf8',+);++if (!quiet) {+ const counts = {};+ for (const role of roles) counts[role] = (counts[role] ?? 0) + 1;+ console.log(`[make-sweep-fixture] preset=${preset} seed=${seed}`);+ console.log(` out: ${outDir}`);+ console.log(` docs written: ${written}`);+ console.log(` clean: ${counts.clean ?? 0}`);+ console.log(` fixable: ${counts.fixable ?? 0}`);+ console.log(` broken-only: ${counts['broken-only'] ?? 0}`);+ console.log('');+ console.log(' Verify the finding counts against a running server:');+ console.log(` ok start --port 7801 # cwd = a COPY of ${outDir}`);+ console.log(' curl -s localhost:<api-port>/api/audit | jq ...');+}diff --git a/packages/app/scripts/measure-sweep.sh b/packages/app/scripts/measure-sweep.shnew file mode 100755index 000000000..b2d331abb--- /dev/null+++ b/packages/app/scripts/measure-sweep.sh@@ -0,0 +1,326 @@+#!/usr/bin/env bash+#+# measure-sweep.sh — ad-hoc measurement of the project-scope Fix-all sweep.+#+# Purpose+# -------+# Drive one full project-scope "Fix all" sweep through the real Problems panel+# against a prod-fidelity server, and report the five numbers the shipping+# configuration's success metrics turn on: panel-open time, full-sweep+# duration, successful-fix count, capacity-refusal count, and main-thread+# blocked time. Each run appends a structured JSONL record to+# specs/2026-07-30-fix-all-sweep-performance/evidence/sweep-measurements.jsonl —+# the git history of that file IS the trend record, exactly like the sibling+# measure:fuzz / measure:stress producers. Explicitly NOT a CI job: a sweep+# takes tens of seconds and needs a large on-disk fixture.+#+# The measured configuration is the shipping stack (R1 collapse + R2 chunk ++# R3 pace/retry) as built from the current worktree; the record labels it so a+# reader never confuses it with the spec's earlier single-lever numbers.+#+# Usage+# -----+# bash scripts/measure-sweep.sh --context "shipping-config baseline"+# bash scripts/measure-sweep.sh --context "smoke" --fixture ~/ok-validation/small+# pnpm run measure:sweep --context "re-measure after retune"+#+# Flags+# -----+# --context "..." Free-text annotation for the JSONL record (required).+# --fixture DIR Content fixture to sweep. Default+# ~/ok-validation/realistic (2,400 docs). NEVER mutated+# — copied to a scratch dir first.+# --sweep-timeout MS Max wait for the sweep to finish. Default 300000.+# --skip-build Reuse the current packages/cli + packages/app dist.+# --keep-scratch Leave the scratch fixture copy on disk (debugging).+#+# Output+# ------+# On a completed measurement:+# - Appends one JSONL record to the evidence log (script "sweep-fixall").+# - Prints a human summary comparing each metric to its §7 target; any MISS+# is surfaced prominently rather than silently recorded.+# A run whose browser measurement did not produce a SWEEP_RESULT line appends+# NOTHING and exits non-zero — a run with no evidence is not a measurement.+#+# JSONL schema+# ------------+# {+# "timestamp": "2026-07-31T04:20:00Z", // ISO 8601 UTC at run start+# "commit": "abc1234",+# "script": "sweep-fixall",+# "config": "R1+R2+R3 (shipping)",+# "fixture": "realistic",+# "context": "shipping-config baseline",+# "metrics": { ...the browser SWEEP_RESULT object... },+# "targets": { panelOpenWarmMs, sweepDurationMs, mainThreadBlockedPct, filesFailedTerminal },+# "targetMisses":[ { name, target, value, cmp } ],+# "durationMs": 74210,+# "host": "local-macos",+# "invokedBy": "user",+# "nodeVersion":"v24.x"+# }++set -euo pipefail++# shellcheck source=./_measure-lib.sh+source "$(dirname "${BASH_SOURCE[0]}")/_measure-lib.sh"++# ── Defaults ───────────────────────────────────────────────────────────────+CONTEXT=""+FIXTURE="$HOME/ok-validation/realistic"+SWEEP_TIMEOUT_MS=300000+SKIP_BUILD=0+KEEP_SCRATCH=0++# ── Arg parsing ────────────────────────────────────────────────────────────+while [[ $# -gt 0 ]]; do+ case "$1" in+ --context) CONTEXT="$2"; shift 2 ;;+ --fixture) FIXTURE="$2"; shift 2 ;;+ --sweep-timeout) SWEEP_TIMEOUT_MS="$2"; shift 2 ;;+ --skip-build) SKIP_BUILD=1; shift ;;+ --keep-scratch) KEEP_SCRATCH=1; shift ;;+ -h|--help)+ sed -n '1,/^$/p' "$0"; exit 0 ;;+ *)+ echo "error: unknown flag: $1" >&2+ echo "run with --help for usage" >&2+ exit 2 ;;+ esac+done++if [[ -z "$CONTEXT" ]]; then+ echo "error: --context is required (free-text annotation for JSONL record)" >&2+ echo "example: --context 'shipping-config baseline'" >&2+ exit 2+fi+assert_numeric_flag "--sweep-timeout" "$SWEEP_TIMEOUT_MS"++FIXTURE="${FIXTURE/#\~/$HOME}"+if [[ ! -d "$FIXTURE" ]]; then+ echo "error: fixture dir not found: $FIXTURE" >&2+ exit 2+fi++# ── Environment ────────────────────────────────────────────────────────────+require_jq+REPO_ROOT="$(resolve_repo_root)"+CLI_BIN="$REPO_ROOT/packages/cli/dist/cli.mjs"+TSX_BIN="$REPO_ROOT/node_modules/.bin/tsx"+SWEEP_SCRIPT="$REPO_ROOT/packages/app/tests/perf/sweep-measure.ts"+EVIDENCE_DIR="$REPO_ROOT/specs/2026-07-30-fix-all-sweep-performance/evidence"+LOG_FILE="$EVIDENCE_DIR/sweep-measurements.jsonl"++if [[ ! -f "$TSX_BIN" ]]; then+ echo "error: tsx not found at $TSX_BIN — run pnpm install in the OK subtree" >&2+ exit 3+fi++# ── 1. Build (turbo-cached; no-op when clean) ──────────────────────────────+if [[ "$SKIP_BUILD" -eq 0 ]]; then+ echo "[measure-sweep] building cli + app (turbo-cached)…"+ ( cd "$REPO_ROOT" && pnpm exec turbo run build \+ --filter=@inkeep/open-knowledge --filter=@inkeep/open-knowledge-app ) \+ || { echo "error: build failed — re-run 'pnpm build' to see output" >&2; exit 4; }+fi+if [[ ! -f "$CLI_BIN" ]]; then+ echo "error: CLI binary not found at $CLI_BIN after build" >&2+ exit 4+fi++# ── 2. Copy fixture to scratch (source is never mutated) ───────────────────+SCRATCH="$(mktemp -d -t ok-sweep-XXXXXX)"+SERVER_LOG="$(mktemp -t ok-sweep-server-XXXXXX.log)"+SERVER_PID=""++cleanup() {+ local ec=$?+ if [[ -n "$SERVER_PID" ]] && kill -0 "$SERVER_PID" 2>/dev/null; then+ echo "[measure-sweep] stopping server (pid $SERVER_PID)…" >&2+ kill -TERM "$SERVER_PID" 2>/dev/null || true+ for _ in 1 2 3 4 5 6 7 8 9 10; do+ kill -0 "$SERVER_PID" 2>/dev/null || break+ sleep 0.5+ done+ kill -0 "$SERVER_PID" 2>/dev/null && kill -KILL "$SERVER_PID" 2>/dev/null || true+ fi+ if [[ "$KEEP_SCRATCH" -eq 1 ]]; then+ echo "[measure-sweep] scratch kept at $SCRATCH" >&2+ else+ rm -rf "$SCRATCH" 2>/dev/null || true+ fi+ if [[ $ec -ne 0 ]]; then+ echo "[measure-sweep] exited non-zero ($ec). Server log: $SERVER_LOG" >&2+ else+ rm -f "$SERVER_LOG" 2>/dev/null || true+ fi+ exit $ec+}+trap cleanup EXIT INT TERM++echo "[measure-sweep] copying fixture → $SCRATCH …"+# Exclude .git (large, unneeded) and .ok/local (runtime state the server recreates).+rsync -a --exclude='.git' --exclude='.ok/local' "$FIXTURE/" "$SCRATCH/"++# Nav doc: any doc works — project scope audits the whole content dir. Pick the+# first markdown file outside .ok, as an extension-less content-relative name.+NAV_MD="$(find "$SCRATCH" -name '*.md' -not -path '*/.ok/*' | sort | head -1 || true)"+if [[ -z "$NAV_MD" ]]; then+ echo "error: no markdown docs found under $SCRATCH" >&2+ exit 5+fi+NAV_DOC="${NAV_MD#"$SCRATCH"/}"+NAV_DOC="${NAV_DOC%.md}"+DOC_COUNT="$(find "$SCRATCH" -name '*.md' -not -path '*/.ok/*' | wc -l | tr -d ' ')"+echo "[measure-sweep] fixture: $DOC_COUNT docs · nav-doc: $NAV_DOC"++# ── 3. Boot the server (serves both API and the Editor SPA) ────────────────+echo "[measure-sweep] starting ok server on a kernel-assigned port…"+( cd "$SCRATCH" && exec node "$CLI_BIN" start --port 0 ) >"$SERVER_LOG" 2>&1 &+SERVER_PID=$!++# The Editor SPA the browser drives is the `ui.lock` port; the API `server.lock`+# confirms the collab/HTTP side is up. Both are written under <content>/.ok/local.+read_lock_port() {+ local lock_name="$1" lock port+ lock="$(find "$SCRATCH/.ok" -name "$lock_name" 2>/dev/null | head -1 || true)"+ [[ -z "$lock" ]] && return 1+ port="$(jq -r '.port // 0' "$lock" 2>/dev/null || echo 0)"+ [[ "$port" =~ ^[0-9]+$ ]] && (( port > 0 )) && { printf '%s\n' "$port"; return 0; }+ return 1+}++EDITOR_PORT=""+for i in $(seq 1 120); do+ if EDITOR_PORT="$(read_lock_port ui.lock)" && read_lock_port server.lock >/dev/null; then+ echo "[measure-sweep] editor ready on port $EDITOR_PORT (after $((i))*0.5s)"+ break+ fi+ EDITOR_PORT=""+ if ! kill -0 "$SERVER_PID" 2>/dev/null; then+ echo "error: server exited before binding a port — log:" >&2+ tail -30 "$SERVER_LOG" >&2 || true+ exit 6+ fi+ sleep 0.5+done+if [[ -z "$EDITOR_PORT" ]]; then+ echo "error: server never bound an editor port within 60s — log:" >&2+ tail -30 "$SERVER_LOG" >&2 || true+ exit 6+fi++# ── 4. Run the browser measurement ─────────────────────────────────────────+TIMESTAMP="$(date -u +%Y-%m-%dT%H:%M:%SZ)"+COMMIT="$(git -C "$REPO_ROOT" rev-parse --short HEAD 2>/dev/null || echo unknown)"+HOST="$(detect_host)"+INVOKED_BY="${USER:-unknown}"+NODE_VERSION="$(node --version 2>/dev/null || echo unknown)"+FIXTURE_TAG="$(basename "$FIXTURE")"++echo "[measure-sweep] driving the sweep (target http://localhost:$EDITOR_PORT)…"+START_MS="$(epoch_ms)"+set +e+MEAS_OUT="$(OK_SWEEP_DOC="$NAV_DOC" "$TSX_BIN" "$SWEEP_SCRIPT" \+ --target="http://localhost:$EDITOR_PORT" \+ --nav-doc="$NAV_DOC" \+ --sweep-timeout="$SWEEP_TIMEOUT_MS")"+MEAS_EXIT=$?+set -e+END_MS="$(epoch_ms)"+DURATION_MS=$(( END_MS - START_MS ))++JSON="$(printf '%s\n' "$MEAS_OUT" | sed -n 's/^SWEEP_RESULT //p' | tail -1)"+if [[ -z "$JSON" ]] || ! jq -e . >/dev/null 2>&1 <<<"$JSON"; then+ echo "" >&2+ echo "error: the browser measurement produced no parseable SWEEP_RESULT (exit $MEAS_EXIT)." >&2+ echo " Nothing measured — no record appended. Server log: $SERVER_LOG" >&2+ exit 7+fi++# ── 5. Compare to §7 targets; surface misses ───────────────────────────────+# panel-open target uses the warm (render-bound) number — the metric R1 moves —+# not the cold-audit-inclusive first activation.+CHECKS_JSON="$(jq -c -n --argjson m "$JSON" '+ [ {name:"panelOpenWarmMs", target:1000, value:$m.panelOpenWarmMs, cmp:"<"},+ {name:"sweepDurationMs", target:90000, value:$m.sweepDurationMs, cmp:"<"},+ {name:"mainThreadBlockedPct",target:5, value:$m.mainThreadBlockedPct,cmp:"<"},+ {name:"filesFailedTerminal", target:0, value:$m.filesFailedTerminal, cmp:"=="}+ ] | map(. + {miss: (if .cmp=="<" then (.value >= .target) else (.value != .target) end)})')"+MISSES_JSON="$(jq -c '[ .[] | select(.miss) | {name,target,value,cmp} ]' <<<"$CHECKS_JSON")"++# ── 6. Compose + append JSONL record ───────────────────────────────────────+mkdir -p "$EVIDENCE_DIR"+RECORD="$(jq -c -n \+ --arg timestamp "$TIMESTAMP" \+ --arg commit "$COMMIT" \+ --arg script "sweep-fixall" \+ --arg config "R1+R2+R3 (shipping)" \+ --arg fixture "$FIXTURE_TAG" \+ --arg context "$CONTEXT" \+ --argjson metrics "$JSON" \+ --argjson targets '{"panelOpenWarmMs":1000,"sweepDurationMs":90000,"mainThreadBlockedPct":5,"filesFailedTerminal":0}' \+ --argjson targetMisses "$MISSES_JSON" \+ --argjson durationMs "$DURATION_MS" \+ --arg host "$HOST" \+ --arg invokedBy "$INVOKED_BY" \+ --arg nodeVersion "$NODE_VERSION" \+ '{timestamp:$timestamp, commit:$commit, script:$script, config:$config, fixture:$fixture,+ context:$context, metrics:$metrics, targets:$targets, targetMisses:$targetMisses,+ durationMs:$durationMs, host:$host, invokedBy:$invokedBy, nodeVersion:$nodeVersion}')"++# Only a COMPLETED sweep earns a row in the trend log. An incomplete run still+# emits SWEEP_RESULT — with sweepDurationMs pinned at the timeout ceiling — so+# appending before this check would file a schema-identical row that a naive+# aggregation reads as a real duration. The summary below still prints the+# partial numbers, and step 7 still exits non-zero; the log just stays clean.+# Same contract measure-fuzz.sh states for its own evidence file.+if [[ "$(jq -r '.sweepCompleted' <<<"$JSON")" == "true" ]]; then+ append_jsonl_atomic "$LOG_FILE" "$RECORD"+ APPENDED_TO_LOG=1+else+ APPENDED_TO_LOG=0+fi++# ── 7. Summary ─────────────────────────────────────────────────────────────+echo ""+echo "──────── measure-sweep summary ────────"+echo " context: $CONTEXT"+echo " commit: $COMMIT fixture: $FIXTURE_TAG host: $HOST"+echo " config: R1+R2+R3 (shipping)"+jq -r '+ " fixable files: \(.fixableFileCount)",+ " panel open (cold): \(.panelOpenColdMs) ms (incl. cold audit walk)",+ " panel open (warm): \(.panelOpenWarmMs) ms",+ " full sweep: \(.sweepDurationMs) ms (completed=\(.sweepCompleted))",+ " successful fixes: \(.lintFixSuccess)",+ " capacity 503s: \(.lintFix503) (transient; retried)",+ " files failed: \(.filesFailedTerminal)",+ " main thread blocked: \(.mainThreadBlockedMs) ms (\(.mainThreadBlockedPct)% of sweep)"+' <<<"$JSON"+echo ""+echo " targets:"+jq -r '.[] | " " + (if .miss then "⚠ MISS " else "✓ pass " end) ++ .name + " " + .cmp + " " + (.target|tostring) + " (got " + (.value|tostring) + ")"' <<<"$CHECKS_JSON"++MISS_COUNT="$(jq 'length' <<<"$MISSES_JSON")"+echo ""+if [[ "$MISS_COUNT" -gt 0 ]]; then+ echo " ⚠ $MISS_COUNT target(s) MISSED — recorded in the JSONL and flagged above."+else+ echo " ✓ all targets met."+fi+if [[ "$APPENDED_TO_LOG" -eq 1 ]]; then+ echo " logFile: $LOG_FILE"+else+ echo " logFile: (not appended — incomplete sweep is not a measurement)"+fi+echo ""++# A completed-but-target-missing run is still a valid measurement (exit 0 —+# the miss is surfaced, not swallowed). Only an incomplete sweep is a failure.+if [[ "$(jq -r '.sweepCompleted' <<<"$JSON")" != "true" ]]; then+ echo "error: the sweep did not complete within ${SWEEP_TIMEOUT_MS}ms — numbers above are partial." >&2+ exit 8+fidiff --git a/packages/app/src/components/ProblemsPanel.dom.test.tsx b/packages/app/src/components/ProblemsPanel.dom.test.tsxindex 2aa2b995e..981cf0ba9 100644--- a/packages/app/src/components/ProblemsPanel.dom.test.tsx+++ b/packages/app/src/components/ProblemsPanel.dom.test.tsx@@ -11,6 +11,7 @@ import type { LintDiagnostic, ValidationAuditResponse } from '@inkeep/open-knowlimport { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react';import type { ReactElement, ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { SWEEP_PROGRESS_CHUNK, sweepProgressInterval } from '@/components/problems-sweep';import { TooltipProvider } from '@/components/ui/tooltip';import { renderLinguiTemplate } from '@/test-utils/lingui-mock';@@ -38,13 +39,20 @@ const AUDIT_SUPERSEDED = 'audit-superseded' as const;let runLintAuditImpl: () => Promise<ValidationAuditResponse | null | typeof AUDIT_SUPERSEDED> =async () => null;let fixLintDocCalls: string[] = [];-let fixLintDocImpl: (docName: string) => Promise<{ ok: boolean; errorDetail?: string | null }> =- async () => ({ ok: true });+let fixLintDocImpl: (docName: string) => Promise<{+ ok: boolean;+ errorDetail?: string | null;+ status?: number | null;+ problemType?: string | null;+}> = async () => ({ ok: true });let projectLintConfigData: unknown = null;const toastError = vi.fn((_message: string) => {});const toastSuccess = vi.fn((_message: string) => {});-vi.doMock('sonner', () => ({ toast: { error: toastError, success: toastSuccess } }));+const toastInfo = vi.fn((_message: string) => {});+vi.doMock('sonner', () => ({+ toast: { error: toastError, success: toastSuccess, info: toastInfo },+}));// Captured so a test can fire a config change the way a rule toggle does.const lintConfigListeners = new Set<() => void>();function emitLintConfigChangedForTest(): void {@@ -167,6 +175,7 @@ beforeEach(() => {addPageCalls.length = 0;toastError.mockClear();toastSuccess.mockClear();+ toastInfo.mockClear();lintConfigListeners.clear();});@@ -185,6 +194,30 @@ function render(ui: ReactElement) {return rtlRender(<TooltipProvider>{ui}</TooltipProvider>);}+/**+ * Open a collapsed project-scope file group. Groups mount collapsed, so a test+ * that reaches into a group's diagnostic rows must first click its header — the+ * file-path label lives inside the CollapsibleTrigger button.+ */+function expandGroup(filePath: string) {+ const header = screen.getByText(filePath);+ fireEvent.click(header.closest('button') ?? header);+}++/**+ * The sweep's screen-reader progress region: a role=status live region whose+ * text is the running "Fixing N of M files" count. Matched by that text so it is+ * never confused with the audit-loading skeleton, which is also role=status but+ * announces the audit rather than the sweep (the two are mutually exclusive by+ * construction, but querying on the text keeps the helper honest regardless).+ * Returns undefined when no sweep is running.+ */+function sweepLiveRegion(): HTMLElement | undefined {+ return screen+ .queryAllByRole('status')+ .find((el) => /Fixing \d+ of \d+ files/.test(el.textContent ?? ''));+}+describe('ProblemsPanel', () => {test('shows the empty state when there are no diagnostics', () => {render(<ProblemsPanel docName="notes" diagnostics={[]} />);@@ -750,14 +783,19 @@ describe('ProblemsPanel — project scope', () => {await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());expect(auditCalls).toBe(1);- // Per-file groups list their diagnostics (expanded by default) with counts.+ // Per-file groups render collapsed: headers with counts, contents unmounted.expect(screen.getByText('notes.md')).toBeTruthy();- expect(screen.getByText('Heading increment')).toBeTruthy();const groups = screen.getAllByTestId('problems-audit-group');expect(groups).toHaveLength(2);+ expect(groups[0]?.getAttribute('data-state')).toBe('closed');expect(groups[0]?.querySelector('[data-testid="problems-audit-file-count"]')?.textContent).toBe('2',);+ // A diagnostic message lives inside a collapsed group, so it is not mounted.+ expect(screen.queryByText('Heading increment')).toBeNull();+ // Expanding the group mounts its rows.+ expandGroup('guides/setup.md');+ expect(screen.getByText('Heading increment')).toBeTruthy();// The summary carries the audit-wide error/warning counts.expect(screen.getByTestId('problems-audit-summary').textContent).toContain('0 errors');expect(screen.getByTestId('problems-audit-summary').textContent).toContain('3 warnings');@@ -779,6 +817,7 @@ describe('ProblemsPanel — project scope', () => {render(<ProblemsPanel docName="notes" diagnostics={[]} />);fireEvent.click(screen.getByTestId('panel-scope-project'));await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());+ expandGroup('guides/setup.md');const tags = screen.getAllByTestId('problems-source-tag');expect(tags.map((tag) => tag.textContent)).toEqual(['markdownlint', 'links']);@@ -804,10 +843,12 @@ describe('ProblemsPanel — project scope', () => {fireEvent.click(screen.getByTestId('panel-scope-project'));await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());+ // The per-file badge counts problems (not collapsed rows) on the header,+ // before the group is opened.+ expect(screen.getByTestId('problems-audit-file-count').textContent).toBe('3');+ expandGroup('guides/setup.md');expect(screen.getAllByTestId('problems-duplicate-group')).toHaveLength(1);expect(screen.getAllByText('Missing title')).toHaveLength(1);- // The per-file badge still counts problems, not collapsed rows.- expect(screen.getByTestId('problems-audit-file-count').textContent).toBe('3');});test('the refresh icon explains itself in a tooltip', async () => {@@ -838,6 +879,7 @@ describe('ProblemsPanel — project scope', () => {await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());expect(auditCalls).toBe(1);+ expandGroup('guides/setup.md');fireEvent.click(screen.getByTestId('problems-create-page'));await waitFor(() =>expect(createPageCalls).toEqual([{ initialDir: '', suggestedName: 'ghost' }]),@@ -934,6 +976,7 @@ describe('ProblemsPanel — project scope', () => {render(<ProblemsPanel docName="notes" diagnostics={[]} />);fireEvent.click(screen.getByTestId('panel-scope-project'));await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());+ expandGroup('guides/setup.md');fireEvent.click(screen.getByRole('button', { name: /Hard tabs/ }));@@ -977,7 +1020,9 @@ describe('ProblemsPanel — project scope', () => {fireEvent.click(screen.getByTestId('panel-scope-project'));await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());- // Expand the collapsed duplicate group, then click the SECOND occurrence.+ // Open the file group, then the collapsed duplicate group inside it, then+ // click the SECOND occurrence.+ expandGroup('guides/setup.md');fireEvent.click(screen.getByTestId('problems-duplicate-group').querySelector('button') as HTMLElement,);@@ -1014,6 +1059,7 @@ describe('ProblemsPanel — project scope', () => {render(<ProblemsPanel docName="notes" diagnostics={[]} />);fireEvent.click(screen.getByTestId('panel-scope-project'));await waitFor(() => expect(screen.getByText('notes.md')).toBeTruthy());+ expandGroup('notes.md');const hashBefore = window.location.hash;fireEvent.click(screen.getByRole('button', { name: /Hard tabs/ }));@@ -1057,6 +1103,99 @@ describe('ProblemsPanel — project scope', () => {expect(toastError).not.toHaveBeenCalled();});+ test('Stop ends a running project sweep and leaves earlier fixes in place', async () => {+ const fixableEdit = {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ newText: ' ',+ };+ runLintAuditImpl = async () =>+ auditResult({+ files: [+ { file: 'a.md', diagnostics: [diag({ fixes: [fixableEdit] })] },+ { file: 'b.md', diagnostics: [diag({ fixes: [fixableEdit] })] },+ { file: 'c.md', diagnostics: [diag({ fixes: [fixableEdit] })] },+ ],+ });+ // Hold the first fix open so the sweep is genuinely mid-flight when Stop is+ // pressed — otherwise it could finish before the click and pass vacuously.+ let releaseFirst: (() => void) | undefined;+ const firstInFlight = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ fixLintDocImpl = async (docName: string) => {+ if (docName === 'a') await firstInFlight;+ return { ok: true as const, status: 200, problemType: null, errorDetail: null };+ };++ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('a.md')).toBeTruthy());++ fireEvent.click(screen.getByTestId('problems-auto-fix'));+ // The Stop control exists only while a sweep is running.+ const stop = await screen.findByTestId('problems-cancel-fix');+ fireEvent.click(stop);+ releaseFirst?.();++ // The sweep bails at the next file boundary: 'a' was already in flight, so+ // it completes, but 'b' and 'c' are never posted.+ await waitFor(() => expect(toastInfo).toHaveBeenCalledTimes(1));+ expect(fixLintDocCalls).toEqual(['a']);+ expect(String(toastInfo.mock.calls[0]?.[0])).toContain('already fixed stay fixed');+ // A stop is not a failure — no error toast, and the spinner clears so the+ // panel is usable again rather than stuck mid-sweep.+ expect(toastError).not.toHaveBeenCalled();+ await waitFor(() => expect(screen.queryByTestId('problems-cancel-fix')).toBeNull());+ // Re-audits after stopping so the remaining count is the honest one.+ await waitFor(() => expect(auditCalls).toBe(2));+ });++ test('a stopped sweep does not poison the next one', async () => {+ const fixableEdit = {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ newText: ' ',+ };+ runLintAuditImpl = async () =>+ auditResult({+ files: [+ { file: 'a.md', diagnostics: [diag({ fixes: [fixableEdit] })] },+ { file: 'b.md', diagnostics: [diag({ fixes: [fixableEdit] })] },+ ],+ });+ let releaseFirst: (() => void) | undefined;+ const firstInFlight = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ fixLintDocImpl = async (docName: string) => {+ if (docName === 'a') await firstInFlight;+ return { ok: true as const, status: 200, problemType: null, errorDetail: null };+ };++ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('a.md')).toBeTruthy());++ fireEvent.click(screen.getByTestId('problems-auto-fix'));+ fireEvent.click(await screen.findByTestId('problems-cancel-fix'));+ releaseFirst?.();+ await waitFor(() => expect(toastInfo).toHaveBeenCalledTimes(1));+ expect(fixLintDocCalls).toEqual(['a']);++ // The stop flag must reset, or the next sweep ends on its first boundary.+ fixLintDocCalls.length = 0;+ fixLintDocImpl = async () => ({+ ok: true as const,+ status: 200,+ problemType: null,+ errorDetail: null,+ });+ await waitFor(() =>+ expect((screen.getByTestId('problems-auto-fix') as HTMLButtonElement).disabled).toBe(false),+ );+ fireEvent.click(screen.getByTestId('problems-auto-fix'));+ await waitFor(() => expect(fixLintDocCalls).toEqual(['a', 'b']));+ });+test('project Auto-fix continues past per-file failures and surfaces one error toast', async () => {const fixableEdit = {range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },@@ -1085,6 +1224,37 @@ describe('ProblemsPanel — project scope', () => {expect(options?.description).toBe('bad.md — conflict');});+ test('project Auto-fix retries a capacity refusal and reports no failure', async () => {+ const fixableEdit = {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ newText: ' ',+ };+ runLintAuditImpl = async () =>+ auditResult({ files: [{ file: 'busy.md', diagnostics: [diag({ fixes: [fixableEdit] })] }] });+ // The server refuses once for agent-session capacity (503 + the capacity+ // URN), then accepts — the sweep must wait it out, not surface it as failed.+ const outcomes = [+ {+ ok: false,+ errorDetail: 'Too many agent sessions',+ status: 503,+ problemType: 'urn:ok:error:too-many-agent-sessions',+ },+ { ok: true },+ ];+ fixLintDocImpl = async () => outcomes.shift() ?? { ok: true };+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('busy.md')).toBeTruthy());++ fireEvent.click(screen.getByTestId('problems-auto-fix'));+ // The same file is posted twice — the initial refusal and the retry that+ // succeeds — proving the component forwards the 503/URN into the retry path.+ await waitFor(() => expect(fixLintDocCalls).toEqual(['busy', 'busy']));+ // A retried-then-succeeded file is not a failure: no error toast.+ expect(toastError).not.toHaveBeenCalled();+ });+test('failure toast omits the dash-suffix when the server gives no error detail', async () => {const fixableEdit = {range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },@@ -1374,3 +1544,224 @@ describe('ProblemsPanel — project scope', () => {expect(screen.queryByText('first.md')).toBeNull();});});++describe('ProblemsPanel — project scope: collapse and expand-all', () => {+ const twoFileAudit = () =>+ auditResult({+ files: [+ {+ file: 'guides/setup.md',+ diagnostics: [diag({ code: 'MD001', message: 'Heading increment', line: 8 })],+ },+ { file: 'notes.md', diagnostics: [diag({ line: 2, message: 'Hard tabs' })] },+ ],+ fileCount: 5,+ warningCount: 2,+ });++ test('file groups mount collapsed: headers with counts, contents unmounted', async () => {+ runLintAuditImpl = async () => twoFileAudit();+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());++ const groups = screen.getAllByTestId('problems-audit-group');+ expect(groups).toHaveLength(2);+ // Every group is closed, so no diagnostic rows are in the tree.+ for (const group of groups) expect(group.getAttribute('data-state')).toBe('closed');+ expect(screen.queryByText('Heading increment')).toBeNull();+ expect(screen.queryByTestId('problems-source-tag')).toBeNull();+ // Yet each header still shows the file path and its problem count.+ expect(screen.getByText('notes.md')).toBeTruthy();+ expect(groups[0]?.querySelector('[data-testid="problems-audit-file-count"]')?.textContent).toBe(+ '1',+ );+ // The reversal affordance is present and points at expanding.+ expect(screen.getByTestId('problems-audit-expand-toggle').getAttribute('aria-label')).toBe(+ 'Expand all file groups',+ );+ });++ test('expand-all opens every group and mounts its rows; collapse-all closes them', async () => {+ runLintAuditImpl = async () => twoFileAudit();+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());++ fireEvent.click(screen.getByTestId('problems-audit-expand-toggle'));+ for (const group of screen.getAllByTestId('problems-audit-group'))+ expect(group.getAttribute('data-state')).toBe('open');+ expect(screen.getByText('Heading increment')).toBeTruthy();+ expect(screen.getByText('Hard tabs')).toBeTruthy();+ // The one control now offers the reverse action.+ expect(screen.getByTestId('problems-audit-expand-toggle').getAttribute('aria-label')).toBe(+ 'Collapse all file groups',+ );++ fireEvent.click(screen.getByTestId('problems-audit-expand-toggle'));+ for (const group of screen.getAllByTestId('problems-audit-group'))+ expect(group.getAttribute('data-state')).toBe('closed');+ expect(screen.queryByText('Heading increment')).toBeNull();+ expect(screen.getByTestId('problems-audit-expand-toggle').getAttribute('aria-label')).toBe(+ 'Expand all file groups',+ );+ });++ test('a single group expands on its own without opening the others', async () => {+ runLintAuditImpl = async () => twoFileAudit();+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());++ expandGroup('guides/setup.md');+ const groups = screen.getAllByTestId('problems-audit-group');+ const setup = groups.find((g) => g.textContent?.includes('guides/setup.md'));+ const notes = groups.find((g) => g.textContent?.includes('notes.md'));+ expect(setup?.getAttribute('data-state')).toBe('open');+ expect(notes?.getAttribute('data-state')).toBe('closed');+ expect(screen.getByText('Heading increment')).toBeTruthy();+ // The other group's rows stay unmounted.+ expect(screen.queryByText('Hard tabs')).toBeNull();+ // One of two open still reads as "not all expanded".+ expect(screen.getByTestId('problems-audit-expand-toggle').getAttribute('aria-label')).toBe(+ 'Expand all file groups',+ );+ });++ test('the expand/collapse-all control is absent when the audit is clean', async () => {+ runLintAuditImpl = async () => auditResult({ files: [], fileCount: 3 });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('No problems across 3 documents.')).toBeTruthy());+ // Nothing to expand, so the control does not render.+ expect(screen.queryByTestId('problems-audit-expand-toggle')).toBeNull();+ });+});++describe('ProblemsPanel — project scope: sweep-progress live region', () => {+ // A diagnostic carrying an auto-fix, so every file in these fixtures is swept.+ const fixableEdit = {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ newText: ' ',+ };++ test('a role=status region announces the running count while sweeping and retires when it ends', async () => {+ runLintAuditImpl = async () =>+ auditResult({ files: [{ file: 'solo.md', diagnostics: [diag({ fixes: [fixableEdit] })] }] });+ // Hold the one fix open so the sweep stays mid-flight to observe.+ let releaseFix: (() => void) | undefined;+ fixLintDocImpl = () =>+ new Promise<{ ok: true }>((resolve) => {+ releaseFix = () => resolve({ ok: true });+ });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('solo.md')).toBeTruthy());++ // No sweep running: no sweep-progress region.+ expect(sweepLiveRegion()).toBeUndefined();++ fireEvent.click(screen.getByTestId('problems-auto-fix'));+ // While the sweep runs, a role=status live region announces the count.+ await waitFor(() => expect(sweepLiveRegion()?.textContent).toBe('Fixing 0 of 1 files'));+ expect(sweepLiveRegion()?.getAttribute('role')).toBe('status');++ releaseFix?.();+ // The region is gone once the sweep ends; the re-audit's own status skeleton+ // carries no "Fixing" text, so it is not mistaken for the sweep region.+ await waitFor(() => expect(sweepLiveRegion()).toBeUndefined());+ });++ test('the announced count advances as the sweep progresses', async () => {+ // A chunk-plus-one sweep publishes several interior flushes (one every+ // sweepProgressInterval files) climbing toward the total; hold the last file+ // so the final interior flush is a stable state to assert on rather than a+ // single frame before the region retires.+ const total = SWEEP_PROGRESS_CHUNK + 1;+ const interval = sweepProgressInterval(total);+ // The last flush before the parked final file lands on the highest interval+ // multiple among the files that actually complete (all but the parked last).+ const lastInteriorFlush = Math.floor((total - 1) / interval) * interval;+ runLintAuditImpl = async () =>+ auditResult({+ files: Array.from({ length: total }, (_, i) => ({+ file: `f${i}.md`,+ diagnostics: [diag({ fixes: [fixableEdit] })],+ })),+ });+ let releaseLast: (() => void) | undefined;+ fixLintDocImpl = () =>+ new Promise<{ ok: true }>((resolve) => {+ if (fixLintDocCalls.length === total) releaseLast = () => resolve({ ok: true });+ else resolve({ ok: true });+ });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('f0.md')).toBeTruthy());++ fireEvent.click(screen.getByTestId('problems-auto-fix'));+ // Opens at zero, then climbs to the last interior flush once that many complete.+ await waitFor(() => expect(sweepLiveRegion()?.textContent).toBe(`Fixing 0 of ${total} files`));+ await waitFor(+ () =>+ expect(sweepLiveRegion()?.textContent).toBe(+ `Fixing ${lastInteriorFlush} of ${total} files`,+ ),+ { timeout: 10_000 },+ );++ // The last file is requested (and parked) just after that flush; wait for it+ // so releasing it actually completes the sweep rather than no-ops.+ await waitFor(() => expect(fixLintDocCalls.length).toBe(total));+ releaseLast?.();+ await waitFor(() => expect(sweepLiveRegion()).toBeUndefined());+ });++ test('the region announces at chunk granularity, not once per file', async () => {+ // With the sub-chunk floor the interval here is two files, so completing an+ // odd (non-boundary) file must NOT move the count — a per-file announcer+ // would — while crossing the next interval boundary must.+ const total = 11;+ expect(sweepProgressInterval(total)).toBe(2);+ runLintAuditImpl = async () =>+ auditResult({+ files: Array.from({ length: total }, (_, i) => ({+ file: `f${i}.md`,+ diagnostics: [diag({ fixes: [fixableEdit] })],+ })),+ });+ // Park the first three fixes so the sweep steps under the test's control+ // across a non-boundary file (held) then an interval boundary (advances);+ // the rest resolve at once so the sweep can finish.+ const parked: Array<() => void> = [];+ fixLintDocImpl = () =>+ new Promise<{ ok: true }>((resolve) => {+ if (fixLintDocCalls.length <= 3) parked.push(() => resolve({ ok: true }));+ else resolve({ ok: true });+ });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('f0.md')).toBeTruthy());++ fireEvent.click(screen.getByTestId('problems-auto-fix'));+ await waitFor(() => expect(sweepLiveRegion()?.textContent).toBe(`Fixing 0 of ${total} files`));+ await waitFor(() => expect(fixLintDocCalls.length).toBe(1));++ // Complete file 1, a non-boundary file. A per-file announcer would read+ // "1 of 11" here — chunked, the count holds at zero until the flush.+ parked[0]?.();+ await waitFor(() => expect(fixLintDocCalls.length).toBe(2));+ expect(sweepLiveRegion()?.textContent).toBe(`Fixing 0 of ${total} files`);++ // Complete file 2, crossing the interval boundary; now the count advances.+ parked[1]?.();+ await waitFor(() => expect(sweepLiveRegion()?.textContent).toBe(`Fixing 2 of ${total} files`));++ // Release the rest: wait for file 3 to be requested (and parked) so its+ // resolver exists, then release it — the remaining files resolve at once and+ // the region retires when the sweep finishes.+ await waitFor(() => expect(fixLintDocCalls.length).toBe(3));+ parked[2]?.();+ await waitFor(() => expect(sweepLiveRegion()).toBeUndefined());+ });+});diff --git a/packages/app/src/components/ProblemsPanel.tsx b/packages/app/src/components/ProblemsPanel.tsxindex fb2673b20..0d94a14a4 100644--- a/packages/app/src/components/ProblemsPanel.tsx+++ b/packages/app/src/components/ProblemsPanel.tsx@@ -5,6 +5,8 @@ import {AlertCircle,AlertTriangle,ChevronRight,+ ChevronsDownUp,+ ChevronsUpDown,FilePlus2,Link2,RefreshCw,@@ -15,6 +17,7 @@ import { type ReactElement, type ReactNode, useEffect, useRef, useState } from 'import { toast } from 'sonner';import { useOptionalPageList } from '@/components/PageListContext';import { type PanelScope, PanelScopeHeader } from '@/components/PanelScopeHeader';+import { runProjectFixSweep, sweepSleep } from '@/components/problems-sweep';import { LINT_PLUGIN_META, type LintPluginMeta } from '@/components/settings/lint-plugin-meta';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -535,6 +538,10 @@ export function ProblemsPanel({// Tracks whether the panel is still mounted so the async project sweep can// stop early instead of posting fixes and setState-ing into an unmounted tree.const mountedRef = useRef(true);+ // Set by the Stop control to end a running sweep at the next file boundary. A+ // ref, not state: the sweep loop reads it between files and a re-render would+ // neither reach the in-flight loop nor be wanted mid-sweep.+ const cancelSweepRef = useRef(false);useEffect(() => {mountedRef.current = true;return () => {@@ -632,35 +639,68 @@ export function ProblemsPanel({): [];+ function cancelProjectFix() {+ cancelSweepRef.current = true;+ }+async function fixAllProjectFiles() {if (projectFixing !== null || projectFixableFiles.length === 0) return;- setProjectFixing({ done: 0, total: projectFixableFiles.length });- const failures: { file: string; detail: string | null }[] = [];- // Sequential on purpose: each fix lands through the agent-write spine and- // flushes disk + git — parallel posts contend on the git flush and multiply- // CRDT sessions. Failures (conflict, symlink refusal, capacity) don't stop+ const total = projectFixableFiles.length;+ // Clear any stop left over from a previous sweep, or this one ends instantly.+ cancelSweepRef.current = false;+ setProjectFixing({ done: 0, total });+ // Sequential with a small inter-file pace and capacity-aware retry: each fix+ // lands through the agent-write spine (disk + git flush) and holds a server+ // session, so an unpaced sweep saturates the shared session pool and starves+ // concurrent agent writes. Pacing leaves headroom; a capacity refusal is+ // retried rather than counted as a failure. Non-capacity failures don't stop// the sweep; the re-audit below shows what remains.- for (const file of projectFixableFiles) {- const outcome = await fixLintDoc(filePathToDocName(file.file));- // Bail if the panel unmounted mid-sweep (tab switch, agent-mode flip): the- // user walked away, so stop posting fixes and skip the state updates React- // would no-op anyway (mirrors the `cancelled` guard in useDocLintConfig).- if (!mountedRef.current) return;- if (!outcome.ok) failures.push({ file: file.file, detail: outcome.errorDetail });- setProjectFixing((prev) => (prev === null ? prev : { ...prev, done: prev.done + 1 }));- }+ const { failures, cancelled } = await runProjectFixSweep({+ items: projectFixableFiles,+ fixItem: (file) => fixLintDoc(filePathToDocName(file.file)),+ sleep: sweepSleep,+ // Commit progress in chunks, not per file, so a large sweep doesn't+ // re-render (and re-announce to a screen reader) the panel thousands of+ // times; the final file always commits, so the count lands on the total.+ onProgress: (done) => setProjectFixing((prev) => (prev === null ? prev : { ...prev, done })),+ // Two ways a sweep ends early. The panel unmounted mid-sweep (tab switch,+ // agent-mode flip) — the user walked away, so stop posting fixes and skip+ // the state updates React would no-op anyway (mirrors the `cancelled`+ // guard in useDocLintConfig). Or the user pressed Stop, which is the same+ // between-files bail but leaves the panel mounted and owing them an answer.+ shouldContinue: () => mountedRef.current && !cancelSweepRef.current,+ });+ // Unmounted: nobody is left to tell, and every setState below would no-op.+ if (cancelled && !mountedRef.current) return;setProjectFixing(null);if (failures.length > 0) {+ // The toast names only the first casualty; log the whole set once so a+ // bulk failure (one root cause across many files, or a mid-sweep server+ // restart) leaves a diagnostic trail for every file, not just the first.+ console.warn(+ `[lint] fix-all: ${failures.length} of ${projectFixableFiles.length} files failed`,+ failures.map((failure) => ({ file: failure.item.file, detail: failure.detail })),+ );// Name the first casualty so the toast is actionable — "1 of 10 failed"// alone gives the user nothing to act on. The detail is the server's// problem+json title (untranslated, like the rule-write error toasts).- const first = failures[0];- toast.error(t`Could not fix ${failures.length} of ${projectFixableFiles.length} files.`, {- description:- first === undefined- ? undefined- : `${first.file}${first.detail === null ? '' : ` — ${first.detail}`}`,- });+ // Suppressed on a user stop: they know why it ended, and a failure toast+ // there reads as "your stop broke something".+ if (!cancelled) {+ const first = failures[0];+ toast.error(t`Could not fix ${failures.length} of ${projectFixableFiles.length} files.`, {+ description:+ first === undefined+ ? undefined+ : `${first.item.file}${first.detail === null ? '' : ` — ${first.detail}`}`,+ });+ }+ }+ if (cancelled) {+ // A stop leaves the project genuinely half-fixed, which is fine — every+ // file already swept stays fixed. Say so, and let the re-audit below+ // replace the count with what actually remains.+ toast.info(t`Stopped fixing. Files already fixed stay fixed.`);}// Guard the re-audit so a failure surfaces the "Try again" state instead of// an unhandled rejection off the fire-and-forget `void fixAllProjectFiles()`.@@ -882,6 +922,7 @@ export function ProblemsPanel({}fixing={projectFixing}onAutoFix={() => void fixAllProjectFiles()}+ onCancelFix={cancelProjectFix}onFixWithAi={onFixWithAi === undefined || audit.status !== 'loaded'? undefined@@ -903,6 +944,7 @@ function ProjectAuditBody({problemCount,fixing,onAutoFix,+ onCancelFix,onFixWithAi,onCreateTarget,creatingTarget,@@ -918,6 +960,9 @@ function ProjectAuditBody({/** Sweep progress while a project auto-fix is running, else null. */fixing: { done: number; total: number } | null;onAutoFix: () => void;+ /** Stop a running sweep at the next file boundary. Files already fixed stay+ * fixed; the panel re-audits so the count reflects what actually remains. */+ onCancelFix: () => void;/** Hand the whole audit to the agent; absent on web and until the audit* loads (there is nothing to describe before then). */onFixWithAi?: () => void;@@ -927,6 +972,23 @@ function ProjectAuditBody({}) {const { t } = useLingui();const loading = audit.status === 'loading' || audit.status === 'idle';+ const loadedFiles = audit.status === 'loaded' ? audit.result.files : [];+ const [expandedFiles, setExpandedFiles] = useState<ReadonlySet<string>>(() => new Set());+ // Every group is open only when the set covers all of them; that is exactly+ // when the one control flips from "expand all" to "collapse all".+ const allExpanded =+ loadedFiles.length > 0 && loadedFiles.every((file) => expandedFiles.has(file.file));+ function toggleFile(file: string, open: boolean) {+ setExpandedFiles((prev) => {+ const next = new Set(prev);+ if (open) next.add(file);+ else next.delete(file);+ return next;+ });+ }+ function toggleAll() {+ setExpandedFiles(allExpanded ? new Set() : new Set(loadedFiles.map((file) => file.file)));+ }return (<PanelBody className="px-2 py-2" data-testid="problems-project-scope">{/* Two rows, not one: the count summary plus two labelled actions plus@@ -949,26 +1011,59 @@ function ProjectAuditBody({</>)}</p>- {/* Icon-only, so the label lives in a tooltip as well as the- accessible name — nothing on the button says what it does. */}- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="ghost"- size="icon"- className="size-6 shrink-0 text-muted-foreground"- aria-label={t`Re-run the project audit`}- data-testid="problems-audit-refresh"- disabled={loading || fixing !== null}- onClick={onRefresh}- >- <RefreshCw aria-hidden="true" className="size-3.5" />- </Button>- </TooltipTrigger>- <TooltipContent data-testid="problems-audit-refresh-tooltip">- <Trans>Re-run the project audit</Trans>- </TooltipContent>- </Tooltip>+ <div className="flex shrink-0 items-center gap-1">+ {/* Groups now mount collapsed, so this restores the fully-expanded+ view in one action; present only once there are groups to act on. */}+ {loadedFiles.length > 0 ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="size-6 shrink-0 text-muted-foreground"+ aria-label={+ allExpanded ? t`Collapse all file groups` : t`Expand all file groups`+ }+ data-testid="problems-audit-expand-toggle"+ onClick={toggleAll}+ >+ {allExpanded ? (+ <ChevronsDownUp aria-hidden="true" className="size-3.5" />+ ) : (+ <ChevronsUpDown aria-hidden="true" className="size-3.5" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent data-testid="problems-audit-expand-toggle-tooltip">+ {allExpanded ? (+ <Trans>Collapse all file groups</Trans>+ ) : (+ <Trans>Expand all file groups</Trans>+ )}+ </TooltipContent>+ </Tooltip>+ ) : null}+ {/* Icon-only, so the label lives in a tooltip as well as the+ accessible name — nothing on the button says what it does. */}+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="size-6 shrink-0 text-muted-foreground"+ aria-label={t`Re-run the project audit`}+ data-testid="problems-audit-refresh"+ disabled={loading || fixing !== null}+ onClick={onRefresh}+ >+ <RefreshCw aria-hidden="true" className="size-3.5" />+ </Button>+ </TooltipTrigger>+ <TooltipContent data-testid="problems-audit-refresh-tooltip">+ <Trans>Re-run the project audit</Trans>+ </TooltipContent>+ </Tooltip>+ </div></div><div className="flex flex-wrap items-center justify-end gap-1">{/* The Auto-fix button is disabled during a sweep, so AT can't focus it@@ -980,6 +1075,28 @@ function ProjectAuditBody({{t`Fixing ${fixing.done} of ${fixing.total} files`}</span>) : null}+ {/* Auto-fix disables itself while sweeping, so without this the only+ way out of a started sweep is a page reload. Rendered only during a+ sweep, beside the disabled Auto-fix it replaces the use of. */}+ {fixing !== null ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="h-6 shrink-0 px-2 text-muted-foreground"+ aria-label={t`Stop fixing files`}+ data-testid="problems-cancel-fix"+ onClick={onCancelFix}+ >+ <Trans>Stop</Trans>+ </Button>+ </TooltipTrigger>+ <TooltipContent data-testid="problems-cancel-fix-tooltip">+ <Trans>Stop fixing. Files already fixed stay fixed.</Trans>+ </TooltipContent>+ </Tooltip>+ ) : null}<AutoFixButtoncount={fixableCount}problemCount={problemCount}@@ -1036,6 +1153,8 @@ function ProjectAuditBody({onNavigate={onNavigate}onCreateTarget={onCreateTarget}creatingTarget={creatingTarget}+ expandedFiles={expandedFiles}+ onToggleFile={toggleFile}/>)}</PanelBody>@@ -1047,11 +1166,17 @@ function ProjectAuditResults({onNavigate,onCreateTarget,creatingTarget,+ expandedFiles,+ onToggleFile,}: {result: ValidationAuditResponse;onNavigate: (filePath: string, diagnostic: DiagnosticLike) => void;onCreateTarget?: (diagnostic: DiagnosticLike) => void;creatingTarget: string | null;+ /** File paths whose group is open. Groups mount collapsed, so a fresh+ * project plane renders headers only until the reader drills in. */+ expandedFiles: ReadonlySet<string>;+ onToggleFile: (file: string, open: boolean) => void;}) {const { t } = useLingui();return (@@ -1086,6 +1211,8 @@ function ProjectAuditResults({onNavigate={onNavigate}onCreateTarget={onCreateTarget}creatingTarget={creatingTarget}+ open={expandedFiles.has(file.file)}+ onOpenChange={(open) => onToggleFile(file.file, open)}/>)))}@@ -1098,16 +1225,22 @@ function ProjectFileGroup({onNavigate,onCreateTarget,creatingTarget,+ open,+ onOpenChange,}: {file: ValidationDocResult;onNavigate: (filePath: string, diagnostic: DiagnosticLike) => void;onCreateTarget?: (diagnostic: DiagnosticLike) => void;creatingTarget: string | null;+ /** Controlled by the parent so the one expand/collapse-all control can drive+ * every group at once; a closed group leaves its diagnostic rows unmounted. */+ open: boolean;+ onOpenChange: (open: boolean) => void;}) {const { t } = useLingui();const sorted = [...file.diagnostics].sort(compareDiagnostics);return (- <Collapsible defaultOpen data-testid="problems-audit-group">+ <Collapsible open={open} onOpenChange={onOpenChange} data-testid="problems-audit-group"><CollapsibleTrigger className="group flex w-full cursor-pointer items-center gap-1.5 rounded px-2 py-1.5 text-left transition-colors hover:bg-muted"><ChevronRightaria-hidden="true"diff --git a/packages/app/src/components/problems-sweep.test.ts b/packages/app/src/components/problems-sweep.test.tsnew file mode 100644index 000000000..d87f432df--- /dev/null+++ b/packages/app/src/components/problems-sweep.test.ts@@ -0,0 +1,351 @@+import { describe, expect, test } from 'vitest';+import {+ CAPACITY_PROBLEM_TYPE,+ CAPACITY_RETRY_BACKOFF_MS,+ isCapacityRefusal,+ runProjectFixSweep,+ SWEEP_PACE_DELAY_MS,+ SWEEP_PROGRESS_CHUNK,+ SWEEP_PROGRESS_MIN_UPDATES,+ type SweepFixOutcome,+ shouldFlushSweepProgress,+ sweepProgressInterval,+} from './problems-sweep.ts';++// A realistic large sweep — the corpus size the panel's project scope is sized+// for (thousands of fixable files).+const LARGE_SWEEP = 2083;++// The 1-based `done` values a sweep of `total` files passes through, [1..total].+function doneValues(total: number): number[] {+ return Array.from({ length: total }, (_, index) => index + 1);+}++describe('shouldFlushSweepProgress', () => {+ test('flushes at each chunk boundary', () => {+ expect(shouldFlushSweepProgress(SWEEP_PROGRESS_CHUNK, LARGE_SWEEP)).toBe(true);+ expect(shouldFlushSweepProgress(SWEEP_PROGRESS_CHUNK * 2, LARGE_SWEEP)).toBe(true);+ });++ test('does not flush between chunk boundaries', () => {+ expect(shouldFlushSweepProgress(SWEEP_PROGRESS_CHUNK - 1, LARGE_SWEEP)).toBe(false);+ expect(shouldFlushSweepProgress(SWEEP_PROGRESS_CHUNK + 1, LARGE_SWEEP)).toBe(false);+ });++ test('flushes on the final file even when the total is not a chunk multiple', () => {+ // Without the final-file clause the counter would stall at the last chunk+ // boundary (2050) and never reach 2083 — the no-off-by-one guarantee.+ expect(LARGE_SWEEP % SWEEP_PROGRESS_CHUNK).not.toBe(0);+ expect(shouldFlushSweepProgress(LARGE_SWEEP, LARGE_SWEEP)).toBe(true);+ expect(shouldFlushSweepProgress(LARGE_SWEEP - 1, LARGE_SWEEP)).toBe(false);+ });++ test('a sweep smaller than one chunk still advances the counter before the end', () => {+ // A 45-file sweep against a slow server ran 20s showing "Fixing 0 of 45" for+ // its whole duration: the only flush was the last file, and the teardown that+ // clears the counter superseded it before it painted. A sweep under one chunk+ // must publish while it is still running.+ const total = 45;+ const beforeLast = doneValues(total).filter((done) => done < total);+ const flushesBeforeEnd = beforeLast.filter((done) => shouldFlushSweepProgress(done, total));+ expect(flushesBeforeEnd.length).toBeGreaterThanOrEqual(4);+ expect(shouldFlushSweepProgress(total, total)).toBe(true);+ });++ test('every sweep size publishes while it runs, never only at the end', () => {+ for (const total of [2, 6, 17, 45, 49, 120, 999]) {+ const beforeLast = doneValues(total).filter((done) => done < total);+ expect(+ beforeLast.some((done) => shouldFlushSweepProgress(done, total)),+ `total=${total} published nothing before its final file`,+ ).toBe(true);+ }+ });++ test('a sweep of one file publishes once, on that file', () => {+ expect(shouldFlushSweepProgress(1, 1)).toBe(true);+ });++ test('the publish interval is capped at one chunk, so large sweeps are unchanged', () => {+ // The floor may only ever make a SMALL sweep chattier; it must not increase+ // the update count of the corpus size chunking was introduced for.+ expect(sweepProgressInterval(LARGE_SWEEP)).toBe(SWEEP_PROGRESS_CHUNK);+ const flushes = doneValues(LARGE_SWEEP).filter((done) =>+ shouldFlushSweepProgress(done, LARGE_SWEEP),+ );+ expect(flushes).toEqual([+ ...Array.from(+ { length: Math.floor(LARGE_SWEEP / SWEEP_PROGRESS_CHUNK) },+ (_, i) => (i + 1) * SWEEP_PROGRESS_CHUNK,+ ),+ LARGE_SWEEP,+ ]);+ });++ test('publishes tens of updates, not one per file, across a large sweep', () => {+ // The responsiveness win: a screen reader hears ~40 announcements over a+ // 2,000-file sweep, not ~2,000. A per-file regression would make this equal+ // the file count.+ const flushes = doneValues(LARGE_SWEEP).filter((done) =>+ shouldFlushSweepProgress(done, LARGE_SWEEP),+ ).length;+ expect(flushes).toBeGreaterThan(1);+ expect(flushes).toBeLessThan(LARGE_SWEEP / 10);+ });+});++describe('isCapacityRefusal', () => {+ test('a 503 carrying the capacity URN is retryable', () => {+ expect(isCapacityRefusal({ status: 503, problemType: CAPACITY_PROBLEM_TYPE })).toBe(true);+ });++ test('a 503 with a different problem type is not a capacity refusal', () => {+ expect(isCapacityRefusal({ status: 503, problemType: 'urn:ok:error:conflict' })).toBe(false);+ });++ test('a 503 with no problem type is not a capacity refusal', () => {+ expect(isCapacityRefusal({ status: 503, problemType: null })).toBe(false);+ });++ test('the capacity URN under a non-503 status is not a capacity refusal', () => {+ // Both the status AND the URN must match — a stray URN on another status is+ // a real failure to report, not a capacity refusal to wait out.+ expect(isCapacityRefusal({ status: 409, problemType: CAPACITY_PROBLEM_TYPE })).toBe(false);+ });++ test('a network failure with no status is not a capacity refusal', () => {+ expect(isCapacityRefusal({ status: null, problemType: null })).toBe(false);+ });+});++describe('runProjectFixSweep', () => {+ // A sleep that never touches the clock: it records the delay it was asked to+ // wait and resolves immediately, so retry/backoff/pacing are exercised without+ // real time passing.+ function recordingSleep(): { sleep: (ms: number) => Promise<void>; waited: number[] } {+ const waited: number[] = [];+ return {+ sleep: async (ms: number) => {+ waited.push(ms);+ },+ waited,+ };+ }++ const CAPACITY: SweepFixOutcome = {+ ok: false,+ errorDetail: 'busy',+ status: 503,+ problemType: CAPACITY_PROBLEM_TYPE,+ };++ test('retries a capacity refusal until it clears, reporting no failure', async () => {+ // Two capacity refusals, then success — the file ends up fixed, not failed.+ const outcomes: SweepFixOutcome[] = [CAPACITY, CAPACITY, { ok: true }];+ const attempts: string[] = [];+ const { sleep, waited } = recordingSleep();+ const result = await runProjectFixSweep({+ items: [{ file: 'a.md' }],+ fixItem: async (item) => {+ attempts.push(item.file);+ return outcomes.shift() ?? { ok: true };+ },+ sleep,+ onProgress: () => {},+ shouldContinue: () => true,+ });+ expect(result.failures).toEqual([]);+ // One initial attempt plus one per refusal that then cleared.+ expect(attempts).toEqual(['a.md', 'a.md', 'a.md']);+ // Backoff grew across the two retries following the schedule.+ expect(waited).toEqual(CAPACITY_RETRY_BACKOFF_MS.slice(0, 2));+ });++ test('reports a file as failed after exhausting the retry budget', async () => {+ const attempts: string[] = [];+ const { sleep, waited } = recordingSleep();+ const result = await runProjectFixSweep({+ items: [{ file: 'stuck.md' }],+ fixItem: async (item) => {+ attempts.push(item.file);+ return CAPACITY;+ },+ sleep,+ onProgress: () => {},+ shouldContinue: () => true,+ });+ // Bounded: one initial attempt plus one per backoff step, then it gives up —+ // never an unbounded loop against a persistently saturated pool.+ expect(attempts).toHaveLength(1 + CAPACITY_RETRY_BACKOFF_MS.length);+ expect(waited).toEqual([...CAPACITY_RETRY_BACKOFF_MS]);+ expect(result.failures).toEqual([{ item: { file: 'stuck.md' }, detail: 'busy' }]);+ });++ test('does not retry a non-capacity failure', async () => {+ const attempts: string[] = [];+ const { sleep, waited } = recordingSleep();+ const result = await runProjectFixSweep({+ items: [{ file: 'conflict.md' }],+ fixItem: async (item) => {+ attempts.push(item.file);+ return { ok: false, errorDetail: 'merge conflict', status: 409, problemType: null };+ },+ sleep,+ onProgress: () => {},+ shouldContinue: () => true,+ });+ // A terminal failure is reported on the first attempt, with no backoff wait.+ expect(attempts).toEqual(['conflict.md']);+ expect(waited).toEqual([]);+ expect(result.failures).toEqual([{ item: { file: 'conflict.md' }, detail: 'merge conflict' }]);+ });++ test('paces between files but not before the first', async () => {+ const { sleep, waited } = recordingSleep();+ await runProjectFixSweep({+ items: [{ file: 'a.md' }, { file: 'b.md' }, { file: 'c.md' }],+ fixItem: async () => ({ ok: true }),+ sleep,+ onProgress: () => {},+ shouldContinue: () => true,+ });+ // A clean sweep waits once between each adjacent pair (no capacity backoff),+ // deliberately holding the sustained rate below the session ceiling — and no+ // needless leading delay before the first file.+ expect(waited).toEqual([SWEEP_PACE_DELAY_MS, SWEEP_PACE_DELAY_MS]);+ expect(SWEEP_PACE_DELAY_MS).toBeGreaterThan(0);+ });++ test('publishes progress in chunks and lands the final count exactly', async () => {+ // Large enough that the interval sits at the full chunk, and not a chunk+ // multiple, to pin the exact-final-count guarantee.+ const total = SWEEP_PROGRESS_CHUNK * SWEEP_PROGRESS_MIN_UPDATES + 3;+ const progress: number[] = [];+ await runProjectFixSweep({+ items: Array.from({ length: total }, (_, index) => ({ file: `f${index}.md` })),+ fixItem: async () => ({ ok: true }),+ sleep: async () => {},+ onProgress: (done) => progress.push(done),+ shouldContinue: () => true,+ });+ // A flush at every chunk boundary, then a final flush on the exact total.+ expect(progress).toEqual([+ ...Array.from(+ { length: SWEEP_PROGRESS_MIN_UPDATES },+ (_, i) => (i + 1) * SWEEP_PROGRESS_CHUNK,+ ),+ total,+ ]);+ });++ test('a sub-chunk sweep publishes while it runs, not only as it tears down', async () => {+ // The shipped regression: 45 fixable files against a slow server showed+ // "Fixing 0 of 45" for the whole 20s run, because the only flush was the one+ // the teardown superseded.+ const total = 45;+ const progress: number[] = [];+ await runProjectFixSweep({+ items: Array.from({ length: total }, (_, index) => ({ file: `f${index}.md` })),+ fixItem: async () => ({ ok: true }),+ sleep: async () => {},+ onProgress: (done) => progress.push(done),+ shouldContinue: () => true,+ });+ expect(progress.filter((done) => done < total).length).toBeGreaterThanOrEqual(4);+ expect(progress.at(-1)).toBe(total);+ });++ test('stops when the caller tears down mid-sweep', async () => {+ const attempts: string[] = [];+ let live = true;+ const result = await runProjectFixSweep({+ items: [{ file: 'a.md' }, { file: 'b.md' }, { file: 'c.md' }],+ fixItem: async (item) => {+ attempts.push(item.file);+ live = false; // the panel unmounts right after the first fix lands+ return { ok: true };+ },+ sleep: async () => {},+ onProgress: () => {},+ shouldContinue: () => live,+ });+ // The remaining files are never touched once the caller has gone away.+ expect(attempts).toEqual(['a.md']);+ expect(result.cancelled).toBe(true);+ });++ test('stops during a capacity backoff when the caller tears down mid-wait', async () => {+ // The panel unmounts while the sweep is waiting out a capacity backoff. The+ // liveness re-check after the backoff sleep must stop the retry before a+ // second POST goes out against a server the UI no longer renders.+ const attempts: string[] = [];+ let live = true;+ const result = await runProjectFixSweep({+ items: [{ file: 'a.md' }],+ fixItem: async (item) => {+ attempts.push(item.file);+ return CAPACITY;+ },+ sleep: async () => {+ live = false; // the panel unmounts during the backoff wait+ },+ onProgress: () => {},+ shouldContinue: () => live,+ });+ // The initial attempt hit capacity; the teardown during the backoff wait+ // stopped the retry, so only the one POST ever went out.+ expect(attempts).toEqual(['a.md']);+ expect(result.cancelled).toBe(true);+ // The one attempt that did run came back refused, so it is reported as a+ // failure even though the teardown stopped the retry.+ expect(result.failures).toEqual([{ item: { file: 'a.md' }, detail: 'busy' }]);+ });++ test('skips the backoff wait entirely when the capacity fix itself tears the caller down', async () => {+ // The fix lands, comes back a capacity refusal, and unmounts the panel in+ // the same tick. The liveness re-check before the backoff sleep must skip+ // the wait — no needless pause against a panel that has gone away.+ const attempts: string[] = [];+ const { sleep, waited } = recordingSleep();+ let live = true;+ const result = await runProjectFixSweep({+ items: [{ file: 'a.md' }],+ fixItem: async (item) => {+ attempts.push(item.file);+ live = false; // the panel unmounts as this capacity refusal comes back+ return CAPACITY;+ },+ sleep,+ onProgress: () => {},+ shouldContinue: () => live,+ });+ expect(attempts).toEqual(['a.md']);+ expect(waited).toEqual([]);+ expect(result.cancelled).toBe(true);+ // The refusal is still reported: the fix ran to a verdict before the+ // teardown, so it is a real outcome rather than work that never happened.+ expect(result.failures).toEqual([{ item: { file: 'a.md' }, detail: 'busy' }]);+ });++ test('reports the in-flight file when a user stop lands on its failed fix', async () => {+ // The Stop control makes cancellation user-reachable mid-sweep, so the+ // cancel path now has a consumer that reads `failures` (the panel logs+ // them). A file whose fix already came back failed must survive the bail —+ // dropping it would silently undercount the diagnostic log purely because+ // the stop landed in that window.+ let stopped = false;+ const result = await runProjectFixSweep({+ items: [{ file: 'a.md' }, { file: 'b.md' }],+ fixItem: async (item) => {+ if (item.file === 'a.md') return { ok: true };+ stopped = true; // the user hits Stop as this failed fix comes back+ return { ok: false, errorDetail: 'boom', status: 500, problemType: null };+ },+ sleep: async () => {},+ onProgress: () => {},+ shouldContinue: () => !stopped,+ });+ expect(result.cancelled).toBe(true);+ expect(result.failures).toEqual([{ item: { file: 'b.md' }, detail: 'boom' }]);+ });+});diff --git a/packages/app/src/components/problems-sweep.ts b/packages/app/src/components/problems-sweep.tsnew file mode 100644index 000000000..3db79bf94--- /dev/null+++ b/packages/app/src/components/problems-sweep.ts@@ -0,0 +1,191 @@+import type { ProblemType } from '@inkeep/open-knowledge-core';++/**+ * The project-scope "Fix all" sweep fixes one file per iteration. Committing the+ * progress counter to React state on every file makes a large sweep (thousands+ * of files) re-render the panel — and re-announce to a screen reader — once per+ * file. That per-file churn, not the network, is what makes the sweep feel like+ * it locks the app up. Progress is instead published in chunks of this size, so+ * a ~2,000-file sweep produces tens of updates rather than thousands.+ */+export const SWEEP_PROGRESS_CHUNK = 50;++/**+ * How many progress publishes a sweep aims for when its file count is too small+ * to reach {@link SWEEP_PROGRESS_CHUNK} boundaries. A fixed chunk alone gives a+ * sweep under one chunk exactly one publish — on its last file, which the+ * teardown that clears the counter immediately supersedes — so the counter sits+ * at its starting value for the whole run. On a slow server that reads as a hung+ * app, which is the failure chunking exists to avoid, not to cause. For any+ * sweep below {@link SWEEP_PROGRESS_CHUNK} × this floor (500 files) the floor+ * deliberately publishes MORE often than the chunk would, so the counter still+ * advances; ten keeps those extra publishes few enough not to pressure+ * re-renders while still moving the counter about every tenth of the sweep.+ */+export const SWEEP_PROGRESS_MIN_UPDATES = 10;++/**+ * Files between progress publishes for a sweep of `total` files: one chunk at+ * full size, shrinking on small sweeps so the counter still visibly advances.+ * Capped at {@link SWEEP_PROGRESS_CHUNK}, so every sweep of {@link+ * SWEEP_PROGRESS_CHUNK} × {@link SWEEP_PROGRESS_MIN_UPDATES} files or more keeps+ * exactly the publish cadence it had before the floor existed.+ */+export function sweepProgressInterval(total: number): number {+ return Math.min(SWEEP_PROGRESS_CHUNK, Math.max(1, Math.ceil(total / SWEEP_PROGRESS_MIN_UPDATES)));+}++/**+ * Whether the sweep should publish its progress counter after finishing the+ * `done`-th of `total` files. True at each interval boundary and unconditionally+ * on the last file, so the reported count lands exactly on `total` even when+ * `total` is not a multiple of the interval — the counter never stalls one+ * interval short of the end.+ *+ * `done` is the 1-based count of files finished so far; the sweep loop calls+ * this starting at 1 (the first completion), never 0.+ */+export function shouldFlushSweepProgress(done: number, total: number): boolean {+ return done === total || done % sweepProgressInterval(total) === 0;+}++/**+ * The problem-type URN the server sends with a 503 when the shared agent-session+ * pool is saturated. Stable wire contract; the sweep matches it literally to+ * tell a retryable capacity refusal from a terminal failure. `satisfies+ * ProblemType` binds it to core's canonical URN union, so a server-side rename+ * fails this file's typecheck rather than silently reclassifying every capacity+ * refusal as a terminal failure — the exact bug the retry path exists to avoid.+ */+export const CAPACITY_PROBLEM_TYPE = 'urn:ok:error:too-many-agent-sessions' satisfies ProblemType;++/**+ * Backoff before each successive capacity retry, in milliseconds — one entry per+ * retry, so the array length is the retry budget. Short and exponential: the+ * pool frees space as soon as an in-flight session crosses the server's idle+ * eviction floor, so the sweep pauses briefly and climbs only if refusals+ * persist. The cumulative wait (7.75s) spans that 5s floor with margin, so a+ * file that keeps hitting capacity still resolves rather than being dropped.+ * Deliberately far shorter per step than the server's Retry-After hint, which is+ * sized for a lone client, not a self-paced sweep that already leaves headroom.+ */+export const CAPACITY_RETRY_BACKOFF_MS: readonly number[] = [250, 500, 1000, 2000, 4000];++/**+ * Delay between successive files, in milliseconds. Collapsing the plane lets the+ * sweep run fast enough to saturate the shared session pool; this pulls the+ * sustained rate back below that ceiling so concurrent agent writes keep their+ * share of the budget. Small on purpose — the per-file round trip already paces+ * most of the interval — and a tuning knob, not a measured constant.+ */+export const SWEEP_PACE_DELAY_MS = 15;++/**+ * A file's fix outcome as the sweep consumes it: success, or a failure carrying+ * the human detail plus the HTTP status and problem-type URN the retry decision+ * reads. Structurally a widening of `fixLintDoc`'s return — its `{ ok: true }`+ * success arm carries a `result` the sweep ignores.+ */+export type SweepFixOutcome =+ | { ok: true }+ | { ok: false; errorDetail: string | null; status: number | null; problemType: string | null };++/**+ * Whether a fix failure is a retryable capacity refusal — the server declining+ * for agent-session capacity (503 + the capacity URN), which clears on its own+ * once in-flight sessions idle out — rather than a terminal failure to report.+ */+export function isCapacityRefusal(outcome: {+ status: number | null;+ problemType: string | null;+}): boolean {+ return outcome.status === 503 && outcome.problemType === CAPACITY_PROBLEM_TYPE;+}++export interface ProjectFixSweepDeps<T> {+ readonly items: readonly T[];+ /**+ * Runs one file's fix (a POST round trip) and resolves to its outcome. Must+ * resolve, never reject: the sweep does not wrap this call, so a rejection+ * propagates out uncaught and aborts the run mid-sweep. Surface every failure+ * as a `{ ok: false }` outcome rather than throwing.+ */+ readonly fixItem: (item: T) => Promise<SweepFixOutcome>;+ /** Awaitable delay; injected so tests drive pacing and backoff without a clock. */+ readonly sleep: (ms: number) => Promise<void>;+ /** Publishes chunked progress; called at chunk boundaries and on the last file. */+ readonly onProgress: (done: number, total: number) => void;+ /** False once the caller has torn down (panel unmounted); ends the sweep. */+ readonly shouldContinue: () => boolean;+}++export interface ProjectFixSweepResult<T> {+ readonly failures: { item: T; detail: string | null }[];+ /** True when shouldContinue() ended the sweep before the last file. */+ readonly cancelled: boolean;+}++/**+ * One file's fix, retried on capacity refusal with the bounded backoff schedule.+ * A non-capacity failure returns on the first attempt (no retry); success short-+ * circuits. Re-checks liveness around each backoff so a teardown mid-wait stops+ * the retries.+ */+async function fixItemWithCapacityRetry<T>(+ item: T,+ deps: Pick<ProjectFixSweepDeps<T>, 'fixItem' | 'sleep' | 'shouldContinue'>,+): Promise<SweepFixOutcome> {+ let outcome = await deps.fixItem(item);+ for (const backoffMs of CAPACITY_RETRY_BACKOFF_MS) {+ if (outcome.ok || !isCapacityRefusal(outcome) || !deps.shouldContinue()) break;+ // A retry that succeeds is otherwise invisible: the sweep absorbs the 503+ // by design, so sustained pool pressure would show up only as a slower+ // wall clock, with nothing to tell an operator whether to tune the session+ // cap or the pace. Costs nothing on the common zero-retry path.+ console.debug('[sweep] capacity refusal, backing off %dms', backoffMs);+ await deps.sleep(backoffMs);+ if (!deps.shouldContinue()) break;+ outcome = await deps.fixItem(item);+ }+ return outcome;+}++/**+ * Drive the project-scope "Fix all" sweep: fix each file in series, pacing+ * between files and retrying capacity refusals so the sweep neither saturates+ * the shared session pool nor drops files the server merely deferred. Progress+ * is published in chunks; a torn-down caller ends the sweep early. Terminal+ * (non-capacity) failures don't stop the sweep — they're collected and returned+ * for the caller to surface. Pure over its injected effects, so pacing, retry,+ * and cancellation are testable without a real clock.+ */+export async function runProjectFixSweep<T>(+ deps: ProjectFixSweepDeps<T>,+): Promise<ProjectFixSweepResult<T>> {+ const total = deps.items.length;+ const failures: { item: T; detail: string | null }[] = [];+ for (const [index, item] of deps.items.entries()) {+ // Pace between files, never before the first, so the sustained rate sits+ // below the session ceiling without adding a needless leading delay.+ if (index > 0) {+ await deps.sleep(SWEEP_PACE_DELAY_MS);+ if (!deps.shouldContinue()) return { failures, cancelled: true };+ }+ const outcome = await fixItemWithCapacityRetry(item, deps);+ // Record before the cancellation bail, not after: this file's fix already+ // ran to a verdict, so bailing first would drop a real failure from the+ // caller's diagnostic log purely because the user stopped the sweep in that+ // window. Recording first costs nothing — the bail below still returns+ // without starting another file.+ if (!outcome.ok) failures.push({ item, detail: outcome.errorDetail });+ if (!deps.shouldContinue()) return { failures, cancelled: true };+ const done = index + 1;+ if (shouldFlushSweepProgress(done, total)) deps.onProgress(done, total);+ }+ return { failures, cancelled: false };+}++/** Real awaitable delay for production pacing/backoff; tests inject their own. */+export function sweepSleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}diff --git a/packages/app/src/editor/lint-config-client.test.ts b/packages/app/src/editor/lint-config-client.test.tsnew file mode 100644index 000000000..a3a31df05--- /dev/null+++ b/packages/app/src/editor/lint-config-client.test.ts@@ -0,0 +1,146 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { fixLintDoc, LINT_FIX_TIMEOUT_MS } from './lint-config-client.ts';++type FetchFn = typeof globalThis.fetch;++let originalFetch: FetchFn;++function stubFetch(fn: FetchFn): void {+ globalThis.fetch = fn;+}++beforeEach(() => {+ originalFetch = globalThis.fetch;+});+afterEach(() => {+ globalThis.fetch = originalFetch;+});++describe('fixLintDoc', () => {+ it('surfaces the 503 status and capacity URN so the sweep can retry backpressure', async () => {+ stubFetch(+ async () =>+ new Response(+ JSON.stringify({+ type: 'urn:ok:error:too-many-agent-sessions',+ title: 'Too many agent sessions.',+ status: 503,+ }),+ { status: 503, headers: { 'content-type': 'application/problem+json' } },+ ),+ );+ const outcome = await fixLintDoc('doc-a');+ expect(outcome).toEqual({+ ok: false,+ errorDetail: 'Too many agent sessions.',+ status: 503,+ problemType: 'urn:ok:error:too-many-agent-sessions',+ });+ });++ it('preserves the server error title and surfaces status and URN for a non-capacity failure', async () => {+ stubFetch(+ async () =>+ new Response(+ JSON.stringify({+ type: 'urn:ok:error:disk-divergence',+ title: 'Document changed on disk.',+ status: 409,+ }),+ { status: 409, headers: { 'content-type': 'application/problem+json' } },+ ),+ );+ const outcome = await fixLintDoc('doc-a');+ expect(outcome).toEqual({+ ok: false,+ errorDetail: 'Document changed on disk.',+ status: 409,+ problemType: 'urn:ok:error:disk-divergence',+ });+ });++ it('surfaces the HTTP status even when the error body is unparseable', async () => {+ stubFetch(async () => new Response('<html>oops', { status: 500 }));+ const outcome = await fixLintDoc('doc-a');+ expect(outcome).toEqual({+ ok: false,+ errorDetail: null,+ status: 500,+ problemType: null,+ });+ });++ it('reports a failure with no URN when a 2xx body fails schema validation', async () => {+ stubFetch(async () => new Response(JSON.stringify({ unexpected: 'shape' }), { status: 200 }));+ const outcome = await fixLintDoc('doc-a');+ expect(outcome).toEqual({+ ok: false,+ errorDetail: null,+ status: 200,+ problemType: null,+ });+ });++ it('reports a failure with no status when the request never reaches the server', async () => {+ stubFetch(async () => {+ throw new TypeError('fetch failed');+ });+ const outcome = await fixLintDoc('doc-a');+ expect(outcome).toEqual({+ ok: false,+ errorDetail: null,+ status: null,+ problemType: null,+ });+ });++ it('resolves a stalled request to a terminal failure after the fix timeout', async () => {+ vi.useFakeTimers();+ try {+ // A request that never responds on its own — it settles only when the fix+ // timeout aborts it. Without the timeout the project-scope sweep, which can+ // only cancel between files, would hang on this one file indefinitely.+ stubFetch(+ (_input, init) =>+ new Promise<Response>((_resolve, reject) => {+ (init?.signal as AbortSignal | undefined)?.addEventListener('abort', () => {+ reject(new DOMException('The operation was aborted.', 'AbortError'));+ });+ }),+ );+ const outcome = fixLintDoc('doc-a');+ await vi.advanceTimersByTimeAsync(LINT_FIX_TIMEOUT_MS);+ // Network-throw-shaped: a null status means the sweep will not mistake the+ // aborted request for a retryable capacity refusal.+ await expect(outcome).resolves.toEqual({+ ok: false,+ errorDetail: null,+ status: null,+ problemType: null,+ });+ } finally {+ vi.useRealTimers();+ }+ });++ it('returns the parsed result on success', async () => {+ stubFetch(+ async () =>+ new Response(+ JSON.stringify({+ file: 'doc-a',+ fixedCount: 2,+ diagnostics: [],+ errorCount: 0,+ warningCount: 0,+ }),+ { status: 200, headers: { 'content-type': 'application/json' } },+ ),+ );+ const outcome = await fixLintDoc('doc-a');+ expect(outcome).toEqual({+ ok: true,+ result: { file: 'doc-a', fixedCount: 2, diagnostics: [], errorCount: 0, warningCount: 0 },+ });+ });+});diff --git a/packages/app/src/editor/lint-config-client.ts b/packages/app/src/editor/lint-config-client.tsindex cb2815e49..8f9e5d035 100644--- a/packages/app/src/editor/lint-config-client.ts+++ b/packages/app/src/editor/lint-config-client.ts@@ -61,26 +61,58 @@ export async function fetchEffectiveLintConfig(docName: string): Promise<LinterCreturn response?.effective ?? null;}+/**+ * Per-request ceiling for one file's auto-fix, in milliseconds. A fix does real+ * server work (CRDT load, markdownlint apply, disk + git flush) but is a+ * localhost round trip, so it takes seconds at most. The project-scope sweep+ * runs these serially and can only cancel between files, so an in-flight request+ * that never returns would freeze the whole sweep with no recovery but a page+ * reload; this bounds a stalled request into a terminal failure the sweep moves+ * past. Generous enough that a legitimately slow fix still completes.+ */+export const LINT_FIX_TIMEOUT_MS = 30_000;+/*** POST a whole-doc auto-fix. The body carries no agent identity on purpose:* a UI-initiated deterministic fix is the principal's write (the human* clicked the button), and the server resolves a bare body to the loaded* principal. Used per-file by the project-scope Fix all sweep.+ *+ * The failure branch surfaces the HTTP `status` and the RFC 9457 problem-type+ * URN alongside the human-readable `errorDetail`, so a caller can tell a+ * retryable capacity refusal (503 / `urn:ok:error:too-many-agent-sessions`)+ * from a terminal failure. `status` is `null` when the request never reached+ * the server (network throw); `problemType` is `null` when the body carried no+ * URN (schema drift on a 2xx, or an unparseable error body).*/export async function fixLintDoc(docName: string,-): Promise<{ ok: true; result: LintFixResult } | { ok: false; errorDetail: string | null }> {+): Promise<+ | { ok: true; result: LintFixResult }+ | { ok: false; errorDetail: string | null; status: number | null; problemType: string | null }+> {+ // Bound the request so a stalled fix resolves to a terminal failure the sweep+ // can move past, rather than hanging it. The abort surfaces through the catch+ // below as `{ status: null }` — a non-capacity failure, so it is not retried.+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), LINT_FIX_TIMEOUT_MS);try {const res = await fetch('/api/lint/fix', {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ docName }),+ signal: controller.signal,});if (!res.ok) {- const errBody = (await res.json().catch(() => null)) as { title?: unknown } | null;+ const errBody = (await res.json().catch(() => null)) as {+ title?: unknown;+ type?: unknown;+ } | null;return {ok: false,errorDetail: typeof errBody?.title === 'string' ? errBody.title : null,+ status: res.status,+ problemType: typeof errBody?.type === 'string' ? errBody.type : null,};}const body = await res.json().catch(() => null);@@ -90,11 +122,19 @@ export async function fixLintDoc(// client/server schema drift leaves a diagnostic trail instead of a// silent failure.console.warn('[lint] fix response failed schema validation', parsed.error.issues);- return { ok: false, errorDetail: null };+ return { ok: false, errorDetail: null, status: res.status, problemType: null };}return { ok: true, result: parsed.data };- } catch {- return { ok: false, errorDetail: null };+ } catch (err) {+ // Network throw, or the AbortSignal firing on the per-request ceiling. The+ // sweep turns this into one line of a bulk failure toast, so without a log+ // there is nothing to distinguish a timeout from DNS from a server crash+ // across hundreds of files. Named per file so these lines correlate with the+ // sweep's bulk-failure summary rather than being N indistinguishable copies.+ console.warn('[lint] fix request failed', docName, err instanceof Error ? err.message : err);+ return { ok: false, errorDetail: null, status: null, problemType: null };+ } finally {+ clearTimeout(timeout);}}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex e58c09abe..03e7487ac 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -1077,6 +1077,7 @@"H-vDm3": ["Relaunching to install the update…"],"H08D2X": ["Open a single markdown file in a temporary session, without project setup."],"H0WlWQ": ["Grid of rows and columns with a header row."],+ "H1TmTu": ["Stopped fixing. Files already fixed stay fixed."],"H3oH0g": ["Redo"],"H6nKok": ["Show in File Manager"],"H86f9p": ["Collapse"],@@ -1127,6 +1128,7 @@],"HzVv6g": ["Paste"],"I1gRhX": ["Failed to rename"],+ "I4LGsH": ["Collapse all file groups"],"I5685_": ["Try a prompt"],"I5AfhE": ["Sync status unavailable — server unreachable."],"I6gXOa": ["Path"],@@ -1842,6 +1844,7 @@"UfW9Kr": ["Your search queries and the full text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."],+ "Ugvy4O": ["Expand all file groups"],"UhpfxY": ["Pan left"],"UkQGhd": ["Hide replace"],"Uobeu9": ["Adds the skill to ", ["rootRel"], " — also read by ", ["0"]],@@ -3209,6 +3212,7 @@"ptQ3_N": ["unlink"],"pvnfJD": ["Dark"],"pzutoc": ["Italic"],+ "q2cLM6": ["Stop fixing files"],"q2kXMG": ["Inline Math"],"q3TWG7": ["Move to Trash"],"q3W2nd": ["Couldn't add that comment: ", ["0"]],@@ -3749,6 +3753,7 @@"yutJKi": ["Checklist with checkboxes."],"yvG-l1": ["Open source lint panel"],"yvHDYG": ["Claude Desktop"],+ "yvSAuM": ["Stop fixing. Files already fixed stay fixed."],"yxF19Y": [["0", "plural", { "one": ["#", " plugin"], "other": ["#", " plugins"] }]],"yz7wBu": ["Close"],"yzF66j": ["Link"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 7ff833445..45b9ce69e 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -2279,6 +2279,10 @@ msgstr "Collapse {keyName}"msgid "Collapse all"msgstr "Collapse all"+#: src/components/ProblemsPanel.tsx+msgid "Collapse all file groups"+msgstr "Collapse all file groups"+#: src/components/BottomComposer.tsxmsgid "Collapse Ask AI"msgstr "Collapse Ask AI"@@ -4353,6 +4357,10 @@ msgstr "Expand {keyName}"msgid "Expand all"msgstr "Expand all"+#: src/components/ProblemsPanel.tsx+msgid "Expand all file groups"+msgstr "Expand all file groups"+#: src/components/GraphPanel.tsxmsgid "Expand graph"msgstr "Expand graph"@@ -10106,6 +10114,7 @@ msgid "Still loading"msgstr "Still loading"#: src/components/acp/ThreadView.tsx+#: src/components/ProblemsPanel.tsxmsgid "Stop"msgstr "Stop"@@ -10125,6 +10134,18 @@ msgstr "Stop {0} reading \"{1}\"? {subRoot} will keep its other skills (as symlimsgid "Stop {0} reading this skill"msgstr "Stop {0} reading this skill"+#: src/components/ProblemsPanel.tsx+msgid "Stop fixing files"+msgstr "Stop fixing files"++#: src/components/ProblemsPanel.tsx+msgid "Stop fixing. Files already fixed stay fixed."+msgstr "Stop fixing. Files already fixed stay fixed."++#: src/components/ProblemsPanel.tsx+msgid "Stopped fixing. Files already fixed stay fixed."+msgstr "Stopped fixing. Files already fixed stay fixed."+#: src/components/acp/ThreadView.tsxmsgid "Stopping"msgstr "Stopping"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 66b67516a..db7d78715 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -1077,6 +1077,7 @@"H-vDm3": ["Ŕēĺàũńćĥĩńĝ ţō ĩńśţàĺĺ ţĥē ũƥďàţē…"],"H08D2X": ["Ōƥēń à śĩńĝĺē ḿàŕķďōŵń ƒĩĺē ĩń à ţēḿƥōŕàŕŷ śēśśĩōń, ŵĩţĥōũţ ƥŕōĴēćţ śēţũƥ."],"H0WlWQ": ["Ĝŕĩď ōƒ ŕōŵś àńď ćōĺũḿńś ŵĩţĥ à ĥēàďēŕ ŕōŵ."],+ "H1TmTu": ["Śţōƥƥēď ƒĩxĩńĝ. Ƒĩĺēś àĺŕēàďŷ ƒĩxēď śţàŷ ƒĩxēď."],"H3oH0g": ["Ŕēďō"],"H6nKok": ["Śĥōŵ ĩń Ƒĩĺē Ḿàńàĝēŕ"],"H86f9p": ["Ćōĺĺàƥśē"],@@ -1127,6 +1128,7 @@],"HzVv6g": ["Ƥàśţē"],"I1gRhX": ["Ƒàĩĺēď ţō ŕēńàḿē"],+ "I4LGsH": ["Ćōĺĺàƥśē àĺĺ ƒĩĺē ĝŕōũƥś"],"I5685_": ["Ţŕŷ à ƥŕōḿƥţ"],"I5AfhE": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē — śēŕvēŕ ũńŕēàćĥàƀĺē."],"I6gXOa": ["Ƥàţĥ"],@@ -1842,6 +1844,7 @@"UfW9Kr": ["Ŷōũŕ śēàŕćĥ ǫũēŕĩēś àńď ţĥē ƒũĺĺ ţēxţ ōƒ ḿàţćĥĩńĝ ƥàĝēś àŕē śēńţ ţō ŷōũŕ ēḿƀēďďĩńĝś ƥŕōvĩďēŕ (ŌƥēńÀĨ ƀŷ ďēƒàũĺţ) ţō ćōḿƥũţē ēḿƀēďďĩńĝś."],+ "Ugvy4O": ["Ēxƥàńď àĺĺ ƒĩĺē ĝŕōũƥś"],"UhpfxY": ["Ƥàń ĺēƒţ"],"UkQGhd": ["Ĥĩďē ŕēƥĺàćē"],"Uobeu9": ["Àďďś ţĥē śķĩĺĺ ţō ", ["rootRel"], " — àĺśō ŕēàď ƀŷ ", ["0"]],@@ -3209,6 +3212,7 @@"ptQ3_N": ["ũńĺĩńķ"],"pvnfJD": ["Ďàŕķ"],"pzutoc": ["Ĩţàĺĩć"],+ "q2cLM6": ["Śţōƥ ƒĩxĩńĝ ƒĩĺēś"],"q2kXMG": ["Ĩńĺĩńē Ḿàţĥ"],"q3TWG7": ["Ḿōvē ţō Ţŕàśĥ"],"q3W2nd": ["Ćōũĺďń'ţ àďď ţĥàţ ćōḿḿēńţ: ", ["0"]],@@ -3749,6 +3753,7 @@"yutJKi": ["Ćĥēćķĺĩśţ ŵĩţĥ ćĥēćķƀōxēś."],"yvG-l1": ["Ōƥēń śōũŕćē ĺĩńţ ƥàńēĺ"],"yvHDYG": ["Ćĺàũďē Ďēśķţōƥ"],+ "yvSAuM": ["Śţōƥ ƒĩxĩńĝ. Ƒĩĺēś àĺŕēàďŷ ƒĩxēď śţàŷ ƒĩxēď."],"yxF19Y": [["0", "plural", { "one": ["#", " ƥĺũĝĩń"], "other": ["#", " ƥĺũĝĩńś"] }]],"yz7wBu": ["Ćĺōśē"],"yzF66j": ["Ĺĩńķ"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 7cf0c7f9a..cb12df2b7 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -2275,6 +2275,10 @@ msgstr ""msgid "Collapse all"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "Collapse all file groups"+msgstr ""+#: src/components/BottomComposer.tsxmsgid "Collapse Ask AI"msgstr ""@@ -4349,6 +4353,10 @@ msgstr ""msgid "Expand all"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "Expand all file groups"+msgstr ""+#: src/components/GraphPanel.tsxmsgid "Expand graph"msgstr ""@@ -10102,6 +10110,7 @@ msgid "Still loading"msgstr ""#: src/components/acp/ThreadView.tsx+#: src/components/ProblemsPanel.tsxmsgid "Stop"msgstr ""@@ -10121,6 +10130,18 @@ msgstr ""msgid "Stop {0} reading this skill"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "Stop fixing files"+msgstr ""++#: src/components/ProblemsPanel.tsx+msgid "Stop fixing. Files already fixed stay fixed."+msgstr ""++#: src/components/ProblemsPanel.tsx+msgid "Stopped fixing. Files already fixed stay fixed."+msgstr ""+#: src/components/acp/ThreadView.tsxmsgid "Stopping"msgstr ""diff --git a/packages/app/tests/integration/project-sweep-capacity.test.ts b/packages/app/tests/integration/project-sweep-capacity.test.tsnew file mode 100644index 000000000..beb275ae7--- /dev/null+++ b/packages/app/tests/integration/project-sweep-capacity.test.ts@@ -0,0 +1,192 @@+/**+ * Integration coverage for the project-scope "Fix all" sweep under agent-session+ * capacity pressure. Drives the REAL client sweep (`runProjectFixSweep` ++ * `fixLintDoc`) against a REAL server whose shared `AgentSessionManager` is+ * capped small, so the retry/pacing path meets the actual 503 the server emits —+ * a fidelity no unit test reaches, since the refusal, its retry, and the+ * eviction that lets the retry win all live across the client/server boundary.+ *+ * Two behaviours are pinned:+ * 1. The server genuinely refuses a new session at the cap with the retryable+ * capacity problem (deterministic — no eviction during the window).+ * 2. A full sweep under a low cap fixes every file with zero capacity+ * failures, while a concurrent agent write to its own doc keeps succeeding+ * throughout — the shared session budget must not starve a live writer.+ */++import { mkdirSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import {+ CAPACITY_PROBLEM_TYPE,+ isCapacityRefusal,+ runProjectFixSweep,+ type SweepFixOutcome,+ sweepSleep,+} from '@/components/problems-sweep';+import { fixLintDoc } from '@/editor/lint-config-client';+import { agentWriteMd, createTestServer, type TestServer } from './test-harness';++type FetchFn = typeof globalThis.fetch;++// A hard tab trips MD010, which markdownlint auto-fixes — so every seeded doc is+// genuinely fixable and a successful sweep leaves zero failures.+const FIXABLE_BODY = '# Doc\n\n\tindented with a hard tab\n';++let server: TestServer | undefined;+let restoreFetch: (() => void) | undefined;++afterEach(async () => {+ restoreFetch?.();+ restoreFetch = undefined;+ await server?.cleanup();+ server = undefined;+});++/** Seed a fixable markdown doc on disk; the fix path loads it from disk via a+ * session, so no file-watcher round trip is needed before fixing. */+function seedFixableDoc(contentDir: string, docName: string): void {+ const filePath = join(contentDir, `${docName}.md`);+ mkdirSync(dirname(filePath), { recursive: true });+ writeFileSync(filePath, FIXABLE_BODY, 'utf-8');+}++/** Rewrite the client's origin-relative `/api/...` calls to the test server, so+ * the real `fixLintDoc` (which posts to a relative path in the browser) reaches+ * this server. Absolute URLs (harness helpers) pass through untouched. */+function installFetchShim(baseUrl: string): () => void {+ const original = globalThis.fetch;+ globalThis.fetch = ((input: Parameters<FetchFn>[0], init?: Parameters<FetchFn>[1]) => {+ const target = typeof input === 'string' && input.startsWith('/') ? baseUrl + input : input;+ return original(target, init);+ }) as FetchFn;+ return () => {+ globalThis.fetch = original;+ };+}++describe('project-scope Fix all under agent-session capacity', () => {+ test('the server refuses a new session at the cap with the retryable capacity problem', async () => {+ // A long idle floor means the two saturating sessions never become+ // evictable during the test, so the third request has no slot and MUST be+ // refused — the refusal is structural, not a timing race.+ server = await createTestServer({+ markdownlintEnabled: true,+ agentSessionOptions: { maxSessions: 2, minEvictableIdleMs: 60_000 },+ });+ const { baseUrl, contentDir } = server;++ for (const n of [0, 1, 2]) seedFixableDoc(contentDir, `capacity-refusal/doc-${n}`);++ const postFix = (docName: string): Promise<Response> =>+ fetch(`${baseUrl}/api/lint/fix`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ docName }),+ });++ // Fill the two-session budget. Distinct docs => distinct sessions that+ // persist after the fix. Both succeed (a passing fix here would fail the+ // whole test if a stray session had already consumed a slot).+ expect((await postFix('capacity-refusal/doc-0')).status).toBe(200);+ expect((await postFix('capacity-refusal/doc-1')).status).toBe(200);++ // The third needs a third session; none can be evicted, so it is refused.+ const refused = await postFix('capacity-refusal/doc-2');+ expect(refused.status).toBe(503);+ expect(refused.headers.get('Retry-After')).toBe('10');+ const body = (await refused.json()) as { type?: unknown };+ expect(body.type).toBe(CAPACITY_PROBLEM_TYPE);++ // The refusal is exactly what the sweep's retry predicate keys on.+ expect(+ isCapacityRefusal({+ status: refused.status,+ problemType: typeof body.type === 'string' ? body.type : null,+ }),+ ).toBe(true);+ }, 30_000);++ test('a full sweep fixes every file with zero capacity failures while a concurrent agent write survives', async () => {+ // Cap = 2 with a moderate idle floor. The concurrent writer holds one slot+ // with a warm (reused) session, leaving the sweep a single slot it must+ // recycle by eviction — so most sweep files hit a real 503 and rely on the+ // retry, while the floor (well above an in-process fix round trip) keeps+ // the just-used session un-evictable long enough that the refusal is real.+ server = await createTestServer({+ markdownlintEnabled: true,+ agentSessionOptions: { maxSessions: 2, minEvictableIdleMs: 700 },+ });+ const { port, contentDir } = server;+ restoreFetch = installFetchShim(server.baseUrl);++ const sweepDocs = [0, 1, 2, 3].map((n) => `capacity-sweep/doc-${n}`);+ for (const docName of sweepDocs) seedFixableDoc(contentDir, docName);++ // The collateral writer keeps writing to its own doc under a stable agent+ // id, so after its first write it reuses one warm session (a reused+ // session skips the capacity gate) and, writing far more often than the+ // idle floor, is never the evictable LRU entry.+ const COLLATERAL_DOC = 'capacity-collateral/agent-doc';+ const WRITER_INTERVAL_MS = 50;+ const writeCollateral = (): Promise<void> =>+ agentWriteMd(port, 'concurrent agent line\n', {+ docName: COLLATERAL_DOC,+ position: 'append',+ agentId: 'collateral-writer',+ agentName: 'Collateral',+ });++ // Establish the warm session before the sweep begins to apply pressure.+ await writeCollateral();++ let sweepDone = false;+ let collateralWrites = 0;+ const collateralFailures: Array<{ status: number | null }> = [];+ const runWriterLoop = async (): Promise<void> => {+ while (!sweepDone) {+ await sweepSleep(WRITER_INTERVAL_MS);+ if (sweepDone) break;+ try {+ await writeCollateral();+ collateralWrites += 1;+ } catch (err) {+ // A real HTTP non-OK surfaces here (harness sets err.status). A+ // capacity 503 would mean the sweep starved the writer.+ collateralFailures.push({ status: (err as { status?: number }).status ?? null });+ }+ }+ };++ let capacityRefusals = 0;+ const fixItem = async (docName: string): Promise<SweepFixOutcome> => {+ const outcome = await fixLintDoc(docName);+ if (!outcome.ok && isCapacityRefusal(outcome)) capacityRefusals += 1;+ return outcome;+ };++ const writerPromise = runWriterLoop();+ const result = await runProjectFixSweep({+ items: sweepDocs,+ fixItem,+ sleep: sweepSleep,+ onProgress: () => {},+ shouldContinue: () => true,+ });+ sweepDone = true;+ await writerPromise;++ // Every file was fixed — no file was recorded unfixable for any reason,+ // capacity or otherwise.+ expect(result.cancelled).toBe(false);+ expect(result.failures).toEqual([]);++ // The retry path actually engaged against a real refusal — the test is not+ // vacuously green because the cap was never reached.+ expect(capacityRefusals).toBeGreaterThan(0);++ // The concurrent writer wrote throughout and was never refused.+ expect(collateralWrites).toBeGreaterThan(0);+ expect(collateralFailures).toEqual([]);+ }, 30_000);+});diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.tsindex a79b8cae3..dca268447 100644--- a/packages/app/tests/integration/test-harness.ts+++ b/packages/app/tests/integration/test-harness.ts@@ -206,6 +206,14 @@ export interface CreateTestServerOptions {*/pullIntervalSeconds?: number;pushIntervalSeconds?: number;+ /**+ * Agent-session cap + idle-eviction floor for the shared AgentSessionManager.+ * Production leaves this undefined (256 / 5 s). Capacity tests pass a small+ * `maxSessions` so a sweep reaches the cap without opening hundreds of real+ * sessions, and a short `minEvictableIdleMs` so a refused session frees on a+ * retry within the test budget.+ */+ agentSessionOptions?: ServerOptions['agentSessionOptions'];}export async function createTestServer(options: CreateTestServerOptions = {}): Promise<TestServer> {@@ -297,6 +305,7 @@ export async function createTestServer(options: CreateTestServerOptions = {}): PmdManager: options.mdManager,pullIntervalSeconds: options.pullIntervalSeconds,pushIntervalSeconds: options.pushIntervalSeconds,+ agentSessionOptions: options.agentSessionOptions,...(ephemeral ? { ephemeral: true, singleDocRelPath: options.singleDocRelPath } : {}),// Skip the durable state-manifest pre-flight gate. Each test allocates a fresh tmpdir, so the gate has nothing// meaningful to assert; the writes would just generate noise across thousandsdiff --git a/packages/app/tests/perf/sweep-measure.ts b/packages/app/tests/perf/sweep-measure.tsnew file mode 100644index 000000000..1b742d729--- /dev/null+++ b/packages/app/tests/perf/sweep-measure.ts@@ -0,0 +1,347 @@+#!/usr/bin/env -S npx tsx+/**+ * `tsx tests/perf/sweep-measure.ts --target=<url>` — project-scope Fix-all+ * sweep measurement.+ *+ * Drives the real Problems panel against a live server and reports the five+ * numbers the shipping configuration's success metrics turn on: panel-open+ * time, full-sweep duration, successful-fix count, capacity-refusal count,+ * and main-thread blocked time. The bash orchestrator (`scripts/measure-sweep.sh`)+ * boots the server against a scratch copy of a fixture, invokes this, and+ * compares the numbers to their targets.+ *+ * Standalone entry — no `@playwright/test` runner (its retries/fixtures fight+ * measurement stability). Mirrors `tests/perf/profile.ts`, but purpose-built+ * for one long sweep rather than the perf-baseline scenario matrix: it skips+ * the CDP trace (a 2,000-request sweep produces a multi-hundred-MB trace that+ * measures nothing here) and keeps only the long-task observer.+ *+ * The result is a single machine-parseable stdout line — `SWEEP_RESULT <json>`+ * — so the orchestrator can parse it without a results file. Every human-facing+ * progress line goes to stderr, keeping stdout a clean channel.+ *+ * CLI:+ * --target=<url> Base URL of the live server. Required.+ * --nav-doc=<name> Extension-less docName to open first (any doc works —+ * project scope audits the whole content dir). Falls back+ * to OK_SWEEP_DOC, then to the app root.+ * --sweep-timeout=<ms> Max wait for the sweep to finish. Default 300000.+ *+ * Exit codes:+ * 0 measurement completed (SWEEP_RESULT written)+ * 1 usage error+ * 2 the run threw before a result could be formed+ */++import { pathToFileURL } from 'node:url';+import { type Browser, chromium, type Page } from '@playwright/test';+import { installLongtaskObserver, readLongtasks } from './lib/longtask-observer.ts';++const DEFAULT_SWEEP_TIMEOUT_MS = 300_000;+const VIEWPORT = { width: 1440, height: 900 };+// The sr-only sweep live region ("Fixing N of M files") is the one signal that+// is present for the whole sweep and gone the instant it ends. The Auto-fix+// button's own progress label uses the short "Fixing N/M" form, so matching the+// long "of M files" phrasing targets the live region alone.+const FIXING_REGION_RE = /Fixing\s+\d+\s+of\s+(\d+)\s+files/;++interface Args {+ target: string;+ navDoc: string | null;+ sweepTimeoutMs: number;+}++function parseArgs(argv: readonly string[]): Args {+ let target = '';+ let navDoc = process.env.OK_SWEEP_DOC ?? null;+ let sweepTimeoutMs = DEFAULT_SWEEP_TIMEOUT_MS;+ for (const raw of argv) {+ if (raw.startsWith('--target=')) target = raw.slice('--target='.length);+ else if (raw.startsWith('--nav-doc=')) navDoc = raw.slice('--nav-doc='.length) || null;+ else if (raw.startsWith('--sweep-timeout=')) {+ const n = Number(raw.slice('--sweep-timeout='.length));+ if (Number.isFinite(n) && n > 0) sweepTimeoutMs = n;+ } else if (raw === '-h' || raw === '--help') {+ usageAndExit(null);+ } else if (raw.startsWith('--')) {+ usageAndExit(`unrecognized flag: "${raw}"`);+ }+ }+ if (!target) usageAndExit('missing required --target=<url>');+ return { target, navDoc, sweepTimeoutMs };+}++function usageAndExit(err: string | null): never {+ const lines = [+ 'Usage: tsx tests/perf/sweep-measure.ts --target=<url> [flags]',+ '',+ ' --target=<url> Required. Base URL of a live OK server.',+ ' --nav-doc=<name> Doc to open first (default: $OK_SWEEP_DOC or app root).',+ ' --sweep-timeout=<ms> Max wait for the sweep. Default 300000.',+ ];+ if (err) process.stderr.write(`[sweep-measure] ${err}\n\n`);+ process.stderr.write(`${lines.join('\n')}\n`);+ process.exit(err ? 1 : 0);+}++function log(line: string): void {+ process.stderr.write(`[sweep-measure] ${line}\n`);+}++/** Encode a docName for the hash route without escaping its path separators. */+function encodeDocRoute(docName: string): string {+ return docName.split('/').map(encodeURIComponent).join('/');+}++interface LintFixTally {+ success: number;+ capacity503: number;+ otherFail: number;+}++interface SweepResult {+ target: string;+ navDoc: string | null;+ appReadyMs: number;+ panelOpenColdMs: number;+ panelOpenWarmMs: number;+ fixableFileCount: number;+ sweepDurationMs: number;+ sweepCompleted: boolean;+ lintFixSuccess: number;+ lintFix503: number;+ lintFixOtherFail: number;+ filesFailedTerminal: number;+ mainThreadBlockedMs: number;+ mainThreadBlockedPct: number;+ longtaskCount: number;+ consoleErrorCount: number;+ notes: string[];+}++async function openProblemsProjectScope(page: Page, notes: string[]): Promise<number> {+ await page.locator('#tab-problems').click();+ // Wait for the panel body (a list or the empty state) so the scope toggle exists.+ await page+ .locator('ul[aria-label="Problems"]')+ .or(page.getByText('No problems found'))+ .first()+ .waitFor({ state: 'visible', timeout: 30_000 });++ // Panel-open cost is the render of the enumerated plane after the audit+ // resolves — measure click → summary populated. The first activation also+ // pays the cold audit walk, so it is reported separately from the warm+ // re-activation below (which is render-bound and comparable to the spec's+ // collapse-by-default number).+ const cold = await timeProjectScopeActivation(page);+ notes.push(`panel-open cold (incl. cold audit): ${cold}ms`);+ return cold;+}++/** Click into project scope and time until the audit summary renders. */+async function timeProjectScopeActivation(page: Page): Promise<number> {+ const summary = page.getByTestId('problems-audit-summary');+ const t0 = Date.now();+ await page.getByTestId('panel-scope-project').click();+ // The summary text is empty until `audit.status === 'loaded'`; a populated+ // error/warning count is the "plane rendered" signal.+ await summary.filter({ hasText: /\d+\s+(error|warning)/ }).waitFor({ timeout: 120_000 });+ return Date.now() - t0;+}++async function run(args: Args): Promise<SweepResult> {+ const notes: string[] = [];+ const tally: LintFixTally = { success: 0, capacity503: 0, otherFail: 0 };+ let consoleErrorCount = 0;++ const browser: Browser = await chromium.launch({+ headless: process.env.OK_PERF_HEADED !== '1',+ args: ['--enable-precise-memory-info'],+ });+ try {+ const context = await browser.newContext({ viewport: VIEWPORT, deviceScaleFactor: 1 });+ const page = await context.newPage();++ // Long-task observer must be installed before the first navigation so+ // `buffered: true` back-fills tasks that land during load.+ await installLongtaskObserver(page);++ page.on('response', (resp) => {+ if (!resp.url().includes('/api/lint/fix')) return;+ const s = resp.status();+ if (s >= 200 && s < 300) tally.success += 1;+ else if (s === 503) tally.capacity503 += 1;+ else tally.otherFail += 1;+ });+ page.on('console', (msg) => {+ if (msg.type() === 'error') consoleErrorCount += 1;+ });+ page.on('pageerror', () => {+ consoleErrorCount += 1;+ });++ // Navigate. Opening a doc gives the right rail (and its Problems tab); the+ // project-scope audit is independent of which doc is open.+ const url = args.navDoc ? `${args.target}/#/${encodeDocRoute(args.navDoc)}` : `${args.target}/`;+ log(`navigating to ${url}`);+ const readyStart = Date.now();+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60_000 });+ await page.locator('#tab-problems').waitFor({ state: 'visible', timeout: 120_000 });+ const appReadyMs = Date.now() - readyStart;+ log(`app ready in ${appReadyMs}ms`);++ const panelOpenColdMs = await openProblemsProjectScope(page, notes);+ log(`panel open (cold) ${panelOpenColdMs}ms`);++ // Warm re-activation: leave project scope, return, and re-time. The audit+ // snapshot is cached across scope flips, so this isolates the render cost.+ await page.getByTestId('panel-scope-doc').click();+ await page.waitForTimeout(300);+ const panelOpenWarmMs = await timeProjectScopeActivation(page);+ log(`panel open (warm) ${panelOpenWarmMs}ms`);++ const autoFix = page.getByTestId('problems-auto-fix');+ await autoFix.waitFor({ state: 'visible', timeout: 30_000 });+ if (await autoFix.isDisabled()) {+ notes.push('Auto-fix button disabled — no fixable files; sweep skipped.');+ log('Auto-fix disabled; nothing to sweep');+ return buildResult(args, {+ appReadyMs,+ panelOpenColdMs,+ panelOpenWarmMs,+ fixableFileCount: 0,+ sweepDurationMs: 0,+ sweepCompleted: true,+ tally,+ mainThreadBlockedMs: 0,+ mainThreadBlockedPct: 0,+ longtaskCount: 0,+ consoleErrorCount,+ notes,+ });+ }++ // Drive the sweep. Time the window in the page's own performance timeline so+ // long tasks (same timeline) can be attributed to it.+ const fixingRegion = page.locator('[role="status"]').filter({ hasText: FIXING_REGION_RE });+ const sweepStartPerf = await page.evaluate(() => performance.now());+ await autoFix.click();++ let fixableFileCount = 0;+ let sweepCompleted = true;+ try {+ await fixingRegion.first().waitFor({ state: 'attached', timeout: 30_000 });+ const text = (await fixingRegion.first().textContent()) ?? '';+ const m = text.match(FIXING_REGION_RE);+ if (m) fixableFileCount = Number(m[1]);+ log(`sweep started: ${fixableFileCount} fixable files`);+ await fixingRegion.first().waitFor({ state: 'detached', timeout: args.sweepTimeoutMs });+ } catch (err) {+ sweepCompleted = false;+ notes.push(+ `sweep did not complete within ${args.sweepTimeoutMs}ms: ${err instanceof Error ? err.message : String(err)}`,+ );+ log(`WARN: sweep incomplete — ${err instanceof Error ? err.message : String(err)}`);+ }+ const sweepEndPerf = await page.evaluate(() => performance.now());+ const sweepDurationMs = Math.round(sweepEndPerf - sweepStartPerf);+ log(`sweep window ${sweepDurationMs}ms (completed=${sweepCompleted})`);++ // Long tasks that fell inside the sweep window are the main-thread blocking.+ const longtasks = await readLongtasks(page);+ const inWindow = longtasks.filter(+ (t) => t.startTime >= sweepStartPerf && t.startTime <= sweepEndPerf,+ );+ const mainThreadBlockedMs = Math.round(inWindow.reduce((sum, t) => sum + t.duration, 0));+ const mainThreadBlockedPct =+ sweepDurationMs > 0 ? round2((mainThreadBlockedMs / sweepDurationMs) * 100) : 0;++ if (fixableFileCount === 0 && tally.success > 0) {+ // The region flicked past too fast to sample (tiny fixtures); the count of+ // distinct successful fixes is then the best available denominator.+ fixableFileCount = tally.success + Math.max(0, tally.otherFail);+ notes.push('fixableFileCount inferred from successful fixes (region not sampled)');+ }+ const filesFailedTerminal = Math.max(0, fixableFileCount - tally.success);++ return buildResult(args, {+ appReadyMs,+ panelOpenColdMs,+ panelOpenWarmMs,+ fixableFileCount,+ sweepDurationMs,+ sweepCompleted,+ tally,+ mainThreadBlockedMs,+ mainThreadBlockedPct,+ longtaskCount: inWindow.length,+ consoleErrorCount,+ notes,+ filesFailedTerminal,+ });+ } finally {+ await browser.close().catch(() => {});+ }+}++function buildResult(+ args: Args,+ parts: {+ appReadyMs: number;+ panelOpenColdMs: number;+ panelOpenWarmMs: number;+ fixableFileCount: number;+ sweepDurationMs: number;+ sweepCompleted: boolean;+ tally: LintFixTally;+ mainThreadBlockedMs: number;+ mainThreadBlockedPct: number;+ longtaskCount: number;+ consoleErrorCount: number;+ notes: string[];+ filesFailedTerminal?: number;+ },+): SweepResult {+ return {+ target: args.target,+ navDoc: args.navDoc,+ appReadyMs: parts.appReadyMs,+ panelOpenColdMs: parts.panelOpenColdMs,+ panelOpenWarmMs: parts.panelOpenWarmMs,+ fixableFileCount: parts.fixableFileCount,+ sweepDurationMs: parts.sweepDurationMs,+ sweepCompleted: parts.sweepCompleted,+ lintFixSuccess: parts.tally.success,+ lintFix503: parts.tally.capacity503,+ lintFixOtherFail: parts.tally.otherFail,+ filesFailedTerminal:+ parts.filesFailedTerminal ?? Math.max(0, parts.fixableFileCount - parts.tally.success),+ mainThreadBlockedMs: parts.mainThreadBlockedMs,+ mainThreadBlockedPct: parts.mainThreadBlockedPct,+ longtaskCount: parts.longtaskCount,+ consoleErrorCount: parts.consoleErrorCount,+ notes: parts.notes,+ };+}++function round2(v: number): number {+ return Number.isFinite(v) ? Math.round(v * 100) / 100 : 0;+}++const isMain =+ process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href;++if (isMain) {+ const args = parseArgs(process.argv.slice(2));+ run(args)+ .then((result) => {+ process.stdout.write(`SWEEP_RESULT ${JSON.stringify(result)}\n`);+ process.exit(0);+ })+ .catch((err) => {+ log(`fatal: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);+ process.exit(2);+ });+}++export { encodeDocRoute, parseArgs, type SweepResult };diff --git a/packages/app/tests/stress/markdown-lint.e2e.ts b/packages/app/tests/stress/markdown-lint.e2e.tsindex dd5bea26f..49d3dfc11 100644--- a/packages/app/tests/stress/markdown-lint.e2e.ts+++ b/packages/app/tests/stress/markdown-lint.e2e.ts@@ -260,11 +260,27 @@ test.describe('markdown lint — Problems panel project scope', () => {const group2 = scopeBody.getByTestId('problems-audit-group').filter({ hasText: doc2 });await expect(group1).toBeVisible({ timeout: 10_000 });await expect(group2).toBeVisible();+ // Headers show the file path and per-file count while collapsed.await expect(group1.getByTestId('problems-audit-file-count')).toHaveText('2');await expect(group2.getByTestId('problems-audit-file-count')).toHaveText('1');- // Groups render their diagnostics expanded by default.+ // Groups mount collapsed, so their diagnostic rows are not in the DOM — the+ // structural guard for the panel-open cost (element count bounded by group+ // count, not by finding count).+ await expect(group1).toHaveAttribute('data-state', 'closed');+ await expect(group2).toHaveAttribute('data-state', 'closed');+ await expect(scopeBody.getByText(MD001)).toHaveCount(0);+ await expect(scopeBody.getByText(MD010)).toHaveCount(0);++ // Expand-all restores the fully-expanded view in one action…+ await scopeBody.getByTestId('problems-audit-expand-toggle').click();+ await expect(group1).toHaveAttribute('data-state', 'open');await expect(group1.getByText(MD001)).toBeVisible();await expect(group2.getByText(MD010)).toBeVisible();+ // …and collapse-all returns them to headers only.+ await scopeBody.getByTestId('problems-audit-expand-toggle').click();+ await expect(group1).toHaveAttribute('data-state', 'closed');+ await expect(scopeBody.getByText(MD001)).toHaveCount(0);+// The audit-wide error/warning counts render above the groups (substring// tolerant of the singular/plural form — leftover docs from earlier tests// in this worker legitimately contribute to the totals).@@ -308,6 +324,8 @@ test.describe('markdown lint — Problems panel project scope', () => {const group = page.getByTestId('problems-audit-group').filter({ hasText: doc2 });await expect(group).toBeVisible({ timeout: 10_000 });+ // Groups mount collapsed, so open them before the diagnostic row exists.+ await page.getByTestId('problems-audit-expand-toggle').click();await group.getByRole('button', { name: /Hard tabs/ }).click();// Hash navigation to the closed doc…@@ -634,6 +652,14 @@ test.describe('markdown lint — WYSIWYG block decorations + navigation', () =>await page.getByTestId('panel-scope-project').click();const group = page.getByTestId('problems-audit-group').filter({ hasText: doc2 });await expect(group).toBeVisible({ timeout: 10_000 });+ // Groups mount collapsed, and Radix unmounts closed content, so the row is+ // not in the DOM yet. Expand as a SEPARATE prior action — folding it into+ // the click below would destroy what this test pins, which is that ONE+ // click both navigates and scrolls.+ await page.getByTestId('problems-audit-expand-toggle').click();+ await expect(group.getByRole('button', { name: /Trailing spaces/ }).first()).toBeVisible({+ timeout: 10_000,+ });// A single click: navigate to the closed doc …await groupdiff --git a/packages/app/tests/stress/unified-problems.e2e.ts b/packages/app/tests/stress/unified-problems.e2e.tsindex f6388f84f..02f873414 100644--- a/packages/app/tests/stress/unified-problems.e2e.ts+++ b/packages/app/tests/stress/unified-problems.e2e.ts@@ -109,6 +109,9 @@ test.describe('unified Problems — project scope', () => {await expect(page.getByText(`${lintDocName}.md`)).toBeVisible({ timeout: 15_000 });await expect(page.getByText(`${linkDocName}.md`)).toBeVisible();+ // Groups mount collapsed; open them to assert the row-level chips.+ await page.getByTestId('problems-audit-expand-toggle').click();+// Rows name their producing validator, not a generic category.const tags = page.getByTestId('problems-source-tag');await expect(tags.filter({ hasText: 'markdownlint' }).first()).toBeVisible();diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex c1ecd6c1b..21f6e3ca1 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -17,6 +17,7 @@ import simpleGit from 'simple-git';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { stringify as stringifyYaml } from 'yaml';import * as Y from 'yjs';+import { MAX_AGENT_SESSIONS } from './agent-sessions.ts';import { BacklinkIndex } from './backlink-index.ts';import { getBootTimings, resetBootTimingsForTest, startBootTimings } from './boot-timings.ts';import { DerivedDocumentIndex } from './derived-document-index.ts';@@ -231,6 +232,49 @@ describe('createServer() — document durability state isolation', () => {});});+describe('createServer() — agent-session cap passthrough', () => {+ let projectDir: string;+ let server: ServerInstance | null;++ beforeEach(() => {+ projectDir = mkdtempSync(resolve(tmpdir(), 'ok-agent-session-cap-'));+ server = null;+ });++ afterEach(async () => {+ await server?.destroy();+ rmSync(projectDir, { recursive: true, force: true });+ });++ test('installs the overridden session cap on the manager', async () => {+ const contentDir = mkdtempSync(resolve(projectDir, 'content-'));+ server = createServer({+ contentDir,+ projectDir,+ quiet: true,+ agentSessionOptions: { maxSessions: 4, minEvictableIdleMs: 0 },+ });+ await server.ready;++ // The manager's `sessionLimit` getter reads back the cap it was constructed+ // with. A missing passthrough would leave it at the default, so this pins+ // the ServerOptions → constructor wiring the low-cap capacity tests rely on.+ expect(server.sessionManager.sessionLimit).toBe(4);+ });++ test('defaults to MAX_AGENT_SESSIONS when no override is supplied', async () => {+ const contentDir = mkdtempSync(resolve(projectDir, 'content-'));+ server = createServer({+ contentDir,+ projectDir,+ quiet: true,+ });+ await server.ready;++ expect(server.sessionManager.sessionLimit).toBe(MAX_AGENT_SESSIONS);+ });+});+describe('createServer() — derived-index branch lifecycle', () => {let projectDir: string;let git: ReturnType<typeof simpleGit>;diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex b3fecb765..303259d04 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -236,6 +236,18 @@ export interface ServerOptions {*/stalenessGraceMs?: number;stalenessSweepIntervalMs?: number;+ /**+ * Agent-session manager tuning, forwarded verbatim to the+ * `AgentSessionManager` constructor. Production leaves this undefined so the+ * manager keeps its own `MAX_AGENT_SESSIONS` / `MIN_EVICTABLE_IDLE_MS`+ * defaults (256 / 5 s); tests pass a small `maxSessions` to exercise the+ * capacity-refusal path (`AgentSessionCapacityError` → 503) without opening+ * hundreds of real sessions.+ */+ agentSessionOptions?: {+ maxSessions?: number;+ minEvictableIdleMs?: number;+ };gitEnabled?: boolean;commitDebounceMs?: number;wipRef?: string;@@ -1557,7 +1569,7 @@ export function createServer(options: ServerOptions): ServerInstance {agentFocusBroadcaster = new AgentFocusBroadcaster(hocuspocus);agentPresenceBroadcaster = new AgentPresenceBroadcaster(hocuspocus);- sessionManager = new AgentSessionManager(hocuspocus);+ sessionManager = new AgentSessionManager(hocuspocus, options.agentSessionOptions);// Registered here (not with the connection provider above) because the// session manager doesn't exist yet at that point; gauges only sample at// metric-export time, so late registration is safe.