feat(stats): first-draft stats capture (S5.1) (#31)
CI / ci (push) Canceled after 0s

Measure the writer, not the text. Running Pass 1 or Pass 2 on an
unaided draft (origin: writer, First Draft Pass State, post type -
lenient defaults, so bare legacy posts qualify) computes four style
metrics natively in Swift at the invocation - before the engine sees
anything - and stamps stats_captured plus four stats_* values into
the piece's frontmatter in place, so the S5.2 trend view is a plain
scan of Post.frontmatter. Capture re-fires while still First Draft
(latest draft wins); a cancelled pass keeps its capture; ai-origin
and advanced pieces never qualify.

The capture exposed an erasure class: the existingStamp-to-stamped
block rewrite rebuilt frontmatter from three parsed fields, silently
dropping everything else. advancePassState and overwrite now update
their owned keys in place (stampingFrontmatter, widened internal per
its own third-caller trigger; bare posts still normalize through
stamped), so captured stats and foreign YAML survive pass completion
AND mid-pass editor saves. Both fixes are flip-verified by pins.

DraftStats carries the four metrics (burstiness, type-token ratio,
sentence-length variation, trigram repetition) as a pure Foundation
model - full precision out, %.3f at store time. 16 new pins across
DraftStatsTests, PostStoreTests, and PassRunTests; full unit bundle
396/396 (sequential gate; parallel runs flake under external CPU
load per the #30 learning). Finish-audit fanout (ponytail/security/
review) ran on the diff: its MEDIUM (overwrite erasure) and the
converged deletions landed here.

Closes #31
This commit is contained in:
AlexKucera committed 2026-10-22 19:05:42 +02:00
1 parent ae234350ef
commit 42bcfce9ba
13 files changed
+611 -20

No files matched your search

+180
View File
@@ -879,3 +879,183 @@ private func researchDay() -> String {
}
#expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty)
}
// MARK: First-draft stats capture (#31, S5.1)
/// Every `stats_` value is the store-time `%.3f` shape (a period, never a
/// localized comma) — the trend view (S5.2) parses them back as Doubles.
private func threeDecimals(_ value: String) -> Bool {
value.range(of: #"^-?\d+\.\d{3}$"#, options: .regularExpression) != nil
}
@Test func `capture stamps five stats keys in place and preserves foreign frontmatter`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Draft\n\nOne two three. Four five! Six?", home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false)
// Hand-add a foreign key INSIDE the block before capturing — the
// in-place stamp must keep it byte-identical.
let withForeign = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try withForeign.write(to: url, atomically: true, encoding: .utf8)
let bodyBefore = PostStore.splitFrontmatter(withForeign).body
let captured = PostStore.captureFirstDraftStats(
id: post.id, body: "# Draft\n\nOne two three. Four five! Six?", home: home,
)
#expect(captured)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after) // the trend-view readiness read
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["stats_captured"]?.count == 19) // yyyy-MM-dd'T'HH:mm:ss, lexically sortable
#expect(matter["stats_burstiness"].map(threeDecimals) == true)
#expect(matter["stats_type_token_ratio"].map(threeDecimals) == true)
#expect(matter["stats_sentence_variation"].map(threeDecimals) == true)
#expect(matter["stats_trigram_repetition"].map(threeDecimals) == true)
#expect(matter["type"] == "post")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
// Body byte-identical — the stamp never touches content (#31 in-place proof).
#expect(PostStore.splitFrontmatter(after).body == bodyBefore)
}
@Test func `capture refuses an ai origin piece untouched`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Machine\n\nAI-born text.", origin: .ai, home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let before = try String(contentsOf: url, encoding: .utf8)
#expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home))
#expect(try String(contentsOf: url, encoding: .utf8) == before)
}
@Test func `capture refuses a piece past first draft`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Done Once\n\nAlready critiqued.", home: home)
try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let before = try String(contentsOf: url, encoding: .utf8)
#expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home))
#expect(try String(contentsOf: url, encoding: .utf8) == before)
}
@Test func `capture refuses an outline piece`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "- an outline item", type: .outline, home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let before = try String(contentsOf: url, encoding: .utf8)
#expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home))
#expect(try String(contentsOf: url, encoding: .utf8) == before)
}
@Test func `recapture while still first draft overwrites latest draft state wins`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Evolving\n\nOne two three. Four five! Six?", home: home)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "One two three. Four five! Six?", home: home))
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "a b c. a b c.", home: home))
let matter = try Post.frontmatter(of: String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
))
#expect(matter["stats_burstiness"] == "-1.000") // σ = 0 over [3, 3] — the second body won
#expect(matter["stats_type_token_ratio"] == "0.500")
#expect(matter["stats_trigram_repetition"] == "0.250")
}
@Test func `capture qualifies a bare legacy post through the lenient defaults`() throws {
// A bare corpus post (no frontmatter at all) scans writer/First
// Draft/post — the capture gate must reach the same verdict, not
// demand stamps that legacy files never carried.
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/posts/bare-legacy", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "# Bare\n\nNo frontmatter here.".write(
to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8,
)
}
#expect(PostStore.captureFirstDraftStats(id: "bare-legacy", body: "No frontmatter here.", home: home))
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-legacy/post.md"), encoding: .utf8,
)
let matter = Post.frontmatter(of: after)
#expect(matter["stats_captured"] != nil)
#expect(after.contains("# Bare")) // the body survived the fresh-block prepend
}
@Test func `advance pass state preserves stats and foreign keys in place`() throws {
// The #31 regression pin: the advance used to rewrite the block from
// its three parsed fields, erasing the stats captured at the pass's
// own invocation (and any foreign frontmatter). The in-place stamp
// keeps every other line byte-identical.
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Kept\n\nBody stays.", home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let seeded = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try seeded.write(to: url, atomically: true, encoding: .utf8)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "Body stays.", home: home))
let advanced = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
#expect(advanced == .pass1Done)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after)
#expect(matter["pass_state"] == "Pass-1 Done")
#expect(matter["stats_captured"] != nil) // survived the advance
#expect(matter["stats_trigram_repetition"] != nil)
#expect(matter["foreign_key"] == "keep-me") // foreign keys too — the latent #24 loss
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostStore.splitFrontmatter(after).body == "# Kept\n\nBody stays.")
}
@Test func `overwrite preserves stats and foreign keys while swapping the body`() throws {
// The #31 finish-audit regression pin: an editor save mid-pass used to
// route through the stamped() rewrite and erase the stats captured at
// the invocation (plus foreign frontmatter). The in-place update keeps
// every non-owned key and swaps only the body.
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Draft\n\nFirst words.", home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let seeded = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try seeded.write(to: url, atomically: true, encoding: .utf8)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "First words.", home: home))
try PostStore.overwrite(id: post.id, body: "# Draft\n\nEdited mid-pass words.", home: home)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after)
#expect(matter["stats_captured"] != nil) // survived the editor save
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostStore.splitFrontmatter(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed
}
@Test func `overwrite normalizes a bare post with the full stamp`() throws {
// The bare-post branch of the #31 audit fix: no block → the #59 stamp
// shape (type first), exactly as before the fix.
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/posts/bare-overwrite", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "Bare body.".write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
try PostStore.overwrite(id: "bare-overwrite", body: "Bare body, edited.", home: home)
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-overwrite/post.md"), encoding: .utf8,
)
let matter = Post.frontmatter(of: after)
#expect(matter["type"] == "post")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(PostStore.splitFrontmatter(after).body == "Bare body, edited.")
}