feat(cold-turkey): pure goal engine (#161)
CI / ci (push) Canceled after 0s

Wayfinder map #158, Build S1: the pure logic slice the writing
lock consumes — no chrome, no clock of its own.

WritingGoal (words | minutes, one goal per block, fixed at arm)
+ WritingGoalRun: update(text:) takes whole-document text and
netNewWords falls out of the delta (deleting costs — net, not
gross; a big paste counts). now is injected into every call, so
the countdown cannot pause by construction; the minutes deadline
is arm+minutes (inclusive), isMet is live truth, unlatched
(delete below target un-mets — complete on the first true tick),
and progress(now:) is the clamped 0…1 the readout hairline rides.
Word counting goes through the new internal DraftStats.words(in:)
— net-words and first-draft stats share one tokenizer and can
never drift.

Finish-audit fanout: the Int() conversion trap in secondsRemaining
fixed at the seam (isFinite + Double(Int.max).nextDown cap — the
naive cap is itself off-by-one at 2^63; flip-verified pin), two
unpinnable > 0 guards in progress deleted, baselineWords narrowed
to let. Equatable and the ?? armedAt fallback kept deliberately
(S2 consumes the former; removing the latter costs formula
duplication). S2 throttle note landed on #162.

Suite 602/602 (xcresult count), swiftformat + swiftlint clean in
app and test targets. Two traps filed to the swift wiki (bare
@Suite stripped by swiftformat; the Double(Int.max) cap).
This commit is contained in:
AlexKucera committed 2026-11-04 12:50:02 +01:00
1 parent d6c4712aaa
commit e3195d68fd
10 files changed
+389 -5

No files matched your search

+3 -4
View File
@@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (6119 symbols, 26141 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **museion** (6169 symbols, 26678 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -200,6 +200,8 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-11-04 | [20261104-issue161-cold-turkey-goal-engine_log.md](docs/devlog/20261104-issue161-cold-turkey-goal-engine_log.md) |
| 2026-11-04 | [20261104-issue160-cold-turkey-contract-render_log.md](docs/devlog/20261104-issue160-cold-turkey-contract-render_log.md) |
| 2026-11-04 | [20261104-issue156-mentor-pane-chrome-editorial-voice_log.md](docs/devlog/20261104-issue156-mentor-pane-chrome-editorial-voice_log.md) |
| 2026-11-04 | [20261104-issue155-shared-conversation-surface-editorial-voice_log.md](docs/devlog/20261104-issue155-shared-conversation-surface-editorial-voice_log.md) |
| 2026-11-03 | [20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md](docs/devlog/20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md) |
@@ -208,7 +210,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-11-03 | [20261103-issue146-postsmodel-split-under-lint-ceilings_log.md](docs/devlog/20261103-issue146-postsmodel-split-under-lint-ceilings_log.md) |
| 2026-11-03 | [20261103-issue144-library-search-across-titles-and-bodies_log.md](docs/devlog/20261103-issue144-library-search-across-titles-and-bodies_log.md) |
| 2026-11-03 | [20261103-issue143-scan-parse-cache-incremental-rescan_log.md](docs/devlog/20261103-issue143-scan-parse-cache-incremental-rescan_log.md) |
| 2026-11-03 | [20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md](docs/devlog/20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md) |
| 2026-11-02 | [20261102-issue141-image-drop-illustration-ingest_log.md](docs/devlog/20261102-issue141-image-drop-illustration-ingest_log.md) |
| 2026-11-01 | [20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md](docs/devlog/20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md) |
<!-- write-log: window-end -->
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Changed
- **cold-turkey:** Pure goal engine (#161, wayfinder map #158 — Build S1 of the Cold Turkey writing lock) — `WritingGoal` (`words(Int)` | `minutes(Int)`, one goal per block, fixed at arm) + `WritingGoalRun`, the armed block: `update(text:)` takes whole-document text and `netNewWords` falls out of the delta (deleting costs — net, not gross; a 2000-word paste counts), and `now` is injected into every call, so the countdown cannot pause by construction. The minutes deadline is arm+minutes (inclusive boundary), `isMet` is live truth, unlatched (deleting below target un-mets; the lock completes on the first true tick), `progress(now:)` is the clamped 0…1 fraction the readout hairline rides, and word counting goes through the new internal `DraftStats.words(in:)` — net-words and first-draft stats share one tokenizer and can never drift ("writer's" is two words, headings are body text, frontmatter never reaches the editor body). Finish-audit fanout (3 reviewers): the `Int()` conversion trap in `secondsRemaining` fixed at the seam (isFinite guard + `Double(Int.max).nextDown` cap — the naive `Double(Int.max)` cap is itself off-by-one at 2^63 and still traps; flip-verified pin), two unpinnable `> 0` guards in `progress` deleted (degenerate zero targets already fall out to 1 through the Double math), `baselineWords` narrowed to `let`; the S2 throttle note landed on #162 (never feed the word count per keystroke). Suite 602 (issue #161)
- **mentor:** Editorial pane chrome (#156, wayfinder map #153 — the #154 contract's build slice 2; the map closes here) — MentorPaneView's chrome now speaks the same two-color editorial voice the transcript gained in #155. The header drops the icon and "Mentor Session" headline for a serif-15/600 "Mentor", and the ready state becomes the semantic green dot (`DesignTokens.readyGreen` — the palette's single sanctioned exception) + lowercase mono `ready`; the base engine version moves to the tooltip (the rare gate/handshake drift note stays visible in orange). The segmented Pass 1 | Pass 2 | Chat picker is gone — the pass bar always carries and owns a compact text-tab selector (mono-10 uppercase tracked, 2pt accent underline on the active tab) above a `PASS N · STATE` status line, the cost line, and the actions as the contract's `MonoButton` (accent solid Run/Restart, surface+border Blind Read, accent-outline Cancel — danger is terracotta, no second hue). The fix-cards row is the ruled plain mono link (no card, no hairline of its own), and the crash / missing-engine / starting states render as quiet state-cards (terracotta tri, serif head, sans-muted body, mini-spinner mono interim). Finish-audit pass: security clean; the orphaned pass-surface MARK, the stale `hermes <base>` doc comment, and a phantom-border comment are fixed; two advisories parked in the devlog (pass-selector state resets on a phase dip — filed as swift-wiki gotcha #28; solid-button contrast ≈ 3.85:1, inherited from #155, to fix pane-wide if flagged). Suite 592 (issue #156)
- **mentor:** Editorial chat voice on the shared transcript (#155, wayfinder map #153 — the #154 contract's build slice 1) — the Mentor and Sessions panes' shared conversation surface now speaks the two-color editorial voice. The model's speaker prefixes map onto three render voices (`speaker(of:)`, pinned): "Mentor:" turns render as full-width serif 15/1.6 prose (markdown parsed at flush, verbatim while streaming — the Vivarium #97 pattern), "You:" turns as right-aligned terracotta-wash capsules (radius 12/12/2/12, capped at 85% of the live column width), and everything else (refusals, pass kick-off labels, Blind Read reveals) as the quiet mono status box on the fg-wash card. ThinkingBlock port: mono-11 toggle over serif-13 muted on the recessed card, open with a spinner while live, collapsed when flushed; research-note cards inherit the wash family. The composer restyles per contract — surface-fill input, ONE accent Send flipping to a terracotta-outlined Stop (plain Return sends, Shift+Return breaks the line — the composer previously sent the draft on Return with no way to type a newline at all), a floating thinMaterial liveness chip above the composer while streaming, and the Debug toggle seated at its trailing edge (the header checkbox is gone; the header keeps title + engine status + session chip). Finish-audit (3 reviewers) hardened it: interpreted markdown opens http(s) ONLY — an `openURL` gate at the sink (engine prose echoes imported content, so a lying label-over-scheme link can never reach a registered handler; pinned via the pure `linkVerdict` seam), Caps Lock no longer turns Shift+Return into a send (pinned), and the two plain-Button toggles speak their state to VoiceOver. Suite 584, flip-verified pins (issue #155)
+2 -1
View File
@@ -25,7 +25,8 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#144:** the library search — a plain-text field under the Posts header (debounced 250 ms, title+body filter over non-archived pieces; body scan runs off-main through `PostStore.readBody`, so frontmatter is never searched), flat results with title matches first (Finder order preserved in both halves, count line above, same `LibraryPostRow`); state is view-local (`query`/`matches`, nil = sections render), so both render sites (unfocused layout + focus-mode reveal) get the field; clearing returns the project sections. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`).
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#143 (OPT-F3):** `scan(home:cache:)` takes an optional `PostScanCache` (path+mtime+size-keyed parse memo — an unchanged post.md is never re-read, a moved piece re-parses at its new path, project/isArchived re-derive from the walk; nil default = the old read-everything behavior, so every other caller is unchanged). The stamp is taken BEFORE the read and keys the store — a mid-scan rewrite can never be pinned as fresh (a late overlapping store keys its own pre-read stamp; the next scan mismatches and re-reads). **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling).
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update iLine truncated
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`).
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`). **#161:** internal `words(in:)` (`tokens(in:).count`) is the one word-count rail — Cold Turkey net-words counts with it, so text metrics can never drift.
- `WritingGoal.swift` — #161 (Cold Turkey S1, map #158) the pure goal engine the writing lock consumes (nonisolated, no UI, no clock): `WritingGoal` (`words(Int)` | `minutes(Int)`, one goal per block, fixed at arm) + `WritingGoalRun` (the armed block: goal + `armedAt` + baseline/current word counts via `DraftStats.words`). `update(text:)` takes whole-document text — typing/deleting/pasting/undo all land the same way, `netNewWords` falls out of the delta (deleting costs; a big paste counts). `now` is INJECTED (`isMet(now:)`, `secondsRemaining(now:)`, `progress(now:)` 0…1 clamped) — the countdown cannot pause by construction; minutes deadline is arm+minutes, inclusive boundary; `isMet` is live truth, unlatched (delete below target un-mets — the lock completes on the first true tick). S2's `WritingLockState` owns the ticker and calls this.
- `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, adaptive ≥340 2-col grid). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` (accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft).
- `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `<home>/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`.
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
+8
View File
@@ -77,6 +77,14 @@ nonisolated struct DraftStats: Equatable {
)
}
/// Word count over the same token semantics every text metric
/// rides (#161: Cold Turkey net-words counts with this — one
/// tokenizer, no drift). "writer's" is two words here, headings
/// are body text, frontmatter is not (the editor never shows it).
static func words(in text: String) -> Int {
tokens(in: text).count
}
/// Lowercased runs of Characters where isLetter || isNumber — the
/// one tokenizer both the TTR and the sentence lengths ride.
/// ponytail ceiling: no apostrophe joining — "writer's" is two tokens
+102
View File
@@ -0,0 +1,102 @@
//
// WritingGoal.swift
// Museion
//
// #161 (Cold Turkey S1): the pure goal engine the writing lock
// consumes. One goal per block, fixed at arm time — net-new-words
// or a never-pausing countdown. No UI, no clock of its own: the
// lock feeds whole-document text and `now`, this struct answers.
//
import Foundation
/// The one goal a Cold Turkey block was armed with (#161). Fixed at
/// arm time; the arm-bar validates the value, the engine just counts.
nonisolated enum WritingGoal: Equatable {
/// Net new words in the open Piece before the block completes.
case words(Int)
/// Minutes from arm until the block completes. Never pauses.
case minutes(Int)
}
/// One armed Cold Turkey block (#161): the goal plus the arm-time
/// facts. Pure value — `update(text:)` records the live editor text
/// (typing, deleting, pasting, undo all land as whole-document
/// text), and `now` is injected, so the countdown can never be
/// paused or deferred from inside the engine. Word counting rides
/// `DraftStats.words` — the one tokenizer all text metrics share, so
/// net-words can never drift from first-draft stats ("writer's" is
/// two words there, headings are body text; frontmatter is not body
/// text — the editor never shows it, so it never counts).
nonisolated struct WritingGoalRun: Equatable {
let goal: WritingGoal
/// When the block armed. The minutes deadline hangs off this and
/// nothing can move it.
let armedAt: Date
/// Whole-document word count at arm.
let baselineWords: Int
/// Whole-document word count as of the last `update(text:)`.
private(set) var currentWords: Int
init(goal: WritingGoal, armedAt: Date, body: String) {
self.goal = goal
self.armedAt = armedAt
let words = DraftStats.words(in: body)
baselineWords = words
currentWords = words
}
/// Record the live editor text. The caller passes the whole
/// document every time; the net falls out of the delta.
mutating func update(text: String) {
currentWords = DraftStats.words(in: text)
}
/// Net new words since arm. Deleting costs — net, not gross; a
/// 2000-word paste counts (gaming yourself is your business,
/// #158 settled).
var netNewWords: Int {
currentWords - baselineWords
}
/// Whole seconds left on a minutes goal (0 once past). Nil for a
/// words goal, which has no clock.
func secondsRemaining(now: Date) -> Int? {
guard let deadline else { return nil }
let seconds = deadline.timeIntervalSince(now).rounded()
// ponytail: clamp at the Int seam — Int() traps past Int.max (an
// absurd-but-legal .minutes payload would kill the editor mid-
// session); NaN clock (unconstructible from Date()) counts expired
guard seconds.isFinite else { return 0 }
return Int(min(max(seconds, 0), Double(Int.max).nextDown))
}
/// Goal met at `now`? Words: net ≥ target. Minutes: `now` has
/// passed the deadline — inclusive, the boundary tick completes.
/// Live truth, unlatched: deleting below target un-mets a words
/// goal; the lock completes on the first tick this reads true.
func isMet(now: Date) -> Bool {
switch goal {
case let .words(target): netNewWords >= target
case .minutes: now >= deadline ?? armedAt
}
}
/// 0…1 toward the goal for the readout hairline — words by net
/// count, minutes by elapsed time. Clamped at both ends (degenerate
/// zero targets fall out to 1 through the Double math).
func progress(now: Date) -> Double {
switch goal {
case let .words(target):
min(1, Double(max(netNewWords, 0)) / Double(target))
case let .minutes(minutes):
min(1, max(0, now.timeIntervalSince(armedAt)) / (Double(minutes) * 60))
}
}
/// The never-moving minutes deadline; nil for a words goal.
private var deadline: Date? {
guard case let .minutes(minutes) = goal else { return nil }
return armedAt.addingTimeInterval(Double(minutes) * 60)
}
}
+1
View File
@@ -24,6 +24,7 @@ Owned by the root AGENTS.md contract.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern; #147: the shared helpers are internal — PostStorePassTests.swift reuses them): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract).
- `PostStorePassTests.swift` (#147 split — PostStoreTests crossed its file-length ceiling; MicropubTests → MicropubModelTests precedent; shared helpers stay in PostStoreTests.swift) — the pass-adjacent write sides: **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
- `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts.
- `WritingGoalTests.swift` (#161, Cold Turkey S1 — scenario header at file top, `@Suite("WritingGoalTests")`; BARE `@Suite` is stripped by this repo's swiftformat — always give the attribute its string argument) — the goal engine's 11 pins: arm baseline + zero net, exact-target completion (499 ≠ met), delete-below-baseline (net −2, progress clamps 0), 2000-word paste counts in full, undo-to-baseline nets zero, words-goal ignores the clock (`secondsRemaining` nil), minutes deadline boundary (−1 s not met, on-the-second met, remaining 60/0), minutes-goal ignores words + deadline immovable, an absurd `.minutes(.max)` never traps the countdown (the Int-seam clamp pin — flip-verified), tokenizer parity with DraftStats ("writer's" 2 / "writer's note" 3 / headings count / digits count / punctuation-only 0), and the `progress(now:)` fractions for both goal kinds.
- `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)). **#34 (S6.2):** `MicropubMediaTests.swift` (own file — `micropubPNG()`/`micropubMediaScripted` helpers internal, the scripted transport routes config → upload → create by target URL) pins the media surface: illustration parse (plain + inline + quoted-title + empty-alt refs captured honestly; remote http(s) and non-`assets/` refs left alone), rewrite (each UPLOADED ref swaps in place with its uploaded URL — position and alt preserved, quoted titles drop, foreign images and unuploaded refs byte-identical, a URL carrying markdown-active chars rides the ANGLE form `![alt](<url>)` — a plain dest would close early and smuggle a live link), the mime matrix (all six formats + the refusal), the config request + `media-endpoint` decode (trust-gated — an injection-carrying endpoint is requestFailed), the multipart `file` POST asserted over BYTES (part head, payload, closing delimiter, per-request boundary), `uploadMedia`'s create-mirroring decode (Location → body url → trust gate; authFailed on 403), the no-photo-keys-EVER create pin (images travel inline in content — a photo property renders wherever the theme decides, live-verified 2026-11-01), the boundary pin (empty map passes through verbatim, adjacent start/end refs rewrite with clean cursor math), and the multi-line-alt agreement pin (a ref whose alt spans lines doesn't parse at all — a parsed-but-unrewritten ref would ship a broken relative link); the #34 model pins live in `MicropubModelTests.swift` — the three-hop ORDER (q=config, multipart carrying the PNG bytes, create with the ref REWRITTEN to its uploaded URL exactly where placed while the disk body keeps the local ref — no photo property keys), the AC2 floor (WHITESPACE-empty alt — the #6 trimmed-emptiness class — refuses naming the destination with ZERO requests served, nothing stamped), missing-file + SYMLINKED-asset refusals pre-wire (containment resolves symlinks — never read through a planted link), DUPLICATE refs to one asset uploading once and sharing the URL, and a piece without illustrations sending exactly ONE request (#33's wire unchanged).
- `TrendViewTests.swift` (#32, S5.2 — scenario header at file top, `@Suite` so suite filters run it) — the trend view's pure facts: scan reads a REAL capture back (`writeNew` + `captureFirstDraftStats` → `firstDraftStats` values match `DraftStats.compute` at %.3f grain; the parsed date round-trips through the exact stamp format via `FixCardStore.formatted` — locale-independent proof), never-captured pieces scan nil BY CONSTRUCTION (an ai piece whose capture RAN and was refused at the gate + an outline + an untouched writer post — no filtering, the keys just never exist), partial/malformed `stats_*` keys never half-load, `TrendMetric.verdict` pins (improving/steady/slipping at ±0.01, trigram inverted), and the y-domain pins (burstiness −1…1 / TTR + trigram fixed 0…1 / sentenceVariation scales to 1.2× peak with floor 1), the explain pin (every metric carries a distinct, non-empty gloss naming its better-direction — a fifth metric without one fails), the finish-audit pins — `non-finite stats values never load` (`nan`/`inf` in one key, all else valid, via the `writeStamped(id:overriding:home:)` shared fixture whose per-key overrides keep each test's one varying fact visible), `read-back gates on the immutable pair` (imported ai/outline pieces carrying hand-stamped keys scan nil; a Pass-1-Done writer piece keeps its arc — pass_state never gates) — both flip-verified (each pin fails on its own guard) — and the exact-tolerance verdict boundary (delta == 0.01 reads steady, strict comparisons).
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), `submit refuses a symlinked cards dir` (#6 audit — throws with nothing written through the link, promote's posture), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
+139
View File
@@ -0,0 +1,139 @@
//
// WritingGoalTests.swift
// MuseionTests
//
// #161 (Cold Turkey S1): the pure goal engine — net-words delta on
// the DraftStats tokenizer, a never-pausing countdown, and the
// goal-met transitions. Scenario: arm a run over a small body, feed
// it whole-document text and injected `now`s; every expectation is
// hand-derived. No clock, no UI — the run answers, the lock asks.
//
import Foundation
@testable import Museion
import Testing
@Suite("WritingGoalTests")
struct WritingGoalTests {
private static let arm = Date(timeIntervalSince1970: 1_000_000)
private static func run(
_ goal: WritingGoal,
body: String = "One two three four five",
at date: Date = WritingGoalTests.arm,
) -> WritingGoalRun {
WritingGoalRun(goal: goal, armedAt: date, body: body)
}
@Test
func `arm baselines the body and starts at zero net`() {
let block = Self.run(.words(500))
#expect(block.baselineWords == 5)
#expect(block.netNewWords == 0)
#expect(!block.isMet(now: Self.arm))
}
@Test
func `typing completes a words goal exactly at target`() {
var block = Self.run(.words(500))
// baseline words ride inside the live text — the NEW words are the delta
block.update(text: "One two three four five " + String(repeating: "word ", count: 500))
#expect(block.netNewWords == 500)
#expect(block.isMet(now: Self.arm))
block.update(text: "One two three four five " + String(repeating: "word ", count: 499))
#expect(block.netNewWords == 499)
#expect(!block.isMet(now: Self.arm))
}
@Test
func `deleting costs net and can go below the baseline`() {
var block = Self.run(.words(3), body: "One two three four five six seven eight nine ten")
block.update(text: "One two three four five six seven eight nine ten eleven twelve thirteen")
#expect(block.netNewWords == 3)
block.update(text: "One two three four five six seven eight")
#expect(block.netNewWords == -2)
#expect(block.progress(now: Self.arm) == 0)
}
@Test
func `a big paste counts in full`() {
var block = Self.run(.words(2000), body: "")
block.update(text: String(repeating: "word ", count: 2000))
#expect(block.netNewWords == 2000)
#expect(block.isMet(now: Self.arm))
}
@Test
func `undo back to the original body nets zero`() {
let body = "One two three four five"
var block = Self.run(.words(1), body: body)
block.update(text: body + " six seven")
#expect(block.netNewWords == 2)
block.update(text: body)
#expect(block.netNewWords == 0)
#expect(!block.isMet(now: Self.arm))
}
@Test
func `a words goal never consults the clock`() {
let block = Self.run(.words(500))
#expect(!block.isMet(now: Self.arm.addingTimeInterval(10 * 3600)))
#expect(block.secondsRemaining(now: Self.arm) == nil)
}
@Test
func `a minutes goal completes exactly at the deadline`() {
let block = Self.run(.minutes(15))
let deadline = Self.arm.addingTimeInterval(15 * 60)
#expect(!block.isMet(now: deadline.addingTimeInterval(-1)))
#expect(block.isMet(now: deadline))
#expect(block.secondsRemaining(now: deadline.addingTimeInterval(-60)) == 60)
#expect(block.secondsRemaining(now: deadline.addingTimeInterval(30)) == 0)
}
@Test
func `a minutes goal ignores words and never pauses`() {
var block = Self.run(.minutes(30))
block.update(text: String(repeating: "word ", count: 2000))
#expect(!block.isMet(now: Self.arm.addingTimeInterval(29 * 60)))
#expect(block.secondsRemaining(now: Self.arm.addingTimeInterval(60)) == 29 * 60)
}
@Test
func `an absurd minutes goal never traps the countdown`() {
// Int() traps past Int.max — the clamp at the conversion seam is the pin
let block = Self.run(.minutes(.max), body: "")
#expect(block.secondsRemaining(now: Self.arm) == 9_223_372_036_854_774_784)
#expect(block.progress(now: Self.arm) == 0)
#expect(!block.isMet(now: Self.arm))
}
@Test
func `token semantics match DraftStats words`() {
#expect(Self.run(.words(1), body: "writer's").baselineWords == 2)
#expect(Self.run(.words(1), body: "writer's note").baselineWords == 3)
#expect(Self.run(.words(1), body: "## Chapter Two").baselineWords == 2)
#expect(Self.run(.words(1), body: "Draft 2026 shipped").baselineWords == 3)
#expect(Self.run(.words(1), body: "").baselineWords == 0)
#expect(Self.run(.words(1), body: "— — !!!").baselineWords == 0)
}
@Test
func `progress rides net for words and elapsed for minutes`() {
var words = Self.run(.words(100))
#expect(words.progress(now: Self.arm) == 0)
words.update(text: "One two three four five " + String(repeating: "word ", count: 50))
#expect(words.progress(now: Self.arm) == 0.5)
words.update(text: String(repeating: "word ", count: 150))
#expect(words.progress(now: Self.arm) == 1)
let minutes = Self.run(.minutes(10))
#expect(minutes.progress(now: Self.arm) == 0)
#expect(minutes.progress(now: Self.arm.addingTimeInterval(300)) == 0.5)
#expect(minutes.progress(now: Self.arm.addingTimeInterval(600)) == 1)
}
}
@@ -0,0 +1,57 @@
# #160: Cold Turkey arm-bar + progress readout — contract render
> **Date:** 2026-11-04
> **Type:** issue
> **Reference:** [wayfinder map #158](https://git.babylondreams.de/AlexKucera/museion/issues/158) · [ticket #160](https://git.babylondreams.de/AlexKucera/museion/issues/160)
## Goal
Resolve wayfinder ticket #160 (prototype, HITL): render the Cold Turkey surfaces — arm-bar, progress readout, completion note, edge states — as the #154-pattern HTML contract in the editorial two-color chrome, rule the open visual calls with Alexander live, and leave the adjusted file as the contract the build slices (#161, #162) implement.
## What Was Done
- Claimed #160 (assignee = AlexKucera, the map's driving dev) before any work.
- Studied the pattern sources: `ref/prototypes/wf154-mentor-pane-prototype.html` (house contract-render shape), `Museion/DesignTokens.swift`, `Museion/FocusChrome.swift` (hover zones, overlay panels), `Museion/PostEditorView.swift` (focusChip save cue, SaveStateDot, focus ground).
- Built `ref/prototypes/wf160-cold-turkey-prototype.html`: state tabs (focus · arm · locked-words · locked-near · locked-minutes · complete · save-fail edge), live rulings panel, interactive arm-bar (minutes|words selector, steppers, Start, Esc), readout with near-goal + hairline variants, completion note with fade, top-seat save-fail chip.
- Ruled six calls with Alexander in two clarify rounds; baked the rulings as the render's defaults and marked them "ruled" in the panel.
- Verified in ego-browser (Chromium): all seven tabs, selector flip (30 MIN → steppers → 40 MIN), Start → locked, Esc → focus, live ruling flips (hairline, title, presence), dot geometry (20px right / 18px bottom), dot click → arm, presence-aware captions. Screenshots eyeballed via vision for layout glitches — none.
- Recorded the resolution: comment on #160, closed it, appended the map's Decisions-so-far line, amended the map's superseded "menu-first v1" settles (#8, #11) and the arming-shortcut fog item.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Seat = BARE mono text on the focus ground (no chip box) | Alexander overrode the chip recommendation — quietest possible surfaces; Start keeps its accent fill as the only boxed element |
| Progress = text + 2px hairline under the numerals | Alexander chose the hairline over text-only; fill = progress, accent when near |
| Piece title absent from the readout | Numerals only — the open Piece is stable while locked, the title adds noise |
| Near-goal = terracotta numerals at 80% | Recommendation stood, unobjected |
| Completion note fades after ~6s | Quiet return to focus; `● 500 words · 14:02` |
| Presence = persistent dot, bottom-right corner | Alexander's lean, confirmed after the dot was actually rendered (first round couldn't test — see gotcha); muted 6px pip, `COLD TURKEY` label on hover, click arms; menu item stays as second path. Amends charting-settle "menu-first v1" |
| Save-fail keeps the top-center chip seat | The #87 focusChip language is an existing app surface; readout owns bottom-center — no collision |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| "The focus dot does not appear" (Alexander, ruling round 1) | The presence ruling's "always" option only changed caption text — no dot element existed in the mock | Rendered the real dot (`surface 0`), wired visibility to the ruling + focus state, click → arm-bar; then re-asked with the artifact visible |
| Dot landed bottom-center | First render put every surface on the center axis | Ruled: tucked bottom-right (20px/18px in the corner) |
| Focus caption said "chrome absent" while the dot showed | Static caption string | Presence-aware caption built per setState call |
| `page.waitForLoad`/`page.textContent` don't exist in ego-browser | Wrong API guess | `waitForTimeout` + `evaluate(() => …)` equivalents |
## Files Changed
| File | Change Summary |
|------|---------------|
| `ref/prototypes/wf160-cold-turkey-prototype.html` | NEW — the ruled contract render (baked defaults = the contract) |
| `docs/devlog/INDEX.md` + root `AGENTS.md` window | this log registered |
## Open Items & Next Steps
- [ ] **Build S1** (#161, open, unblocked): `WritingGoal` engine — net-words delta + never-pausing countdown, pure logic + tests.
- [ ] **Build S2** (#162, blocked by #160 ✓ + #161 + #159 ✓): integration — WritingLockState, kiosk entry/exit, arm-bar/readout per this contract, typing-continuity hard AC.
- [ ] Calibration gate (#163, blocked by #162): Alexander writes a real block on the pinned corpus.
- Fog stays fog: preset chips (post-calibration), S5.1 stats tie-in, keyboard arming shortcut (needs #87 probe discipline).
---
*Log written by write-log skill*
@@ -0,0 +1,73 @@
# Cold Turkey S1 — the goal engine (wayfinder #161)
> **Date:** 2026-11-04
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/161 (map: #158, work issue: #140)
## Goal
Build the pure logic slice the Cold Turkey writing lock consumes — no chrome, no UI: the `WritingGoal` model (words | minutes, fixed at arm), a net-words counter on the DraftStats tokenizer (baseline at arm, deleting costs, pastes count), and a never-pausing countdown. Tests pin word-delta math, timer boundaries, and goal-met transitions. AC: pure Swift, suite green with executed tests counted from the xcresult (#31/#134).
## What Was Done
- `Museion/WritingGoal.swift` (new) — `WritingGoal` (nonisolated enum: `words(Int)` | `minutes(Int)`) + `WritingGoalRun` (one armed block): baseline/current word counts, `update(text:)` (whole-document text in, net falls out of the delta), `netNewWords`, `secondsRemaining(now:)`, `isMet(now:)` (words: net ≥ target; minutes: `now` ≥ arm+minutes, inclusive boundary), `progress(now:)` (0…1, clamped — the readout hairline's number). `now` is injected everywhere; the struct owns no clock, so the countdown cannot pause by construction.
- `Museion/DraftStats.swift` — added `static func words(in:) -> Int` (`tokens(in:).count`, internal). One tokenizer for stats AND net-words: the two counts can never drift (the ticket's "cite DraftStats" demand, answered structurally).
- `MuseionTests/WritingGoalTests.swift` (new) — `@Suite("WritingGoalTests")`, 11 pins: arm baseline/zero net, exact-target completion (+499 ≠ met), delete-below-baseline (net −2, progress clamps 0), 2000-word paste counts in full, undo-to-baseline nets zero, words-goal ignores the clock, minutes deadline boundary (−1 s not met, on-the-second met, `secondsRemaining` 60/0), minutes-goal ignores words + deadline immovable, tokenizer parity ("writer's" = 2, "writer's note" = 3, headings count, digits count, punctuation-only 0), progress fractions both goal kinds, and the trap pin (`.minutes(.max)` never traps the countdown — flip-verified: removing the clamp crashes the runner).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| `WritingGoalRun` is a value struct with injected `now` | "Never pauses" is guaranteed by construction — there is no pause API and no owned timer. The lock (S2) owns the ticker and polls; the engine stays pure and testable without clock mocks. |
| Reuse `DraftStats.tokens` via a new internal `words(in:)` | The ticket demands consistency with DraftStats counting. Calling the same tokenizer is the only design where consistency cannot rot; a copied counter would drift on the first tokenizer edit. |
| `isMet` is live truth, unlatched | Deleting below target after touching it un-mets a words goal — the honest readout shows the real net; the lock completes on the first tick `isMet` reads true. |
| `progress(now:)` included in S1 | The #160 contract render's readout (numerals + 2px hairline, terracotta near-goal) needs one clamped fraction; it's five pure lines, and S2 would otherwise reopen this file. |
| Engine named `WritingGoalRun`, not `WritingLock*` | Charting decision 7 reserves `writingLock` for S2's app-state machine (`WritingLockState`, armed → locked → complete); the engine is the goal math only. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| SwiftFormat error "Unexpected token }" on the new file | `WritingGoal` declared `struct` with enum `case`s — swiftc said it first ("enum 'case' is not allowed outside of an enum") | `nonisolated enum WritingGoal` |
| Compile errors: "static member 'run' cannot be used on instance" | Bare `run(...)` calls inside instance test methods can't reach a `private static` helper | `Self.run(...)` at every call site |
| Patch tool mangled `= Self.run(` into `block Self.run(` (dropped `=`) | Fuzzy replace of `= run(.minutes` ate the `=` while matching | Full-file rewrite instead of a third patch |
| `@Suite` attribute kept vanishing | This repo's SwiftFormat 0.64.3 (`--swiftversion 6.3 --language-mode 5`) strips a BARE `@Suite` but keeps argumented ones — every surviving suite in the repo carries `@Suite("Name")` or `@Suite(.serialized)` | `@Suite("WritingGoalTests")`; verified it survives a format pass |
| `netNewWords == 500` failed (got 495) | Test-authoring bug: fed baseline body + 495 extra words and expected net 500 — the baseline's 5 words ride inside the live text | Expect the delta honestly: 500/499 extra words; comment pins the semantics |
| `EditorSessionTests/debounce flushes…` failed once in the first full run (saveState `.changed`) | Load flake, the #147 class — a new parallel suite shifts Swift Testing's schedule; the suite is untouched by this diff | Verified in isolation (8/8 green) + green in the definitive full run; no code change. Watch it — if it flakes again under future suite growth, its wait window needs the #147 treatment |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/WritingGoal.swift` | New — `WritingGoal` enum + `WritingGoalRun` pure engine |
| `Museion/DraftStats.swift` | Added internal `words(in:)` (the shared word-count rail) |
| `MuseionTests/WritingGoalTests.swift` | New — 10-pin suite |
## Verification
- Definitive full run (`-only-testing:MuseionTests`, settled tree, `-resultBundlePath`): xcresult **602 executed / 602 passed / 0 failed** (601 pre-audit + the flip-verified trap pin; `wg161d.xcresult` — zero Swift files changed after it). Two earlier red runs were the compile/static-helper errors and the test-authoring bug above.
- swiftformat + swiftlint clean on all three touched files (post-format tree is what the green run tested); repo-wide swiftlint's 59 serious violations all live in pre-existing `spike/` harnesses, none in app or test targets.
- GitNexus `detect_changes`: footprint = `DraftStats`/`tokens` (additive member) — the medium-risk flag is the type's existing fan-out via `captureFirstDraftStats`; no existing call site changed.
## Finish audit (2026-11-04, three-reviewer fanout)
Accepted and applied:
- **Int-conversion trap** (security, LOW — empirically verified by the reviewer): `Int()` in `secondsRemaining` SIGTRAPs on `.minutes(Int.max)` / NaN dates — process death mid-writing-session. Fixed at the conversion seam: `isFinite` guard + clamp to `Double(Int.max).nextDown` (the naive `Double(Int.max)` cap is itself off-by-one — it rounds UP to 2⁶³ and still traps). Pinned; flip-verified (clamp removed → `Crash: Museion` poisons the runner).
- **Dead guards** (ponytail): the two `> 0` guards in `progress` were unpinnable — degenerate zero targets already fall out to 1 through the Double math (probe-verified: `min(1, x/0)` = 1 for x ≥ 0 and NaN). Deleted.
- **`baselineWords` → `let`** (ponytail): never mutated after init; `private(set) var` was dead flexibility.
Deferred (with landing place):
- `Equatable` on both types (ponytail: no comparators) — kept: DraftStats pure-model precedent, consumed by S2 next slice; delete-for-a-session is churn.
- `?? armedAt` in `isMet` (ponytail: unreachable) — kept: removal costs deadline-formula duplication; general reviewer verified it fails open and is the shortest correct form.
- `.words(0)` progress-1/isMet-false inconsistency + 0.4 s `secondsRemaining` rounding edge (general, LOW) — degenerate/arm-bar-forbidden inputs; no action.
- `words(in:)` per-call token materialization (security, INFO) → noted on ticket #162: throttle the lock's count onto the readout tick, never per keystroke.
## Open Items & Next Steps
- [ ] **#162 (Build S2)** now unblocked: wire `WritingGoalRun` into `WritingLockState`, kiosk per the #159 factsheet, arm-bar/readout per the #160 render. Typing-continuity hard AC rides S2.
- [ ] **#163 calibration gate** after S2 lands.
- [ ] Fog stays fog: S5.1 tie-in, preset chips — post-calibration calls, not graduated by this slice.
---
*Log written by write-log skill*
+2
View File
@@ -5,6 +5,8 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-11-04 | issue | [20261104-issue161-cold-turkey-goal-engine_log.md](20261104-issue161-cold-turkey-goal-engine_log.md) | #161: pure goal engine — WritingGoal enum + run struct, DraftStats.words rail, injected now, 10 pins; 601/601 green |
| 2026-11-04 | issue | [20261104-issue160-cold-turkey-contract-render_log.md](20261104-issue160-cold-turkey-contract-render_log.md) | #160: contract render ruled — bare mono surfaces, hairline readout, no title, fade ~6s, arming amended dot-first (corner dot) |
| 2026-11-04 | issue | [20261104-issue156-mentor-pane-chrome-editorial-voice_log.md](20261104-issue156-mentor-pane-chrome-editorial-voice_log.md) | #156: pane chrome — serif header + green ready dot, mode picker dead (selector + status line), MonoButton actions, crash/starting cards editorial |
| 2026-11-04 | issue | [20261104-issue155-shared-conversation-surface-editorial-voice_log.md](20261104-issue155-shared-conversation-surface-editorial-voice_log.md) | #155: shared transcript restyle — three voices (capsule/serif prose/status box), ThinkingBlock port, composer + floating liveness chip, debug toggle moved to composer edge |
| 2026-11-03 | issue | [20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md](20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md) | Gateless launch: workspace is the first frame, async check, rail pill + fail card, auto-fired provisioning/backup. |