Tests/OrgCoreTests/FlashcardOracleTests.swift

c98c5d987c74e64b70f0263e5f8c44b1ae29c815
orgstar/Tests/OrgCoreTests/FlashcardOracleTests.swift

270 lines · 14439 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5/// org-fc itself, run in Emacs, when it's installed: the load-path directory in
  6/// `ORGSTAR_ORG_FC`, else a Doom or package.el install.
  7struct FlashcardOracleTests {
  8    static let loadPath: String? = {
  9        if let path = ProcessInfo.processInfo.environment["ORGSTAR_ORG_FC"] { return path }
 10        let fm = FileManager.default, home = NSHomeDirectory()
 11        let roots = ["\(home)/.config/emacs/.local/straight", "\(home)/.emacs.d/.local/straight"].flatMap { root in
 12            ((try? fm.contentsOfDirectory(atPath: root)) ?? []).filter { $0.hasPrefix("build-") }.sorted().reversed().map { "\(root)/\($0)" }
 13        } + ["\(home)/.emacs.d/elpa", "\(home)/.config/emacs/elpa"]
 14        for root in roots {
 15            let names = (try? fm.contentsOfDirectory(atPath: root)) ?? []
 16            if let name = names.filter({ $0 == "org-fc" || ($0.hasPrefix("org-fc-") && $0.dropFirst(7).first?.isNumber == true) }).sorted().last {
 17                return "\(root)/\(name)"
 18            }
 19        }
 20        return nil
 21    }()
 22
 23    static var enabled: Bool { loadPath != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil }
 24
 25    static let now = 1_795_000_000.25
 26
 27    /// Loads org-fc, with the clock at `now` (or `nows`, one per call to `time-to-seconds`), IDs
 28    /// `id-1`, `id-2`, … and `cl-random` returning `randoms` in turn as fractions of its limit.
 29    static func prelude(history: String = "/dev/null") -> String {
 30        """
 31        (setq load-path (cons \(loadPath!.debugDescription) load-path) make-backup-files nil auto-save-default nil create-lockfiles nil
 32              org-id-track-globally nil org-fc-review-history-file \(history.debugDescription))
 33        (require 'org-fc)
 34        (defvar oracle-now \(now))
 35        (defvar oracle-randoms nil)
 36        (defvar oracle-ids 0)
 37        """
 38    }
 39
 40    static func form(_ body: String) -> String {
 41        """
 42        (cl-letf (((symbol-function 'time-to-seconds) (lambda (&optional _) oracle-now))
 43                  ((symbol-function 'org-id-new) (lambda (&rest _) (format "id-%d" (setq oracle-ids (1+ oracle-ids)))))
 44                  ((symbol-function 'cl-random) (lambda (limit &optional _) (* limit (pop oracle-randoms)))))
 45          \(body))
 46        """
 47    }
 48
 49    /// Runs `command` on `text` with the caret at the start of the heading `title`.
 50    static func run(_ command: any OrgCommand, on title: String, in text: String, now: Double = now, answers: [String: String] = [:]) -> (text: String, failed: String?) {
 51        let found = (text as NSString).range(of: "(?m)^\\*+ " + NSRegularExpression.escapedPattern(for: title), options: .regularExpression).location
 52        let caret = found == NSNotFound ? 0 : found
 53        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], now: Date(timeIntervalSince1970: now), answers: answers)
 54        switch command.run(in: context) {
 55        case .commit(let result):
 56            var new = text
 57            for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) }
 58            return (new, nil)
 59        case .failed(let message): return (text, message)
 60        default: return (text, "other")
 61        }
 62    }
 63
 64    static let cards = """
 65        #+title: Cards
 66        #+filetags: :lang:
 67
 68        * Capital of France
 69        Paris
 70        * Hund :german:
 71        SCHEDULED: <2026-11-20 Fri>
 72        :PROPERTIES:
 73        :CUSTOM: kept
 74        :END:
 75        dog
 76        ** Notes
 77        masculine
 78        * Two sided
 79        Front text
 80        ** Back
 81        Back text
 82        * Animals
 83        The {{cat}{animal}} sat on the {{mat}}, and $x^{2}$ is {{$x^{2}$}{math}@4}.
 84        * Enumerate {{one}}
 85        - {{two}}
 86        - {{three}{hint}}
 87        * Type it
 88        *Answer*
 89        * Typed back
 90        Question
 91        ** Back
 92        =exact=
 93        * Not typed
 94        ** Child
 95        * Context
 96        {{a}} {{b}} {{c}} {{d}}
 97        * Already :fc:
 98        :PROPERTIES:
 99        :ID: kept-id
100        :END:
101        """
102
103    static let steps: [(title: String, command: any OrgCommand, answers: [String: String], form: String)] = [
104        ("Capital of France", MakeFlashcard(.normal), [:], "(org-fc-type-normal-init)"),
105        ("Hund", MakeFlashcard(.double), [:], "(org-fc-type-double-init)"),
106        ("Two sided", MakeFlashcard(.double), [:], "(org-fc-type-double-init)"),
107        ("Animals", MakeFlashcard(.cloze), ["cloze-type": "deletion"], "(org-fc-type-cloze-init 'deletion)"),
108        ("Enumerate", MakeFlashcard(.cloze), ["cloze-type": "enumeration"], "(org-fc-type-cloze-init 'enumeration)"),
109        ("Type it", MakeFlashcard(.textInput), [:], "(org-fc-type-text-input-init)"),
110        ("Typed back", MakeFlashcard(.textInput), [:], "(org-fc-type-text-input-init)"),
111        ("Not typed", MakeFlashcard(.textInput), [:], "(org-fc-type-text-input-init)"),
112        ("Context", MakeFlashcard(.cloze), ["cloze-type": "context"], "(org-fc-type-cloze-init 'context)"),
113        ("Already", MakeFlashcard(.normal), [:], "(org-fc-type-normal-init)"),
114    ]
115
116    /// Each `org-fc-type-*-init` on headings with and without drawers, planning, subheadings,
117    /// a `Back` heading, cloze holes with hints, positions and math, and on a heading that is
118    /// already a card or has no answer line (both refused, nothing changed).
119    @Test(.enabled(if: enabled)) func makingCardsMatchesOrgFc() throws {
120        let calls = Self.steps.map { step in
121            "(goto-char (point-min)) (re-search-forward \(("^\\*+ " + step.title).debugDescription)) (beginning-of-line) (ignore-errors \(step.form))"
122        }.joined(separator: "\n")
123        let theirs = try EmacsOracle.evaluate(Self.cards, Self.form("(progn \(calls) (list (buffer-substring-no-properties (point-min) (point-max))))"), prelude: Self.prelude())
124        let ids = Counter()
125        var ours = Self.cards
126        var refused: [String] = []
127        for step in Self.steps {
128            let result = Self.run(Self.numbered(step.command, ids), on: step.title, in: ours, answers: step.answers)
129            ours = result.text
130            if result.failed != nil { refused.append(step.title) }
131        }
132        #expect(refused == ["Not typed", "Already"])
133        #expect(ours.contains("{{cat}{animal}@0}") && ours.contains("| front    | 2.50 |   0 |     0.00 | 2026-11-18T11:06:40Z |"))
134        #expect(ours == theirs.first, "\(theirs.first ?? "")")
135    }
136
137    final class Counter: @unchecked Sendable {
138        var count = 0
139        func next() -> String {
140            count += 1
141            return "id-\(count)"
142        }
143    }
144
145    /// `command`, giving IDs `id-1`, `id-2`, … as the oracle's `org-id-new` does.
146    static func numbered(_ command: any OrgCommand, _ ids: Counter) -> any OrgCommand {
147        (command as? MakeFlashcard).map { made in MakeFlashcard(made.type) { ids.next() } } ?? command
148    }
149
150    static func initialized() throws -> String {
151        let ids = Counter()
152        var text = Self.cards
153        for step in Self.steps {
154            text = Self.run(Self.numbered(step.command, ids), on: step.title, in: text, answers: step.answers).text
155        }
156        return text
157    }
158
159    static let ratings: [(id: String, position: String, rating: Flashcards.Rating, days: Double, random: Double)] = [
160        ("id-1", "front", .good, 0, 0.5),
161        ("id-1", "front", .good, 0.02, 0.5),
162        ("id-1", "front", .good, 1.1, 0.5),
163        ("id-1", "front", .good, 7.5, 0.13),
164        ("id-1", "front", .hard, 25, 0.97),
165        ("id-1", "front", .easy, 60, 0.0),
166        ("id-1", "front", .again, 140, 0.4),
167        ("id-2", "back", .easy, 0, 0.5),
168        ("id-2", "back", .hard, 1.5, 0.5),
169        ("id-2", "back", .hard, 8, 0.71),
170        ("id-2", "front", .again, 8, 0.5),
171        ("id-4", "1", .easy, 0, 0.5),
172        ("id-4", "4", .good, 0, 0.5),
173        ("id-5", "2", .hard, 0, 0.5),
174    ]
175
176    /// Ratings through every box and branch of SM2 (learning boxes, easy from box 0, fuzzed
177    /// intervals, ease clamped, again back to box 0), written to the drawer and to the review
178    /// history as `org-fc-review-rate` writes them.
179    @Test(.enabled(if: enabled)) func ratingsMatchOrgFc() throws {
180        let start = try Self.initialized()
181        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-fc-\(UUID().uuidString)")
182        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
183        defer { try? FileManager.default.removeItem(at: folder) }
184        let history = folder.appendingPathComponent("reviews.tsv")
185        let calls = Self.ratings.map { r in
186            """
187            (setq oracle-now \(Self.now + r.days * 86400) oracle-randoms (list \(r.random)))
188            (goto-char (point-min)) (re-search-forward "^:ID: +\(r.id)$") (org-back-to-heading)
189            (org-fc-review-update-data
190              (org-fc-position :name "\(r.position)" :card (org-fc-card :id "\(r.id)" :file (org-fc-file :path "/cards.org") :algo (org-fc-algo-sm2)))
191              '\(r.rating.rawValue) 3.25)
192            """
193        }.joined(separator: "\n")
194        let theirs = try EmacsOracle.evaluate(start, Self.form("(progn \(calls) (list (buffer-substring-no-properties (point-min) (point-max))))"), prelude: Self.prelude(history: history.path))
195        let theirHistory = try String(contentsOf: history, encoding: .utf8)
196        var ours = start
197        var ourHistory = ""
198        for r in Self.ratings {
199            let now = Self.now + r.days * 86400
200            let card = Flashcards.cards(in: ours).first { $0.id == r.id }!
201            let position = card.positions.first { $0.name == r.position }!
202            ourHistory += Flashcards.historyLine(at: Date(timeIntervalSince1970: now), path: "/cards.org", id: r.id, position: position, rating: r.rating, seconds: 3.25)
203            let result = Self.run(RateFlashcard(card: r.id, position: r.position, rating: r.rating, random: r.random), on: "Cards", in: ours, now: now)
204            #expect(result.failed == nil)
205            ours = result.text
206        }
207        #expect(ourHistory.split(separator: "\n").count == Self.ratings.count)
208        #expect(ours != start)
209        #expect(ours == theirs.first, "\(theirs.first ?? "")")
210        #expect(ourHistory == theirHistory)
211    }
212
213    /// `org-fc-update` on a cloze card given new holes, `org-fc-suspend-card` and
214    /// `org-fc-unsuspend-card`.
215    @Test(.enabled(if: enabled)) func updatingAndSuspendingMatchOrgFc() throws {
216        var start = try Self.initialized()
217        start = start.replacingOccurrences(of: "sat on the {{mat}@1}", with: "sat on the {{mat}@1} by the {{door}{where}}")
218        let form = """
219            (progn
220              (goto-char (point-min)) (re-search-forward "^\\\\* Animals") (org-fc-update)
221              (goto-char (point-min)) (re-search-forward "^\\\\*\\\\* Notes") (org-fc-suspend-card)
222              (goto-char (point-min)) (re-search-forward "^\\\\* Capital") (org-fc-suspend-card)
223              (goto-char (point-min)) (re-search-forward "^\\\\* Capital") (org-fc-unsuspend-card)
224              (list (buffer-substring-no-properties (point-min) (point-max))))
225            """
226        let theirs = try EmacsOracle.evaluate(start, Self.form(form), prelude: Self.prelude())
227        var ours = Self.run(UpdateFlashcard(), on: "Animals", in: start).text
228        ours = Self.run(SuspendFlashcard(), on: "Notes", in: ours).text
229        ours = Self.run(SuspendFlashcard(), on: "Capital", in: ours).text
230        ours = Self.run(SuspendFlashcard(suspend: false), on: "Capital", in: ours).text
231        #expect(ours.contains("{{door}{where}@2}") && ours.contains(":suspended:fc:german:"))
232        #expect(ours == theirs.first, "\(theirs.first ?? "")")
233    }
234
235    /// The positions a review shows: org-fc's own filters (`org-fc-index-filter-due` and the
236    /// sibling burying) over cards whose positions `org-fc-review-data-parse` reads, against
237    /// `Flashcards.due` over the cards orgstar reads.
238    @Test(.enabled(if: enabled)) func dueCardsMatchOrgFc() throws {
239        var text = try Self.initialized()
240        // Some positions due later, one card suspended.
241        for (id, position, rating) in [("id-1", "front", Flashcards.Rating.easy), ("id-4", "0", .good), ("id-5", "1", .easy), ("id-2", "front", .easy)] {
242            text = Self.run(RateFlashcard(card: id, position: position, rating: rating, random: 0.5), on: "Cards", in: text).text
243        }
244        text = Self.run(SuspendFlashcard(), on: "Context", in: text).text
245        let now = Self.now + 3600
246        let form = """
247            (let (cards)
248              (org-fc-map-cards
249               (lambda ()
250                 ;; As org-fc's indexer, only headings with review data.
251                 (when-let* ((_ (org-fc-review-data-position))
252                        (card (org-fc-card :id (org-id-get) :type (intern (org-entry-get nil "FC_TYPE"))
253                                           :cloze-type (let ((c (org-entry-get nil "FC_CLOZE_TYPE"))) (and c (intern c)))
254                                           :suspended (and (org-fc-suspended-entry-p) t) :algo (org-fc-algo-sm2)))
255                        (data (org-fc-review-data-parse '(position ease box interval due))))
256                   (oset card positions
257                         (mapcar (lambda (row) (org-fc-position :card card :name (car row) :due (parse-iso8601-time-string (plist-get (cdr row) 'due)))) (oref data rows)))
258                   (push card cards))))
259              (setq cards (nreverse cards))
260              (cl-letf (((symbol-function 'current-time) (lambda () (seconds-to-time \(now)))))
261                (dolist (filter org-fc-review-card-filters) (setq cards (funcall filter cards))))
262              (mapcan (lambda (card) (mapcar (lambda (pos) (concat (oref card id) " " (oref pos name))) (oref card positions))) cards))
263            """
264        let theirs = try EmacsOracle.evaluate(text, form, prelude: Self.prelude())
265        let ours = Flashcards.due(Flashcards.cards(in: text).map { (path: "", card: $0) }, at: Date(timeIntervalSince1970: now), shuffle: false)
266            .map { "\($0.card.id) \($0.position)" }
267        #expect(ours.count >= 5 && !ours.contains { $0.hasPrefix("id-1 ") } && !ours.contains { $0.hasPrefix("id-8 ") })
268        #expect(ours == theirs)
269    }
270}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form