diff --git a/Museion/ProseList.swift b/Museion/ProseList.swift index 5cd756d..e214236 100644 --- a/Museion/ProseList.swift +++ b/Museion/ProseList.swift @@ -121,8 +121,13 @@ nonisolated enum ProseList { let hiddenLineCount: Int } - static func parents(in text: String) -> [ParentHint] { + /// `observeLines` (brief-24): reports how many lines the scan visited — + /// the typing-budget instrument. Nil in production; tests inject it to + /// pin that single-line typing edits scan ZERO lines (the #142 in-place + /// re-key) while full passes scan O(lines). Per-call, no shared state. + static func parents(in text: String, observeLines: ((Int) -> Void)? = nil) -> [ParentHint] { let scanned = lines(in: text) + observeLines?(scanned.count) var out: [ParentHint] = [] for (idx, line) in scanned.enumerated() where line.isList { let bounds = blockBounds(scanned, from: idx, indent: line.indent) diff --git a/Museion/ProseListTextView.swift b/Museion/ProseListTextView.swift index e740182..26dd482 100644 --- a/Museion/ProseListTextView.swift +++ b/Museion/ProseListTextView.swift @@ -90,6 +90,12 @@ final class ProseListTextView: NSTextView { /// rejected, or none) → the full pass. var pendingPlainEdit: (range: NSRange, delta: Int)? + /// Brief-24 typing-budget window for paths that call `refreshFolds()` + /// bare (the PostEditorView coordinator's textDidChange tail) — a + /// per-instance, test-owned hook; nil in production. The per-call + /// `observeScan` parameter takes precedence when both are set. + var onLineScan: ((Int) -> Void)? + override func shouldChangeText(in affectedRange: NSRange, replacementString: String?) -> Bool { let accepted = super.shouldChangeText(in: affectedRange, replacementString: replacementString) pendingPlainEdit = nil @@ -202,7 +208,11 @@ final class ProseListTextView: NSTextView { /// recorded single-line edit takes the in-place re-key (no rescan, no /// storage swap); no folds → chrome-only refresh, everything else → the /// full pass. - func refreshFolds() { + /// `observeScan` (brief-24): the typing-budget instrument — reports the + /// line count of every full-buffer scan this refresh performs. Nil in + /// production; the typing-budget pins inject it to prove single-line + /// edits take the in-place re-key (zero scans) at any buffer size. + func refreshFolds(observeScan: ((Int) -> Void)? = nil) { defer { pendingPlainEdit = nil } if let edit = pendingPlainEdit, !folds.isEmpty, rekeyAfterPlainEdit(edit) { return @@ -211,7 +221,7 @@ final class ProseListTextView: NSTextView { chrome.refresh() return } - refreshFoldRendering() + refreshFoldRendering(observeScan: observeScan) } func toggleFold(_ parent: ProseList.ParentHint) { @@ -227,8 +237,8 @@ final class ProseListTextView: NSTextView { /// same marker text; no match → the fold dies), restyle the document, /// re-hide every live scope, and park a caret that landed inside a /// hidden scope at its parent's marker end. - func refreshFoldRendering() { - let parents = ProseList.parents(in: string) + func refreshFoldRendering(observeScan: ((Int) -> Void)? = nil) { + let parents = ProseList.parents(in: string, observeLines: observeScan ?? onLineScan) // ponytail: nearest-same-marker re-key can move a fold across duplicate // marker texts — track the edit delta in shouldChangeText if that bites. var seenKeys = Set() diff --git a/MuseionTests/ProseRekeyTests.swift b/MuseionTests/ProseRekeyTests.swift index fae09f4..eaeeb53 100644 --- a/MuseionTests/ProseRekeyTests.swift +++ b/MuseionTests/ProseRekeyTests.swift @@ -261,3 +261,109 @@ struct ProseRekeyMathTests { #expect(result.park == 15) // caret parks at the marker line's content end } } + +// MARK: - #142 typing budget (brief-24: fold-typing-budget-pin) + +/// The typing-cost guard the landed re-key optimization never had: a quiet +/// regression that routes single-line typing edits back to the full pass +/// would keep every correctness pin above green (the full pass re-derives +/// CORRECT folds — it is only O(buffer) per keystroke). These pins count +/// scanned LINES through the real keystroke pipeline (shouldChangeText → +/// storage mutate → refreshFolds) — an operation count, never wall-time — +/// and hold the budget flat as the buffer doubles: the cheap path's cost +/// rides the fold count, not the document size. +extension ProseFoldRekeyTests { + /// One folded list + `filler` plain lines below it. Plain filler lines + /// are not list markers, so they add buffer without adding parents. + private func budgetText(filler: Int) -> String { + "intro\n\n- parent\n - child\n" + (0 ..< filler).map { "filler line \($0)\n" }.joined() + } + + /// Type one character through the real pipeline at N and 2N filler lines + /// and return each run's scanned-line total. + private func typingScans(filler: Int) -> Int { + let text = budgetText(filler: filler) + let textView = makeView(text) + guard let parent = ProseList.parents(in: text).first else { + preconditionFailure("fixture must arm a parent") + } + textView.toggleFold(parent) + var scanned = 0 + // The coordinator's keystroke tail with the budget instrument armed. + textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x") + textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x") + textView.refreshFolds { scanned += $0 } + return scanned + } + + @Test func `typing beside a fold scans zero lines at N and 2N`() { + let atN = typingScans(filler: 200) + let at2N = typingScans(filler: 400) + #expect(atN == 0, "single-line typing edit took the full pass at N: \(atN) lines scanned") + #expect(at2N == 0, "single-line typing edit took the full pass at 2N: \(at2N) lines scanned") + // The budget itself: doubling the buffer must not move it. + #expect(atN == at2N) + } + + @Test func `coordinator keystroke pipeline scans zero lines beside a fold`() throws { + // The through-seam pin (aegis ruling): the REAL entry — insertText + // through the PostEditorView coordinator's delegate tail + // (shouldChangeText → storage → textDidChange → refreshFolds) — + // never a direct test call. The instance hook (onLineScan) is the + // budget window for paths that call refreshFolds() bare. + let text = budgetText(filler: 200) + let textView = makeView(text) + let parent = try #require(ProseList.parents(in: text).first) + textView.toggleFold(parent) + var scanned = 0 + textView.onLineScan = { scanned += $0 } + let session = EditorSession( + target: .externalFile(URL(fileURLWithPath: "/dev/null")), + debounce: .seconds(3600), + ) + let coordinator = ProseTextView.Coordinator( + representable: ProseTextView(session: session, dropBridge: ProseDropBridge()), + ) + textView.delegate = coordinator // production wiring (PostEditorView) + textView.setSelectedRange(NSRange(location: 0, length: 0)) + textView.insertText("x", replacementRange: NSRange(location: 0, length: 0)) + #expect(scanned == 0, "real keystroke took the full pass: \(scanned) lines") + #expect(textView.folds.count == 1) // and the fold survived the real pipeline + // Liveness in the same harness: a structural insert through the same + // coordinator MUST scan the whole buffer (206 — see the control's + // arithmetic) — proving the instance window counts real work. + scanned = 0 + textView.setSelectedRange(NSRange(location: 0, length: 0)) + textView.insertText("y\n\n", replacementRange: NSRange(location: 0, length: 0)) + #expect(scanned == 206, "instance window lost exact accounting: \(scanned)") + } + + @Test func `full pass scans scale with the buffer at N and 2N`() { + /// The control that keeps the zero-pin honest: route the SAME edit + /// shape to the full pass (a multi-line replacement — structural + /// edits never take the cheap path) and the instrument must report + /// the whole buffer, growing with it. If the observer ever goes + /// dead (unwired, wrong seam), this fails — the zero-pin above can + /// never pass vacuously. + func fullPassScans(filler: Int) -> Int { + let text = budgetText(filler: filler) + let textView = makeView(text) + guard let parent = ProseList.parents(in: text).first else { + preconditionFailure("fixture must arm a parent") + } + textView.toggleFold(parent) + var scanned = 0 + textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x\n\n") + textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x\n\n") + textView.refreshFolds { scanned += $0 } + return scanned + } + let atN = fullPassScans(filler: 200) + let at2N = fullPassScans(filler: 400) + // 4 fixture lines + filler + 2 from the split intro line ("x\n\n" + // turns intro into three lines) — exactly the buffer's line count. + #expect(atN == 206, "control lost exact line accounting: \(atN)") + #expect(at2N == 406, "control lost exact line accounting: \(at2N)") + #expect(at2N > atN, "the instrument must scale with the buffer") + } +} diff --git a/docs/devlog/20261113-fold-typing-budget-pin_log.md b/docs/devlog/20261113-fold-typing-budget-pin_log.md new file mode 100644 index 0000000..bc5297d --- /dev/null +++ b/docs/devlog/20261113-fold-typing-budget-pin_log.md @@ -0,0 +1,60 @@ +# Fold typing budget — operation-count pin at N/2N + +> **Date:** 2026-11-13 +> **Type:** opt (test-only instrument + pins; zero production behavior change) +> **Reference:** brief-24 `fold-typing-budget-pin` (unticketed instrument-audit commitment; #142 referenced as context only — CLOSED, no Fixes footer). Base `7ed3041` (museion main tip at claim, re-verified via ls-remote). **Incident:** the brief was dual-dispatched (aegis one-shot spawn + discussion announcement); the sibling session began implementing in this worktree concurrently and was dispatcher-terminated at zero commits per @aegis ruling — this branch is the ruling's surviving implementation, with the sibling's coordinator-seam idea folded in as the through-seam pin. Takeover is recorded in the ack file; every gate below ran AFTER hunk-level decontamination of the tree. + +## Goal + +The landed #142 in-place re-key (`rekeyAfterPlainEdit` — single-line typing edits re-key folds with per-fold O(1) math, no rescan, no storage swap) has correctness coverage (`ProseFoldRekeyTests`) but no typing-cost guard: a quiet regression that routes single-line edits back to the full pass would keep every correctness pin green — the full pass re-derives CORRECT folds, it is only O(buffer) per keystroke. Ship the missing pin: an operation-count instrument through the real editor seam, budget held flat as the buffer doubles. Explicitly NOT a wall-time benchmark. + +## What Was Done + +- Instrument (production diff, default-nil, zero behavior change): `ProseList.parents(in:observeLines:)` reports the line count it scanned; `refreshFolds(observeScan:)` / `refreshFoldRendering(observeScan:)` thread a per-call observer to it; `refreshFoldRendering` also consults a per-instance `onLineScan` hook (`observeScan ?? onLineScan`) — the window for production paths that call `refreshFolds()` bare, i.e. the PostEditorView coordinator's textDidChange tail. Per-call and per-instance only, no shared/static state — the brief-23 lesson (parallel hosted suite races a global counter). Precedent: `WritingGoal.update(text:countWords:)`, PostScanCache's counted miss/hit seams. +- Pin 1 `typing beside a fold scans zero lines at N and 2N`: one folded list + 200 plain filler lines (N) and 400 (2N); type "x" in the intro line through the keystroke pipeline (`shouldChangeText` → storage mutate → `refreshFolds(observeScan:)`). Scanned lines == 0 at both sizes, equal across sizes — the cheap path's cost rides the fold count, not the document. +- Pin 2 (control) `full pass scans scale with the buffer at N and 2N`: the same edit shape routed to the full pass (multi-line replacement — structural edits never take the cheap path) must report EXACTLY the buffer's line count: 206 at N, 406 at 2N (4 fixture lines + filler + 2 from the split intro line). A dead/unwired instrument passes pin 1 vacuously but fails pin 2. +- Pin 3 (through-seam, the ruling's addition) `coordinator keystroke pipeline scans zero lines beside a fold`: real `insertText` on a real `ProseListTextView` whose delegate is a REAL `ProseTextView.Coordinator` (constructed like production: `ProseTextView(session:dropBridge:)`) — insertText → shouldChangeText → storage → coordinator `textDidChange` (paragraph reattribute, caret centering, edit feed) → `refreshFolds()` bare → in-place re-key. Zero scans, fold survives; then a structural insert through the same live harness must report exactly 206 — the instance window is non-vacuous in the same test. Headless-safe by construction: `centerCaretWhileTyping` guards on `textView.window`. +- Mutation check (the pin-brief RED equivalent — pins of existing good behavior cannot fail at base): severing the single `observeLines?(scanned.count)` firing → pin 2 AND pin 3 fail (both instruments proven live, both zero-pins exposed as vacuous-green without their controls); wiring restored → green. + +## Incident & Decontamination (ruling steps 1–2) + +- Sibling session `local-8a52f739…` (aegis one-shot) claimed the ack at 17:02:32 and wrote `MuseionTests/ProseTypingBudgetTests.swift` (untracked, compile-broken — pins a `typingBudget` member that existed nowhere; test-first, production edit never landed) into this worktree at 17:09:46, mid-implementation, while the owner's background suite ran. Dispatcher-terminated; the file was removed by the sibling mid-rewrite and verified absent. +- Takeover ack block appended to `brief-24-fold-typing-budget-pin-ack.txt` (owner session id, ruling attribution, sibling id + termination). +- Hunk-level decontamination: every modified line in `ProseList.swift`, `ProseListTextView.swift`, `ProseRekeyTests.swift`, `docs/devlog/INDEX.md` matched the surviving owner's known hunks; zero deletions outside the two changed signatures; no other tracked or untracked paths in the tree. All pre-interleave gate numbers were voided per the ruling and re-run below. + +## Gates (all fresh, post-decontamination, `-derivedDataPath /tmp/b24-dd2`) + +- Focused: MuseionTests/ProseFoldRekeyTests **11/11 passed**, `** TEST SUCCEEDED **` (8 pre-existing + 3 new pins). +- Mutation run: firing severed — `** TEST FAILED **`; exactly `full pass scans scale with the buffer at N and 2N` and `coordinator keystroke pipeline scans zero lines beside a fold` failed, other 9 passed. Wiring restored, count re-verified present. +- Full unit target: xcresult `Test-Museion-2026.11.13_17-19-25-+0100.xcresult`, `xcresulttool` summary: **result Passed, 692 passed / 0 failed / 0 skipped, totalTestCount 692** (689 trunk + 3 new pins), `** TEST SUCCEEDED **`, exit 0. +- swiftformat: `0/3 files require formatting`. swiftlint (3 touched files): 4 violations — identical count to pristine base `7ed3041` (all pre-existing: two file_length, one opening_brace, one type_body_length); net zero added. +- One vacuous-run trap hit and discarded during development: `-only-testing` with an underscore-mangled test name matched ZERO tests and exited 0 — the #134-class lesson; class-level filters only. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Per-call observer + per-instance hook, never a global counter | Brief-23 lesson: the hosted suite runs Swift Testing tests in parallel; shared counters race. The per-instance hook lives on a view one test exclusively owns. | +| Exact line counts (206/406), not `> 0` | An exact count proves the instrument reads the real buffer through the real seam — `> 0` passes on any accidental firing. | +| Through-seam pin self-controls in one test | The instance window needs its own liveness proof; folding the structural 206-assert into the same test keeps the ruling's "one pin" while closing the vacuous loop. | +| Coordinator harness: real `ProseTextView.Coordinator` + `EditorSession(target: .externalFile)` | Production wiring (`tv.delegate = context.coordinator`) reproduced with the lightest session; sessionRef stays nil so the edit feed no-ops and the tail reaches `refreshFolds()`. | +| No CHANGELOG entry | Test-only change plus default-nil parameters and a nil-default property; nothing user-facing. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Control initially pinned 205/405 | Counted the split intro line as +1 — "x\n\n" at location 0 turns `intro` into THREE lines | Recomputed from `lines(in:)` semantics: 206/406 — confirmed by the green exact-count runs | +| Underscore `-only-testing` filter exited 0 with no test lines | Backtick/space test names don't match underscore-mangled identifiers — zero tests, vacuous green (#134 class) | Class-level `-only-testing:MuseionTests/ProseFoldRekeyTests` everywhere | +| First post-format build broke | Not formatting — the sibling's untracked test file had landed mid-flight (see Incident) | Suspend-edits, read-only forensics, report-for-ruling; sibling terminated, tree proven clean, gates voided and re-run | +| xcresulttool "doesn't exist" on first full-run query | Shell quoting produced a `/.`-suffixed path against a pruned bundle list | Re-list bundles, query the run's own bundle; counts always from `xcresulttool`, never the build-log tail | + +## Open Items & Next Steps + +- [ ] None on this seam. Two observations for @aegis (NOT folded in, one finding per branch): + 1. `rebuildChromeLayers` re-derives `ProseList.parents(in:)` — a full line scan — on every chevron refresh in a laid-out view, one async main-queue tick after each cheap-path edit; `skipIfParentsAbove` skips only rect queries, not the scan. Headless tests never see it (`chrome.refresh` early-returns at zero bounds). Candidate: consult the freshly re-keyed fold keys before scanning. + 2. The coordinator's `textDidChange` calls `ProsePresenter.fenceDelimCount(storage.string)` on EVERY keystroke — a whole-buffer character pass per keystroke, independent of folds (seen while building the through-seam harness). Same class of typing-cost item as the seam this branch pins. + +--- + +*Log written by hand on the brief-24 branch (daedalus).* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 0c10e23..f57f7aa 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-13 | opt | [20261113-fold-typing-budget-pin_log.md](20261113-fold-typing-budget-pin_log.md) | Unticketed pin (brief-24): typing-cost guard for the #142 re-key — per-call line-scan observer through the real keystroke pipeline; zero scans beside a fold at N/2N, exact-count control 206/406, mutation-checked | | 2026-11-13 | opt | [20261113-cold-turkey-full-tokenization_log.md](20261113-cold-turkey-full-tokenization_log.md) | Unticketed opt (argus digest): minutes feeds skip word counting entirely; DraftStats.words count-only — no token array per keystroke; +3 pins (RED-first rail-trip seam, corpus equivalence), suite 684 | | 2026-11-11 | fix | [20261111-fix-library-search-stale-after-mutation_log.md](20261111-fix-library-search-stale-after-mutation_log.md) | Search snapshots re-key on Home + a rescan-rail content revision (list change OR re-read post.md — body-only edits included); stale rows drop to the recompute spinner (#144/#157 mounted gap) | | 2026-11-10 | follow-up | [20261110-issue179-followup-bind-root-task_log.md](20261110-issue179-followup-bind-root-task_log.md) | Bind hoisted to the WorkspaceView root task (stale watchedHome after repoint); PR #185 closed as superseded by 5bf0955 |