feat(mentor): promote & consult Learnings (#26)
CI / ci (push) Canceled after 0s

Only the writer's explicit confirmation promotes a Fix Card into a
Learning — one confirm, one entry, never a repetition counter. The
Learning is a plain markdown file under <home>/learnings/<type>s/
carrying the card's teaching fields (pattern, problem, diagnostic
question, the demonstration example) plus promotion provenance; the
instance-bound anchor and mechanical replacement stay on the card.
Every pass consults these files via query_learnings; the Learnings
pane replaces its placeholder. Promote consults the on-disk card as
the truth and rejects symlinked learnings paths before any write
(finish-audit round). Dismiss/decay follows in #27.

Closes #26
This commit is contained in:
AlexKucera committed 2026-10-21 12:13:24 +02:00
1 parent 154bb8a114
commit 0e5c28ad95
18 files changed
+1133 -82

No files matched your search

+170 -20
View File
@@ -92,6 +92,11 @@ nonisolated enum FixCardStore {
/// "open" on submit; a Status terminal once the writer closes it.
var status: Status
var anchorStatus: AnchorStatus
/// #26 (S4.1): when the writer promoted this card into a Learning —
/// the EXPLICIT confirm only; nil until then. Optional: pre-#26 card
/// JSON decodes nil (a missing key never errors), and one stamp per
/// card is enforced at promote.
var promotedAt: Date?
}
/// The wire shape of one submitted card (ADR-0006 input fields only —
@@ -238,6 +243,7 @@ nonisolated enum FixCardStore {
quote: input.anchor.quote,
occurrence: input.anchor.occurrence,
),
promotedAt: nil,
)
}
@@ -272,21 +278,28 @@ nonisolated enum FixCardStore {
/// Timestamped card filename prefix, lexicographically sortable
/// (ProfileBackup convention).
private static func stamp(_ date: Date) -> String {
formatted(date, "yyyyMMdd-HHmmss")
}
/// en_US_POSIX date formatting, created per access — no non-Sendable
/// statics (repo convention). stamp() and promote's day stamps share it.
private static func formatted(_ date: Date, _ format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd-HHmmss"
formatter.dateFormat = format
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.string(from: date)
}
/// First free filename for `base` (no extension): base, base-2, base-3…
/// First free filename for `base`: base, base-2, base-3… (#26: `ext` —
/// cards are .json, Learnings .md.)
// ponytail: exists-then-write race needs two concurrent same-second
// same-pattern submits to matter (atomic rename = replace, not corrupt);
// O_EXCL retry if a second writer ever appears.
private static func uniqueFile(_ dir: URL, base: String) -> String {
var name = "\(base).json"
// same-pattern writers to matter (atomic rename = replace, not
// corrupt); O_EXCL retry if a second writer ever appears.
private static func uniqueFile(_ dir: URL, base: String, ext: String = "json") -> String {
var name = "\(base).\(ext)"
var suffix = 2
while FileManager.default.fileExists(atPath: dir.appendingPathComponent(name).path) {
name = "\(base)-\(suffix).json"
name = "\(base)-\(suffix).\(ext)"
suffix += 1
}
return name
@@ -378,22 +391,17 @@ nonisolated enum FixCardStore {
/// The piece's visible learnings: raw markdown per file under
/// `<home>/learnings/<type>s/` (LITERAL plural — "posts", "outlines"),
/// name-sorted. Raw contents, no parsing — promotion stays a later
/// decision (#26). Missing dir → empty (fresh start is the correct
/// v1 answer); a missing piece still throws.
// ponytail: decay filtering is pass-through until issue #26 defines
// the frontmatter fields.
/// name-sorted. Raw contents, no parsing — the pass rail consults
/// exactly these files (query_learnings; #26 promote writes them).
/// Missing dir → empty (fresh start is the correct v1 answer); a
/// missing piece still throws.
// ponytail: decay filtering is pass-through until a decay policy is
// defined on the #26 frontmatter fields.
static func learnings(piecePath: String) throws -> [(file: String, markdown: String)] {
let postURL = try resolvePostURL(piecePath)
let text = try String(contentsOf: postURL, encoding: .utf8)
// ADR-0012 layout: <home>/<projects|archive>/<project>/<id>/post.md —
// the Home is four components up from the file.
var home = postURL
for _ in 0 ..< 4 {
home.deleteLastPathComponent()
}
let type = Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post
let dir = home.appendingPathComponent("learnings/\(type.rawValue)s", isDirectory: true)
let (home, type) = homeAndType(postURL: postURL, text: text)
let dir = learningsDir(home: home, type: type)
let files = ((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? [])
.filter { $0.hasSuffix(".md") }
.sorted()
@@ -404,4 +412,146 @@ nonisolated enum FixCardStore {
return (file: name, markdown: markdown)
}
}
/// #26: the Learnings directory for a content type under a Home —
/// LITERAL plural ("posts", "outlines"). ADR-0005: Museion owns these
/// files, the engine profile never does.
static func learningsDir(home: URL, type: Post.ContentType) -> URL {
home.appendingPathComponent("learnings/\(type.rawValue)s", isDirectory: true)
}
/// post.md URL + its text → (Home, content type) — the ADR-0012 layout
/// walk learnings(piecePath:) and promote(pieceURL:) share: the Home is
/// four components up from the file, the type from the frontmatter
/// (default post).
private static func homeAndType(postURL: URL, text: String) -> (home: URL, type: Post.ContentType) {
var home = postURL
for _ in 0 ..< 4 {
home.deleteLastPathComponent()
}
return (home, Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post)
}
// MARK: - Promote (#26, S4.1/S4.3)
/// #26 (S4.1/S4.3): promote a card into ONE plain markdown Learning
/// under `<home>/learnings/<type>s/` — the writer's EXPLICIT
/// confirmation only: one confirm = one entry, never a repetition
/// counter (an already-promoted card throws before anything is
/// written). The Learning is Museion's file (ADR-0005): plain
/// markdown, hand-editable, git-diffable; `learnings(piecePath:)`
/// serves it to the next pass. Returns the card with `promotedAt`
/// stamped — its JSON rewritten in place (close()'s pattern), every
/// other field untouched. A missing/unreadable piece throws (trust
/// boundary, resolvePostURL).
@discardableResult
static func promote(pieceURL: URL, card: StoredFixCard, now: Date = Date()) throws -> StoredFixCard {
let postURL = try resolvePostURL(pieceURL.path)
let text = try String(contentsOf: postURL, encoding: .utf8)
let (home, type) = homeAndType(postURL: postURL, text: text)
let dir = learningsDir(home: home, type: type)
// Security (audit): a pre-planted symlink under the Home must not
// turn promote into a file-plant primitive — reject before any
// write when an existing learnings component is a symlink (the
// read side skips symlinked dirs, Post.scan posture).
for component in [home.appendingPathComponent("learnings"), dir] {
let values = try? component.resourceValues(forKeys: [.isSymbolicLinkKey])
if values?.isSymbolicLink == true {
throw CardError(message: "learnings path is a symlink: \(component.path)")
}
}
// The on-disk card is the truth, not the caller's copy: a stale
// palette copy (promotedAt nil while disk is stamped) or a
// vanished/undecodable card JSON must refuse BEFORE anything is
// written — one confirm = one entry, no duplicate Learnings.
let cards = cardsDir(for: postURL)
guard let entry = decoded(in: cards).first(where: { $0.card.id == card.id }) else {
throw CardError(message: "card not found: \(card.id)")
}
guard entry.card.promotedAt == nil else {
throw CardError(message: "card already promoted")
}
// ONE file: <yyyyMMdd>-<pattern slug>.md, collision -2/-3 (submit's
// uniqueFile, .md edition) — written from the on-disk card.
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let base = "\(formatted(now, "yyyyMMdd"))-\(PostStore.slug(from: entry.card.pattern))"
try learningMarkdown(card: entry.card, now: now).write(
to: dir.appendingPathComponent(uniqueFile(dir, base: base, ext: "md")),
atomically: true,
encoding: .utf8,
)
// Stamp the card in place (close()'s rewrite): promotedAt on,
// everything else untouched — the on-disk one-stamp guarantee.
// (Learning-first ordering is deliberate — the inverse would lock
// re-promotion forever after a mid-promote crash.)
var stamped = entry.card
stamped.promotedAt = now
try encoder.encode(stamped).write(to: cards.appendingPathComponent(entry.file), options: .atomic)
return stamped
}
/// The Learning file's exact shape (tests pin it): the TEACHING text —
/// pattern, problem, diagnostic question, and the demonstration
/// example when the lane is one — never the instance-bound evidence
/// (the anchor quote and a mechanical fix are apply-machinery from the
/// originating piece; the card JSON keeps them, `from_card` traces
/// back). Single-line frontmatter values (newlines flatten to a
/// space), then a human-readable body with an italic provenance
/// footer that omits missing parts — never a dangling separator.
private static func learningMarkdown(card: StoredFixCard, now: Date) -> String {
func flat(_ value: String) -> String {
value.components(separatedBy: .newlines).joined(separator: " ")
}
var keys = [
"pattern: \(flat(card.pattern))",
"problem: \(flat(card.problem))",
]
if !card.diagnosticQuestion.isEmpty {
keys.append("diagnostic_question: \(flat(card.diagnosticQuestion))")
}
// Demonstration lanes: the fix IS the example rewrite — teaching
// material, it travels. Mechanical lanes: the fix is a literal
// replacement string from one instance — it teaches nothing
// general and would mislead as "the fix".
let example = card.lane == .demonstration ? card.fix : ""
if !example.isEmpty {
keys.append("fix: \(flat(example))")
}
keys.append("lane: \(card.lane.rawValue)")
keys.append("emitter: \(card.emitter.rawValue)")
if let piece = card.provenance?.piece {
keys.append("piece: \(flat(piece))")
}
if let pass = card.provenance?.pass {
keys.append("pass: \(pass)")
}
if let engine = card.provenance?.engine {
keys.append("engine: \(flat(engine))")
}
keys.append("promoted: \(formatted(now, "yyyy-MM-dd"))")
keys.append("from_card: \(card.id.uuidString)")
var body = [
"# \(flat(card.pattern))",
"**Problem.** \(flat(card.problem))",
]
if !card.diagnosticQuestion.isEmpty {
body.append("**Diagnostic.** \(flat(card.diagnosticQuestion))")
}
if !example.isEmpty {
body.append("**Example.** \(flat(example))")
}
var footer = [(card.provenance?.piece).map(flat) ?? "a fix card"]
if let pass = card.provenance?.pass {
footer.append("Pass \(pass)")
}
footer.append(formatted(now, "yyyy-MM-dd"))
body.append("*Promoted from \(footer.joined(separator: " · ")).*")
return "---\n\(keys.joined(separator: "\n"))\n---\n\n\(body.joined(separator: "\n\n"))\n"
}
}