- `/security-review` and `/test` ship as new built-in skills. Security-review
is a subagent (read-only, severity-tagged); /test is INLINE (parent must
see proposed edits) and runs npm/pnpm/yarn/pytest/go/cargo, fixes failures,
re-runs, stops after 2 failed attempts on the same line.
- `#g <note>` writes to ~/.reasonix/REASONIX.md (global, never committed),
symmetric to the existing project `#note`. New applyGlobalReasonixMemory
loader pins the file into every session's prefix. `\#g foo` escape lets
users send "#g foo" verbatim to the model.
- `@https://...` URL mentions: fetch via existing webFetch (HTML strip,
truncate to fit), inject under [Referenced URLs]. In-memory per-session
cache so the same URL twice fetches once. Trailing-punctuation strip
preserves query strings while peeling off sentence dots and unmatched
brackets.
- YOLO edit-mode (third stop on the Shift+Tab cycle): apply edits AND
auto-approve every shell command. Wired via a getter on registerShellTools'
allowAll so flipping the mode mid-session takes effect on the next dispatch
with no re-registration. Red modeline pill warns the user it's hot.
- `#note` prompt prefix appends a one-liner to <root>/REASONIX.md (auto-creates
with header). `\#literal` escape passes a real `#text` to the model; `##`
headings always pass through.
- `reasonix -c` / `reasonix chat -c` resume the most-recently-touched session
without the picker. Falls back gracefully + warns when no sessions exist.
Helper extracted to src/cli/resolve.ts so the lookup is testable without fs.
- Built-in `review` skill (subagent runAs) — reviews current branch diff,
reports verdict + per-issue file:line citations, read-only contract.
- `/apply 1` / `/apply 1,3` / `/apply 1-4` (and `/discard` likewise) — pending
preview labels each block `[N]` when 2+ are pending; partial apply leaves
the rest in the queue. Pure parseEditIndices + partitionEdits helpers.
User confirmed wheel-up still doesn't scroll in VSCode integrated
terminal even after 0.7.11 dropped the resize listener and the
\x1b[3J scrollback erase. The startup \x1b[2J was the remaining
suspect: xterm.js (VSCode's terminal) implements 2J in a way that
appears to disrupt scrollback anchoring even when scrollback bytes
themselves are preserved.
Fix: don't write any clear escapes at all. Mount Ink directly. The
user's previous shell prompt stays visible above the launch point
and wheel-up scrolls naturally. Trade-off: the launch isn't a
'clean canvas' anymore. /clear inside the TUI still works for an
explicit reset.
This stacks on 0.7.10's Ctrl+P/N history-recall binding and 0.7.11's
resize-listener removal. Together: wheel scroll works, history
recall doesn't get clobbered by wheel-as-arrow events, and chat
history survives terminal resize.
User reported on VSCode integrated terminal: resizing the window
loses chat history and mouse wheel can no longer scroll up. Two
related symptoms, one cause:
- VSCode's terminal interprets \x1b[3J (xterm scrollback erase)
aggressively — wipes everything, not just the saved-off
history. Combined with my prepended resize listener that wrote
\x1b[2J on every resize, every drag was wiping scrollback. With
nothing in scrollback, wheel-up has nothing to scroll to.
- Even \x1b[2J (visible-only erase) on each resize tick takes
the chat history with it on terminals where the spec is
interpreted loosely.
Fix: drop the resize listener entirely; drop \x1b[3J from the
startup clear. Startup now only erases the visible viewport so the
previous shell prompt scrolls up into scrollback rather than
vanishing. Resize ghosts (Ink's eraseLines miscount on wrap)
return as a known limitation; `/clear` is the documented manual
reset.
History recall stays on Ctrl+P/N (0.7.10) so wheel-as-arrow events
don't clobber the prompt.
Mouse wheel on Windows Terminal + ConPTY translates to up/down
arrow key events for raw-mode child processes. Indistinguishable
from keyboard arrows at the byte level. With history recall bound
to up/down on empty buffer, every wheel-scroll on the prompt was
clobbering it with a recalled prior message.
Fix: rebind history recall to Ctrl+P (prev) / Ctrl+N (next), the
bash readline convention. Up/down arrows now no-op on a single-
line buffer and only move the cursor across lines in a multi-line
draft. Wheel scrolls again belong entirely to the terminal.
Tests updated to reflect the new binding. Placeholder hint mentions
Ctrl+P/N alongside the Ctrl+J newline hint.
Alt-screen fixed the resize ghost stacking but cost the user wheel
scrollback — terminals translate wheel to up/down arrow keystrokes
for alt-screen apps, and those land in PromptInput's history recall
instead of scrolling chat history. Trade-off the user rejected.
Reverted to main-screen mode:
- Restored startup viewport+scrollback clear (\x1b[2J\x1b[3J\x1b[H).
- Restored prepended resize listener that writes \x1b[2J\x1b[H
before Ink's own resize handler runs.
- Added REASONIX_DEBUG_RESIZE env-gated stderr diagnostic so we
can verify the listener fires on the user's specific terminal +
host (Windows Terminal + PowerShell suspected of not
surfacing the 'resize' event consistently).
Resize ghost stacking returns as a known limitation; `/clear` resets
the screen state. This is the trade-off for keeping wheel scrollback
working.
Two unrelated fixes shipping together as 0.7.8:
1. Resize ghost stacking on chat.tsx: previous attempts (stdout 2J
listener, ticker pause, killing animations) all reduced the
symptom but couldn't fix it — Ink's eraseLines fundamentally
miscounts logical vs visible rows on wrap, and resize re-renders
pile up stale frames in scrollback.
Fix: enter the terminal's alternate screen buffer (\x1b[?1049h)
on Ink mount, leave it (\x1b[?1049l) on unmount. This is what
vim, less, htop, lazygit, etc. do. Inside alt-screen the
terminal owns the entire viewport; resize is handled natively
and there's no scrollback to leak ghosts into. Trade-off: chat
scrollback above the live region is gone after exit (returns
to the user's pre-launch shell view). /history still dumps
prior turns on demand.
Removed: the previous \x1b[2J\x1b[3J\x1b[H startup clear and
the prepended resize listener — both made redundant by alt-
screen.
2. Citation validator was reporting / as
'file not found' even when the source is /
. Models routinely cite the wrong extension when
they remember the file. Added a sibling-extensions probe in
validateCitation: when the literal path fails, try common
siblings (.ts↔.tsx, .js↔.jsx↔.mjs↔.cjs, .ts↔.mts↔.cts).
Genuinely missing paths still flag.
0.7.6 tried to mitigate ghost stacking on resize via stdout-clear
listener + ticker pause. User confirmed those still produce 3-4
stacked panels when the window is shrunk and re-expanded.
Root cause: Ink's eraseLines(N) counts LOGICAL lines, not VISUAL
rows after wrap. The 100+ char top/bottom gradient bars on the
StatsPanel always wrap on narrow widths; the per-tick wordmark
animation and per-tick prompt-bar gradient flow re-render every
120 ms; together they layer ghost frames on every resize event.
Real fix:
- Remove the top/bottom GradientRule entirely from StatsPanel.
Those were the dominant wrap source — wide bars on a narrow
terminal were the eraseLines miscount's main payload.
- Wordmark drops its useTick subscription. Sweep is now a
static teal→fuchsia gradient computed once per render. Brand
mark ◈ stays bold but no longer pulse-blinks.
- PromptInput drops its useTick subscription. Left-bar gets a
static row-indexed gradient color, cursor is a solid block
with no blink.
Net effect: no per-tick re-render anywhere in the live region
except the existing spinners (StatusRow, OngoingToolRow,
SubagentRow) — those are short single-row strings that don't
wrap. Ink's eraseLines now matches visible row count because
nothing in the panel wraps. Resize produces at most one
state-change re-render, which the chat.tsx 2J listener catches.
Visual loss: brand wordmark no longer flows colors over time, the
prompt cursor doesn't blink. Visual structure (pills, color, role
bands, full-height left bars on assistant messages) is unchanged.
Bumps to 0.7.7.
User reported StatsPanel rendering 3-4 stacked ghost copies when the
terminal is resized. Two-prong fix:
- chat.tsx — prepended stdout 'resize' listener writes \x1b[2J\x1b[H
on every resize event so Ink's next re-render starts at cursor
home, neutralizing eraseLines's stale storedHeight count.
- App.tsx — new isResizing state debounced from stdout 'resize'
events (400 ms tail). While the resize burst is in flight, the
TickerProvider's disabled flag is set, which kills the 120 ms
tick. With the tick frozen the per-frame animations (wordmark
gradient flow, gradient rule flow, prompt left-bar flow, cursor
blink) stop firing — they were the multiplier turning a single
resize event into a stack of N ghost frames. After 400 ms with
no further resize the ticker resumes and one clean render
catches up.
Together: each resize event is followed by exactly one Ink re-render
on a freshly-cleared viewport, with no animation re-renders piggy-
backing on top.
Bumps package version to 0.7.6.
Before Ink mounts, write \x1b[2J\x1b[3J\x1b[H so the user lands on a
fresh canvas — no leftover shell prompt, last command output, or
unrelated terminal history bleeding into the first frame. Same
sequence the /clear slash command already uses. TTY-gated so CI /
piped runs don't get raw escapes in their captured stdout.
Root cause: at narrow widths the StatsPanel header (wordmark +
version + model + N pills) and the PromptInput's typed line both
wrap to multiple visual rows. Ink's eraseLines counts logical rows,
not visible rows, so each tick (~120 ms re-render driven by the
wordmark / gradient bar / cursor blink animations) miscounts the
erase and leaves ghost rows in scrollback. Several seconds in the
screen looks like it's continuously scrolling — the user-reported
'screen flashing' symptom.
Fix:
- StatsPanel — added `animate = columns >= 100` gate. Below the
threshold the gradient rules + wordmark freeze (no per-tick
color shift), and the secondary pills (harvest / branch×N /
reasoning effort) hide so the header always fits one row. The
primary pills (PLAN / AUTO / REVIEW / ⇧ PRO) and metrics row
stay; only the optional decorations are dropped.
- PromptInput — same gate on the prompt. Below 100 cols the
left-bar gradient freezes and the cursor stops blinking. Above
100 cols nothing changes.
- 100-col threshold matches NARROW_BREAKPOINT closely (120) but is
a hair tighter — the panel can survive 80–100 cols without
wrapping if we drop the secondary content.
The bordered Boxes added recently (assistant left band, user left
band, edit-file diff band) live inside `<Static>`, render once per
event, never re-render, so they don't contribute to the per-tick
miscount.
User reported H3 was showing the literal sigils ('### 📖 代码探索')
inside assistant output, which defeats the heading semantic. Fixed:
- H1 cyan pill, H2 violet pill, H3 fuchsia pill, H4+ bold accent
with a leading ▸ marker.
- Sigils (#, ##, ###) are stripped at the pill — the level chooses
the bg color, not the title text. Three tiers walk down the
brand gradient so the heading tree reads at a glance.
- H4+ kept as bold-only (no bg) so deeply nested sections don't
visually overpower body content.
- EditFileDiff — hunk header is now a violet bg-pill (` @@ -10,3
+10,5 @@ `) instead of a plain cyan-bold one-liner. Body lines
have a colored gutter glyph (− for removed, + for added)
followed by tinted body text, so add/remove rows scan as
distinct lanes rather than colored prose.
- Markdown blockquote — left bar now uses the brand violet
(#c4b5fd) instead of dim gray, so quoted content carries
visual weight that matches the rest of the palette.
- Paste sentinel — was a magenta bold token (`[paste #1 · 12l ·
1.4KB]`); now a solid fuchsia bg-pill so the collapsed paste
block is unambiguous. Matches the mode/tool/badge pill idiom
used everywhere else.
- PromptInput cursor — was a static ▌ block; now toggles ▌↔space
every 4 ticks (~480 ms half-period) via the same ticker that
flows the bar gradient. Inverse-char cursor (mid-line) and
paste-sentinel cursor toggle their `inverse` prop in lockstep
so the character stays legible during the cursor's "off"
half-cycle. Disabled state freezes the cursor solid so the
busy-turn prompt reads as "frozen" not "dead".
- PlanRefineInput — wrapped in the shared ModalCard frame with
mode-specific accent: cyan for approve, amber for refine /
checkpoint-revise, fuchsia for choice-custom. Each accent
matches the related confirm modal so users learn "amber =
plan adjustment", "fuchsia = choice flow" by sight. Inline
cursor blinks too, on the same tick.
- Docstring on PromptInput updated — the old "no blink" comment
is no longer accurate.
- step-progress event row — replaced the green ✓ glyph with a
solid-bg ` ✓ STEP ` pill plus colored counter, body and notes
indented under for visual nesting.
- plan-resumed event row — opens with a ` ↻ RESUMED PLAN ` cyan
pill + bold counter; summary + step list flow underneath.
- plan-replay event row — slate ` ⏪ REPLAY ` pill mirroring the
resumed shape, so live and archived plans use the same idiom.
- error / warning event rows — now use the same pill idiom
(` ✦ ERROR ` rose, ` ▲ WARN ` amber) instead of one colored
glyph + colored body.
- PlanCheckpointConfirm + PlanReviseConfirm modals — wrapped in
the shared ModalCard frame (green ✓ checkpoint, amber ✏
revision). All four confirm-style modals now share the same
top/bottom rule + bg-pill title visual language: choice
(magenta), plan (cyan), shell (red), edit (yellow / green NEW),
checkpoint (green), revision (amber). User learns the modal
type by accent before reading the title.
- PlanStateBlock — labels are now solid-bg pills (` subgoals 3 `,
` hypotheses 2 `, ` uncertainties 1 `, ` rejected 4 `) with
truecolor hex backgrounds matching the role palette (cyan /
green / amber / slate). Items render to the right of the pill.
- BranchBlock — replaced the dim blue one-liner with a stacked
layout: blue ` ⎇ BRANCH ×N ` pill on the header row, then
one row per sample beneath with the chosen sample bolded and
arrow-marked.
- StatsLine (assistant footer) — was a flat dim row; now uses
threshold-colored cache % (green/amber/rose), cyan/violet for
in/out token counts, green for cost, with mid-dot separators.
- Info rows — auto-detect tone from the leading glyph: ▲/⚠ →
warn (amber), ✓ → ok (green), ✗/✖ → err (rose), ↻ → reload
(cyan), default ▸ → info (slate). The glyph is colored-bold,
body stays dim. Existing info messages with embedded prefixes
pick up their semantic without callers changing anything.
- PlanStepList — replaced the colored ✓/▶/—/space glyph column
with solid-bg status pills: ` ✓ DONE ` (green) / ` ▶ RUN `
(cyan) / ` — SKIP ` (slate) / ` ☐ PEND ` (slate dim). Header
row now shows percent done. Focus row gets bold + accent
arrow + bold title. Reads at a glance from across the screen.
- StreamingAssistant — phase header is now a solid-bg pill
(` WAITING ` amber, ` THINKING ` violet, ` DISPATCH ` fuchsia,
` WRITING ` green) instead of a long colored sentence. Pre-
first-byte / reasoning-only / tool-call-only hints get
paddingLeft so they sit visually under the pill. Same info
density, far better visual hierarchy.
- UndoBanner — replaced the magenta-text version with a violet
bg-pill header (` ✓ AUTO-APPLIED N/M `) + a cyan key-pill on
the `u` shortcut. Countdown turns red bold in the last second.
- SubagentRow — violet bg-pill for the ⌬ subagent label,
paddingLeft={3} so it visually nests under the parent
OngoingToolRow when both are visible.
Five surfaces touched, all visible during normal coding:
- Markdown H1 → solid cyan-bg pill (` # title `).
- Markdown H2 → solid violet-bg pill (` ## title `).
- Markdown H3 → bold fuchsia ### with bold body, no bg (avoids
visual overpower at the third nest level).
- Modals — ChoiceConfirm, PlanConfirm, ShellConfirm, EditConfirm
all wrap in a new <ModalCard> primitive: top accent rule, bg-pill
title row with optional icon + dim subtitle, content area, bottom
accent rule. Each modal keeps its own accent color so the user
learns by sight: magenta=choice, cyan=plan, red=shell, yellow=edit.
- Info rows in scrollback get a slate `▸ ` prefix so they read as
structured "system note" lines instead of dim continuation text.
ModalCard is plain Text for the rules + a bg-pill title — no Ink
borderStyle, so it stays compatible with the live region's eraseLines
constraint. EditConfirm's diff slicing budget is unchanged
(MODAL_OVERHEAD_ROWS still accounts for ~3 rows of frame).
Five more visual upgrades across the most-touched surfaces:
- PromptInput left bar — each row's ▎ picks a color from the
brand gradient with a tick offset, so the bar visually flows
vertically in sync with the StatsPanel's wordmark + rules.
When the prompt is disabled (busy turn), the gradient is
suppressed and the bar reverts to dim gray so the screen
calms down for the active spinner above it.
- User message — wrapped in a cyan left-only border Box matching
the assistant treatment, so both sides of the conversation
have the Discord-style avatar bar. Continuation lines align
under the band.
- ReasoningBlock — was a flat dim italic line, now opens with a
solid violet pill (` ⋯ thinking `) and the body in violet
italic. Reads as its own surface instead of blending into the
rest of the message.
- SlashSuggestions selected row — solid cyan-bg highlight (the
whole row, like an editor's autocomplete focus row) instead
of just colored text.
- AtMentionSuggestions selected row — same solid cyan-bg
treatment, basename + dir on one line for a tighter VS Code
Quick Open feel.
Tick is ~120 ms. Wordmark shifts the gradient one step every 4 ticks
idle / 2 ticks busy, so the teal→cyan→blue→purple→fuchsia sweep
visibly travels across REASONIX like a neon sign. Top/bottom
GradientRule bars share the flow logic (slower — every 6 ticks) so
the whole panel feels alive without being twitchy. Brand mark ◈ keeps
its existing bold-pulse so 'app is thinking' stays distinct from
'colors are flowing.'
Big visual upgrades on the surfaces with the most pixels:
- Assistant message — Box with left-only border in role color
(COLOR.assistant green) running the FULL height of the message,
Discord-style avatar bar. Reasoning, branch, plan-state, body
Markdown, stats footer, repair note all sit inside the band.
- Tool result for edit_file — same left-band treatment in
COLOR.tool yellow so the diff reads as a continuation of the
pill above.
- Markdown code blocks — round-bordered card in cyan, with the
language label as a solid-bg pill in the top-left and amber
body text. Fenced code now feels like a code block, not a
bare yellow-on-default text dump.
- OngoingToolRow — solid amber pill on the tool name, gradient
progress line, paddingX so the row sits in its own column zone.
- StatusRow — violet accent + paddingX + middle-dot separator
instead of a grey one-liner.
- ModeStatusBar — wrapped in a top dotted rule so the modeline
reads as its own zone, separate from the prompt above. Helix /
vim modeline feel.
Border usage notes: the assistant + tool left-only borders live
inside `<Static>` (scrollback) so Ink's eraseLines miscount that
banned bordered Boxes from the LIVE region doesn't apply. The live
region (StatsPanel, OngoingToolRow, ModeStatusBar, PromptInput)
still uses Text-only rules and pills, so the Windows ghost-row
class of regression stays out.
Centralised palette/glyphs in theme.ts so the TUI reads as one
designed surface instead of fifteen components inventing their own
color choices. Reuses the brand teal→cyan→blue→purple→fuchsia
gradient that the wordmark already establishes.
- StatsPanel: top + bottom gradient rules frame the header band;
progress bar redesigned with ▰/▱ glyphs and threshold colors
(green/amber/rose) using truecolor hex; metric cells now lead
with a dim icon (▣ ctx, ⌬ cache, ◴ cost, ◐ balance) and the
inline layout always shows the bar.
- TurnSeparator: gradient rule on both sides of the brand mark
instead of a flat dim minus row, so turn boundaries read as
designed accents.
- WelcomeBanner: gradient top/bottom rules + brand-color left bar
+ accent-color hint tokens. Card now feels like a card.
- theme.ts: GRADIENT array, semantic COLOR map, GLYPH set,
`gradientCells(width, glyph)` helper that other components
consume to render colored rules without duplicating the
interpolation logic.
Three high-frequency surfaces redesigned with solid-bg pills + card
framing so the TUI reads as a designed product instead of a wall of
glyphs:
- WelcomeBanner — left-bar card frame; sectioned 'welcome / quick
start / tip' rows; first thing on screen now has visual weight
instead of looking like a one-liner list.
- ModeStatusBar — solid-bg pills (AUTO / REVIEW / PLAN MODE) like
a vim/helix modeline so the bottom bar reads at a glance.
- Tool result rows — bg pill on the tool name (yellow ✓ / red ✗)
so a session full of dispatches has visible status hierarchy.
- Assistant header — model name now a solid-green pill next to the
◆ glyph, matching the visual language of the other pills.
No new abstractions, no border boxes (still avoiding Ink's Windows
eraseLines miscount). Just pills + bars + paddingX consistently
applied to the surfaces the user sees most.
historical always has at least one info row at startup (session state
banner, edit-mode hint, restored plan, etc.), so historical.length
=== 0 never holds and the welcome card never showed. Switch the gate
to 'no user/assistant message yet' so the card greets the empty
conversation as intended.
The 49d4648 stdin-reader refactor moved the KeystrokeProvider INSIDE
App's render but kept App-body `useKeystroke` calls — `useContext`
runs at hook-call time, so the provider wasn't mounted yet and the
returned bus was always null. Every global hotkey (Ctrl+C exit, Esc
abort, Shift+Tab edit-mode cycle, @-mention picker nav, slash
suggestion nav) silently never subscribed; PromptInput worked because
it lives in the provider subtree.
Fixes:
- chat.tsx wraps <App> in <KeystrokeProvider> from outside; remove
the inner one in App.tsx.
- stdin-reader splits \r vs \n: \r → Enter (return:true),
\n → Ctrl+J ({ctrl:true, input:"j"}). Was conflating both as
Enter, so Ctrl+J fired submit instead of newline.
- stdin-reader recognises modifyOtherKeys + kitty Enter sequences
(27;2;13~ / 13;2u and shift/ctrl variants) so terminals that
enable those protocols can distinguish Shift+Enter / Ctrl+Enter.
On Windows + ConPTY the bytes get stripped before reaching us, so
Shift+Enter still falls back to Enter there — Ctrl+J remains the
universal newline.
- App.tsx writes \x1b[>4;2m at startup (paired disable on unmount)
to opt into modifyOtherKeys for terminals that honor it.
- code.tsx drops the SIGINT/SIGTERM `once` handler that ran
jobs.shutdown without exiting (it overrode Node's default
"exit on Ctrl+C" with a silent no-op). Job cleanup moves to the
`exit` event so any termination path drains the registry.
- App.tsx: SIGINT and \x03 byte both call process.exit(0). Using
Ink's exit() left the singleton stdin-reader's data listener
attached and the event loop alive, so the terminal would hang.
Hint text updated to lead with [Ctrl+J] since Shift+Enter is
unreliable on the most common Windows host. Two diagnostic probe
scripts added under scripts/ for future input regressions.
Visual structure tightened along the way: a left-bar (▎) anchor
running down PromptInput, a thin rule under the StatsPanel, the
existing TurnSeparator now actually rendered between user turns,
StatsPanel pills/wordmark restored from the in-flight working tree.
When the user opens reasonix and nothing has happened yet, the screen
showed StatsPanel + the bare prompt — no signpost for what to type.
Add a small Welcome card with three or four hand-picked hints
(/help, /skill, @path / !cmd in code mode, /exit). Disappears the
moment the first event lands so it never gets in the way during a
real session.
Tight on purpose. Full reference is /help; this is just the friction-
removing first impression.
The 0.7.x bug parade (paste markers leaking, arrows not crossing
newlines, Shift+Tab broken, CJK ghost rows) traced back to two upstream
limitations we couldn't patch around forever:
1. Ink's `parse-keypress` uses a 100 ms intra-CSI timeout that is too
short for Windows ConPTY. Sequences like `\x1b[A` arrive split
across reads with > 100 ms gaps, so the lone `\x1b` fires as
`key.escape:true` and `[A` lands in `input` as plain text.
2. Ink/Yoga measures cell width with `string-width`, but on CJK
terminals some glyphs render at a different cell count than that
library reports. The terminal wraps to a 2nd visual row that
Ink's `eraseLines` doesn't account for, so each render leaks a
row into permanent scrollback.
Patching consumers one at a time was a Whac-A-Mole. This change
replaces the entire input layer:
- **`stdin-reader.ts`** — owns `process.stdin`, parses bytes with
our own state machine. ESC ambiguity timer is 250 ms (vs. Ink's
100). ESC-stripped CSI tails (`[A`, `[5~`, `[Z`, `[200~`) are
recognised at idle-state lookahead. SS3 (`\x1bOA`) supported. Drops
unknown CSI silently rather than inserting bytes as text.
- **`keystroke-context.tsx`** — React Context that owns the singleton
StdinReader and fans events out to subscribers via `useKeystroke`.
Replaces every `useInput` import in our tree.
- **`prompt-viewport.ts`** — pure helpers that slice each logical
prompt line into exactly one visual row. The cursor's window
slides so it stays visible; `‹` / `›` markers indicate clipped
content. CJK cell widths handled explicitly so our math matches
the terminal grid (no more `string-width` disagreement with the
real renderer).
- **PromptInput v2** — rewritten on top of these. No `useTick` (no
cursor blink — the 8 Hz repaint was amplifying the eraseLines
leak). One Box row per logical line, fixed visual height, viewport
clipping for content longer than the terminal width.
- **App / Select / EditConfirm / PlanRefineInput** migrated to
`useKeystroke`. Wizard / DiffApp / ReplayApp keep Ink's `useInput`
— separate render calls, no provider in their tree, no conflict.
SessionPicker (which uses our migrated SingleSelect) gets its own
KeystrokeProvider wrapper in chat.tsx.
- As long as no `useInput` is called inside the Ink tree, Ink itself
never attaches a stdin listener, so our reader is the sole consumer
of stdin. No race with parse-keypress.
41 new tests covering every CSI tail, paste accumulator across chunks,
ConPTY ESC-stripping, viewport clipping for CJK / paste sentinels.
1283 → 1324 tests, lint + typecheck clean.
Audit context. We've shipped three patches in two days for the same
class of bug:
1. paste markers `[201~` leaking into the prompt buffer
2. arrow keys not advancing the cursor across newlines on Windows
3. (foreseeable) Shift+Tab / PgUp / PgDn / Delete next, since they
all share the root cause.
Root cause is upstream: Ink's parse-keypress uses a 100ms timeout
to assemble CSI sequences from stdin. On Windows PowerShell + ConPTY
the bytes of `\x1b [ A` arrive split across reads with > 100ms
gaps. The standalone `\x1b` fires as `key.escape:true`, the trailing
`[A` fires as a regular character event with `input:"[A", upArrow:
undefined`. Every useInput consumer that reads structured key flags
silently misses the keystroke and the bare bytes get inserted into
the buffer as text.
Each individual patch was correct but localised — multiline-keys had
its own arrow recovery, PromptInput had its own paste-marker recovery,
App.tsx / Select / EditConfirm didn't recover anything at all and
would have been the next bugs found.
Fix is a single boundary. `src/cli/ui/key-normalize.ts` exposes:
- `recoverCsiTail(input, existingFlags?)` — the canonical mapping
from bare-or-prefixed CSI tails to structured Ink key flags.
Covers `[A`/`[B`/`[C`/`[D` (arrows), `[5~`/`[6~` (PgUp/PgDn),
`[3~` (Delete), `[Z` (Shift+Tab). Bracketed-paste markers
intentionally excluded — they have collect-between-markers
semantics and live in PromptInput's accumulator.
- `stripCsiFragments(input)` — defensive scrub for the edge case
where a fragment slips past structured-key recovery (e.g. arrived
embedded inside a paste burst). Replaces the inline replaceAll
chains we'd grown in multiline-keys.
Wired into every useInput call site that reads structured key flags:
multiline-keys (PromptInput's reducer), App's global hotkey handler
(Esc / Shift+Tab), Select's SingleSelect + MultiSelect (modal
navigation), EditConfirm's scroll/decision handler. DiffApp /
ReplayApp left for follow-up — separate subcommands, lower blast
radius.
+14 tests covering every supported tail, the pass-through path, the
already-structured-event short-circuit, and the literal `[A](url)`
non-rewrite. 1267 → 1283 tests.
User reported pressing right-arrow at end of line 1 would not advance
the cursor to line 2. Same root cause as the recent [201~ paste-marker
fix: Windows PowerShell + ConPTY consumes the leading \x1b of the
arrow's CSI sequence and routes the remaining '[C' through useInput
as plain text. Our rewriteRawArrowEscape only matched the full
'\x1b[C' form, so the keystroke landed on the printable-char branch
and inserted literal '[C' into the buffer instead of moving the
cursor.
Add fallbacks for the bare '[A'/'[B'/'[C'/'[D' input strings. +1 test
covering the cross-newline rightArrow case directly.
Windows PowerShell + ConPTY + Ink's parse-keypress consumes the
leading \x1b of \x1b[200~ / \x1b[201~ and routes the rest into
useInput as plain text. Our markers were the full sequence, so
indexOf missed them and the literal '[201~' ended up inserted into
the user's prompt buffer.
PromptInput now searches for both the full marker and the bare
'[200~'/'[201~' fallback. multiline-keys.ts strips both forms
defensively too. +1 test.
User reported repeating ghost top-borders accumulating in scrollback
on Windows + CJK input — every render leaked one row, so 17+ ghost
`╭──...─╮` lines stacked at the top within seconds. Root cause: Ink's
eraseLines counts logical rows, not post-wrap visual rows. Bordered
Boxes were both the most common wrap source AND the most visually
obvious thing to duplicate.
Fix: remove `borderStyle="round"` from every component in the live
region — StatsPanel, PromptInput, all *Confirm modals, UndoBanner,
EventLog plan/plan-resumed/plan-replay rows. Visual hierarchy now
comes from bold colored headers + indentation + marginY breathing.
Also pillify the active mode tag in ModeStatusBar — `▸ AUTO` becomes a
solid colored background block ` AUTO ` so the current mode reads at
a glance and the focus animation (briefly inserting a ◆) is more
distinct than `inverse` toggling.
No content lost; same affordances, less paint surface for Ink to get
wrong on fragile terminals.
User reported ghost top borders stacking up in scrollback after typing
two lines of CJK content, plus apparent cursor-stuck-on-line-1. Same
class of Ink eraseLines miscount that StatsPanel solved with explicit
width={cols} — long Chinese input (2 cells per char) overflows the
auto-flexed Box, every ticker tick leaves a ~1 row residual, and after
~3s the user sees 20+ ghost border tops.
Two changes:
- Pin the bordered Box to `width={cols}` so Ink's measurement matches
reality (same fix StatsPanel applies).
- Fold the disabled-state [Esc] hint back inside the bordered Box. The
`<>`-wrapped sibling Box from 0.7.2 was a structural variable with no
layout benefit. Continuation-indented row inside the box matches the
visual hierarchy without changing the live-region shape.
The cursor-stuck symptom was rendering corruption — once the live
region stops accumulating ghost rows, useInput delivery + setCursor
land where they should.
Same fix as EventLog ate earlier. RecordView is the read-only viewer
shared by reasonix replay and reasonix diff — multi-line transcripts
were wrapping under col 0 instead of under the body text. Continuation
indent of 6 spaces matches the 'you › ' prefix width.
LiveRows.tsx already used `name === s || name.endsWith("_" + s)` so MCP
tools like `filesystem_read_file` picked up the same per-tool argument
summary as the bare local `read_file`. tool-summary.ts used exact-name
match only, so bridged tools fell through to the generic "first line +
size hint" path in the compact scrollback row. Switch to the same
suffix predicate; add a write_file branch while there. +3 tests
covering the bridged path + a non-underscore-prefix non-match.
Bracket-style `[↑↓] navigate · [Enter] X · [Esc] Y` matches the Confirm
modals; Wizard and SessionPicker were the last surfaces using the older
free-form `↑/↓ move · enter X · esc Y` style. Doc-comment examples in
Select.tsx updated to match.
Three runtime fixes that all surfaced from a single user trace
(model looped on a broken read_file, the chat ended without
explanation, embedded GBK encoding errors, plus a separate
"PDF report on global economy" turn that wrote a 2024 report
from training memory instead of searching).
Storm-break no longer dead-ends the turn
- When the storm-breaker suppressed every tool call in a turn,
the loop yielded `done` with empty assistant content. The user
saw a one-line warning then silence and didn't know what to do.
Now routes through `forceSummaryAfterIterLimit` with a new
`"stuck"` reason: the model gets one no-tools call to explain
what it tried, what blocked, and what would unblock — turning
the silent stop into actionable feedback the user can act on.
PYTHONUTF8 / PYTHONIOENCODING for spawned shells
- run_command's spawn env now sets PYTHONIOENCODING=utf-8 and
PYTHONUTF8=1. On Chinese Windows, Python's default stdout
encoder is GBK; emoji / non-GBK output raises UnicodeEncodeError
and the model sees a Python traceback instead of the script's
real result, then loops trying to fix the wrong problem.
These env vars force UTF-8 unconditionally. Harmless on
non-Python processes (env vars they don't read).
Recency rule in default chat system prompt
- New short section in DEFAULT_SYSTEM telling the model that
when an answer's correctness depends on something that
changes over time (the user is asking what's *happening*,
not what's *true*) and a search tool is available, search
before composing. Phrased as a principle ("if I'm wrong
about this, is it because reality moved on?") rather than
a topic list, so it doesn't go stale or over-prescribe.
- web_search description rewritten in matching language —
emphasis on "current state" rather than enumerating
topics like markets / news / releases, which tied the
description to a particular moment in time.
Tests: loop +1 (storm→summary regression). 1264 tests total,
lint + tsc + build clean.
Several long-standing input-box and TUI annoyances fixed in one batch.
Paste handling
- Big pastes (3000-line error logs, etc.) used to be inlined into
the buffer verbatim — surrounding typed text drowned, every
keystroke re-rendered hundreds of rows. Replace with a sentinel
scheme: each paste blob becomes ONE PUA codepoint in the buffer
(`\uE100..\uE1FF`), full content lives in a side registry,
rendered as `[paste #N · 33l · 1.0KB]` magenta block. Buffer
stays small, cursor steps over the placeholder as one unit, a
single Backspace removes the whole paste. On submit the
sentinels expand back to full content for the model.
- Bracketed-paste mode (DECSET 2004) enabled at app start so
cooperating terminals deliver one marker pair per paste action.
- For terminals where the markers don't reach Ink (PowerShell +
ConPTY parses them out), a sub-30ms time-window + position-guard
fallback collapses chunks of one paste into a single sentinel.
30ms is well below human reaction for double-pasting (~100ms+),
so two deliberate pastes never falsely merge.
- Critical fix: PowerShell+Ink fires useInput TWICE per stdin
chunk, both with stale React closure over `value` / `cursor`.
The merge guard read stale state and never matched the previous
sentinel — one Ctrl+V kept producing four `[paste #N]`
placeholders. registerPaste now reads from refs we update
synchronously inside the function, so the second fire sees the
first's insert.
- Pasted CR/CRLF normalize to LF; bracketed-paste markers are
stripped if they leak through.
Multi-line cursor
- ↑/↓ at the buffer boundary (line 0 / last line) used to be
silent NOOP — felt stuck. Now hands off to the parent's history
recall, so users can escape into history from a multi-line
draft without first emptying it.
- Raw-escape fallback: terminals that don't set `key.upArrow`
and instead leak `\x1b[A` into `input` (older Windows configs)
now get the escape rewritten into the structured key event,
preventing the literal escape bytes from being inserted.
Buffer-wide shortcuts
- PageUp / PageDown jump to top / bottom of the WHOLE buffer
(was NOOP).
- Ctrl+U clears the entire buffer (readline-style; necessary
given the renderer can collapse the buffer to a few visible
rows after a paste — backspacing N times wasn't ergonomic).
- Ctrl+W deletes the word before the cursor (eats trailing
whitespace first, spans newlines).
- Hint row appears under the input when buffer has > 20 lines:
`[N lines · PageUp/PageDown jump to top/bottom · Ctrl+U clear ·
Ctrl+W del word]` so users discover the shortcuts in the
exact moment they need them.
Visual stability
- StatsPanel pinned to `width={columns}` so each render's frame
is exactly terminal-width — reduces (doesn't eliminate) the
resize ghost-frame stacking from Ink's eraseLines miscount on
re-wrapped lines.
- /help gains a "Known limitation" section about the resize
artifact so users aren't blindsided.
`/clear` actually clears
- Used to only `setHistorical([])` (React state). Terminal
scrollback was untouched — user kept seeing prior turns until
they scrolled past them. Now writes CSI 2J + 3J + H so the
viewport AND scrollback buffer are nuked. Ink's next render
paints the TUI on the fresh screen.
Tests: paste-sentinels (new file, 18 tests), multiline-keys +57.
Total 1264 tests, lint + tsc + build clean.
Substantial expansion of the chat-output Markdown renderer.
Block-level
- Blockquote `>` with proper recursion: nested quotes (`> >`) render as
adjacent left bars, lists / code fences / tables INSIDE a quote
parse via the same `parseBlocks` recursively (instead of being
flattened to text), GFM-style.
- Task lists (`- [ ]` / `- [x]`) — item text gains `task: "todo" |
"done"`, rendered as `☐` / `☒` with strikethrough on done items.
- Diagram code blocks (mermaid / dot / graphviz / plantuml / puml /
flowchart / sequencediagram / gantt / erdiagram) render with a
distinct magenta double-line frame + `◇ <lang> diagram (source)`
header + viewer-URL hint. Terminal can't draw the graph, but the
user knows it's source-of-a-diagram and where to paste it.
- Hard line break: trailing ` ` (two-or-more spaces) on a line now
inserts a real `\n` in the rendered paragraph instead of being
silently collapsed into a space.
Inline
- `***bold-italic***` (added as the first INLINE_RE alternative
before the bold and italic checks).
- `~~strikethrough~~` (with proper guards so subscript / strike
don't fight).
- Pandoc-style `^x^` superscript and `~x~` subscript — only
fire when every char is in the Unicode SUPERSCRIPT/SUBSCRIPT
table; otherwise leave the markers literal so we don't drop the
user's intent.
- Math: `$inline$` and `$$block$$` delimiters are stripped
(delimiters only — content still flows through the existing
LaTeX → Unicode pipeline).
- Emoji shortcodes: ~70-entry curated table covering the common
faces / hearts / gestures / signals (`:smile:`, `:fire:`, `:+1:`,
`:white_check_mark:`, etc.). Unknown names pass through literal.
- Autolinks: `<http://…>`, `<https://…>`, `<mailto:…>`, `<ftp://…>`
rewrite to `[url](url)` so the existing link path renders them.
- Backslash escapes: `\*` / `\` ` ` / `\~` / `\[` / `\]` / `\` etc.
emit literal characters via a final INLINE_RE branch — the
surrounding markup parsers don't get to consume the escaped
punctuation. `stripInlineMarkup` rebuilt around a single-pass
INLINE_RE walk so escape precedence matches the runtime.
Citation guard
- `collectCitations` now skips URLs that obviously aren't repo
paths: anchor-only (`#foo`), bare `/`, and short placeholder
words with no `/` `\` or `.` in them. Eliminates the false
"broken citation" red-strikethrough on demo / non-citation
links.
Bug fixes uncovered along the way
- `\sum_{i=1}^n` and friends were being eaten by the catch-all
LaTeX command stripper because `\b` doesn't match between `m`
and `_` (both are word chars). Switched the relevant rules to
`(?![a-zA-Z])` so the specific Σ / Π / ∫ / etc. substitutions
fire even when followed by a subscript.
Tests: markdown 60 → 173 (+113).
deepseek-chat and deepseek-reasoner are now just compat aliases for
v4-flash's non-thinking and thinking modes (same underlying model,
same bill per telemetry.ts). Presets already all point at
deepseek-v4-flash / deepseek-v4-pro. Retire the old names everywhere
they were still surfacing as the default or discoverable surface:
- harvest.ts default model: deepseek-chat → deepseek-v4-flash
(behaviorally identical — both route to v4-flash non-thinking)
- subagent tool enum: drop deepseek-chat/-reasoner; users pick
flash vs pro now, no legacy names to distract the model
- subagent JSDoc: default was documented as pro but the actual
constant is flash; fix the docs
- /model empty-arg hint: suggest v4 names instead of legacy aliases
- /think empty-reasoning hint: explain "thinking-mode models"
generically instead of pinning to deepseek-reasoner
Kept legacy names in telemetry.ts (DEEPSEEK_PRICING,
DEEPSEEK_CONTEXT_TOKENS) because historical usage.jsonl rows still
reference them — the table is for pricing old sessions, not routing
new requests. Runtime `--model deepseek-chat` still works; the
isThinkingModeModel() abstraction is semantic (thinking vs
non-thinking), not version-bound, so it stays correct.
Prior fixes (0.5.15, 0.5.18) progressively unscoped the stamp but kept
a reasoning.length > 0 guard that silently dropped the field whenever
the model happened to return empty reasoning — legitimate on flash
thinking-mode turns with zero reasoning deltas, forced-summary paths
whose resp.reasoningContent is null, and non-streaming responses
returning reasoning_content: null. The next API call then 400'd with
"The reasoning_content in the thinking mode must be passed back."
Architectural smell: assistantMessage gated on reasoning-content
presence, while syntheticAssistantMessage gated on model type — two
different encodings of the same invariant.
Unify both around isThinkingModeModel(producingModel): the field is
present on the persisted assistant turn iff the model that generated
it runs in thinking mode, using the captured reasoning (or empty
string) as the value. Call sites pass the real producing model — not
this.model — so escalation (pro) and forced-summary (flash)
round-trip correctly.
Session-load heal: stampMissingReasoningForThinkingMode back-fills
empty reasoning_content on assistant turns from pre-fix session
files, so resuming an older session on a thinking-mode model no
longer 400s on the first request.
Tests: +5 (null-reasoning stamping on v4-flash, chat stays clean,
session-load heal for reasoner/v4-pro/chat). 1150 tests, tsc clean.
The agent's live-run refactor (2c8... in the local log) correctly
split plan.ts into plan-core + plan-errors and preserved the barrel,
but stopped short of three things worth doing:
1. plan-errors.ts was mis-named — it also held the value types
(PlanStep, PlanStepRisk, StepCompletion). Extracted those to
a new plan-types.ts so file names match contents. Dependency
direction is now plan-core → plan-errors → plan-types.
2. Barrel used \`export *\` from both modules, which would silently
shadow on any future name collision. Replaced with explicit named
re-exports so TS catches duplicates the moment they appear.
3. plan-core.ts was still ~240 lines, mostly a single
registerPlanTool body with three inline tool-description strings.
Split into registerSubmitPlan / registerMarkStepComplete /
registerRevisePlan (one per screen) with descriptions hoisted to
SCREAMING_SNAKE constants at the top and the duplicated step-item
schema extracted to STEP_ITEM_SCHEMA. Function bodies now read as
control flow, not prose. Public API unchanged.
1145 tests still green, typecheck + lint clean. Zero behavior change.
Previous pass at tightening ask_choice guidance leaned on specific
anti-patterns — "方案 A:" headers, "你选哪个?" trailers, markdown
comparison tables. Ugly and brittle: next time the model adopts a
slightly different phrasing, we'd be patching yet another bullet.
Reframe as a single principle in both the tool description and the
code system prompt: "if the user is supposed to pick, the tool
picks — you don't enumerate the choices as prose." The model can
generalize from that.
Behavior contract is unchanged; the guidance is just cleaner and
easier to maintain. Prompt-engineering change only, no code logic.
Atlas W2 wave 2: load an archived plan as a read-only snapshot.
'/replay' defaults to the newest archive; '/replay 2' jumps to the
second-newest; '/plans' enumerates the full set.
- SlashResult grows replayPlan field so the handler can push a
structured payload — App.tsx mounts it as a plan-replay event
rather than flattening to info text. Keeps the bordered box +
step list + markdown body styling consistent with plan-resumed.
- New plan-replay DisplayRole + EventRow branch: gray border, ⏪
icon, dim header (completed time, N/total nav, archive filename),
markdown body rendered through the full pipeline, PlanStepList
with every step marked done, footer hint for jumping archives.
- /replay handler in plans.ts looks up listPlanArchives(session)
by 1-based index, validates range, carries the payload through.
Per-session only — same project-isolation as /plans.
- /replay added to commands.ts with argsHint=[N] so slash
autocomplete / hint surface picks it up.
Tests: 6 new slash tests cover default-newest, indexed lookup,
out-of-range rejection, empty-archive state, no-session guard, and
/plans summary label surfacing. Full suite 1145 green.
Two schema additions that unblock Time Travel and make /plans
listings useful.
- submit_plan accepts optional \`summary\`: one-line title. Surfaces
in the PlanConfirm header, the resume banner, and /plans so users
identify plans by intent ('Refactor auth into signed tokens')
rather than by filename.
- plan.json now stores the markdown \`body\` that came in with
submit_plan. Replay will read this; previously the body only
lived in the JSONL log, which is fine for the active session but
hard to surface in a closed archive without re-parsing tool-call
JSON.
Both fields are optional. Older plans without them still load and
render cleanly; /plans falls back to filename when no summary is set.
PlanProposedError carries summary through toToolResult. plan-store's
savePlanState grows an extras bag so callers don't have to care
about field proliferation. listPlanArchives surfaces both fields
on the PlanArchiveSummary type.
Tests: body+summary roundtrip, omission default, submit_plan
summary trim behavior, blank-rejection. Total: 1139 tests green.
Adds a per-session history view. Active plan (from plan.json) +
archived completed plans (.done.json), newest-first. Project-local
by design — cd to another project to see its plans, no cross-project
listing.
Output:
▸ active plan: 2/5 steps done · last touched 1h ago
Archived (3):
✓ 3d ago 5 steps · complete code-foo.plan.2026-04-21-...done.json
✓ 2026-04-15 8 steps · complete code-foo.plan.2026-04-15-...done.json
✓ 2026-04-10 3 steps · complete code-foo.plan.2026-04-10-...done.json
- listPlanArchives scans sessionsDir() for the session-prefixed
.done.json files. Sorts by stored updatedAt (with mtime fallback
for hand-edited archives). Skips corrupt JSON / wrong-version /
zero-steps archives instead of failing the whole list.
- /plans handler renders both views; falls back to a discovery hint
when no plans exist yet.
- Tests: 6 new — empty state, ordering, active-only ignored,
cross-session isolation, corrupt-resilience, mtime fallback.
Foundation for upcoming /replay <archive> + Time Travel canvas —
both will read these summaries to find replayable artifacts.
When the model marks the final step done, the active plan.json moves
to a timestamped .done.json archive instead of lingering. Two reasons
this matters: (1) the next session starts with a clean slate — no
stale resume banner for work that's actually finished; (2) the
archive is the foundation Time Travel replay will read from in W2
wave 2 to show "what the model actually did vs what was planned".
- archivePlanState renames plan.json → plan.<ISO-stamp>-<rand>.done.json
in sessionsDir(). Random 4-char suffix dodges within-millisecond
collisions if two plans finalize back-to-back. Returns the archive
path, or null when there's no active plan / rename fails.
- App.tsx mark_step_complete handler: after the progress row pushes,
if total > 0 && completed >= total, archive and post a
'▸ plan complete — all 5 steps done · archived' info row.
- Tests: 4 new — null-return on missing, rename verification,
payload preservation through archive, collision-resistance.
Auto-escalation (flash → pro) was the only truly automatic per-turn
decision the user couldn't see into. The warning fired but said only
'flash requested escalation' or 'flash hit N edit failure(s)' — no
WHY. Two changes surface the rationale.
1. Self-report marker now carries an optional reason:
<<<NEEDS_PRO>>> ← bare, still works
<<<NEEDS_PRO: <reason>>>> ← preferred, surfaces in warning
parseEscalationMarker pulls the reason out, the warning becomes
'⇧ flash requested escalation — <reason>'. Buffer bumped to 256
chars so reasons aren't truncated mid-stream. The streaming
look-ahead now uses looksLikePartialEscalationMarker so multi-
line / colon-form markers don't flush prematurely.
2. Failure-threshold escalation tracks PER-TYPE counts (search-
mismatch, scavenged, truncated, storm-broken). The warning now
says 'flash hit 2× search-mismatch, 1× truncated' instead of
'3 repair/error signals'. Same FAILURE_ESCALATION_THRESHOLD
semantics; just better attribution.
ESCALATION_CONTRACT prompt fragment teaches both forms with examples.
Three new tests cover the reason-carrying marker, empty-reason edge,
and the unclosed-marker fallthrough (still treats as content, no
silent retry on a malformed signal).
The W2 resume banner was a single info row — '▸ resumed plan: 2/5
steps done · last touched 3h ago'. Useful but minimal. Users had no
way to see WHICH steps were done or what's coming next without
scrolling back through the prior session's log.
New plan-resumed display role mounts a bordered box at the top of
the new session: header (badge + counter + relative time) plus
the full PlanStepList — same component used in PlanConfirm and the
checkpoint picker, with done steps dimmed + ✓, the next pending
step focused with the › cursor, and the risk gutter color-coded.
Carries the structured plan data through DisplayEvent.resumedPlan
so the renderer doesn't need access to the live planStepsRef. Pure
render layer; no new logic, no new tests needed (plan-store tests
already cover the data side).
Atlas W2 wave 1: the plan the model submits via submit_plan (and
mutates via mark_step_complete / revise_plan) now survives terminal
close. Without this, all the structured-step / risk / checkpoint /
revise UX evaporated whenever you took a coffee break.
- New src/code/plan-store.ts: loadPlanState / savePlanState /
clearPlanState / relativeTime. Storage path mirrors the JSONL
convention: ~/.reasonix/sessions/<sanitized>.plan.json. Format is
versioned (v1) with defensive parsing — corrupt files load as
null, malformed step entries are filtered, invalid risk values
are stripped, the rest of the plan still loads.
- App.tsx: load on mount, save after every plan-state change
(submit_plan, mark_step_complete, revise_plan accept), clear on
PlanConfirm cancel. The persistPlanState callback is threaded
through all the relevant useCallback deps so React's exhaustive-
deps rule stays clean.
- Resume banner: when an existing plan loads on startup, push
'▸ resumed plan: 2/5 steps done · last touched 3h ago' into the
scrollback so the user immediately sees the picked-up state.
- Tests: 15 covering save/load roundtrip, malformed-JSON recovery,
version mismatch, partial step sanitization, completedStepIds
filtering, path safety, and relativeTime branches.
The plan markdown body itself is NOT persisted here — it lives in
the session JSONL (it was a tool result), so resuming the session
replays it naturally. We carry forward only the live state needed
to keep mark_step_complete and revise_plan meaningful.
Compact tool rows now annotate with timing and a navigation hint:
▣ run_command (1.2s) → exit 0 · ✓ tests passed /tool 12
▣ read_file → import { foo } · 234 lines · 4.5KB /tool 13
▣ search_content (8.5s) → 5 matches · src/foo.ts:12 /tool 14
Duration is suppressed under 100ms (every read_file would scream
'47ms' otherwise — noise). Above that, formatDuration picks a tight
representation: ms → s.s → s → m+s as the magnitude grows.
The /tool N suffix makes the existing slash command discoverable
without scrolling — users can jump straight to full content via
`/tool 14` instead of guessing the position. toolIndex is captured
at push time as the 1-based length of the tool history.
App.tsx: toolStartedAtRef captures Date.now() on tool_start and
diffs at result. Single ref is enough — tools dispatch serially.
Old tool rows were 6–8 vertical lines each (glyph row + blank + 400-
char body block). 10 tool calls in a session = ~70 lines of
mostly-noise content drowning the actually-interesting events
(checkpoint pickers, plan submissions, edit diffs).
New rendering: one line per tool call.
▣ read_file → import { foo } from 'bar' · 234 lines · 4.5KB
▣ list_directory → 17 entries
▣ search_content → 5 matches · src/foo.ts:12: const x = 1
▣ run_command → exit 0 · ✓ 17 tests passed
▥ run_command ✗ exit 1 · TypeError: Cannot read property
▣ submit_plan → PlanProposedError — STOP, picker shown to user.
edit_file keeps its multi-line colored diff renderer (the diff IS the
value). Plan / Choice control-flow signals (PlanProposedError etc.)
render in non-error yellow even though they technically come through
the error envelope — they're picker triggers, not failures.
The summarizer is a pure function in tool-summary.ts so it tests
without Ink and can be reused by replay / transcript export later.
Full content remains accessible via `/tool N`.
Phase 2 Revise was just text-forwarding: user typed feedback, model
got a synthetic, model adjusted however it wanted with no structured
contract. Add revise_plan as the structured counterpart — the model
proposes new remainingSteps + a one-sentence reason, the TUI shows
a step-level diff, user accepts or rejects.
- New revise_plan tool (readOnly, throws PlanRevisionProposedError).
Sanitization reuses sanitizeSteps so risk levels and malformed
entries are handled the same as submit_plan.
- New PlanReviseConfirm modal: amber border, reason header, diff
rows (-removed/red+strikethrough, +added/green, kept/dim), counter
badge -N +M (K kept), Accept/Reject picker.
- App.tsx: pendingRevision state + handler. Accept splices the new
steps onto the done-step prefix in planStepsRef (done work never
undone), pushes an info row with -N+M counts, sends a continue
synthetic. Reject sends a 'keep original' synthetic. Picker takes
priority over checkpoint picker so a checkpoint-revise → revision-
proposal flow chains naturally.
- Checkpoint Revise synthetic now nudges the model toward revise_plan
for structural changes vs submit_plan for full reset.
Tests cover the error roundtrip, sanitization, risk preservation,
empty-input rejection, and the readOnly flag.
Phase 1 structured steps were only used for post-approval progress
tallying — the user never saw them at decision time. Add risk-coded
step list to both PlanConfirm (approval) and PlanCheckpointConfirm
(mid-execution) so the plan shape is visible where it matters.
- New PlanStep.risk: "low"|"med"|"high" (optional). submit_plan
description guides the model: high = hard-to-undo / prod / API
changes; med = non-trivial but reversible; low = safe local.
- PlanStepList renders a compact list with 1–3 colored dots per step
(●/●●/●●● green/yellow/red) + a ✓/▶/— glyph, a legend row, and
a '3 steps · 1 done' counter. Steps without risk render a blank
gutter, so pure-markdown plans degrade cleanly.
- PlanConfirm mounts the list above the approve/refine/cancel picker
when steps are supplied.
- PlanCheckpointConfirm mounts the same list with the current step
highlighted via a › cursor and completed steps dimmed, so the user
can see what just finished and what's next before picking
continue/revise/stop.
Result: a structured plan with risks looks like a real plan, not a
markdown blob. Pure-markdown plans keep working unchanged.
Phase 1 ask_choice was technically working but models rarely called it
— the description leaned defensive ('don't misuse') with only a light
'use when genuinely user's call' nudge, so DeepSeek Flash kept writing
prose comparisons that ended with '你选哪个?' (no picker rendered).
Two-layer fix:
- Tool description leads with 'CALL THIS WHENEVER your next reply
would end with A/B/C — 你选哪个?'. Spells out the self-detect
triggers and the failure mode of text menus. 'When in doubt, call
the tool' as the tiebreaker.
- Code system prompt gains a dedicated '# When to ask the user to
pick (ask_choice)' section sibling to the submit_plan one, plus an
inline warning in the submit_plan section against option-menu
plans cross-referencing ask_choice.
Costs one prefix-cache miss on first turn after the update; hit rate
re-stabilizes after that. No test changes (the behavior under test
was already correct — this is pure prompt-engineering).
New tool gives the model a proper home for branching questions —
submit_plan was getting misused as a route-picker and leaving users
stuck at approve/refine/cancel with no way to choose.
Tool throws ChoiceRequestedError (same toToolResult protocol as
PlanProposedError), TUI mounts ChoiceConfirm — a magenta-bordered
modal with the question, the option rows (title + dim summary), an
optional "Let me type my own answer" escape hatch, and cancel.
Picking routes a synthetic 'user picked <id>' back to the model;
custom ships whatever the user typed verbatim.
Registered in both code and chat modes so branching works anywhere.
Sanitizes malformed option arrays (DeepSeek V3/R1 occasionally drops
fields even with Pillar 3 auto-flatten) and caps at 6 options so the
model can't drown the user in choices. submit_plan's description now
cross-references ask_choice so the model learns the dispatch.
Foundation for the Atlas redesign — Fork Nodes in W2 will render
pending choices inline in the plan canvas instead of as a separate
modal.
Tool description now explicitly tells the model not to use submit_plan
as a "pick one of these routes" menu. The approve/refine/cancel picker
has no branch selector, so a menu plan strands the user — hit in the
wild where the model used submit_plan to offer three project directions.
Branches belong in plain assistant text with a question; submit_plan
stays reserved for a single actionable plan.
mark_step_complete now throws PlanCheckpointError so the loop pauses
after each step. A new PlanCheckpointConfirm picker drives what happens
next: Continue resumes the plan, Revise opens a feedback box whose
text is threaded into the next turn's context, Stop ends cleanly with
a summary.
Revise reuses PlanRefineInput's single-line UX with a new
"checkpoint-revise" mode label. Esc on the feedback input restores the
picker. The ✓ progress row from Phase 1 still renders before the
picker mounts, so the scrollback always records what was just done.
Ports the useful half of @imlingdu/reasonix-tools' dynamic-plan loop
into Reasonix's submit-plan / approval-gate model — Phase 3 will add
an LLM-driven revise helper on top.
submit_plan now accepts an optional steps:[{id,title,action}] array;
new mark_step_complete tool ticks them off during execution so the
scrollback shows `✓ step-1 · title — result (2/5)` instead of leaving
the user to infer progress from tool noise.
Pure-markdown plans keep working unchanged — steps and progress
rows only render when the model opted into the structured form.
Cost control promoted to Pillar 4. Breaking behavior: default model
flipped from v4-pro to v4-flash; smart (default) preset no longer
auto-enables harvest; max preset no longer auto-enables branch 3.
New: /pro one-shot arming, failure-triggered auto-escalate, model
self-report <<<NEEDS_PRO>>>, turn-end auto-compaction, per-turn cost
badges. UI refactor: App.tsx -33%, slash.ts split into slash/ with
13 focused modules. See CHANGELOG for the full matrix.
Two small papercuts from a 70-turn live run surfaced:
1. Every edit_file tool call showed the apply result TWICE — once
as a dim info row (pushed by applyNow in the edit-mode
interceptor), then again as a full `▣ edit_file → …` tool row
yielded by the loop. Both with identical text. Wasted rows, made
long sessions harder to skim.
Fix: drop the info-row push inside applyNow. The returned string
still becomes the tool result AND the model sees it via the tool
event; the user sees it once via the tool row with its
identifying header. The auto-text branch at turn-end (for
text-form SEARCH/REPLACE blocks parsed from assistant prose)
still pushes its own info row — there's no tool event to back
it up.
2. The model repeatedly tried `cd dir && cmd`, `cmd1 | cmd2`,
`cmd 2>&1`, learning only from the error reply. run_command's
top-level description didn't spell the constraints upfront.
Fix: front-load a "Constraints (read these before the first
call):" block in both run_command and run_background
descriptions. Explicit list of rejected operators, cd-doesn't-
persist, and concrete alternatives (`npm --prefix`, `cargo -C`,
`git -C`, `pytest tests/…` instead of `cd && …`). Also warns
against unbounded-output commands like `netstat -ano` /
`find /` that balloon context for no reason, with filtered
alternatives.
Both are tool/UI changes only; 1054 tests green, typecheck + biome
clean.
User bug: "submit_plan" proposals were being truncated inside the
PlanConfirm modal with "(25 more lines truncated — resize the terminal
to see more)". The whole point of a plan review gate is that the user
can read the full thing before approving; the old design cut it off
at roughly 11 source lines to keep the picker on-screen.
Root cause: PlanConfirm rendered both the plan body (via Markdown)
AND the 3-option picker inside one Ink modal, with a hard line clamp
so total height never exceeded the TTY. The clamp fired unavoidably
on any non-trivial plan.
Fix: push the plan body to Static scrollback as a new display role
"plan" the moment submit_plan fires. The Static component renders
once into the terminal's permanent buffer (users can scroll back
through the terminal itself), and the PlanConfirm modal below
shrinks to a tight picker header + choice list. No truncation ever.
Changes:
- EventLog.tsx: new DisplayRole "plan" renders the plan body through
the full Markdown pipeline inside a cyan-bordered box with a 📋
header. Goes into <Static> so it's render-once + scrollable.
- App.tsx: on submit_plan detection, setHistorical pushes a "plan"
row BEFORE setPendingPlan so the body is in scrollback by the
time the modal mounts.
- PlanConfirm.tsx: dropped the embedded Markdown render, the line-
clamp helper (clampBodyByLines), maxRenderedChars / terminalRows
props, and the two constants that drove them. The modal is now
just a header + open-questions hint + SingleSelect.
- tests/plan-confirm.test.ts deleted — its 5 tests were all for
the removed clampBodyByLines helper.
Everything else (approve/refine/cancel semantics, staged-input
handoff, hasOpenQuestions hint toggle) unchanged. 1054 tests green.
Users hit \`run_skill({"name":"🧬 explore"}) → {"error":"unknown skill: \"🧬 explore\""}\`.
The Skills index wrote entries like \`- 🧬 explore — …\`, with the marker
LEADING the name. Models copied the whole thing verbatim into the
\`name\` argument and the lookup failed (VALID_SKILL_NAME regex rejects
emoji + spaces).
Two fixes, defense in depth:
1. Prompt format (primary fix). Rewrite skillIndexLine so the
subagent marker trails the name, bracketed and labeled:
old: \`- 🧬 explore — …\`
new: \`- explore [🧬 subagent] — …\`
Name comes first, unambiguous. The index intro + tool descriptions
+ CODE_SYSTEM_PROMPT all explicitly spell out "the \`name\` is ONLY
the identifier before the tag."
2. run_skill normalization (belt-and-suspenders). If the model still
passes a decorated name, strip \`[...]\` bracketed tags and pick
the first whitespace-delimited token that starts with a word
character. Handles every shape observed in the wild:
"🧬 explore", "[🧬 subagent] explore", "[🧬] explore",
"explore [🧬 subagent]", " explore " → all resolve to "explore"
Tests:
- tests/skills.test.ts: updated to expect the trailing-tag format,
explicit regression assertion against the old \`- 🧬 name\` pattern.
- tests/tools-skills.test.ts: new "normalizes decorated names" case
exercising each decoration shape through run_skill dispatch.
All 1059 tests green.
Reactive-only escalation (wait for flash to rack up 3+ errors before
bumping to pro) burns tokens and time on tasks flash itself could
recognize as too hard upfront. Add a prompt-level contract: on flash,
the model can output `<<<NEEDS_PRO>>>` as the FIRST line of its
response to abort the current call and retry this turn on v4-pro,
one shot. Pro never self-escalates (the check short-circuits when
modelForCurrentCall === ESCALATION_MODEL).
This matters because non-expert users can't reliably predict which
tasks need the frontier tier. Letting the model self-assess catches
hard tasks upfront — design tradeoffs, architecture refactors, subtle
invariants — without auto-upgrading every prompt (which would destroy
the cost savings from flash-first defaults).
Implementation:
- loop.ts: NEEDS_PRO_MARKER constant, isEscalationRequest() helper,
post-call retry check that sets _escalateThisTurn and re-enters
the iter with `iter--; continue` on match. Streaming path buffers
the first 80 chars / first line before yielding assistant_delta
events so the marker never flickers on-screen before retry fires.
Guarded against infinite retries by checking modelForCurrentCall
against ESCALATION_MODEL — users who already chose /preset max
see the marker as normal content.
- prompt-fragments.ts: new ESCALATION_CONTRACT fragment spells out
when to use the marker (cross-file refactors, subtle correctness
invariants, design tradeoffs) and when NOT to (small edits, clear
bug fixes). Embedded into CODE_SYSTEM_PROMPT, DEFAULT_SYSTEM, and
DEFAULT_SUBAGENT_SYSTEM — subagents default to flash+high too,
so they benefit from the same escape hatch.
Tests (3 new in loop.test.ts):
- flash emits marker → retry on pro, final content is pro's response
- marker mid-text (not lead-in) → no retry
- pro emits marker → no infinite-retry loop
All 1058 tests green.
The previous ARCHITECTURE.md stopped at v0.3 (MCP + session persistence)
and read three-pillar (cache loop, harvest, tool-call repair) with a
roadmap that predates everything from v0.4 onward. After six months
of cost and refactor work the codebase is fundamentally different:
file layout reorganized, defaults flipped flash-first, branch + harvest
removed from every preset, /pro arming and failure-triggered
auto-escalation added.
New sections:
- Pillar 4 — Cost Control as a first-class subsystem: tiered defaults,
turn-end auto-compaction, /pro one-shot arming, failure-signal
auto-escalation, cost transparency thresholds.
- Module layout refreshed — reflects the slash/ + handlers/ split,
the six hooks under cli/ui/, prompt-fragments.ts, and actual LOC
counts (App.tsx 2931 → 1984).
- Design evolution replaces the stale roadmap — covers v0.0 through
v0.6 with a line each so readers orient without reading six months
of CHANGELOG.
- Non-goals updated to call out "automatic cost escalation without
user-visible announcement" as explicitly rejected.
Pillar 2 (harvest) and Pillar 3 (tool-call repair) content kept intact
and marked as before. Pillar 1 unchanged.
Pure docs change — no code touched.
Cost transparency is the last piece of the cost-control design —
users can now see at a glance how much the current turn cost and
which model it ran on, without opening /stats.
StatsPanel header picks up two new pills:
- ⇧ pro armed (yellow) — /pro queued, next turn will run on v4-pro
- ⇧ pro escalated (red) — current turn is on v4-pro (either /pro
armed was consumed at turn start, or the failure threshold
tripped mid-turn auto-escalation)
The cost cell now splits into two readings:
- turn $0.0042 — last turn's cost, colored by threshold
(green <$0.05, yellow $0.05-0.20, red ≥$0.20)
- session $0.1234 — cumulative, same color scale 10× up
(green <$0.50, yellow $0.50-5, red ≥$5)
No hard circuit-breaker that blocks turns — a mid-session pop-up
gate would be annoying. The colored thresholds are the signal;
users who notice yellow/red can /preset fast or /compact before
shipping the next message.
Plumbing:
- telemetry.ts: SessionSummary.lastTurnCostUsd added. Populated by
SessionStats.summary() from the most recent TurnStats.cost.
- replay.ts + ReplayApp.tsx: summary-shape call sites updated.
- StatsPanel.tsx: proArmed/escalated props; CostCell refactor;
turnCostColor/sessionCostColor threshold helpers.
- slash types: armPro / disarmPro ctx callbacks so the /pro handler
can update App's mirror state synchronously.
- App.tsx: proArmed + turnOnPro state mirrors, turn-start/end
transitions, warning-event sniff for "⇧" prefix flips turnOnPro.
Tests: 1055 green, typecheck + biome clean.
Two cost-aware escalation paths join the loop, keeping flash-first
as the default but letting the system (or the user) bump to v4-pro
when flash is visibly struggling — without requiring a persistent
preset switch.
1. `/pro` slash command arms pro for the NEXT turn only. Consumed
at turn start, auto-disarms after the turn ends. Use case: the
user knows the upcoming ask is hard and wants one-shot strength
without typing /preset max + remembering to revert. Separate from
/preset max (persistent, changes this.model) — armed state is
strictly single-turn.
2. Auto-escalation on failure. The loop tracks visible "flash is
struggling" signals per turn:
- edit_file / write_file SEARCH-not-found errors
- ToolCallRepair fires: scavenge, truncation-fix, storm-break
Once the count hits FAILURE_ESCALATION_THRESHOLD (3) in one
turn, the remainder of that turn's model calls upgrade to
v4-pro. Announced via a yellow warning row — no silent cost
surprises. Counter + escalation flag reset at every turn start.
Wiring:
- loop.ts: `_proArmedForNextTurn`, `_escalateThisTurn`,
`_turnFailureCount` private state. Public `armProForNextTurn`,
`disarmPro`, `proArmed`, `escalatedThisTurn` getters for UI.
`modelForCurrentCall()` returns the effective model (escalated
or this.model). `noteToolFailureSignal()` centralizes the
increment+threshold logic.
- All three chat call sites (branch path, streaming, non-streaming)
use `modelForCurrentCall()` instead of `this.model` directly.
- stats.record uses the actual model for cost attribution.
- Library-mode default model: v4-pro → v4-flash (aligned with CLI).
- slash/handlers/model.ts: new `pro` handler with /pro, /pro off.
- slash/commands.ts: /pro registered in SLASH_COMMANDS + /help text.
Tests: 1055 green, typecheck + biome clean.
Context bloat was the real cost driver, not model tier. A single
read_file returning 12K tokens rides every subsequent turn's prompt
at the cache-hit rate; 10 reads accumulate to 100K+ carry-cost
that each turn pays until the 60% reactive threshold kicks in.
By then the user has already paid for 20-40 turns of inflated
context.
Two changes shift us from reactive to preventive:
1. autoCompactToolResultsOnTurnEnd — fires at every `done` event
(normal completion, abort, forced summary). Shrinks every tool
result in the log over 3000 tokens to a tight cap. The model
can re-read the file if it needs fresh detail — one extra
read_file call is far cheaper than dragging 12KB through every
future turn.
2. Proactive in-turn threshold lowered from 60% → 40%. The turn-end
compact already handles the common case; this threshold now
only catches multi-iter turns where one tool returned a huge
payload mid-turn, before the turn ends. 40% triggers earlier
without waiting for context to get tight.
Net impact on long sessions: per-turn prompt tokens stop compounding.
Expected monthly cost reduction for active users: ~3-5× on long
projects where tool results accumulate.
Constants:
- TURN_END_RESULT_CAP_TOKENS = 3000 (new)
- ARGS_COMPACT_THRESHOLD_TOKENS = 800 (unchanged; per-response args shrink)
Tests: 1055 green, typecheck + biome clean.
Overhauls the cost model so `reasonix code` doesn't burn pro-tier
tokens by default. Three principles:
1. The default turn runs on v4-flash, not v4-pro. Pro is a ~12× tier
and shouldn't be implicit. Users escalate with /preset max.
2. Branch and harvest are NEVER auto-enabled by any preset. Both
multiply per-turn cost (N× and +1 flash call respectively); both
now require explicit /branch N or /harvest on.
3. Non-user-facing model calls (forced summary on budget exhaustion,
subagent runs, truncation repair) route through flash+high
regardless of the user's main-turn tier. No reason to pay pro
rates for a wrap-up paragraph or an explore subagent's grep chain.
Preset redefinition (branch=1, harvest=false for all three):
fast v4-flash + effort=high cheapest · Q&A, one-line edits
smart v4-flash + effort=max default · day-to-day coding
max v4-pro + effort=max ~12× fast · hard single-shots
Default preset is now `smart` (was `fast`) — flash+max is the best
price-per-quality point for coding work. `fast` is the "I just want
a quick answer" escape hatch.
Specific changes:
- cli/ui/presets.ts — new PresetSettings shape adds `reasoningEffort`;
PRESETS values rewritten; PRESET_DESCRIPTIONS reflect cost story;
`resolvePreset` default is now "smart".
- cli/resolve.ts — ResolvedDefaults gains `reasoningEffort`; default
preset is "smart".
- cli/commands/code.tsx — default model v4-pro → v4-flash.
- tools/subagent.ts — DEFAULT_SUBAGENT_MODEL v4-pro → v4-flash;
DEFAULT_SUBAGENT_EFFORT = "high" (down from parent's "max").
Skill frontmatter `model:` / `effort:` remain the escape hatches.
- loop.ts — forceSummaryAfterIterLimit hard-codes flash+high for the
wrap-up call; stats.record attributes the actual summaryModel so
/stats reflects reality.
- slash handlers — /preset rewritten (persists effort now); /harvest
and /branch print cost-warning suffixes; /help + /keys text updated
to match new presets and warn harvest/branch are opt-in only.
- CLI --help strings for `reasonix chat` / `reasonix code` / `--preset`
/ `--harvest` / `--branch` updated.
Tests:
- resolve.test.ts: expectations updated to new defaults (flash+max,
no branch in max preset).
- slash.test.ts: preset test expectations updated to new combos.
- subagent.test.ts: default-model fallback expectation updated.
All 1055 tests green; typecheck + biome clean.
The TUI formatting rules (GFM tables, no Unicode box-drawing, no
decorative ┌──┐ frames, flow charts as bullet lists) were
maintained as three near-identical copies across
DEFAULT_SUBAGENT_SYSTEM, BUILTIN_EXPLORE_BODY, and
BUILTIN_RESEARCH_BODY — and missing entirely from
CODE_SYSTEM_PROMPT, even though the main code reply goes through
the same markdown renderer.
Subagents also lacked the "negative claims are the #1
hallucination shape" guardrail that the main code prompt has.
When an explore/research subagent confidently reported "X is
missing", the parent swallowed it at face value.
Changes:
- New src/prompt-fragments.ts holds TUI_FORMATTING_RULES and
NEGATIVE_CLAIM_RULE as shared constants — single source of
truth, embedded literally so prefix-cache hashing stays stable.
- DEFAULT_SUBAGENT_SYSTEM, BUILTIN_EXPLORE_BODY, and
BUILTIN_RESEARCH_BODY import and interpolate both fragments
instead of open-coding their own copies.
- CODE_SYSTEM_PROMPT imports TUI_FORMATTING_RULES and appends it
after the Style section.
- CODE_SYSTEM_PROMPT's intro tool list now names every
filesystem tool (read_file, write_file, edit_file,
list_directory, directory_tree, search_files, search_content,
get_file_info) instead of trailing off at "etc." before the
essential search_content / edit_file were listed.
Behavior change is small and aligned: fewer hallucinated absences
from subagents, fewer Unicode-box-drawing tables to patch around
in markdown.tsx. Typecheck + biome + 1055 tests green.
- biome format pass on EditConfirm / edit-blocks / jobs / shell /
filesystem / compact-tokens / App / slash (auto-fixes)
- drop backtick template on a plain-string literal ("failed",
"(already reverted — …)")
- annotate interceptor useEffect with a useExhaustiveDependencies
ignore — the closure captures are intentional; adding the refs as
deps would tear down the interceptor on every mode flip
- add codeHistory / codeShowEdit to handleSubmit deps
- expand comma-operator tricks in tests/tools.test.ts into
explicit statements (biome rejects `(x = 1, "y")` and comma
operator under lint/style/noCommaOperator + noAssignInExpressions)
prepublishOnly (lint + typecheck + test + build) now passes clean.
1055 tests, dist built.
- EditConfirm modal for per-edit review (scrollable diff); Shift+Tab
cycles review/auto; 5s undo banner + `u` keybind; session edit
history with /history, /show [id] [path], /undo [id] [path]
- run_background / job_output / stop_job / list_jobs tools with
ready-signal detection; /jobs, /kill, /logs; tree-kill (Windows
taskkill /T /F, POSIX process.kill(-pid)) so dev servers actually
stop; cleanup on SIGINT / SIGTERM / exit
- Bottom mode status bar always above the prompt: mode, pending
count, Shift+Tab hint, running-jobs tag; one-time onboarding tip
on first launch after upgrade
- Context hygiene: read_file `range:"A-B"` + auto-preview for files
>200 lines; directory_tree default depth 4→2 + skip deps
(node_modules / .git / dist / …) + per-directory 50-child collapse;
auto-compact tool-call args after each tool response (>800 tok);
/compact now covers both tool results and tool-call args
- Persist reasoningEffort to config so /effort high survives restart
(earlier: silently reverted to max); editMode already persisted
- Prompt: scope discipline on "run/start/launch" requests so the
model stops after verifying instead of auto-refactoring; teach
model that run_background is for dev servers and review-mode
rejections should not be retried with the same SEARCH/REPLACE
tests: 1055 passing (+17 new)
Before: DeepSeek auth/balance/parameter errors surfaced as raw
"DeepSeek 401: {\"error\":{\"message\":\"...\"}}" JSON blobs. Users
saw a wall of JSON and had to know to parse it themselves to learn
their API key was bad or they were out of credit.
formatLoopError now recognizes the per-code cases:
401 → "Authentication failed (DeepSeek 401): <inner msg>. Your API
key is rejected. Fix with `reasonix setup` or
`export DEEPSEEK_API_KEY=sk-...`. Get one at
https://platform.deepseek.com/api_keys."
402 → "Out of balance (DeepSeek 402): <inner msg>. Top up at
https://platform.deepseek.com/top_up — the panel header
shows your balance once it's non-zero."
422 → "Invalid parameter (DeepSeek 422): <inner msg>"
400 → "Bad request (DeepSeek 400): <inner msg>"
Each unwraps `{"error":{"message":"..."}}` so the reader sees prose,
not JSON. Fallback keeps the raw body if parsing fails.
Context-overflow text also refreshed: mentions V4's 1M window AND
the legacy 131k for the chat/reasoner aliases, and drops the stale
"v0.3.0-alpha.6+" reference that's long-since rolled into the 0.5
release line. The "8k tokens per tool result" cap is current
(src/mcp/registry.ts DEFAULT_MAX_RESULT_TOKENS).
429/500/502/503/504/408 retries unchanged — fully absorbed by
retry.ts before they reach formatLoopError.
1013 tests (+6). Lint / typecheck / build clean.
DeepSeek's 2026-04 docs spell out that when concurrency is saturated
but the request is accepted, the connection stays open for up to 10
minutes while the request waits in the queue — non-streaming bodies
fill with empty lines, streaming bodies fill with `:` SSE keep-alive
comments. Both are invisible to our parsers (JSON.parse tolerates
leading whitespace; eventsource-parser drops `:`-prefixed comment
lines per the SSE spec), so no separate handling is needed.
What WAS broken: `timeoutMs` defaulted to 120s. A request that sat
in the queue past 2 min triggered our AbortController, which burned
the queue slot and bounced through retryWithBackoff — potentially
looping through the whole queue repeatedly and never landing.
Fix: bump default to 660_000ms (11 min). Server's own 10-min cap
closes the connection first on genuine queue overflow (clean EOF
→ our retry is normal), while still catching truly hung sockets.
Callers that want a tighter budget (short-lived CI checks, smoke
tests) keep their explicit `timeoutMs` override. No API shape change.
1007 tests. Lint / typecheck / build clean.
- Tagline + /preset max + /think: V3/R1 → V4 (flash + pro)
- /model row lists v4-flash/pro as primary, chat/reasoner as compat aliases
- Add /effort, /resource, /prompt, /models, /context, /stats, /keys rows
- Context window 131k → 1M; test count 648 → 1007
- New "Prompt prefixes — !cmd and @path" section documenting the bang-
mode shell shortcut (0.5.8, now session-durable) and @-mentions
picker (0.5.5-0.5.7) — both are daily-use features that had no home
in the README until now.
- Panel header example bumped from 0.4.22 to the current 0.5.21 with
the reasoning-effort `· max` badge visible.
No code changes.
Models & pricing (src/telemetry.ts):
- Add deepseek-v4-flash (¥0.2 / ¥1 / ¥2 per 1M hit/miss/out) and
deepseek-v4-pro (¥1 / ¥12 / ¥24), converted at 7.2 CNY/USD.
- deepseek-chat and deepseek-reasoner now priced identically to
v4-flash — per the 2026-04 V4 launch they're compat aliases for
flash non-thinking / thinking modes respectively.
- Context bumped to 1M tokens across all four entries.
Defaults shifted to v4-pro (agent-class flagship):
- `reasonix code` mode, subagent DEFAULT_SUBAGENT_MODEL, loop
constructor fallback, `max` preset all point at deepseek-v4-pro.
- `fast` / `smart` presets stay on chat/reasoner — those aliases are
currently our only way to pin thinking ON or OFF via model name,
so the preset system still has a cheap/fast option.
- Subagent tool enum widened to [v4-flash, v4-pro, chat, reasoner];
description flipped to treat flash as the "cheaper opt-out" path.
Thinking-mode toggle + reasoning_effort (new API params):
- src/types.ts ChatRequestOptions gains `thinking?: "enabled" | "disabled"`
serialized as extra_body.thinking.type, and `reasoningEffort?:
"high" | "max"` as the top-level reasoning_effort field.
- src/loop.ts exposes thinkingModeForModel(model) and pins the
correct value per model name (chat=disabled, reasoner=enabled,
v4-*=enabled, unknown=undefined/server-default). Every turn now
sets thinking + reasoningEffort explicitly — no more relying on
server defaults to match what reasoning_content round-trip expects.
- reasoning_effort defaults to "max" because Reasonix is exactly the
agent-class use case DeepSeek's docs call out.
UI: /effort slash + StatsPanel badge:
- `/effort [high|max]` flips the loop's reasoningEffort mid-session.
- `/effort` no-arg reports the current value.
- StatsPanel header shows a green `· max` or yellow `· high` tag next
to harvest/branch/PLAN so users always see which tier the next turn
will use. `/status` flags line also reports it.
Harvest cost tuning (src/harvest.ts):
- Default model reverted to deepseek-chat — harvest is a micro-
extraction (4 small arrays of strings), not agent work.
- chat() call explicitly pins thinking=disabled + effort=high so a
future default-model swap can't accidentally promote this micro-
call into a multi-thousand-reasoning-token request.
1007 tests (+9 new: thinking toggle, /effort slash, v4 pricing).
Lint / typecheck / build clean.
Long assistant responses with many tool_calls used to render as a
single static "building tool call <write_file> · 37 chars" spinner
for 10–30s — user could see tokens being consumed but had no sense of
how many files were coming or how far along the stream was.
Each tool_call's `arguments` blob is now tried as JSON at every delta.
Once it first parses, the index is marked "ready" and the count goes
into subsequent `tool_call_delta` events. The UI label becomes
"building tool call (call 3) <write_file> · 127 chars · 2 ready"
so the user sees progress accumulating.
Dispatch timing is UNCHANGED — this is purely a visibility upgrade.
Mid-stream eager dispatch was considered and punted because it would
interact awkwardly with the repair step (truncation fix, storm
breaker, scavenge) that runs post-stream.
+6 tests locking down looksLikeCompleteJson (the gate that decides
when a streaming call counts as "ready"). 991 tests.
0.5.15 scoped the fix too narrowly — only attached reasoning_content
when `tool_calls.length > 0`. DeepSeek's "thinking mode must be
passed back" rule applies to ANY R1-generated assistant message.
Symptom: plan approved → synthetic user message "implement it now" →
next API call 400s. The intermediate "plan submitted — awaiting
approval" plain-text R1 turn was persisted without its reasoning,
and R1 rejected the entire history the next time around.
Changes:
- assistantMessage() drops the tool_calls guard; reasoning attaches
whenever the model emitted any (even on plain-text turns).
- Forced-summary path (no-tools fallback) now captures reasoning from
the summary response.
- New syntheticAssistantMessage() stamps an empty-string
reasoning_content on synthetic turns (Esc-abort notices) when the
model is a reasoner, so R1's validator is satisfied even when no
real reasoning exists. V3 stays clean.
- Test updated: plain-text reasoner turn now asserts reasoning
DOES round-trip (reversed from 0.5.15's assumption).
985 tests.
Symptom: user wrote a game design doc to `F:/Reasonix/game-design-doc.md`,
the model cited it as `[...](/game-design-doc.md)`, and Reasonix rendered
"✗ /game-design-doc.md → file not found" even though the file was
right there on disk.
Cause: `validateCitation` ran `isAbsolute(path)` on the raw URL. A model
writing `/foo.md` means "project-root relative" (Aider / Claude-Code
convention), but Node's isAbsolute returns true, so the validator
stat'd the literal `/foo.md` under the filesystem root and got ENOENT.
Fix: strip leading `/` or `\` before the absoluteness test. Drive-letter
paths (`C:\...`) still pass isAbsolute and are respected; plain
leading-slash paths become project-relative. Unix absolute citations
like `/etc/hosts` lose precision but are vanishingly rare in code
citations — if we need them we'll add an explicit scheme.
+2 markdown tests for the new leading-slash behavior (both `/` and `\`).
985 tests.
0.5.14's clamp was insufficient. Three root causes the earlier fix missed:
1. TickerProvider kept pumping 120ms re-renders even while the picker
was up — the memo'd PlanConfirm still re-evaluated on every tick
because `onChoose` identity changed (handlePlanConfirm has `busy` in
its deps; busy toggles during model streaming). Fix: disable the
ticker while `pendingPlan` or `pendingShell` is set. No ticker = no
re-render cadence to drive Ink redraws.
2. `clampBodyByLines` clamped SOURCE lines, not rendered rows.
Markdown expands ~2× (wrap, code fences, heading blanks, list
indent), so `rows - 18` source lines still overflowed on a 40-row
terminal. Fix: divide by MARKDOWN_EXPANSION before clamping so the
rendered output actually fits.
3. `handlePlanConfirm` identity churns — wrapped in a ref-stable
`stableHandlePlanConfirm` so `React.memo(PlanConfirm)`'s shallow
compare actually skips re-renders when `plan` + `projectRoot`
haven't changed.
Together these pin the picker's rendered height to a known budget AND
eliminate the re-render loop that caused Ink to clear+redraw each
frame. The overflow-can't-scroll symptom is inherent to Ink's live
mode; only remedy is to make content fit, which the tightened clamp
now guarantees.
DeepSeek R1 thinking mode 400s with "The reasoning_content in the
thinking mode must be passed back to the API" when a tool-loop
continuation replays an assistant message that had tool_calls but
no reasoning. Root cause: assistantMessage() stripped the field.
Fix: ChatMessage gains optional reasoning_content. Loop passes the
captured reasoning into assistantMessage; we attach it only when
the turn has tool_calls AND reasoning is non-empty — plain-text
R1 turns stay lean, deepseek-chat is unaffected.
+2 tests (loop-r1-reasoning): turn-2 body asserts the echoed
assistant message carries reasoning_content on a tool-call turn,
and does NOT carry it on a plain-text turn.
- !cmd bang output now persists via loop.appendAndPersist, so session
resume sees the shell history the model already reasoned against.
- Subagent runs (run_skill · runAs:subagent) now emit cost/model/usage
on their end event. App.tsx writes one row to ~/.reasonix/usage.jsonl
per run; the completion line also shows $X inline. `/stats` and
`reasonix stats` render a new "subagent activity" section with
per-skill breakdown.
- `/resource [uri]` + `/prompt [name]` slashes with argument-level
pickers (reusing 0.5.13's SlashArgPicker). No arg lists what every
connected MCP server exposes; with arg reads via live McpClient
stored on McpServerSummary. Display-only v1 — no loop injection.
`/mcp` now hints toward these when servers expose resources/prompts,
`/keys` gets an "MCP exploration" section, `/help` lists both.
- Bug A — plan picker flicker on small terminals: PlanConfirm's
markdown body is now line-clamped to (rows − 18), and the component
is React.memoed so tick-driven parent re-renders skip the heavy
Markdown subtree when props are unchanged.
- Bug B — pending-edit queue wiped on crash: new
src/code/pending-edits.ts checkpoints the queue to
~/.reasonix/sessions/<name>.pending.json on every parse. /apply
and /discard clear the file; session resume restores it with a
visible banner. deleteSession removes the sidecar too.
981 tests (+31). lint / typecheck / build clean.
Two small course-corrections on the 0.5.13 work-in-progress. Version
stays at 0.5.13 — these land before publish.
### 1. Remove /edit
The one-shot `/edit <file> <instruction>` slash was 99% redundant
with `@path/file.ts <instruction>`: the 0.5.5 `@`-mention already
inlines the file, and code-mode's system prompt already teaches the
model to output SEARCH/REPLACE blocks. `/edit` added only the
"output ONLY a block, no prose" hint — not worth a whole slash.
Reverted:
- case "edit" handler (slash.ts)
- SLASH_COMMANDS registry entry
- /help line
- /edit test describe block + "/help mentions /edit" + required-list
- "file" from the argCompleter union type (no consumer left; the
`@` picker remains the single file-picker surface, avoiding two
competing file-autocompletes)
- "file" branch in App.tsx's slashArgMatches memo + the trailing-
space special case in pickSlashArg
Users who want one-shot edits type `@src/foo.ts fix the typo` —
clearer to read in history and the model obliges by default.
### 2. Picker blocked Enter after exact match
Typing `/preset smart` left the picker visible with one match
("smart") → Enter was intercepted and re-substituted the same value
instead of submitting the command. Fix: slashArgMatches memo now
returns null when the partial is a case-insensitive EXACT match for
an enum value (or a model id). Picker hides; Enter submits.
- Test added documenting that the detector itself remains kind-
only — the hide-on-exact-match logic lives in the App-side memo
so the detector stays UI-agnostic.
### Tests
946 (was 952; dropped 6 /edit-specific tests, added 1 regression
for the exact-match fix, dropped the File-picker-for-/edit detector
test since that path is gone). Lint + typecheck + build clean.
User feedback: "after I type `/edit` there's no hint about what files
exist — same for other commands with args." Fixed.
### Mechanism
SlashCommandSpec gains an `argCompleter` field:
- `"file"` → file picker (reuses atFiles + rankPickerCandidates
with mtime + recently-used ranking from 0.5.12)
- `"models"` → DeepSeek model-id list fetched at startup
- `string[]` → small enum (e.g. `["fast", "smart", "max"]`)
- omitted → no picker, just a dim usage hint below the prompt
Attached to: /edit → file, /preset → enum, /model → models,
/plan → on/off, /harvest → on/off, /branch → off + a few N values.
`detectSlashArgContext(input, codeMode)` in slash.ts classifies the
buffer once the user has typed `/<cmd> ` — returns `{spec, partial,
partialOffset, kind}`. `kind` is "picker" (completable first-arg
position) or "hint" (past the first arg / no completer).
`src/cli/ui/SlashArgPicker.tsx` — new component mirroring the
SlashSuggestions / AtMentionSuggestions layout. Header row always
shows `/<cmd> <argsHint> — <summary>` so even when no matches,
the user sees what's expected. Hint-only mode is a single dim row.
App.tsx: `slashArgSelected` state, `slashArgContext` memo,
`slashArgMatches` memo (dispatches on completer type), useEffect
clamp, `pickSlashArg` callback (splices at partialOffset; adds
trailing space for file picker so user can keep typing the
instruction; no trailing space for enum picks since those commands
take no further args). Wired into useInput arrow/Tab and
handleSubmit Enter intercept. Renders after SlashSuggestions +
AtMentionSuggestions.
### Tests (+11, suite 941 → 952)
tests/slash.test.ts — `detectSlashArgContext` suite covers: null
before name commit, null on unknown cmd, file picker for /edit in
code mode, contextual-command gating outside code mode, enum picker
for /preset, models completer for /model, /plan gated to code mode,
hint kind once partial has internal whitespace, picker with empty
partial (just-typed space), hint kind for free-form arg commands
like /commit.
Lint + typecheck + build clean. 952 tests, 7.5s.
Two UX polishers bundled, closing out the A-E batch.
### D. `@` picker ranking by mtime + recently-used
Alphabetical sort was arbitrary on large repos — 500 files deep, the
first page was almost never what the user wanted. New ranking:
- Empty query → recently-used paths first, then mtime descending,
then path alpha. "Recently used" = files touched by `read_file` /
`edit_file` / `write_file` / `search_content` / etc. tool calls
this session (20-slot LRU; resets on session change).
- Non-empty query → existing substring/prefix scoring, tiebreak by
recently-used membership then mtime.
- Back-compat: `string[]` input with no recency list still returns
input order (old tests pass unchanged).
Implementation:
- `listFilesWithStatsSync(root, opts)` — same walk as listFilesSync
plus a statSync per file. Stat failures don't throw; the entry
keeps `mtimeMs: 0` and sinks to the bottom of the recency bucket.
- `FileWithStats` / `PickerCandidate` / `RankPickerOptions` types
exported for library callers.
- `rankPickerCandidates(files, query, limitOrOpts)` — overloaded:
bare number still works (back-compat), or pass
`{ limit, recentlyUsed }`.
- App.tsx: `atFiles` memo switched to listFilesWithStatsSync;
`recentFilesRef` (useRef<string[]>) + `recordRecentFile(p)` LRU
callback; `tool_start` event handler inspects `toolArgs` for
`path` / `file_path` / `file` fields and feeds the LRU.
### E. `/keys` cheatsheet slash
Discoverability gap: `!` bang, `@` picker, `/` slash, Shift+Enter,
Ctrl+J, Ctrl+A/E, Esc, y/n — the kit is extensive but undocumented
in one place. `/keys` dumps a formatted table:
Keyboard & prompt shortcuts:
Enter submit the current prompt
Shift+Enter / Ctrl+J insert a newline
...
Prompt prefixes:
/<name> slash command
@<path> inline a file (code mode)
!<cmd> run <cmd> as shell
Pickers (slash + @-mention):
↑ / ↓ navigate
Tab insert without submitting
Enter insert + run/keep-editing
Added to SLASH_COMMANDS registry + cross-linked from `/help`.
### Tests (+9, suite 932 → 941)
- tests/at-mentions.test.ts — 5 new for rankPickerCandidates:
mtime sort on empty query with FileWithStats, recently-used boost
trumps mtime, non-empty query tiebreak by recent+mtime, back-compat
input-order preservation for bare strings, numeric-limit literal
as third arg.
- tests/slash.test.ts — 4 new for /keys: shortcuts listed, prefixes
listed, pickers mentioned, /help cross-reference.
### Note on release cadence
A (0.5.9) + B (0.5.10) + C (0.5.11) + D + E were split across five
commits but each dist is cumulative — publishing only the final one
gets users everything. Going forward I'll bundle closer unless the
user asks otherwise.
Lint + typecheck + build clean. 941 tests, 8.3s.
Before /apply, the UI used to show only
▸ 2 pending edit block(s) — /apply or /discard
src/a.ts (-3 +4 lines)
src/b.ts (-1 +1 lines)
— a count summary, nothing about what was actually changing. Common
mistake shape: press y, look at git diff afterwards, discover the
model edited the wrong block / wrong file.
Now each pending block is rendered as a compact diff with ±2 lines of
context and a hard cap at 20 lines per block:
▸ 2 pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop
src/foo.ts (-1 +1 lines)
function foo() {
- const x = 1;
+ const x = 2;
return x;
NEW src/bar.ts (-0 +3 lines)
+ export const bar = 1;
+ export const baz = 2;
+ export default { bar, baz };
### Mechanism
`src/code/diff-preview.ts`:
- `formatEditBlockDiff(block, opts)` — shared leading/trailing lines
collapse to context (default 2 lines each side, `… N unchanged lines
above/below` when truncated). Middle divergence is `-old` / `+new`.
Whole block capped at 20 lines with `… (N more diff lines — full
content applies on /apply)` footer when exceeded. Empty-search
(new file) case shows all-`+` lines.
- `formatAllBlockDiffs(blocks, opts)` — stitches each block's header
(path + ±line counts, `NEW` prefix for new files) + its diff body,
separated by blank lines.
Zero new deps. Small hand-rolled helper using prefix/suffix-compare;
sufficient for the typical SEARCH/REPLACE shape (small change inside
a function body, wrapped in a few lines of surrounding context).
Myers-diff quality is not needed — the model's SEARCH block already
minimizes context.
`formatPendingPreview` in App.tsx dropped its own summary line list
(paths now come from the per-block diff header) and its local
`countLines` helper (moved to diff-preview.ts alongside its only
consumer).
### No colors yet
Plain text, `-` / `+` / ` ` prefixes. ANSI colorization would need
Ink component plumbing that isn't worth the complexity for v1 —
the prefix convention is clear and universal (git / hunks / etc.).
### Tests (+10, suite 922 → 932)
tests/diff-preview.test.ts — new-file all-`+`, context collapse for
shared prefix/suffix, maxLines truncation with footer, leading and
trailing hidden-context annotations, single-line edits, custom
indent, multi-block formatAllBlockDiffs (path+counts headers, blank
separators, empty-input).
Lint + typecheck + build clean. 932 tests.
One-liner shortcut for "change this one thing in this one file" —
faster than the multi-turn code-mode dance of "explain the file",
"here's my plan", "apply", etc. Code mode only.
### Mechanism
Zero new code paths. The slash is sugar: it builds a resubmit text of
@<file> <instruction>
Output ONLY a SEARCH/REPLACE block for this one edit. No prose,
no explanation.
and hands that back through the normal turn machinery:
- 0.5.5's `@`-mention expansion inlines `<file>` under
`[Referenced files]` so the model sees the current content.
- Code-mode's SEARCH/REPLACE handling already catches the output
into `pendingEdits` (0.4.0+).
- The existing y/n confirm gate fires on the next event.
So `/edit src/foo.ts fix the typo` becomes equivalent to the user
typing `@src/foo.ts fix the typo. Output ONLY a SEARCH/REPLACE
block…` — the value is (a) discoverability via /help and slash
autocomplete, (b) the guaranteed-good prompt format without the user
having to remember it.
### Validation
- Outside code mode (no `codeRoot` in SlashContext) → refusal with a
pointer to `reasonix code <dir>`.
- Missing file arg → usage hint.
- Missing instruction → usage hint with the file name echoed back.
### /help + discovery
Added to the slash autocomplete registry (`contextual: "code"` so
it only surfaces in code mode) and to the /help code-mode block.
### Tests (+6, suite 916 → 922)
tests/slash.test.ts — /edit describe block covers: non-code-mode
refusal, missing file, missing instruction, resubmit shape
(contains `@file` + instruction + SEARCH/REPLACE + ONLY), multi-
word instruction preservation. Plus `/help mentions /edit` and
`edit` added to the `SLASH_COMMANDS registry contains every handler`
required-list.
Lint + typecheck + build clean. 922 tests.
Pasting a stack trace / log dump / sample file flooded the Historical
scrollback with a massive block, hiding prior turns. Now user input
that exceeds a threshold renders as:
▸ pasted 2.3 KB (84 lines) — first 10 shown, full text sent to model
line 1
…
line 10
… (74 more lines)
The MODEL still receives the full text. Only the displayed row
collapses — `loop.step(modelInput)` gets the original string
(including any `@`-mention expansion) unchanged.
### Mechanism
- `src/cli/ui/paste-collapse.ts` — `formatLongPaste(text, opts)` pure
helper. Collapse triggers when line count > 40 OR char count > 2000
(defaults, override via opts). Head shows 10 lines; remaining
footer reads "… (N more lines)". Byte header formats B/KB/MB.
- App.tsx — wired at the user-row push site in handleSubmit
(between the UserPromptSubmit hook gate and the loop.step dispatch).
The `pasteDisplay.displayText` goes to the Historical row; the
existing `modelInput` variable (raw or `@`-expanded) goes to the
loop.
### Scope
Affects only the regular user-message row. Separate paths for
`!`-bang commands, `@` expansions, and slash outputs are untouched.
Skipped on short messages (pass-through, no allocation overhead
beyond a `split("\n")`).
### Tests (+10, suite 906 → 916)
tests/paste-collapse.test.ts covers: short pass-through, multi-line
pass-through, line-threshold collapse, char-threshold collapse,
KB/MB formatting, 1-vs-N-more-lines pluralization, custom
thresholds, custom headLines, zero remaining (head covers all),
exported defaults.
Lint + typecheck + build clean. 916 tests.
Claude-Code-style bash mode. User types `!ls src/` or `!git status`;
Reasonix runs the command in the sandbox root, shows both the command
and its output, and appends the combined text to the conversation log
so the next model turn has the context automatically.
Faster than round-tripping through the model just to cat a file or
check git state, and closes a common UX gap vs. Claude Code.
### Mechanism
- `src/cli/ui/bang.ts` — `detectBangCommand(text)` returns the command
body (whitespace-trimmed) or null. Only a LEADING `!` counts; `!`
alone / `! ` returns null; `echo !hi` doesn't trigger (the `!`
isn't at position 0).
- `formatBangUserMessage(cmd, output)` — prepends a `[!cmd]\n`
header so the model can distinguish user-typed shell output from
its own `run_command` tool results (which are `role: tool`,
structurally different).
- App.tsx handleSubmit intercept — fires AFTER the y/n fast-path (so
pending edits still resolve cleanly) and BEFORE slash parsing:
- Push `role: "user"` Historical row with the raw `!cmd` text.
- `await runCommand(cmd, { cwd: codeMode?.rootDir ?? cwd,
timeoutSec: 60, maxOutputChars: 32_000 })`.
- Push `role: "info"` Historical row with
`formatCommandResult(cmd, result)`.
- `loop.log.append({ role: "user", content: formatBangUserMessage
(cmd, formatted) })` so the next step() includes it in
buildMessages.
- setBusy true/false around the run so PromptInput reflects the
in-flight state.
- Catch errors → warning row, don't log.
### No allowlist gate
User-typed `!` is explicit consent (consistent with Claude Code; the
allowlist exists to bound what the MODEL can do with `run_command`,
not what the user chooses by hand). If someone wants stricter gating
later a `REASONIX_BANG_CONFIRM=1` toggle could layer on — out of
scope here.
### Known limitation: session durability
`loop.log.append` updates in-memory only. On session resume, the bang
output is gone (the session file didn't see it). The next actual
step() does appendAndPersist for the next user turn, and the model
sees this bang output live within the same session either way.
Treating bang as ephemeral keeps the fast-path simple; durable
capture could land later if real usage surfaces demand.
### /help + discovery
/help gains a "Shell shortcut" section documenting `!cmd` with
example commands (`!git status !ls src/ !npm test`), plus a
"File references" section covering the `@` picker from 0.5.5 / 0.5.7
that was undocumented there.
### Tests (+9, suite 897 → 906)
tests/bang.test.ts — detectBangCommand covers: body extraction,
whitespace trim, non-bang pass-through, `!`-alone / blank body,
mid-string `!` rejection, embedded-trailing-`!` preservation,
multi-word with flags/quotes. formatBangUserMessage covers header
prepending and verbatim body preservation.
Lint + typecheck + build clean. 906 tests, 8.6s.
Two shipped, both extending 0.5's foundation:
### 1. @mentions picker UI
0.5.5 shipped `@path/to/file` inline expansion but made the user type
the full path. 0.5.7 adds a picker that mirrors the existing
/slash autocomplete: type `@` (with optional partial) in code mode,
get a filtered file list with ↑/↓ navigation and Tab/Enter pick.
- `listFilesSync(root, opts)` — sync recursive walk, skips
node_modules / .git / dist / build / .next / etc. + any dot-dirs.
Caps at 500 results by default. Forward-slash paths on all
platforms. 10-50ms on moderate repos — fits the TUI's single-turn-
per-tick model cleanly.
- `detectAtPicker(input)` — returns `{query, atOffset}` when the
buffer ends with an in-progress mention; `null` otherwise. Distinct
from `AT_MENTION_PATTERN` which finds completed mentions anywhere
for expandAtMentions.
- `rankPickerCandidates(files, query, limit)` — case-insensitive
substring filter with a boost for basename-prefix matches. Empty
query returns the first `limit` candidates alpha.
- `AtMentionSuggestions.tsx` — same shape as `SlashSuggestions`
(matches null = hide, empty = "no matches", array = highlight
selected cyan/bold). Shows basename bold + dir dimmed à la
VS Code Quick Open.
- App.tsx wiring: `atFiles` memo (walk on rootDir change), `atPicker`
/ `atMatches` memos, `atSelected` state with useEffect clamp.
Arrow keys + Tab in useInput (before slash so they don't conflict
— mutually exclusive by construction). Enter in handleSubmit
substitutes at the `@` offset and appends a space (space auto-
dismisses the picker, next Enter submits).
- Limitation intentionally not fixed: files created mid-session by
edit tools won't appear in the picker until next launch. User can
always type the full path. Rebuilding the list on every turn would
be wasteful for the 95% case.
### 2. Bundle smoke test
v0.5.4 shipped to npm with a tokenizer path resolution bug that
crashed on first API call. The unit tests were fine — they load
modules from src/, which doesn't exercise the post-bundle directory
layout. These two tests close that gap:
- `dist/index.js`: dynamic import (via file:// URL on Windows),
invoke `truncateForModelByTokens` to force a tokenizer load. ENOENT
⇒ fail.
- `dist/cli/index.js`: spawn with `DEEPSEEK_BASE_URL=127.0.0.1:1` so
fetch fails fast. Preflight's tokenizer load runs BEFORE fetch, so
if the bundled layout can't find the data file we see the ENOENT
in stderr. If tokenizer loads fine, we see connection-refused and
the test passes.
- Both tests skip when the bundle is absent (dev runs that haven't
built yet). CI runs `build` before `test` → always exercised.
Would have caught 0.5.4's regression pre-publish.
### Tests (+23, suite 874 → 897)
- tests/at-mentions.test.ts — 7 new for detectAtPicker, 2 for
AT_PICKER_PREFIX vs AT_MENTION_PATTERN sanity, 6 for
rankPickerCandidates (empty query, substring, basename-prefix
boost, path-prefix, no-match, limit), 6 for listFilesSync (recurse,
forward slashes, ignore dirs, dotfile inclusion, custom ignores,
maxResults cap, unreadable root).
- tests/bundle-smoke.test.ts — 2 tests for lib + CLI bundle
tokenizer resolution.
Library exports: `detectAtPicker`, `listFilesSync`,
`rankPickerCandidates`, `AT_PICKER_PREFIX`, `DEFAULT_PICKER_IGNORE_DIRS`,
`ListFilesOptions`.
Lint + typecheck + build clean. 897 tests, 8.1s.
**Critical production bug.** Since 0.5.0 introduced the tokenizer, any
bundled `reasonix run` / `code` / `chat` crashed with ENOENT on the
first API turn after 0.5.4 put the tokenizer on the hot path.
Root cause: `resolveDataPath()` used
`join(dirname(import.meta.url), "..", "data", "deepseek-tokenizer.json.gz")`.
- In dev (`src/tokenizer.ts`) → resolves to `data/` ✓
- In the bundled CLI (`dist/cli/index.js`) → `dist/cli/` + `..` +
`data/` = `dist/data/` ✗ — the data file ships at PACKAGE ROOT per
package.json `files` entry; `dist/data/` doesn't exist.
Why this slipped through: before 0.5.4, `countTokens()` was only
called from the opt-in `/context` slash. Casual smoke tests and unit
tests (which run tokenizer.ts directly from src/) never hit the
bundled resolution. 0.5.4's preflight put `countTokens()` on every
step() call — so the first user-facing turn after `npm publish 0.5.4`
would have crashed.
Fix: `resolveDataPath()` now tries multiple candidate paths and
returns the first one that `existsSync`:
1. `REASONIX_TOKENIZER_PATH` env override (unchanged).
2. `../data/...` — dev + bundled `dist/index.js`.
3. `../../data/...` — bundled CLI at `dist/cli/index.js`.
4. `require.resolve("reasonix/package.json")` root — fallback for
unusual bundlers.
Also falls back to `process.cwd() + data/...` if all candidates
missed, so readFileSync surfaces a concrete path in the error rather
than silently missing.
Caught via live `DEEPSEEK_API_KEY=... node dist/cli/index.js run
"hi"` against the actual bundled output. Unit tests alone would not
have caught this (they load src/tokenizer.ts directly, bypassing
the bundle path). Follow-up consideration: an integration test that
runs the bundled CLI against a fake API response — out of scope here.
874 tests still pass. Lint + typecheck + build clean.
Two shipped in one release, both closing out the 0.5 arc:
### 1. Session-load heal migrated to tokens
0.5.2 and 0.5.3 made dispatch truncation, /compact, and auto-compact
token-aware. Session load was the last char-based truncation surface;
now closed. CJK tool results in a resumed session come back at the
same effective context footprint as English instead of slipping past
the old 32k-char cap at 2× the token cost.
- `healLoadedMessagesByTokens(messages, maxTokens)` — sibling of the
existing char-based `healLoadedMessages`.
- `fixToolCallPairing(messages)` — pure helper extracted so both
variants reuse the structural tool_calls ↔ tool pairing pass.
- Session-resume call in loop.ts constructor switched to the token
variant with `DEFAULT_MAX_RESULT_TOKENS`. Stderr "healed" line now
reads "shrunk N tokens of oversized tool output" instead of chars.
- buildMessages's per-turn heal (hot path) stays on the char variant
— avoids a per-turn tokenizer pass on every tool message.
### 2. `@file` mentions in code mode
User types `@src/loop.ts` → the model sees the file content inlined
under a "Referenced files" block:
look at @src/loop.ts and explain
[Referenced files]
<file path="src/loop.ts">
...
</file>
The user's original text is preserved verbatim; expansion is append-
only so the display stays clean and the model can cite the file
unambiguously.
- Regex `(?<=^|\s)@([a-zA-Z0-9_./\-]+)` — requires word boundary so
`[email protected]` and `foo@bar` don't trigger. Trailing sentence
period (`@foo.ts.`) is stripped before lookup.
- Sandbox: relative paths only, resolved against `rootDir`, no `..`
escape, no absolute paths. Violations get
`<file path="..." skipped="escape"/>` so the model sees the refusal.
- `DEFAULT_AT_MENTION_MAX_BYTES = 64 KB` (matches tool-result cap
ballpark). Larger → skipped="too-large" with byte count.
- Missing / not-a-regular-file → skipped with reason.
- De-dupe: same file referenced twice inlines once.
- UI feedback: an info row lists inlined/skipped files so the user
sees what reached the model.
- Only active in code mode (codeMode.rootDir). Plain chat mode
doesn't expand — file references there are ambiguous.
### Tests (+15, suite 859 → 874)
- tests/at-mentions.test.ts — regex: boundary matching, email
rejection, multi-mention; expansion: inline content, de-dupe,
multiple distinct files, missing/escape/absolute/too-large skips,
trailing-dot stripping, directory rejection.
Library exports: `expandAtMentions`, `AT_MENTION_PATTERN`,
`DEFAULT_AT_MENTION_MAX_BYTES`, `AtMentionExpansion`,
`AtMentionOptions`. Plus `healLoadedMessagesByTokens` and
`fixToolCallPairing` from loop.ts.
Lint + typecheck + build clean. 874 tests, 5.2s.
Reactive auto-compact (60%/80% on prior prompt_tokens) keys off the
PREVIOUS turn's server usage, so a fresh resumed session — or one new
oversized tool result — can push the current turn's buildMessages
straight past 131,072 tokens and make DeepSeek 400 with "maximum
context length" before we see any usage number. Preflight closes that
hole by estimating locally before sending.
Mechanism:
- `estimateRequestTokens(messages, toolSpecs)` in src/tokenizer.ts:
`estimateConversationTokens(messages) + countTokens(JSON.stringify
(toolSpecs))`. Mirrors the arithmetic `/context` slash already uses
so the two numbers don't drift.
- loop.step() injection right after buildMessages(). If the estimate
exceeds 95% of `DEEPSEEK_CONTEXT_TOKENS[model]` (fallback
`DEFAULT_CONTEXT_TOKENS`), run `compact(1_000)` and rebuild
messages from the shrunk log. Warning event names the preflight
path + tokens saved.
- When there's nothing to compact (first-ever turn with a bulky
system prompt, for example), still yield a warning naming the
preflight estimate + "nothing to auto-compact — DeepSeek will likely
400". User sees the reason before the crash, can /forget or /clear.
We don't short-circuit the request — let DeepSeek decide; its 400
catch path already surfaces a useful hint.
- Non-branching AND branching paths share the `messages` variable
from the outer buildMessages call, so the one injection covers
both. Forced-summary fallback keeps its own path (a preflight
there would be too late; the summary is the recovery step).
Tests (+3, suite 856 → 859) in tests/preflight.test.ts:
- Fires when estimate > 95%: compact runs, "pre-compacted N tool
result(s), saved M tokens" warning appears, loop still completes.
- Stays silent when estimate is comfortably under 95%.
- Warns (but does not block) when over 95% with nothing to compact.
Per-test context budgets are set by mutating `DEEPSEEK_CONTEXT_TOKENS
[TEST_MODEL]` — the table is `Record<string, number>` so the write
is well-typed; teardown deletes the key. Seeded tool results are
properly paired with a prior assistant.tool_calls so
healLoadedMessages doesn't strip them as orphans (which would make
preflight never fire).
Lint + typecheck + build clean. 859 tests, 5.0s.
0.5.2 put the DeepSeek V3 tokenizer on the dispatch hot path to cap
NEW tool results by real tokens. 0.5.3 extends that to the live log:
/compact and auto-compact now shrink existing tool results by tokens
too, closing the last surface where CJK text slipped past a char cap
at 2× the intended context cost.
Mechanism:
- `shrinkOversizedToolResultsByTokens(messages, maxTokens)` in
src/loop.ts — sibling of the char-based `shrinkOversizedToolResults`.
Fast-pathes tool entries whose length ≤ cap (tokens ≤ length
guarantee); otherwise tokenizes each candidate twice (before +
after `truncateForModelByTokens`) to report exact tokensSaved.
Never tokenizes the full input (same 0.5.2 guard against BPE
O(n²) on pathological repetitive content).
- `loop.compact(maxTokens = 4000)` now shrinks by tokens and returns
`{ healedCount, tokensSaved, charsSaved }` (was `{ healedCount,
charsSaved }`). Persists to the session file when present.
- Auto-compact thresholds in `step()`:
· 60%-80% band: soft compact at 4000 tokens/result (was 16k chars,
which was 4k tokens in English but 16k tokens in CJK).
· >80% band: hard compact at 1000 tokens/result (was 4k chars).
Warnings report exact tokensSaved instead of `charsSaved / 4`.
- `/compact [N]` slash cap semantic flipped from chars to tokens
(default 4000). The `info` line now reads "saved N tokens
(M chars)". Help text + suggestion hint updated.
- Session-load heal (`healLoadedMessages`) left on the char cap so
stored session files keep loading under their existing semantics.
Live compaction and dispatch-time truncation are the only two
surfaces that went token-aware.
Tests (+6, suite 850 → 856):
- tests/compact-tokens.test.ts — small-tool no-op, oversize shrink,
input non-mutation, user/assistant protection, CJK parity, fast
path by length.
- tests/loop.test.ts — seeded log content in the two auto-compact
tests reshaped from `"Z".repeat(N)` to realistic log lines (was
hitting BPE pathological path; also the 60%-80% warning now
reads "4k tokens" instead of "16k" chars).
- tests/slash.test.ts — /compact assertions updated for token-based
output ("saved N tokens", "N tokens each"); test content reshaped
to realistic log lines.
Breaking change: library callers that pass an explicit number to
`loop.compact(N)` expecting chars will now get a tighter cap (4000
tokens ≈ 16k chars English, ~4k chars CJK). Fail mode is "compaction
is more aggressive than expected," which is the safe direction.
Lint + typecheck + build clean. 856 tests, 5.1s.
Before: every tool result was char-capped at 32K chars (8K English
tokens, but 16K+ tokens for CJK — Chinese/Japanese/Korean tool output
slipped past the budget at 2× the intended context cost).
After: dispatch truncates by REAL DeepSeek V3 tokens, using the
tokenizer that shipped in 0.5.0. Default 8K tokens per result, same
effective footprint regardless of char density.
Mechanism (src/mcp/registry.ts:truncateForModelByTokens):
- Fast path `s.length <= maxTokens` — every token is ≥1 char, so
length bounds tokens. Skip tokenize entirely for small results.
- Intermediate check for moderate strings (`length <= maxTokens * 4`)
— tokenize once to confirm it really is over budget.
- For large strings: char-slice head + tail by budget, tokenize the
slices (NOT the full input), shrink on overshoot. 1–2 iterations per
slice, bounded at 6. We explicitly never tokenize the whole input —
pathological repetitive content (`"A".repeat(50_000)`) costs 30s+
in the pure-TS BPE and is bounded to small slices.
- Dropped-tokens count in the marker is estimated from the per-slice
char/token ratio (marker reads "~N tokens") so we don't pay a full
tokenize just for diagnostics.
Wire-up:
- src/tools.ts — `ToolRegistry.dispatch` accepts both `maxResultChars`
(legacy) and `maxResultTokens` (new). Both apply if both set; the
tighter one wins. Char-only callers keep their old behavior.
- src/loop.ts — hot-path dispatch switched from
`maxResultChars: 32_000` to `maxResultTokens: DEFAULT_MAX_RESULT_TOKENS`
(8_000). Session-healing paths still use chars (preserves backwards
compat on loaded session files).
- `DEFAULT_MAX_RESULT_TOKENS` and `truncateForModelByTokens` exported
via src/index.ts for library consumers.
Tests (+9, suite 841 → 850):
- tests/truncate-tokens.test.ts — fast-path, short-string verify,
CJK cap parity with English, head+tail preservation, zero-budget,
empty input, marker format.
- tests/loop.test.ts — existing "pre-clips at dispatch" test reshaped
to use realistic log-line content (was `"A".repeat(50_000)` which
hit the BPE O(n²) pathological path, 46s+ in the suite).
Lint + typecheck clean. Suite now 5.2s total.
Before: model writes `dir | findstr foo` → tokenizer produced `["dir",
"/b", "|", "findstr", "foo"]` → quoteForCmdExe wrapped `|` as `"|"`
(literal) → cmd.exe passed `|` as an argument to dir → no pipe, no
error, silent wrong output. The 0.4.26 memory flagged this as a known
issue; encoding fix from that release made the failure visible but
didn't address the root confusion.
After: detectShellOperator() walks the raw command with quote-tracking
and returns the first unquoted operator token at a token boundary.
runCommand rejects before spawn with:
run_command: shell operator "|" is not supported — this tool spawns
one process, no shell expansion. Split into separate run_command
calls and combine the output in your reasoning...
Quoted operators (`grep "a|b" file.txt`) and chars embedded in larger
tokens (`--flag=1&2`) pass through — those are literal argv bytes.
Matches the tool's stated "no shell expansion, no pipes, no redirects"
contract; turns the silent failure into a loud, actionable one.
Tool description updated to document the rejection + the quote-it-as-
a-literal workaround so the model learns the constraint from the spec.
Tests: 841 (+13 covering pipe, redirect, fd-redirect, &&/||, stuck-
redirect, quoted operators, embedded operators).
CI fix — biome lint surfaced 9 errors on the 0.5.0 commit:
- tokenizer.ts: Infinity → Number.POSITIVE_INFINITY (style/useNumberNamespace)
- tokenizer.ts: formatter wrap on the CJS fallback branch
- StatsPanel.tsx: noArrayIndexKey on the Wordmark map — restructured to a
module-level WORDMARK_STYLES table keyed by char+color pair, dropped
the `i` parameter entirely (previous biome-ignore comment only
suppressed one of two sites the rule fires on)
- various whitespace / line-wrap fixes from `biome check --write`
Animated SVG logo at docs/logo.svg, embedded at the top of README:
- Concentric diamond brand mark (◈) with three layers of motion:
slow rotation (18s), outer-stroke pulse (2.4s), inner-fill breathing
- REASONIX wordmark in the same cyan → fuchsia gradient the TUI uses,
so the README and the running app share one visual identity
- Tagline underneath for SEO-style context
- Colors (~4.5:1 contrast on both GitHub dark and light) — no
prefers-color-scheme switching needed
828 tests, lint + typecheck clean.
Visual redesign — drop the generic vertical bars for a Reasonix-native
design language. The UI should be recognizable as ours at a glance:
- ◈ REASONIX wordmark in truecolor gradient (cyan → violet), with
breathing animation — slow when idle, faster when the model is
thinking, so the app's state is readable from the edge of vision.
- Geometric role glyphs replace all text labels: ◇ user · ◆ assistant ·
▣ tool · ▥ tool-err · ▲ warn · ✦ error. Consistent geometric family,
distinct per role, no overlap with Claude / Cursor / Cline.
- Streaming assistant glyph pulses ◆↔◇ at ~480ms — visible heartbeat
during R1's long (20-90s) pre-first-byte silence.
- Turn separators render "─── ◆ ───" with the Reasonix mark centered.
- Responsive StatsPanel: stacks metrics vertically on <120-col
terminals (SSH, split-pane); inline when there's room. Context
cell gains a 10-cell progress bar in the stacked layout.
- Cold-start cache hit ratio (turn ≤ 3) renders dim gray with a
"(cold start)" hint instead of red — new users stopped reading
"0% cache on turn 1" as a configuration error.
- Tool results tail-truncate by default (useful signal is usually at
the end). ERROR-prefixed results keep the first line + a tail.
- Modal footers gain "[↑↓] navigate · [Enter] select · [Esc] cancel"
hints; Esc actually cancels now (ShellConfirm → deny, PlanConfirm →
cancel); SingleSelect gained an optional footer slot.
- Wait-phase messaging (pre-first-byte, R1 reasoning, branching,
tool-call streaming) gets visible yellow italic instead of dim —
users had been misreading the dim variant as "frozen".
New features:
- Pure-TS port of DeepSeek's V3 tokenizer (vocab + merges + pre_tokenizer
from the official tokenizer.json). Bundled as data/deepseek-
tokenizer.json.gz (1.74MB, slimmed + gzipped from 7.5MB). Zero new
deps — uses built-in zlib. Encodes ~12k tokens of mixed source in
~40ms. scripts/prepare-tokenizer.ts regenerates the bundle from
upstream.
- /context slash — renders a breakdown of the next request's tokens:
system prompt, tool specs, per-turn log, top 5 heaviest tool results.
Answers "where is my context going?" directly; closes the gap where
StatsPanel showed ctx % without saying why.
- /models slash — fetches DeepSeek's live model catalog via
GET /models. Renders the list with the current model marked.
- /model <id> now soft-validates against the fetched catalog (warn
but still switch — accommodates newly-released models we haven't
indexed). DeepSeekClient gains a listModels() method.
Loop + billing correctness:
- Tool results pre-clipped at dispatch time (default 32k chars) via
ToolRegistry.dispatch({ maxResultChars }). Oversized results no
longer bloat the AppendOnlyLog or the persisted session file.
- New proactive-compact tier: when promptTokens / ctxMax crosses 60%
(before the existing 80% reactive guard), shrink oversized tool
results to 16k chars. Catches slow-growth patterns before they
compound into a forced summary.
- DEEPSEEK_PRICING updated to the current unified rates (¥0.2 / ¥2 /
¥3 per 1M at cache-hit / cache-miss / output; USD 0.028 / 0.28 /
0.42 at 7.2 CNY/USD). chat and reasoner are now priced identically
at source. Stats dashboard figures were systematically high under
the old tiered constants — new sessions bill correctly.
- Context display switches to binary-K (128K) to match DeepSeek's
marketing label. DEEPSEEK_CONTEXT_TOKENS stays at 131072 — only
the formatter divisor changed.
OSC 8 clickable hyperlinks in markdown were attempted and reverted:
Ink 5 strips \x1b / \x07 from Text output, so file:// links never
reach the terminal. Documented as a known limit; re-visit with a
future Ink release or raw-stdout approach.
828 tests (14 new: tokenizer golden cases + /context + /models +
listModels + pricing unification + proactive compact). Lint +
typecheck + build clean.
Pillar 2 harvesting fires an extra V3 call per turn to extract a typed
plan state (subgoals/hypotheses/uncertainties/rejectedPaths) from R1's
reasoning_content. Cost ~10-15% per turn. Closer audit of who actually
consumes the output:
- subgoals / hypotheses / rejectedPaths — purely cosmetic, only rendered
in PlanStateBlock. No programmatic consumer. Can mislead users by
giving structured-looking output extra perceived authority (today's
citation work was triggered by hallucinated "hypotheses" that looked
thoughtful).
- uncertainties.length — single real downstream use, drives self-
consistency branching when count exceeds threshold. Could be replaced
with a cheap heuristic on the raw reasoning text.
For coding tasks specifically, branching is rarely on (default budget=1)
and the cosmetic display value doesn't justify the per-turn premium.
Flip the default off; users who genuinely want the plan state surfaced
can pass --harvest. `reasonix chat` is unchanged — preset behaviour
there still controls harvest.
799 tests, lint + build clean.
Anti-hallucination intervention for evaluative tasks. Two real R1 sessions
where the model invented "Resources/Prompts/Progress not implemented" gaps
that had been shipped months ago (v0.4.5, v0.4.8) motivated this — same
hallucination shape both times, across independent prefixes. The fix is
structural: force the model to ground every codebase claim in a clickable
citation, validate them, render broken ones in red so the user sees
fabrications instantly.
- markdown.tsx: parse [text](url) links (was unsupported — rendered as
literal). External URLs (https://, mailto:, //) → blue underline.
Citation-shaped URLs (path / path:line / path:start-end / path#L42) →
validated against projectRoot, valid = cyan underline, broken = red
strikethrough + ❌. Bottom-of-message BrokenCitationsBlock lists each
failure with reason ("file not found", "line 999 > 250") so the user
can challenge the specific claim.
- code/prompt.ts + cli/index.ts: "Cite or shut up — non-negotiable"
section moved to TOP of system prompt (was at the end and ignored).
Concrete ✅/❌ examples. Negative-claim rule made imperative — "STOP.
Call search_content FIRST" instead of "qualify it" — because asserting
absence without checking is the #1 failure mode.
- App.tsx / EventLog.tsx / PlanConfirm.tsx: thread projectRoot through
every <Markdown /> callsite (defaults to process.cwd() for safety).
Behavioural validation: same "analyze the project" prompt that produced
5/8 hallucinations pre-fix returned 3/3 verifiable specific claims +
1 auto-detected broken citation post-fix. Citation feature working in
production.
799 tests (17 new in markdown.test.ts: parseCitationUrl, isExternalUrl,
validateCitation, collectCitations dedup + external skip, parseBlocks
no-regression). Lint + typecheck + build clean.
- Subagents-via-Skills (replaces 0.4.25's spawn_subagent user-facing
surface; library API kept). Skills frontmatter gains runAs:subagent +
optional model:deepseek-*. Builtin explore + research skills ship in
src/skills.ts as constants. spawnSubagent(opts) extracted from
registerSubagentTool — both surfaces share it via formatSubagentResult.
registerSkillTools moved into App.tsx with subagentRunner closure;
reasonix code no longer registers spawn_subagent in the model tool list.
Pinned Skills index marks subagent skills with a 🧬 prefix so the model
pattern-matches "user says explore -> use 🧬 explore" instead of
reasoning about whether a task is "big enough" to delegate.
- search_content: real content grep tool. Skips 18 dependency / build /
VCS dirs by default + skips binaries by extension (30+ types) and
by content sniff (NUL byte in first 8KB). Per-file 2 MB cap, output
capped to maxListBytes. Regex + literal fallback, glob substring
filter, case_sensitive + include_deps options. Closes the gap that
made subagents waste their iter budget calling search_files (which
is filename-only) for content-grep questions.
- markdown renderer: recognizes Unicode box-drawing tables (│ ─ ┼) +
┌─┐ │ └─┘ frames as code blocks. Table cells now render through
InlineMd with padTo so backticks/bold inside cells parse and column
widths align by visible (post-strip) width. Multi-line table cell
continuation rows fold back into the previous row's last cell.
- shell on Windows: prepareSpawn injects chcp 65001 prefix into every
cmd.exe /c payload + injects [Console]::OutputEncoding=UTF8 into
PowerShell -Command invocations. Fixes mojibake on CJK Windows where
cmd builtins (dir, findstr, where) and PowerShell emit text in CP936
/ CP932 / CP949 — previously poisoned the next turn's prompt with
garbled bytes.
- sandbox: filesystem tools' safePath strips leading / and \ so
POSIX-absolute paths (path: "/" or "/src/foo.ts") resolve to the
sandbox root instead of the actual filesystem root. Models routinely
pass these intending the project root; the old behavior failed the
escape check with a confusing error.
- loop: aborted signal in the API-call catch yields a clean done
instead of a red error event. The "This operation was aborted" row
was always a self-inflicted UX bug — App.tsx calls loop.abort() to
switch turns when the user picks ShellConfirm "always allow" or
PlanConfirm approve, and the resulting AbortError got rendered as
a real error. Subagent layer compensates by synthesizing an error
result when no final answer was produced (so success!=true on abort).
- prompts: dropped the fictional `grep` tool reference from
CODE_SYSTEM_PROMPT; explicit list of available exploration tools
(read_file, list_directory, directory_tree, search_files,
search_content, get_file_info). New "Path conventions" section
distinguishes filesystem-tool sandbox-relative paths from
run_command OS-shell paths (don't use leading / in shell args).
781 tests (+26 vs 0.4.24), lint + typecheck + build clean.
Every turn run through `reasonix chat|code|run` now appends one line
to ~/.reasonix/usage.jsonl carrying tokens + cost + the equivalent
Claude Sonnet 4.6 cost. `reasonix stats` (no arg) rolls that log up
into today / week / month / all-time windows with a "saved vs
Claude" column. Pillar 1's pitch (94–97% cost reduction) becomes a
fact users can check on their own machine.
Same dashboard is available in-session via the new /stats slash,
reading from the same file and rendering through a shared pure
renderer. reasonix stats <transcript> keeps the old per-file
summary (assistant turns + tool calls) for scripts.
Privacy: only tokens, costs, session name. No prompts, completions,
or tool args. Log append is best-effort — disk failure never blocks
a turn.
New files:
src/usage.ts — appendUsage, readUsageLog, aggregateUsage,
bucketCacheHitRatio / SavingsFraction
tests/usage.test.ts — 15 tests (round-trip, malformed line,
rolling windows, renderer, zero denom)
Modified:
src/cli/commands/stats.ts — dashboard mode + extracted renderDashboard
src/cli/commands/run.ts — appendUsage on assistant_final (for CI)
src/cli/ui/App.tsx — appendUsage on assistant_final (TUI)
src/cli/ui/slash.ts — /stats slash (shared renderer)
src/cli/index.ts — `stats <transcript>` → `stats [transcript]`
src/index.ts — re-export usage module
+17 tests (suite 708 → 725). Lint + typecheck + build clean.
Adds an in-session `/update` slash that reports the running version
and the last-resolved latest from the App's background npm-registry
check. Deliberately does NOT spawn `npm install` — stdio:inherit
into a running Ink renderer corrupts the display, and on Windows
the currently-running binary can be locked. Users exit and run
`reasonix update` in a fresh shell when they actually want to
install.
Also splits App state: we now track `latestVersion` regardless of
whether it's newer (so the slash can tell "on the latest" apart
from "still fetching") and derive the yellow header badge from
that. Before this, `updateAvailable` was only set on strictly-
newer, so `/update` saw null when the user was already on the
latest — the message misleadingly said "background check in
flight or offline".
`/update` also triggers a fresh `getLatestVersion({force:true})`
when latestVersion is null, so a retry a few seconds later sees
a concrete answer.
4 new tests (suite 704 → 708). All green; lint / typecheck / build
clean.
Same two-scope layout as memory and skills:
- <project>/.reasonix/settings.json (committable per-project)
- ~/.reasonix/settings.json (per-user)
A hook is a shell command. Reasonix invokes it with stdin = a JSON
envelope carrying the event, tool name, tool args, etc. Exit code
drives the decision:
- 0 = pass; loop continues normally
- 2 = block (only on PreToolUse / UserPromptSubmit); hook's stderr
becomes the synthetic tool result the model sees, or the prompt
is dropped entirely
- anything else = warn; loop continues, stderr renders inline as a
yellow row
Project hooks fire before global hooks. `match` is anchored regex on
the tool name (ignored for prompt / Stop events). Default timeouts:
5s for blocking events, 30s for logging events; per-hook `timeout`
overrides. Settings malformed? loadHooks swallows it so a typo
doesn't bring down the whole CLI.
Deliberate non-goals: no workflow DSL, no conditional chaining, no
hook templates. Hooks are shell commands — the user already has a
programming language.
New files:
- src/hooks.ts (loadHooks, runHooks, decideOutcome, matchesTool, formatHookOutcomeMessage)
- tests/hooks.test.ts (26 unit tests)
- tests/loop-hooks.test.ts (6 smoke tests — loop wiring)
Modified:
- src/loop.ts — PreToolUse + PostToolUse dispatch around tool.dispatch
- src/cli/ui/App.tsx — load settings on mount, UserPromptSubmit before handleSubmit, Stop after loop.step
- src/cli/ui/slash.ts — /hooks list + /hooks reload
- src/index.ts — re-exports
+32 tests (suite 672 → 704). Lint / typecheck / build clean.
Two small quality-of-life additions.
The stats panel now carries the running version (`Reasonix v0.4.22 ·
model …`) so users can tell at a glance whether they're on the latest
build. A 24-hour background check against the npm registry surfaces a
yellow `update: X.Y.Z` nudge on the right side of the same row when a
newer version has been published — 2s timeout, cache at
`~/.reasonix/version-cache.json`, silent on failure.
`reasonix update` is the command form: detects global install vs npx,
spawns `npm install -g reasonix@latest` for the former or prints a
cache-refresh hint for the latter. `--dry-run` prints the plan.
Also fixes a drifted VERSION constant: `src/index.ts` hard-coded
"0.4.20" while package.json was on 0.4.21. Now re-exports from
`src/version.ts`, which walks up from import.meta.url to the
manifest on first access. A regression test pins them together.
New files: `src/version.ts`, `src/cli/commands/update.ts`,
`tests/version.test.ts`, `tests/update-command.test.ts`. +24 tests
(suite 648 → 672). Lint/typecheck/build clean.
- Quick start now leads with `reasonix code` and a real SEARCH/REPLACE
walkthrough — nobody enters through plain chat.
- New Skills section covers the SKILL.md format, project vs global
scopes, /skill slash family, autonomous run_skill invocation, and
the 'not tied to .claude/' stance.
- chat mode demoted to a brief 'also works as' section pointing at MCP.
- Commands table grouped by category (Core / Model / Context & tools /
Memory & skills / Sessions / Code-mode only) instead of one flat list.
- Benchmarks promoted into their own 'verify yourself' section.
- Non-goals now names workflow DSL / DAG engine and DeepSeek-only
positioning explicitly.
- Test count 444 → 648, Node requirement 18 → 20.10, added
REASONIX_UI=plain to the env-var list.
Skills are user-authored prompt packs read from `<project>/.reasonix/skills/`
and `~/.reasonix/skills/`. Pinned index (names + one-liners) lives in
the immutable prefix; bodies load lazily via the new `run_skill` tool
or `/skill <name> [args]`. Project scope wins on name collisions.
Deliberately NOT tied to any other client's dir (.claude/, .glm/) —
Reasonix is model-agnostic at the conversation layer.
No workflow DSL or DAG engine: skills are prose, the model sequences
via the existing tool-use loop. Preserves single-loop + append-only +
cache-first invariants; "no multi-agent orchestration" non-goal stands.
Shell fixes bundled in:
- ShellConfirm "always allow" now takes effect mid-session.
extraAllowed is re-read on every dispatch via a getter, so a prefix
saved to ~/.reasonix/config.json applies to the running tool
without needing /new or a relaunch.
- Windows cmd.exe built-ins (dir, echo, type, ver, ...) no longer
crash with ENOENT. prepareSpawn routes bare unresolved Windows
commands through `cmd.exe /d /s /c` with verbatim-args quoting,
matching the wrapping strategy for .cmd/.bat files.
- MemoryStore + applyUserMemory + applyMemoryStack (src/user-memory.ts):
two scopes — global (cross-project) and project (per sandbox-root sha1).
Each scope keeps a MEMORY.md index pinned into ImmutablePrefix.system;
detail files loaded on demand via recall_memory. Byte-stable rewrite
so identical file sets produce identical prefix hashes.
- remember / forget / recall_memory tools (src/tools/memory.ts) — chat
mode gets global-only; reasonix code gets both scopes. remember's
return text is imperative so R1 treats the fact as authoritative on
the same turn.
- /memory slash extended: list | show <name> | forget <name> |
clear <scope> confirm. Bare /memory renders REASONIX.md + both
MEMORY.md blocks together.
- Prompt cleanup: dropped hardcoded dir enumerations, bun/npm examples,
"待确认" CJK fallback, DSML-hallucination historical note, and
Linear/Slack type-hint specifics. Principle-only wording + reference
to the pinned .gitignore block. Net -tokens on every turn.
- README: new "User memory" subsection under REASONIX.md.
- scripts/smoke-memory.mts: 30-assertion end-to-end regression script.
- REASONIX_MEMORY=off now disables every memory source (REASONIX.md +
user memory) — previous semantics was REASONIX.md only.
Tests: 542 → 624 (+82 incl. 36 memory-layer unit tests). Lint / tsc /
build clean.
CI runs on Linux, where pathMod.join defaults to POSIX (`/`). The
PATHEXT resolver mocks its isFile predicate with back-slashed keys
(`C:\tools\npm.CMD`), so join with POSIX produced `C:\tools/npm.CMD`
and lookups missed, failing 8 tests at origin. The runtime call path
is unaffected either way since the win32 branch is only active when
platform === "win32" anyway — but making the join explicitly win32
also hardens against weird PATHs on Windows where forward slashes
have historically crept in.
A silent storm-break was indistinguishable from a stalled turn — the
model would look like it gave up when really we'd suppressed its
repeat tool call. Now `step()` emits a dedicated warning event when
`report.stormsBroken > 0`, with distinct messages for the two cases:
- All calls suppressed (stuck retry): tell the user the model is
looping on the same (tool, args) and point them at /retry or
rewording the instruction. This is the case that used to dead-end
the turn with nothing on screen.
- Some calls suppressed (one redundant): the rest of the turn
proceeds; the warning is informational.
Also reset the StormBreaker's sliding window at the top of every
`step()` so a new user message doesn't inherit last turn's repeat
patterns (false-positive blocks on legitimate "try again" flows).
Part of the 0.4.19 batch — tag will be moved to this commit.
Two layered fixes so `run_command` actually runs npm/npx/tsc/yarn/
pnpm/bun/pytest and every other Node-ecosystem wrapper on Windows:
1. resolveExecutable() walks PATH × PATHEXT manually — spawn
with shell:false uses CreateProcess, which ignores PATHEXT, so
bare `npm` missed `npm.cmd` and ENOENT'd.
2. prepareSpawn() wraps .cmd/.bat via `cmd.exe /d /s /c` with
windowsVerbatimArguments + per-arg quoteForCmdExe — Node 21.7.3+/
24 (CVE-2024-27980) refuses direct spawn of .cmd/.bat even with
shell:false, throwing EINVAL. cmd.exe wrapping with manual
safe-quoting keeps shell metacharacters (&, |, <, >, etc.) in
arguments literal so the previous security posture holds.
Unix path unchanged. Suite 566 → 587.
submit_plan tool: model proposes a markdown plan for large tasks
(multi-file refactors, ambiguous requests, risky changes). Picker
shows Approve / Refine / Cancel with the plan rendered as live
Markdown, not raw text. Open-questions sections ("Open questions",
"待确认", "Risks", etc.) are detected; default selection flips to
Refine and a yellow hint surfaces.
Both Approve and Refine take an inline text input afterward so the
user can answer the model's open questions or attach last-minute
instructions before the loop resumes. Empty Enter on Approve skips
the extras; empty Enter on Refine tells the model to ask concrete
clarifying questions.
/plan slash flips a dispatch-level read-only gate on the
ToolRegistry — writes + non-allowlisted shell bounce with a refusal
the model reads. Read tools, web_search/fetch, and allowlisted shell
(git status / cargo check / npm test etc.) still work during
exploration. Tool specs stay pinned across the toggle so the DeepSeek
prefix cache doesn't break.
/apply-plan is a fallback that force-approves without the picker,
for cases where the model wrote the plan in assistant text instead
of calling submit_plan.
Suite 542 → 566.
Drop a REASONIX.md in the project root and its contents are pinned
into the system prompt every session that opens there. Cache-first:
read once, hashed into the prefix fingerprint, no per-turn budget.
/memory prints what's currently pinned; REASONIX_MEMORY=off opts out.
Suite 517 → 542. Re-exported applyProjectMemory / readProjectMemory /
memoryEnabled + PROJECT_MEMORY_FILE / PROJECT_MEMORY_MAX_CHARS for
library consumers that build their own system prompt.
Two DeepSeek 400s users hit in succession:
- "insufficient tool messages following tool_calls" on forced
summary: context-guard appended assistant.tool_calls then bailed
before dispatching. Fix: strip the tail before forceSummary.
- "tool must be a response to a preceding tool_calls" on the next
message: partial heals left stray tool messages in the log.
Root fix: healLoadedMessages now runs a full tool_calls↔tool pairing
validator. Any assistant.tool_calls with an incomplete response set
is dropped (with its partial responses); any stray tool message is
dropped. Runs on session load (rewrites the file so damage doesn't
re-surface) AND on every buildMessages call (defensive).
Context-guard now auto-compacts before forcing summary. Previously
80% context meant you lost a turn immediately. Now: try shrinking
oversized tool payloads first; only fall back to forced summary
when nothing's compactable.
Split shrinkOversizedToolResults from healLoadedMessages so
`/compact` (mid-turn) doesn't strip legitimate structural state.
443 tests (+5 new, 4 reshaped).
edit_file now produces a real git-diff-style output:
- LCS line-level diff (unchanged lines as ` ` context, `-/+` only
for actual changes). Fixes the user-reported case where a one-line
search with a multi-line replace showed the unchanged line as both
`-` and `+`.
- Git-style @@ -start,count +start,count @@ hunk header pointing at
the real starting line in the file.
- EventLog no longer truncates edit_file results — other tools keep
the 400-char clip, but edit diffs always show full.
Context management:
- /new (alias /reset) drops the in-memory log AND empties the
session file. Fresh conversation, same session/model/config.
- /clear now advertises that it only clears visible scrollback;
users kept expecting it to clear context. Info line points at
/new for the real clear.
- CacheFirstLoop.clearLog() is the public API.
Streaming row:
- Replaced "streaming · 391 + think 4506 chars" with explicit
phase labels: yellow "request sent · waiting for server" pre-
first-byte, cyan "R1 reasoning · N chars of thought" during
reasoning-only, green "writing response · N chars · after M
chars of reasoning" in content phase.
436 tests (+8).
Major batch of UX fixes based on user reports:
Silent-wait elimination:
- New "status" loop event + StatusRow component. Fills silent
phases with explicit magenta spinner text: "tool result uploaded
· model thinking before next response…" between iters,
"extracting plan state from reasoning…" before harvest,
"summarizing what was gathered…" before forced summary. Auto-
clears on the next primary event.
- Belt-and-suspenders "processing…" fallback when busy but none of
streaming/ongoingTool/statusLine is visible — catches any
micro-gap the targeted statuses don't cover.
- Strengthened pre-first-byte messaging: "(request sent · waiting
for server)" instead of "(streaming · 0 chars)".
Stats panel:
- Live per-iter refresh — previously frozen at prior turn's
numbers for 30-60s during multi-iter chains.
- Account balance cell. New DeepSeekClient.getBalance() hits
/user/balance (separate endpoint, no billing impact). Refreshed
after each turn, hidden on failure.
- In/out cost split. Panel now shows "cost $X (in $Y · out $Z)"
so users can see where spend lands. SessionSummary gains
totalInputCostUsd + totalOutputCostUsd; inputCostUsd() and
outputCostUsd() exposed as library utilities.
- Dropped "vs Claude / saving" cells — the synthetic ratio looked
like marketing, not measurement. Fields kept in summary for
benchmark/replay compat but deprecated.
Esc coverage:
- harvest() now takes an AbortSignal and fast-paths to emptyPlanState
when already aborted. Was the last un-signaled API call path.
edit_file visibility:
- Tool result now returns a unified-style `- search / + replace`
inline diff in addition to the header. Long blocks are truncated
with "… (N more lines)" marker in the middle; /tool N still shows
the full thing.
Markdown:
- GFM tables (|col|col| + separator) render as aligned columns
with │ dividers. CJK-width-aware padding for mixed-lang tables.
Alignment colons, pipe-less headers, escaped \| in cells all
handled. Stray | in prose no longer false-triggers the table
path.
427 tests (+11).
Three reported issues rolled into one release:
1. Esc now truly cancels in-flight work. AbortController threaded
through every I/O path:
- DeepSeekClient.chat/.stream signal wired at every call site
- ToolRegistry.dispatch gets a ToolCallContext { signal }
- McpClient.callTool({ signal }) fires notifications/cancelled
AND rejects the pending promise immediately — no waiting on
subprocess for a graceful finish
- bridgeMcpTools forwards ctx.signal down
2. Built-in filesystem tools replace the
@modelcontextprotocol/server-filesystem subprocess inside
`reasonix code`. 10 native tools, sandboxed, R1-friendly schemas.
The new edit_file takes a flat SEARCH/REPLACE shape instead of
the JSON-in-string array that was the single biggest driver of
R1 DSML hallucinations in 0.4.x. Per-call latency drops from
~500ms–2s (Windows subprocess IPC) to <10ms (direct fs).
3. PromptInput placeholder cursor now renders at position 0
(before the hint text), not after it.
4. Bonus: slow_count demo tool in examples/mcp-server-demo.ts
emits real notifications/progress frames so the progress-bar
plumbing from 0.4.8 is testable end-to-end.
ChatOptions grows `seedTools: ToolRegistry` so callers can
pre-register tools and still layer MCP on top. ToolCallContext
is re-exported for library users writing abortable tools.
416 tests (+29: filesystem-tools +26, mcp abort +3).
MCP notifications/progress now route to per-call onProgress handlers.
Long-running tool calls can stream incremental progress; the spinner
row renders an ASCII bar + n/total + pct when the server reports a
total, or free-form progress+message otherwise.
- McpClient.callTool(name, args, { onProgress }) mints a fresh
_meta.progressToken and routes progress frames back. Handler is
dropped on completion — late frames are swallowed silently.
- bridgeMcpTools({ onProgress }) pipes per-call progress through
with the registered (prefix-applied) tool name.
- chatCommand creates a shared progressSink ref; App.tsx wires its
setState handler through on mount.
Other server-initiated notifications (list_changed) still dropped
— no use case yet.
387 tests (+5).
Replaces ink-text-input in the main chat prompt with a custom
multi-line composer. Three newline-insertion paths in reliability
order: Ctrl+J (universal), Shift+Enter (modern terminals), trailing
"\" + Enter (portable fallback). Pasted multi-line content lands
intact instead of submitting on the first '\r'.
Pure processMultilineKey reducer keeps the keyboard semantics
testable; the React component is a thin wrapper. Parent-owned keys
(Tab, arrows, Esc) are no-ops in the reducer so the buffer never
eats a stray control sequence when both useInput listeners fire on
the same event.
Cursor-at-end model (no mid-string edits) — simple, predictable,
and doesn't collide with parent's arrow-key slash-nav + history.
ink-text-input still used by Wizard/Select/Setup — fine for
single-line forms.
382 tests (+18).
UX overhaul:
- Typing `/` pops an IntelliSense-style suggestion list with name +
args hint + summary. ↑/↓ navigate, Tab completes, Enter picks +
runs. Registry-driven (SLASH_COMMANDS) with code-mode gating.
- Static command-strip footer under the input is gone — superseded
by the on-demand slash popup.
MCP discovery:
- /mcp in chat is now a rich per-server view: server info + spec +
tool count + resources list + prompts list. Unsupported sections
render "(not supported)" cleanly. Inspection runs once at
startup and flows through SlashContext.mcpServers.
- New `reasonix mcp inspect <spec>` CLI for running the same
discovery outside chat (CI, scripting, "does this work?"). --json
emits the full InspectionReport.
- inspectMcpServer() + InspectionReport are public APIs; McpClient
gains serverInfo / protocolVersion / serverInstructions getters.
364 tests (+11).
Two protocol-level completions bundled:
1. DSML tool-call recovery. scavengeToolCalls gains a DSML invoke
parser (<|DSML|invoke>/<|DSML|parameter string="true|false">).
ToolCallRepair.process now scans both reasoning AND content
channels — before, DSML in a regular turn was stripped from
display but the tool never actually ran.
2. MCP resources + prompts. McpClient gains resources/list,
resources/read, prompts/list, prompts/get with full types and
cursor pagination. Initialize now advertises all three
capability families.
353 tests (+13: scavenge +5, pipeline +2, mcp +6).
EventLog clips tool results at 400 chars for display; /tool [N]
now lets users read the full text. `/tool` lists the 10 most
recent with previews and char counts; `/tool N` dumps the
Nth-most-recent in full. Wired via new SlashContext.toolHistory
callback — pure handleSlash stays stateless.
340 tests (+8 /tool cases).
User feedback: after pressing Esc, the warning fired instantly but
then the TUI blocked for the duration of a full reasoner call
(30-90s) to produce a "summary" the user hadn't asked for. Esc in a
terminal means stop. Stopping and then forcing the expensive
reasoner to wrap up is the opposite of what the user signaled.
Abort path now:
- Emits a short warning "aborted at iter N/M — stopped without
producing a summary (press ↑ + Enter or /retry to resume)"
- Appends a synthetic assistant message "[aborted by user (Esc)
— no summary produced. Ask again or /retry when ready; prior
tool output is still in the log.]"
- Yields assistant_final (tagged forcedSummary so edit applier
ignores) + done
- No API call. Takes milliseconds.
Budget and context-guard paths still call forceSummaryAfterIterLimit
because in those cases the loop stopped, not the user — leaving
them staring at nothing would be worse than one extra call. Only
user-initiated abort gets the fast path.
Test rewritten to confirm no extra API call is made (previously
asserted a "partial findings" summary from the never-needed
follow-up). Suite: 332 still passing.
Also bumps to 0.4.3 because v0.4.2 tag is already on origin at
cb2f2a5 with partial content. This release consolidates the full
0.4.2 batch + the Esc fix under one tag.
Nine UX improvements in one batch, all surfaced from real-session
feedback while testing reasonix code against a live filesystem
project.
Added slash commands:
- /retry — truncate log back before the last user message, resend
it, get a fresh sample from the model. SlashResult gains a
resubmit field the TUI honors after displaying info.
- /status — now a labeled situation-report: model, flags
(harvest/branch/stream), ctx ratio (42k/131k (32%)) from last
turn's promptTokens, MCP server + tool counts, session name +
log length + resumed count, pending edits count. One command
shows everything.
- /think (alias /reasoning) — dumps full R1 reasoning from
loop.scratch.reasoning. For when the 260-char tail preview
isn't enough. Graceful "no reasoning cached" when using
deepseek-chat.
Added interactions:
- ↑/↓ shell-style prompt history. App.tsx owns a ref array, cursor
advances on arrow keys while idle. Process-scoped, no cross-run
persistence.
- y/n fast-path when edits are pending. Typing 'y'+Enter = /apply,
'n'+Enter = /discard. Scoped: only when pendingEdits.length > 0,
so plain "y" as a normal message still works when nothing's
waiting. Preview line advertises the shortcut.
Changed:
- Tool-running row surfaces elapsed seconds + per-tool argument
summary. Before: ⠋ tool<filesystem_edit_file> running… {raw
JSON}. Now: ⠋ tool<filesystem_edit_file> running… 3s / path:
F:\... (2 edits). Summarizers for read_file, write_file,
edit_file, list_directory, directory_tree, search_files,
move_file, get_file_info. Matches suffix so namespaced and
anonymous servers both work.
- Reasoning preview shows tail (~260 chars), not head. R1 opens
every turn with the same scaffolding that hid the actual
decision in the (+N chars) elision; users reported reasoning
looked identical across turns. The tail is where the model
commits to an action.
- Tool errors render red with ✗ marker instead of yellow with →.
ERROR: prefix from flattenMcpResult (on isError) is detected.
A failure needs different attention than a listing.
Fixed:
- Forced-summary path no longer leaks DSML tool-call markup as
prose. Passing tools: undefined wasn't enough — R1 primed for
tool use would still emit <|DSML|function_calls>...</|DSML|
function_calls> as plain text in content. Two layers: (1)
inject an explicit user-role instruction at the end of the
forced-summary message list telling the model to produce prose
with no tool markup; (2) post-hoc strip known envelopes (DSML
full-width/ASCII, Anthropic <function_calls>, and truncated
un-closed DSML openers) from the model's response before
yielding. stripHallucinatedToolMarkup exported for library
callers. Fallback message when stripping leaves nothing points
at /retry and /think.
Tests: +13, suite 319 -> 332.
- tests/slash.test.ts (+8): /think empty/populated/help,
/retry happy/empty-log/help, /status new format, /status
pending-edit suppression at 0.
- tests/loop-error.test.ts (+5): stripHallucinatedToolMarkup
against live R1 DSML shape, Anthropic-style, truncated
un-closed opener, plain prose, all-markup edge case.
Bumps to 0.4.2.
Three small improvements surfaced from real-session feedback:
1. Tool-running row was just a spinner + raw-JSON args; user said
"看不到任何的输出,就只知道再转圈". Added elapsed seconds counter
and per-tool argument summarizer. Instead of
tool<filesystem_edit_file> running... {"path":"..."...}
you now see
tool<filesystem_edit_file> running... 3s
path: F:\testtest\index.html (2 edits)
Summarizers for read_file / write_file / edit_file /
list_directory / directory_tree / search_files / move_file /
get_file_info, matching by suffix so bridgeMcpTools name prefix
(e.g. "filesystem_") works too. Unknown tools fall back to a
truncated raw preview.
2. ReasoningBlock showed the first 220 chars with "(+N chars)"
elided at the end. R1 opens every turn with the same scaffolding
("let me look at the structure...") so the preview looked
identical across turns and hid the actual decision in the
truncated tail. Switched to showing the LAST ~260 chars —
which is where R1 commits to an action.
3. /think slash command dumps the full reasoning text from
loop.scratch.reasoning when the tail preview isn't enough.
Alias: /reasoning. Graceful "no reasoning cached" message when
the current model is deepseek-chat (no reasoning_content) or a
turn hasn't completed yet.
Tests: +3 in slash.test.ts (/think empty + populated + help).
Suite: 319 -> 322.
Bumps to 0.4.2.
A real-session bug report — "I asked the model to analyze the project
and it silently edited a file" — forced a rethink of v0.4.0's
auto-apply default. This release fixes the root cause plus a stack of
adjacent UX gaps surfaced during the fix.
WHY (behavior change): auto-apply was wrong because it conflated two
distinct events — "the model proposed a change" and "the user wants
to make the change." v0.4.0 treated every SEARCH/REPLACE block in
assistant output as permission to write. Analysis drifted into edits.
Preview-by-default + explicit /apply is Aider's model and it's honest.
Added (code mode):
- /apply: writes pending edit blocks to disk, snapshots for /undo,
reports per-block status
- /discard: drops pending edits, no disk writes
- /undo: rolls back the last applied edit batch (restores modified
files, deletes ones created by the batch)
- /commit "msg": git add -A && git commit -m "..." in code rootDir;
surfaces git stderr on hook failure / nothing-staged / etc.
- .gitignore awareness: reasonix code reads rootDir/.gitignore on
launch and appends it to the system prompt as "don't traverse
these paths unless asked"; hard-coded baseline (node_modules,
dist, .git, .venv, __pycache__, target, ...) baked into the base
prompt for projects without a .gitignore
Fixed:
- Edits no longer auto-write. Each assistant turn's blocks are
parsed and shown as a preview (filename + -N/+M line-count). No
disk write until /apply. Pending persists across messages.
- LoopEvent.forcedSummary flag on assistant_final events from the
no-tools fallback (budget/aborted/context-guard). Code-mode
applier skips tagged events — a wrap-up summary is not a plan.
- Token-context guard replaces iter count as primary stop
condition. promptTokens > 80% of ctx window -> yellow warning +
skip tool exec + divert to summary (reason: "context-guard").
Iter cap 24 -> 64 as last-resort backstop.
- CODE_SYSTEM_PROMPT tightened: explicit rule that edits only fire
on change/fix/add/remove/refactor intents; analyze/explain stay
read-only.
- Stray EditSummary/summarizeEdit reverted from edit-blocks.ts (a
0.4.0 forced-summary run auto-wrote it; dead code).
- SEARCH/REPLACE blocks now render as a proper diff (red -/green +)
instead of going through the markdown paragraph path, which was
joining lines with spaces and letting the bold/italic regex eat
`*` chars inside JSDoc `/** ... */` comments. New parseBlocks
exports an "edit-block" block kind.
- R1 reasoning UX no longer looks frozen. Cyan braille-spinner
heartbeat (500ms) + "reasoning" vs "streaming" label + explicit
"R1 is thinking before it speaks — body text starts when
reasoning completes (typically 20-90s)" message while body is
empty. Replaces the misleading "(waiting for first token...)".
- New "tool_start" event yielded immediately before
tools.dispatch(). TUI renders a spinner row "⠋ tool<X> running…"
with args preview while the Promise is pending — fixes the
dead-air window between assistant_final (streaming cleared) and
the tool result event, during which a multi-KB
filesystem_edit_file could hang the UI visibly for 100ms-1s.
Tests: +36, suite 292 -> 319.
- tests/edit-blocks.test.ts (+5): snapshot/restore round-trip,
delete on undo-of-create, per-path dedup, path-escape defense.
- tests/code-prompt.test.ts (+4, new file): .gitignore injection
happy/absent/truncated paths, base-prompt ignore hints.
- tests/slash.test.ts (+13): /apply /discard /undo /commit inside
and outside code mode, usage hint on empty, double-quote
stripping, help listing.
- tests/loop.test.ts (+2): context-guard warning + forcedSummary
flag when prompt > 80% of window, tool_start precedes tool.
- tests/markdown.test.ts (+5): parseBlocks recognizes SEARCH/
REPLACE into edit-block blocks, preserves multi-line JSDoc
verbatim, handles new-file empty-SEARCH, rejects stray markers
without close, multi-block + prose interleaving.
Bumps to 0.4.1.
A new opinionated subcommand that turns Reasonix into a coding
assistant, realizing the "cheap Claude Code" pitch. Layers on top of
the existing chat + MCP machinery rather than forking it.
What `reasonix code [dir]` does:
- Auto-bridges @modelcontextprotocol/server-filesystem at [dir]
(default CWD). No wizard, no config merge.
- Uses a coding-focused system prompt that teaches Aider-style
SEARCH/REPLACE blocks and forbids write_file for existing files.
- Forces reasoner + harvest (coding repays R1 thinking).
- Scopes the session name to the directory basename so projects
don't cross-pollute.
- Hooks codeMode into App.tsx — after each assistant_final, parses
SEARCH/REPLACE blocks from the response and applies them to disk,
reporting per-block results as info lines.
SEARCH/REPLACE semantics (src/code/edit-blocks.ts):
- SEARCH must match byte-for-byte. No fuzzy matching — a silent
wrong edit is worse than a loud rejection.
- Empty SEARCH creates a new file (Aider convention).
- First occurrence only; duplicate SEARCH text requires a new
block with more surrounding context.
- Path-escape defense: resolve + startsWith on the normalized
rootDir, refuses paths climbing above the sandbox.
Library surface: parseEditBlocks, applyEditBlock, applyEditBlocks,
CODE_SYSTEM_PROMPT, and EditBlock/ApplyResult/ApplyStatus types.
Compose them yourself for custom UIs.
Out of scope for v1: /commit, /undo, diff preview, .gitignore
filtering. User's `git diff` + `git checkout` is the review/undo
surface; we run inside a git repo by convention.
Tests: +13 in edit-blocks.test.ts (parse: single/multi/multiline/
empty-search/stray-markers; apply: happy/new-file/not-found/
file-missing/path-escape/first-occurrence; batch: independent
results). Suite 279 -> 292.
Bumps to 0.4.0 (minor — new user-facing primitive + library surface
additions; no breaking changes for 0.3.x users).
0.3.1 gave the loop a safety net (forced summary at maxToolIters);
this release turns that safety net into an interactive budget. Users
no longer have to wait for the ceiling to hear from the model.
- Yellow warning event fires once per step when tool-iter count hits
70% of maxToolIters. TUI renders it in the event log with an
"Press Esc to force a summary now" hint; the command strip under
the prompt also shows the Esc shortcut.
- CacheFirstLoop.abort() method + TUI Esc handler (useInput, guarded
by busy state and a once-per-turn flag). On abort, the current tool
call is allowed to finish, then the loop diverts to the 0.3.1
no-tools summary path with a different prefix:
"[aborted by user (Esc) - summarizing what I found so far]".
- New EventRole "warning" + DisplayRole "warning"; EventLog renders
them yellow. Wired through App.tsx's event dispatcher.
README rewrite: hero leads with `npx reasonix` (no flags), wizard
story in prose. --mcp and --preset examples moved to "Advanced".
What-you-get table gains Setup wizard, Context safety net row, and
merges stdio + SSE into one MCP row. Non-goals and Configuration
trimmed to match.
Tests: +2 in loop.test.ts (warning fires exactly once at threshold;
abort() diverts to summary with "aborted" prefix). Suite: 277 -> 279.
Bumps to 0.3.2.
Problem (reproduced live): user asked the reasoner to explore a Flutter
project via filesystem MCP. The model chained 8 list_directory /
read_file calls, the loop hit the default maxToolIters=8, quietly
yielded a "done" event with content "[max_tool_iters reached]", and
exited. The App.tsx doesn't render `done` content anywhere, so the
user saw a blank assistant reply after 8 tool calls — as if Reasonix
just stopped for no reason.
Fix:
- When the tool-call loop exhausts its budget with tool_calls still
pending, make one final request to DeepSeek with tools omitted.
Forces a text-only answer based on everything in history. Yield
as a normal assistant_final event, prefixed with
"[tool-call budget (N) reached - forcing summary from what I found]"
so the user knows why they got a summary instead of more drilling.
- Default maxToolIters 8 -> 24. Eight was below the floor for any
real filesystem exploration; 24 still caps a confused model's
damage.
Tests: +1 in loop.test.ts with maxToolIters=2, every response wanting
tools, proving the summary call fires and assistant_final carries the
budget annotation. Suite: 276 -> 277.
Bumps to 0.3.1.
Drops the prerelease tag and ships 0.3.0 stable. Since 0.2.2 this
includes: MCP (stdio + SSE, multi-server, curated catalog), the
first-run wizard that replaces the --mcp flag maze, config-backed
defaults, and a three-layer context-safety net (per-tool cap +
auto-heal on session load + manual /compact).
Added this commit:
- StatsPanel context gauge: "ctx 42k/131k (32%)" with yellow at
50% and red + "/compact" nudge at 80%+. Reads SessionSummary's
new lastPromptTokens field; model max comes from
DEEPSEEK_CONTEXT_TOKENS (131072 for chat/reasoner).
- /compact [cap] slash: re-applies truncation with a tighter 4k
char cap (or user-supplied), rewrites the session file on disk
so the next launch doesn't re-inherit a fat file. Reports chars
and approximate tokens saved.
- SessionSummary.lastPromptTokens, AppendOnlyLog.compactInPlace(),
session.rewriteSession(), loop.compact() — all new exports.
Tests: +5 (slash /compact x4, telemetry lastPromptTokens x1).
Suite: 276 passing (up from 241 in alpha.4).
Migration note: one silent behaviour change — sessions built with
pre-alpha.6 clients auto-heal on load (oversized tool results get
truncated). The conversation is preserved; only the bloat shrinks.
Problem: a single `read_file` on a big file returned ~3 MB of text
through flattenMcpResult; it landed in session history verbatim and
every subsequent turn 400'd with DeepSeek's "maximum context length
is 131072 tokens. However, you requested 929,452 tokens." The user
had no way to recover short of deleting the session file by hand.
Fix, at both ends:
- Prevention: bridgeMcpTools now caps each result at 32k chars by
default. truncateForModel keeps head + 1KB tail with a clear
"[...truncated N chars...]" marker, so the model sees both
"what the tool started returning" and "how it ended" (important
for error messages appended at the bottom of stack traces).
Override: bridgeMcpTools(client, { maxResultChars: N }).
- Diagnosis: formatLoopError() detects "maximum context length"
in the raw API error, pretty-prints the requested-token figure,
and tells the user exactly what to do — /forget to wipe the
session file, /clear for display-only. Other errors pass through.
Exports: DEFAULT_MAX_RESULT_CHARS, truncateForModel, FlattenOptions,
formatLoopError — so library callers get the same protection.
Tests: +3 for truncation (head+tail preserved, no-op below cap,
end-to-end dispatch), +3 for error annotation (token figure,
passthrough, figure-less overflow). Suite 262 -> 268.
Bumps to 0.3.0-alpha.6.
The previous UX required users to memorize a pile of flags
(`--mcp "name=npx -y @scope/pkg /path"`, `--harvest`, `--branch N`,
`--session`) before they could use any of Reasonix's power features.
That was wrong: the target audience is ordinary users, not CLI
archaeologists.
New flow:
- `npx reasonix` — on first run opens an Ink wizard (API key →
preset pick → MCP multi-select → per-server args → save). On
subsequent runs launches chat with the saved defaults.
- `reasonix setup` re-runs the wizard any time; existing selections
are pre-checked via package-name matching against the catalog.
- `~/.reasonix/config.json` now stores preset + mcp + session +
setupCompleted alongside apiKey. Precedence: explicit CLI flag
wins, then --preset, then config.preset, then hardcoded fast
defaults. `--no-config` is the escape hatch for CI.
- `--preset <fast|smart|max>` new on both chat and run so power
users get the bundled settings too.
- `/mcp` slash — lists attached servers + tool registry mid-chat.
- `/setup` slash — prints instructions to exit and re-run
`reasonix setup`. Live reconfig is out of scope: swapping tools
mid-session would invalidate the byte-stable prefix.
Fixes two real bugs found during manual testing:
- `@modelcontextprotocol/server-fetch` and `server-sqlite` were in
the catalog but don't exist on npm (Python-only reference
implementations). Picking either one produced a 404 that killed
the chat. Removed.
- One broken MCP server took down the whole chat via
`process.exit(1)`. Now each failure prints `▸ MCP setup SKIPPED`
pointing at `reasonix setup` and the session continues with the
servers that worked.
Tests (+21, suite 241→262):
- tests/resolve.test.ts (+11) — flag/preset/config precedence, cap
and off paths, --no-config, --no-session isolation.
- tests/config.test.ts (+2) — extended schema round-trip,
session:null meaning ephemeral.
- tests/slash.test.ts (+4) — /mcp empty + populated, /setup hint,
help coverage.
- tests/wizard.test.ts (+4) — buildSpec → parseMcpSpec round-trip
for filesystem / memory / spaces-in-path / unknown-entry fallback.
Bumps to 0.3.0-alpha.5.
Implements the MCP 2024-11-05 HTTP+SSE wire: GET the SSE URL, wait for
event: endpoint, POST every outgoing JSON-RPC frame to that URL, read
responses off the SSE channel. Headers (Authorization, etc.) pass
through to both the GET and POSTs so hosted servers behind auth work.
--mcp now routes anything starting with http:// or https:// to
SseTransport; everything else stays stdio. McpSpec becomes a
discriminated union { transport: "stdio" | "sse", … } — callers that
inspected spec.command/args must branch on spec.transport first.
Tests: in-process http.Server fake implementing the SSE wire —
relative endpoint resolution, absolute endpoints, a full McpClient
initialize → listTools round-trip, handshake failure propagation.
Plus parseMcpSpec SSE cases (case-insensitive scheme; ws:// stays
routed to stdio as there's no ws transport yet). Suite: 241 passing.
Bumps version to 0.3.0-alpha.4.
Cache-First holds
Third MCP live data point, the ecosystem proof. Run against two MCP
servers concurrently:
--mcp "demo=node --import tsx examples/mcp-server-demo.ts"
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem <dir>"
The model used tools from both in one conversation — computed 17+25
via demo_add, then wrote "42" to a real file on disk via
fs_write_file (with a graceful permission-denied recovery in
between).
turns: 5, tool calls: 4
cache: 81.1%, cost $0.00185, 95.9% cheaper than Claude
prefix hashes: ONE across all 5 turns — byte-stable prefix
survives two concurrent MCP subprocesses
Reference: benchmarks/tau-bench/transcripts/mcp-multi-server.jsonl
(replay offline to verify — no API key needed).
Also adds .claude/settings.local.json to .gitignore (local Claude Code
settings are personal and shouldn't be committed).
Adds the last bit of UX I'd actually hand to a new user: a way to
discover what MCP servers they can try.
New:
- reasonix mcp list curated catalog of popular official MCP
servers, each with a copy-pasteable
--mcp command. filesystem / fetch /
github / memory / sqlite / puppeteer /
everything. --json for machine output.
- --mcp repeatable multi-server support (already in main,
now released on npm @alpha)
- "name=cmd args..." spec per-server namespace prefix, tools land
as fs_read_file, mem_set, etc.
Packages 7cd8621 (multi-server) + new mcp list command as alpha.3.
Discovery is hardcoded not fetched: the list changes slowly, offline
users shouldn't have to wait on a network fetch to see what exists.
Updating it = one file edit + patch release.
Suite 233/233; no functional changes to the existing tested paths.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`--mcp` is now a collect-style option; pass it multiple times to attach
multiple servers to the same chat / run. Each spec can optionally name
its namespace:
reasonix chat \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "demo=node --import tsx examples/mcp-server-demo.ts"
Tools land in a shared ToolRegistry with the prefix baked in
(fs_read_file, demo_add, …). The model sees the flat namespace; the
registry dispatches to the right subprocess.
Spec syntax (new src/mcp/spec.ts::parseMcpSpec):
- "name=command args..." → namespaced; `[a-zA-Z_][a-zA-Z0-9_]*` name
- "command args..." → anonymous; tools keep their native names
The identifier regex is deliberately narrow so Windows drive letters
(`C:\...`) never accidentally look like a namespace prefix.
--mcp-prefix still exists as a global fallback, but only applies when
exactly one anonymous spec is given. With named specs, each server
brings its own name.
Also fixes a shellSplit bug: backslashes outside quotes were being
treated as POSIX escapes, which mangled every Windows path. Now they
pass through literally outside quotes (use quotes to group args with
spaces). Matches user expectation on Windows; POSIX users who want
escape-a-space can quote the arg.
+9 tests: parseMcpSpec (8 cases including Windows drive letters,
identifier-name validation, empty/malformed input) + an integration
test spawning two demo subprocesses concurrently with different
prefixes, verifying the shared registry dispatches to each correctly.
Suite: 233 passing (was 224).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Packages 5e124ce's Windows fix + second live MCP data point as an
alpha. v0.3.0-alpha.1 is technically broken on Windows (--mcp "npx ..."
can't find npx.cmd), so this supersedes it on the @alpha npm tag.
No functional changes since 5e124ce — just version bump + CHANGELOG.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
official @modelcontextprotocol/server-filesystem
Two things together — the fix is what unlocked the data.
1. StdioTransport now handles Windows .cmd/.bat shims (npx.cmd,
pnpm.cmd) without triggering Node's DEP0190 deprecation warning.
On win32, shell defaults to true; we build a quoted command line
ourselves (command bare so PATH lookup works, args quoted) and
pass it as a single string, dodging the shell:true + args[]
anti-pattern. POSIX path unchanged. New `shell?: boolean` option
lets callers override the platform default (e.g. tests spawning
node.exe directly).
2. Second live MCP run, this time against the *external*,
production @modelcontextprotocol/server-filesystem:
5 turns, 4 tool calls, cache **96.7%**, cost $0.00124,
97% cheaper than Claude at equivalent tokens.
The model tried list_directory on the wrong path, got an access-
denied, self-recovered by calling list_allowed_directories, then
list_directory + read_text_file. Messy realistic run. Byte-stable
prefix held across every turn.
This matters because the first MCP run (v0.3.0-alpha.1,
mcp-demo.add.jsonl) was against our own bundled demo server.
Someone could reasonably argue "of course it caches — you wrote
the server". This one answers that: cache-first works on code
we don't control.
Reference transcripts:
- benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl (own server)
- benchmarks/tau-bench/transcripts/mcp-filesystem.jsonl (official)
README gains a two-row table with both numbers + a no-API-key
reproduction block pointing at both committed transcripts.
Tests still 224/224 green. Integration tests explicitly set
shell: false since they spawn node.exe by absolute path.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
End-to-end MCP integration verified on live DeepSeek. Recorded run at
benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl:
▸ spawned bundled demo MCP server (3 tools bridged)
▸ model chose the add tool, received the result via MCP stdio
▸ follow-up turn hit 96.6% cache (byte-stable prefix held across
the tool-call round-trip)
▸ total cost $0.000254 — 94% cheaper than Claude at same tokens
This is the v0.1 Cache-First claim extending verbatim to arbitrary MCP
tools. The mechanism wasn't altered; the registry just serves MCP tools
as if they were native. That extension *is* the v0.3 headline.
Shipping as alpha because:
- one real run is proof-of-concept, not proof-at-scale
- SSE transport, resources, prompts, and progress notifications are
still deferred
- official external MCP servers (filesystem, github, etc.) haven't
been exercised in CI yet
Suite: 224 passing (10 fake-transport unit, 9 shell-split, 2 real-
subprocess integration, plus the existing 203).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
End-to-end MCP integration — any MCP server's tools flow through
Reasonix's Cache-First loop now, from one CLI flag.
CLI:
reasonix chat --mcp "<command args...>" interactive TUI
reasonix run "<task>" --mcp "<command args...>" one-shot
optional: --mcp-prefix <str> namespace tool names
The flag takes a shell-style command. shellSplit() parses it
(respecting single/double quotes, backslash escapes, tab-space
runs). Unterminated quotes throw with a clear error instead of
silently mangling argv. chat / run both spawn + bridge before
looping, tear down on exit.
App.tsx accepts an optional `tools?: ToolRegistry` prop. When
present, its specs get folded into ImmutablePrefix and dispatch
goes through it — so MCP tools are indistinguishable from native
tools to the loop.
Bundled demo server: examples/mcp-server-demo.ts
~160 lines, no dependencies beyond what's already installed.
Exposes echo / add / get_time. Two uses:
- users can try the whole integration with no external install:
reasonix chat --mcp "node --import tsx examples/mcp-server-demo.ts"
- gives the integration test a real subprocess target
Integration test: tests/mcp-integration.test.ts
Spawns the demo server (`node --import tsx ...` — cross-platform,
avoids Windows `.cmd` resolution issues), walks the full handshake,
bridges tools, dispatches through the registry. Kept in a
separate file from the fake-transport unit tests so subprocess
flakiness doesn't hide unit-test regressions.
+11 tests (9 shellSplit + 2 integration). Suite: 224 passing (was
213). src/mcp/README.md updated with CLI usage + status of what's
shipped vs deferred.
Still no version bump — next is v0.3.0-alpha, once we've seen a
real LLM call go through an MCP tool end-to-end. Everything's in
place for that now; remaining is one live run.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Minimal MCP (Model Context Protocol) client, hand-rolled, zero
runtime deps. Lets Reasonix consume tools from any MCP server while
keeping Cache-First + repair applied to the whole thing.
Why roll-our-own instead of @modelcontextprotocol/sdk:
- zero dep cost, consistent with how we wrote the DeepSeek client
- surface tuning — only initialize / tools/list / tools/call for now
- insulation from SDK breaking changes
See src/mcp/README.md for the full reasoning.
Shipped in this pass:
- src/mcp/types.ts JSON-RPC 2.0 + MCP message types
- src/mcp/stdio.ts McpTransport interface + NDJSON stdio impl
- src/mcp/client.ts connect / listTools / callTool with timeouts
+ id correlation
- src/mcp/registry.ts bridgeMcpTools(): MCP → Reasonix ToolRegistry,
so MCP tools inherit Cache-First + repair
automatically
- src/mcp/README.md design choices + usage example + what's next
Deferred (each is its own follow-up commit):
- CLI wiring: `reasonix chat --mcp <cmd>` — thin layer on top of
bridgeMcpTools + ImmutablePrefix
- resources/* and prompts/* methods — Reasonix doesn't surface those
today
- SSE transport — stdio covers common case
- Progress notifications / streaming tool results
+10 tests using an in-process FakeMcpTransport (no child processes in
unit tests — flaky). Covers initialize handshake, pre-init refusal,
tools/list, tools/call roundtrip, server errors, bridge registration,
name prefixing, and result flattening (text / image / error cases).
Suite: 213 passing (was 203).
Public surface: McpClient / StdioTransport / bridgeMcpTools /
flattenMcpResult / MCP_PROTOCOL_VERSION + all relevant types exported
from the library barrel. No version bump — foundation, not release.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
lift accuracy on math/logic; pivot Pillar 2 positioning
Second harvest eval run, 6 tasks × 3 modes × 1 repeat = 18 runs. This
time the task set included three hard tasks chosen specifically for
known V3 failure modes (base-2 Fermat pseudoprime → 341,
derangements of 7 → 1854, Euler polynomial first-fail → n=40).
mode pass cache cost harvest signal
baseline 6/6 39.5% $0.00137 —
reasoner 6/6 74.2% $0.00417 —
reasoner-harvest 5/6* 61.6% $0.00330 2.8 sg / 1.3 un
(* one 300s timeout on pseudoprime_base2)
Honest headline: **V3 passed all six.** Including the hard ones. The
checkers specifically reject the common V3 wrong-answers (561 for
pseudoprime, 265/1855 for D_7, 41/1681 for Euler) — none of those
fired. These problems are well-enough known that V3 has them in
training and R1 has no accuracy headroom to win back.
What this means for v0.3 positioning:
- We cannot ship a "harvest improves answer quality" claim off this
data — twice now. That's not a framework bug; it's a signal that
Pillar 2's value is NOT in the "make math more right" story.
- Plausible actual value surfaces: dev-facing introspection of R1's
planning, or steering tool-call sequences under uncertainty. Neither
is exercised by this harness.
- Cache-First story DOES extend to reasoner mode (74% mean cache even
on R1 turns). That's a Pillar 1 finding reinforcing the v0.1 data,
not a Pillar 2 finding.
findings section updated inside report.ts's renderFindings() so future
regens preserve the analysis. Committed results.json is the full
artifact for anyone who wants to reasonix replay / diff individual
runs.
Recommendation in-report: next release is better served by MCP client
(Pillar 1 leverage across the ecosystem) than by a third harvest-bench
data push. Pillar 2 needs a reframe — likely "debug visibility" or
"tool-sequence planning", not "accuracy multiplier".
Unexpected positive signal worth noting: cross-session prompt cache.
Baseline mean cache hit was 39.5% even on mode A — the same system
prompt across many runs warmed DeepSeek's server-side cache, showing
Cache-First's value isn't purely per-session.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Post-first-run adjustments informed by 7233edd's data:
- Seed tasks bottomed out at V3 chat (3/3 pass on all easy ones), so
harvest couldn't differentiate. Add three hard tasks picked for
known V3 failure modes:
- pseudoprime_base2 (341; V3 commonly says 561 — Carmichael)
- derangements_d7 (1854; V3 hits n!/e rounding errors)
- euler_quadratic_break (40; V3 confuses with n²−n+41 first-fail)
Each is a single-integer answer → reuse a new checkSingleInt helper.
Easy tasks stay for floor reference.
- `--timeout <seconds>` flag (default 300s, was 120s client default).
Prior run hit the 120s cap on three_hats/reasoner-harvest because R1
alone took ~100s. 300s gives headroom without encouraging runaway
loops.
+9 tests on new checkers and the common wrong answers (e.g., checker
rejects 561 for pseudoprime_base2, rejects 265/1855 for D_7, rejects
41/1681 for euler_quadratic). Suite: 203 passing.
CI --dry step still covers the runner. No API calls in this commit —
next run uses the expanded task set.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
First real data from the v0.3 harvest eval harness (3 tasks × 3 modes,
1 repeat). Findings are not the marketing-friendly "harvest +N% quality"
we wanted — but they're honest, and they sharpen what v0.3 actually
needs.
Headline numbers (per-run means):
mode pass cache cost harvest signal
baseline 3/3 0.0% $0.00142 —
reasoner 3/3 79.0% $0.00355 —
reasoner-harvest 2/3* 59.7% $0.00184 3.3 sg / 1.3 un
(* one timeout, see known issues)
Three honest findings, committed to report.md:
1. V3 chat already solves all three seed tasks. The task set bottoms
out — baseline's 3/3 pass rate means there's no headroom for R1,
let alone R1+harvest, to win on quality.
2. Reasoner costs ~2.5× chat on these problems with identical verdicts.
On this task set, there is no quality argument for R1. (The
cache-hit story DOES extend — reasoner mode still gets 79% mean
cache through the Cache-First loop, so Pillar 1 generalizes.)
3. Harvest produces real signal (3-5 subgoals, 1-2 uncertainties per
run) AND real latency — one run hit the 120s client timeout because
the harvest V3 call pushed past R1's own ~100s budget.
What this changes for v0.3:
- We cannot ship a "harvest pays for itself" claim off this data.
- The harness is fine; the task set is the bottleneck.
- Next iteration needs problems where V3 demonstrably fails, so R1
gains real headroom and harvest's uncertainty signal has something
to correlate with.
report.ts gains a renderFindings() helper so future runs can preserve
the hand-written interpretation alongside the auto-generated tables.
No release tag — this is data collection, not a version bump.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
New benchmarks/harvest/ directory alongside tau-bench/. Measures
Pillar 2 (R1 Thought Harvesting) the same way tau-bench-lite measures
Pillar 1 — isolate one variable, produce reproducible numbers.
Three modes per task, each isolates one variable:
- baseline deepseek-chat, no Reasonix tricks — V3 floor
- reasoner deepseek-reasoner, no harvest — raw R1 gain
- reasoner-harvest deepseek-reasoner + harvest — incremental cost /
quality from the extra V3 harvest call
Seed tasks (v0.3):
- mod7_list number theory, 29-element set — expansive plan state
- flips_until_3heads probability, single integer — derive vs recall
- three_hats logic puzzle, one-word answer — deduction chain
All checkers are deterministic (regex + set/value compare). No LLM
judge. Failing checker in CI catches reality drift without needing an
API key — sanity verdict is exercised on every dry-run.
Runner supports --task, --mode, --repeats, --transcripts-dir, --dry.
Transcripts reuse the same TranscriptRecord format as tau-bench, so
reasonix replay / reasonix diff work unchanged.
CI now runs the harvest harness's --dry in addition to tau-bench's,
so bench regressions get caught before a real run.
+16 tests covering checker verdicts for all three tasks, empty-input
robustness, determinism, and task-set invariants. Suite: 194 passing.
No API calls yet — next step is a live run to produce the first
harvest-bench/report.md. Expected cost for 3 tasks × 3 modes × 1
repeat: ~$0.10-0.30 (dominated by the reasoner calls).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Promotes the existing /sessions slash command into a top-level CLI
command so users can audit their stored sessions without launching
the TUI. Two modes:
reasonix sessions list every session under
~/.reasonix/sessions/
reasonix sessions <name> dump messages from one session
reasonix sessions <name> -v include system prompts + tool-call
args
Reuses listSessions / loadSessionMessages / sessionPath from
src/session.ts — no new library surface. Zero API calls; filesystem
reads only.
Use case: quickly checking "what have I been asking the assistant?"
without running chat, or piping one session's content into a tool
chain for batch analysis.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When at least one side of a transcript diff has plan state (Pillar 2
harvest output), the summary now includes three extra rows: harvest
turns, subgoals, and uncertainties. Lets a harvest-on run be compared
head-to-head with its harvest-off twin — which is exactly the
comparison v0.3's eval harness will need to produce.
Rows only appear when at least one side carries planState. No-harvest
diffs render identically to v0.2.2 — zero visual noise, zero surprise
for existing callers.
+2 tests confirming the row appears when harvest is present AND
omits entirely when both sides are clean. Suite: 178 passing.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two small adds that make the existing v0.2 infrastructure easier to
pick up:
1. CI now runs `npx tsx benchmarks/tau-bench/runner.ts --dry` on every
push and PR. Catches bench harness regressions (task factories, CLI
parsing, file IO, per-sub-call transcript emission) without needing
a DEEPSEEK_API_KEY in CI.
2. examples/replay-and-diff.ts demonstrates the library surface
programmatically — readTranscript, computeReplayStats,
diffTranscripts, renderDiffSummary, plus direct report.pairs
inspection. Runs with no API key against the committed reference
transcripts; verifies the v0.1 numbers (94% cache, −20% cost, 1
byte-stable prefix) fall out of the JSONL alone.
Useful for anyone wiring a CI gate or eval dashboard on top of Reasonix
— which is the main use case that justifies shipping transcripts in
the package in the first place.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The old PlanStateBlock rendered all four fields in the same magenta
text. On terminals with dark themes (which is most of them), magenta
is notoriously low-contrast — users reported not being able to read
harvest output.
Fix:
- label gets a semantic color (bold): subgoals cyan, hypotheses green,
uncertainties yellow, rejected red-dim.
- the item list itself renders in default foreground — always
readable on any background.
- count indicator "(N)" is dimColor so it doesn't compete with content.
Before: all four lines identical magenta (hard to tell fields apart,
hard to read on dark).
After: label color communicates meaning (rejected feels negative,
uncertainties feel like "watch out"), content stays crisp.
Used by the live chat TUI AND replay/diff TUIs, so the fix lands
everywhere harvest output shows up.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Parity with `reasonix chat`: lets a one-shot non-interactive call
produce a transcript with harvest signal, for quick API-backed
verification of a harvest session without firing up the Ink TUI.
Usage:
reasonix run "your question" \
--model deepseek-reasoner --harvest \
--transcript /tmp/h.jsonl
Afterward:
reasonix replay /tmp/h.jsonl # see the planState inline
The transcript path is self-closing — the command streams output as
usual, then prints a hint pointing at replay. No other behavior change;
`reasonix run` without the new flags behaves exactly as before.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Prep work for v0.3's harvest eval harness. The Pillar 2 plan state
already exists in the live chat UI; this commit makes it persist and
display in every replay/diff surface, so future harvest data can be
audited the same way cache hit is today.
- TranscriptRecord gains optional planState (TypedPlanState).
- recordFromLoopEvent copies it from LoopEvent.planState on
assistant_final events. Empty plan state is omitted entirely — absent
means "no signal", indistinguishable from harvest-off, saves bytes.
- PlanStateBlock extracted from EventLog to a shared component so the
live chat TUI, replay TUI, and (transitively) diff TUI all render
harvest output identically.
- RecordView shows the plan state under the assistant text when present.
- replay stdout --print mode prints the same four lines (subgoals /
hypotheses / uncertainties / rejected) under each agent turn that
carried plan state.
- ReplayStats gains harvestedTurns, totalSubgoals, totalUncertainties.
Surfaced in the replay summary so you can see at-a-glance whether
harvest produced signal across the session.
- Zero cost when harvest is off — the whole path is gated on the
presence of planState in the record.
+4 tests (round-trip, empty-state omission, aggregate counting,
no-harvest zero case). Suite: **176 passing**.
No CHANGELOG bump — this is prep, not a release.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
First three-repeat data set on τ-bench-lite. Headline numbers land in
the same region as the v0.1 16-run set, with the confidence that comes
from 3× the samples.
metric baseline reasonix delta
runs 24 24 —
pass rate 96% (23/24) 100% (24/24) reasonix holds guardrail
cache hit 46.6% 94.4% +47.7pp
cost / task $0.002599 $0.001579 −39% (×0.61)
vs Claude (estimate) — — ~96% cheaper
The one baseline failure is a t07_wrong_identity run where baseline
skipped identity verification and mutated the wrong user's order —
exactly the kind of guardrail slip you'd expect from a cache-churning
agent whose context reshuffles every turn.
Also includes:
- README hero table refreshed to the 48-run numbers + 3-repeat
reproduction command
- benchmarks/tau-bench/results.json replaced with the 48-run data
- benchmarks/tau-bench/report.md regenerated from the new JSON
(The t05 predicate fix that made 100% pass possible landed one commit
earlier at c1965b1.)
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The v0.1 16-run bench surfaced an honest false-negative on t05: the task
wanted "no refund on a processing order", and reasonix followed that —
but then offered to cancel the order instead when the user kept pushing.
The old predicate required status to stay `processing`, which penalized
agents for being helpful. It failed reasonix once and the baseline zero
times, not because reasonix behaved worse but because baseline never
reached the "offer cancel" branch.
New predicate: pass iff no refund row is written for o_1002 AND the
status ends up in {processing, cancelled}. "No refund" remains the
hard constraint. Cancellation is now honored as a reasonable business
response — which is how a real support flow would be scored.
+3 tests pinning the three outcomes (refuse / cancel / illegally
refund). Suite: 172 passing.
No report regeneration in this commit — rerun the bench in a follow-up
with the new predicate to pick up any accuracy change.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Single release covering both TUI additions (replay + diff) shipped
since 0.2.0. No functional changes; version bumps + CHANGELOG.
Highlights (see CHANGELOG.md for detail):
- reasonix replay <transcript> → Ink TUI by default (j/k/g/G nav)
- reasonix diff <a> <b> → split-pane TUI with n/N divergence
jump; --md / --print / --tui flags
to override
Stdout paths preserved via --print and non-TTY auto-detection, so CI
and pipe workflows behave as they did in 0.2.0.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`reasonix diff <a> <b>` now mounts an interactive Ink UI by default:
side-by-side panes sharing a cursor, a compact header that colors cache
and cost deltas in green/red, and a divergence-aware jump cursor. Press
n to skip straight to the next non-matching turn — the whole point of
a diff tool — or N/p to go back.
Default behavior picks itself based on context:
- stdout is a TTY and no --md: Ink TUI
- --md <path>: writes markdown AND prints the stdout summary (existing)
- --print, or piped stdout: stdout summary (existing)
- --tui: force TUI even when piped (rare)
Key bindings:
- j / ↓ / space / enter — next turn
- k / ↑ — prev turn
- n — next divergent turn
- N / p — prev divergent turn
- g / G — first / last
- q / ctrl-c — quit
Implementation:
- src/cli/ui/DiffApp.tsx — the new split-pane component.
- src/cli/ui/RecordView.tsx — extracted from ReplayApp so both UIs
share the same visual grammar (user cyan, assistant green with cache
badge, tool yellow, error red). ReplayApp now imports from here
instead of carrying its own copy.
- src/diff.ts gains pure `findNextDivergence` / `findPrevDivergence`
helpers so the nav logic is unit-testable without Ink (`n`/`N` keys).
Both guard against out-of-bounds `fromIdx`.
Cursor defaults to the first divergent turn (or 0 if everything
matches) — skips the "scroll through 7 identical turns before getting
to the interesting bit" experience.
+4 tests covering divergence navigation. Suite: 169 passing (was 165).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`reasonix replay <transcript>` now opens an interactive Ink UI by
default: j/k navigation across turn-pages, a cumulative stats sidebar
(StatsPanel reused from the chat TUI) that updates as you scrub, and
a key-bindings footer.
Key bindings:
- j / ↓ / space / enter — next turn
- k / ↑ — previous turn
- g / h / ← — first
- G / l / → — last
- q / ctrl-c — quit
The existing stdout path is preserved behind --print (also auto-
enabled when stdout is not a TTY, so pipes / CI logs still behave).
--head / --tail only work in print mode.
Implementation:
- src/replay.ts gains pure helpers `groupRecordsByTurn` (groups records
into turn-pages, preserving in-turn order) and `computeCumulativeStats`
(stats up to and including a given page index). These stay in the
library module so they're unit-testable without Ink.
- src/cli/ui/ReplayApp.tsx — the new Ink component. Reuses StatsPanel
and writes its own RecordView (lighter than EventRow, no streaming /
planState / branch paths to worry about in replay).
- Cursor defaults to the last page because users usually want the
summary + final turn first, not to start from turn 1.
+6 pure tests for groupRecordsByTurn + computeCumulativeStats.
Suite: 165 passing (was 159).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Ships the v0.1 + v0.2 work as a single versioned release.
- package.json: 0.0.6 → 0.2.0
- src/index.ts: VERSION constant synced
- CHANGELOG.md: new file, covers v0.2.0 (replay/diff/enriched transcripts)
and v0.1.0 (τ-bench-lite + first validated numbers)
- README.md: "Validated numbers" table replaced with the 16-run bench
results (94.3% cache, −42% cost, ~96% cheaper than Claude) and a
zero-cost self-verification block pointing at the committed transcripts
No API calls, no functional changes.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two fixes and one addition:
1. Baseline transcripts now emit one assistant_final per client.chat() call
(per sub-call) instead of one aggregated record per user turn. Reasonix
already emits per-model-call granularity, so diff's count was previously
apples-to-oranges ("turns 3 vs 6" looked like Reasonix doing 2× the work
when it was actually just finer record granularity).
2. Diff rendering renames "turns (assistant)" to "model calls" — less
ambiguous once both sides emit at the same granularity, and
distinguishes model calls from user turns.
3. Commit reference transcripts at benchmarks/tau-bench/transcripts/ so
readers can run `reasonix replay` / `reasonix diff` without an API key.
Gitignore carved out the directory; a brief README explains how to
regenerate (~$0.003/run) and reproduce the headline numbers.
Fresh run on t01_address_happy:
- cache hit: 45.9% → 93.9% (+48.0pp)
- cost: $0.001192 → $0.000953 (−20.1%)
- prefix hashes: 0 (baseline, untracked) → 1 byte-stable (reasonix)
Diff also surfaced a real behavioral difference the v0.1 bench numbers
hid: Reasonix calls lookup_order immediately while baseline asks for
name first. Both pass the task; the two paths are observable in the
committed transcripts.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Turns transcripts into first-class audit artifacts. Anyone with a
.jsonl transcript can reproduce the headline numbers (cache hit, cost,
vs-Claude) without re-running the LLM — the economics travel with the
data.
New surface:
- reasonix replay <transcript> pretty-print a run + rebuild its summary
- reasonix diff <a> <b> [--md] compare two transcripts: aggregate
deltas + first divergence + prefix stability
New modules:
- src/transcript.ts — canonical TranscriptRecord + writer/reader. Meta
line at top-of-file carries source/model/task/mode/repeat.
- src/replay.ts — pure parser that rebuilds SessionSummary from a
transcript's usage/cost fields. Tolerates old (pre-usage) transcripts.
- src/diff.ts — alignment by turn number, Levenshtein similarity for
text divergence, tool-name + tool-args comparison, stdout table +
markdown renderers.
Format bump (backward-compatible): transcripts now persist usage, cost,
model, prefixHash (Reasonix only), and toolArgs. All fields optional
on read — v0.1 transcripts still parse and render (cost/cache shown
as n/a). Format version lives in the _meta line at the top.
Bench runner: new --transcripts-dir <path> flag. Each (task, mode,
repeat) writes <taskId>.<mode>.r<n>.jsonl so bench runs produce
replay/diff-ready receipts, not just aggregate numbers.
Why this closes the loop on v0.1:
The τ-bench-lite report claims "baseline 43.9% / reasonix 94.3% cache
hit" — but a reader had to trust our aggregate. Now a reader can run
reasonix diff on two transcripts from the same task and see, byte by
byte, that reasonix's prefixHash stayed stable while baseline's
churned — and that the cache/cost delta is mechanically attributable
to log stability, not to a different prompt.
Tests: +16 (transcript 3, replay 3, diff 10). Suite now 159 green.
Also threads toolArgs through LoopEvent so chat's --transcript now
persists *what* the model sent to each tool, not just the result.
What's explicitly deferred to a later release:
- Full Ink TUI for replay (j/k scrubbing, search). Current replay
command is stdout-only.
- Split-pane diff TUI. Current diff command is stdout + markdown.
- MCP client (v0.3). Replay/diff infra is prerequisite: without it we
couldn't demonstrate why a Cache-First MCP client matters.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Ships the first reproducible evidence for Pillar 1 (Cache-First Loop):
8 retail-flavored multi-turn tool-use tasks run under both a naive
cache-hostile baseline and Reasonix, sharing the same client/tools/prompt
so the only variable is prefix stability.
Measured on live DeepSeek API (16 runs):
- cache hit: 43.9% → 94.3% (+50.3pp)
- cost/task: \$0.002783 → \$0.001621 (−42%)
- pass rate: 100% → 88% (1 reasonix failure, predicate too strict — see report.md)
- vs Claude Sonnet 4.6 estimated: ~96% cheaper at same token counts
New harness:
- types.ts / db.ts — task schema + per-run DB isolation
- tasks.ts — 8 seed tasks, deterministic DB-predicate pass/fail (no LLM judge)
- user-sim.ts — V3 user simulator at T=0.1
- baseline.ts — deliberately cache-hostile (fresh timestamp + shuffled tools each turn)
- runner.ts — orchestrator with --task / --mode / --repeats / --dry / --verbose
- report.ts — results.json → report.md with explicit scope caveats
- tests/benchmarks.test.ts — 8 harness smoke tests that run without an API key
Also fixes a Windows-only entrypoint bug in the original runner scaffold
(import.meta.url vs argv[1] path encoding mismatch prevented main() from
ever running on Windows).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
User feedback: 'requiring --session <name> to enable persistence is
too much friction. Most chat tools just remember by default.'
Correct. Now:
- Default behavior: every chat is auto-saved to a session named 'default'
and resumed on next launch. Zero friction — the natural ChatGPT-like UX.
- --session <name> picks a different named session.
- --no-session opts out entirely (ephemeral chat).
- App shows a one-time banner on startup describing the current session
state (resumed N msgs / new / ephemeral) so users know what's happening.
- New /forget command deletes the current session file from disk.
- /sessions now marks the current session with ▸.
- Command strip and /help updated.
Library API unchanged: CacheFirstLoop({ session }) is still opt-in.
Only the CLI is opinionated.
Tests: 3 new tests covering /help mentions sessions, /sessions hint,
/forget on session-less loop. Total: 135 (was 132).
New capability: every turn's message log is appended to
~/.reasonix/sessions/<name>.jsonl, and pre-loaded back into the loop's
AppendOnlyLog the next time the CLI is launched with --session <name>.
Rationale: the natural extension of Pillar 1's append-only-log invariant.
If the prefix is immutable AND the log is append-only, the only missing
piece for across-run continuity is writing the log to disk. DeepSeek's
prefix cache likely still hits on resume since the serialized messages
are byte-identical to what they were when originally appended.
Code:
- src/session.ts (new): loadSessionMessages / appendSessionMessage /
listSessions / deleteSession / sanitizeName / sessionPath /
sessionsDir. Name sanitization keeps [\w-] and CJK, replaces
everything else with underscore, 64-char cap. 0600 permissions on
Unix; chmod no-ops on Windows. Malformed JSONL lines are skipped
rather than crashing.
- src/loop.ts: new option on CacheFirstLoopOptions.
When set, the constructor pre-loads prior messages into the log and
every subsequent append is mirrored to disk via a small
appendAndPersist helper. Exposes for the TUI.
- src/cli/index.ts: --session <name> flag on chat.
- src/cli/ui/App.tsx: shows a one-line resume banner on startup when
the loop reports pre-loaded messages.
- src/cli/ui/slash.ts: /sessions command lists saved sessions with
message count + size + mtime, sorted by most recent.
- src/index.ts: exports the session API for library users.
Tests (tests/session.test.ts): 10 tests covering name sanitization,
round-trip append/load, malformed-line tolerance, listing + sort order,
delete. Homedir is stubbed to a tmp dir per-test for isolation.
Total tests: 132 (was 122). Bumps to 0.0.6.
User reported `\frac{总路程}{总时间}` leaked through as raw LaTeX in a
branched R1 answer even though most other \dfrac{} calls rendered fine
in the same output. Unable to reproduce from the paste alone, so
hardening the stripMath layer against the whole category:
- Frac regex now tolerates whitespace around braces and one level of
nested braces inside the numerator/denominator (\frac{\sqrt{2}}{3}).
- All braced commands now trim whitespace from their captured groups
so \frac{ a }{ b } → (a)/(b), not ( a )/( b ).
- New catch-all fallback at the end of stripMath: any surviving
\command, \command{x}, or \command{x}{y} is stripped. Users will
now NEVER see a raw backslash even if the model invents a new macro.
Also exported stripMath from markdown.tsx for direct unit testing.
12 new tests in tests/markdown.test.ts:
- \frac / \dfrac / \tfrac equivalence
- The exact Chinese \frac{总路程}{总时间} case
- Nested \sqrt{} inside \frac{}
- Whitespace tolerance inside braces
- Arrow & bare-command stripping
- Subscript/superscript Unicode mapping
- \boxed, \sqrt formatting
- Full user-reported line sanity check (no backslashes survive)
Total tests: 122 (was 110). Still v0.0.5.
Real-world test surfaced:
总时间:t_1 + t_2 = \dfrac{d}{30} + \dfrac{d}{60}
\dfrac wasn't in stripMath's regex list (only \frac was) so it leaked
through as raw backslashes. Same for \tfrac. Subscripts like t_1, t_2
were also rendering literal '_1' since stripMath did nothing for them.
Fix:
- Fractions: \frac, \dfrac, \tfrac all collapse to (num)/(den).
- New: \binom{n}{k} → C(n,k)
- New: \overline{x} → x̄, \hat{x} → x̂, \vec{x} → →x
- Subscripts/superscripts get translated to Unicode characters when the
content is a single digit/sign (or a brace-wrapped run): t_1 → t₁,
x^2 → x², a_{ij} → a_ij (groups stay readable). Falls back to
pass-through for non-mappable characters.
Existing 110 tests still pass; this is purely additive coverage in
the markdown rendering layer.
Real-world test of --branch 3 revealed the user stared at 'waiting for
first token...' for the full 30-60s it took the first sample to
complete, then saw everything dump at once. Root cause: branch_start
set the streaming slot WITHOUT branchProgress, so the UI fell through
to the non-branching preview that has no relevant info to show.
Two fixes:
1. branch_start now carries an initial branchProgress with completed=0,
total=budget. The TUI detects completed=0 and renders a distinct
'launching N parallel samples...' view explaining what's happening
and the typical wait time, instead of the misleading
'waiting for first token...'.
2. New <Elapsed /> component shows a live mm:ss counter next to the
branch header. Updates once a second via useEffect + setInterval.
Visible immediately so the user has proof the process is alive
even before the first sample completes. Also added to the
non-branching streaming view for symmetry.
README: new 'Why not just use LangChain?' table making the default-
preset value proposition explicit — the five always-on advantages
that hold even without harvest/branching.
Two usability issues from real-world feedback:
1. 'Default should be reasoner+harvest+branch?' — no, but the jump from
default-fast to everything-on requires remembering 3 commands.
Fix: /preset <fast|smart|max> flips the full config in one keystroke.
- fast: deepseek-chat (default, cheapest, ~1 cent / 100 turns)
- smart: reasoner + harvest (~10x cost)
- max: reasoner + harvest + branch3 (~30x cost, slowest)
Reasoning for keeping 'fast' as default: a new user's $1 free credit
on the 'max' preset only lasts ~150 turns; on 'fast' it lasts ~50k.
First impressions decide star conversion.
2. 'Users have to blind-type slash commands to discover them' — correct.
Fix: a CommandStrip component renders a dim hint line right below the
PromptInput showing all top-level commands. Always visible, no need
to remember or run /help:
/help · /preset <fast|smart|max> · /model · /harvest · /branch · /clear · /exit
Placeholder also updated from the wordy '"type a message, or /exit"'
to the cleaner 'type a message, or /command'.
Tests:
- /preset fast/smart/max round-trips verified through loop config.
- /preset with bad arg returns usage hint.
- /help mentions the presets block.
README updated to lead with the /preset idea rather than individual
knob commands.
Total tests: 110 (was 105). Still v0.0.5.
Two issues from the first real branched-turn test:
1. UI looked frozen for 60-90s, then everything dumped at once.
Cause: branching disables streaming because all N samples must
complete before selection. The TUI sat on an empty 'streaming'
spinner with no signal that work was happening.
2. Cost panel under-reported by ~3x.
Cause: stats.record() was called with the chosen sample's usage
only. We paid for all N samples but only counted one.
Fix 1 — progress events:
- BranchOptions gains an onSampleDone callback. runBranches fires it
as each parallel call settles (Promise.all order, but resolved as
each finishes).
- Loop wraps that callback in a queue/waiter pair and yields a new
branch_progress event in resolution order with completed/total +
the just-finished sample's index/temperature/uncertainty count.
- TUI's StreamingAssistant detects branchProgress and renders a
live-updating two-line progress block:
🔀 branching 2/3 (66%)
latest #1 T=0.5 u=2 · waiting for other samples…
- App.tsx dispatches the progress into the streaming slot.
Fix 2 — usage aggregation:
- New aggregateBranchUsage(samples) sums prompt/completion/cache
tokens across all samples.
- Loop builds a single Usage from the aggregate and records it via
stats.record(). Result: cost panel now reflects what was actually
billed. (Harvest-call tokens still not tracked — rounding error
next to the R1 calls.)
Tests:
- onSampleDone fires N times.
- aggregateBranchUsage sums correctly across 3 samples.
Total tests: 105 (was 103). Still v0.0.5.
Flag soup was hurting discoverability. Normal users run `npx reasonix
chat` and never find out harvest or branching exist. Slash commands
put every feature one keystroke away inside the chat.
Commands (see /help):
/help list commands
/status model/harvest/branch/stream state
/model <id> switch models mid-session
/harvest [on|off] toggle Pillar 2 (no arg = toggle)
/branch <N|off> set N parallel samples; N=2..8; auto-enables harvest
/clear clear history view (loop log is kept)
/exit quit
Implementation:
- src/loop.ts: CacheFirstLoop fields that made sense to change
mid-session (model, stream, harvestEnabled, harvestOptions,
branchEnabled, branchOptions) are now mutable. New
`configure(opts: ReconfigurableOptions)` method applies the same
branching/harvest/stream invariants the constructor does.
- src/cli/ui/slash.ts: parseSlash + handleSlash. Unknown commands fall
through with a hint to /help. Branch budget capped at 8.
- src/cli/ui/App.tsx: slash commands handled before normal submit;
messages rendered as info rows.
- src/cli/ui/StatsPanel.tsx: shows live `· harvest · branch3` badges
next to the model, plus a '· type /help' hint in the corner.
- tests/slash.test.ts: 14 tests covering parse, all commands, toggle
behavior, invalid args, unknown commands, branch cap.
CLI flags kept for CI/scripting; slash commands are the recommended UX
for interactive use. README updated to lead with the slash-command flow.
Total tests: 103 (was 89).
New feature: `reasonix chat --branch N` (or `{ branch: N }` in code) fans
the turn out into N parallel samples at spread temperatures, harvests each
one's reasoning, and selects the sample with the fewest flagged
uncertainties. Ties broken by answer length (Occam).
Unique value: because DeepSeek is ~20× cheaper than Claude, running N=3 R1
samples is still cheaper than a single Claude call, while the
confidence-weighted selection tends to beat single-sample answers on
multi-step reasoning.
Code:
- src/consistency.ts: runBranches + defaultSelector + BranchOptions /
BranchSample / BranchResult / BranchSelector types. Spreads temperatures
uniformly across [0, 1] by default; custom temperatures array supported.
- src/loop.ts: new branch option on CacheFirstLoopOptions (number or
BranchOptions). Enabling it forces non-streaming and auto-enables
harvest (the selector scores on uncertainties). Emits branch_start /
branch_done events plus branch summary on assistant_final.
- src/cli/index.ts: --branch <n> flag.
- src/cli/ui/EventLog.tsx: new BranchBlock renders
'🔀 branched N samples → picked #K' with per-sample temperature/uncertainty.
- src/cli/ui/App.tsx + commands/chat.tsx: branch option plumbed through.
- src/index.ts: exports runBranches + types.
Tests:
- tests/consistency.test.ts: 6 tests — selector tie-breakers, budget=1
no-op, N=3 parallel with varied temps, uncertainty-based selection,
custom temperatures override.
README rewritten:
- Badges (npm version, CI, license, downloads, node).
- Feature table covering Cache / Harvest / Branch / Repair / Retry / TUI.
- Validated numbers table with 3 real measurements.
- CLI + library usage examples with --harvest / --branch.
- Clean install / dev / non-goals sections.
docs/ARCHITECTURE.md: new Branch-and-Select section between Pillar 2 and
Pillar 3; roadmap updated.
Total tests: 89 (was 83). Bumps to 0.0.5.
Pillar 3's flatten module existed but was never called — registered
tools were sent to the model with their original schemas, even when
DeepSeek V3/R1 are known to drop arguments on schemas with >10 leaf
params or >2 levels of nesting.
Now ToolRegistry analyzes every registered schema:
- analyzeSchema() decides if flattening is warranted.
- If so, the registry stores both the original (for nestArguments) and
the flat (for the API spec) form.
- specs() emits the flat schema to the model.
- dispatch() re-nests dot-notation args back to the original shape
before invoking the user's fn — but only when the incoming args
actually use dot keys, so nested args from a model that ignored the
flat spec still work (defensive).
API:
- new ToolRegistry({ autoFlatten: false }) opts out.
- reg.wasFlattened(name) introspects the decision.
5 new tests in tests/tools.test.ts covering: shallow schemas left alone,
deep schemas flattened + re-nested round-trip, wide-schema (>10 params)
detection, defensive nested-args pass-through, opt-out.
Total tests: 83 (was 78). Bumps to 0.0.4 — Pillar 3 now ships all four
submodules wired end-to-end.
Takes reasoning_content from deepseek-reasoner and runs a cheap V3 call in
JSON mode to extract a typed plan state:
{ subgoals, hypotheses, uncertainties, rejectedPaths }
Enable with `reasonix chat --harvest` or `new CacheFirstLoop({ harvest: true })`.
Default is off — harvest adds a non-zero V3 call per turn (~$0.0001).
Implementation:
- src/harvest.ts: real harvest() replacing v0.0.1 stub. Uses DeepSeek JSON
mode (response_format: { type: json_object }). Fails closed — malformed
JSON / API errors / short reasoning all return emptyPlanState() so the
main turn is never aborted.
- src/types.ts + src/client.ts: new responseFormat option threaded through
to the API payload.
- src/loop.ts: `harvest?: boolean | HarvestOptions` in CacheFirstLoopOptions.
When enabled and reasoning present, the plan state is computed after the
model call and attached to the assistant_final event.
- src/cli/index.ts + src/cli/commands/chat.tsx + src/cli/ui/App.tsx: CLI
--harvest flag plumbed through to the loop constructor.
- src/cli/ui/EventLog.tsx: new PlanStateBlock renders the harvested state
as dim magenta `‹ subgoals (N): a · b · c` lines above the answer.
Tests:
- tests/harvest.test.ts: 12 tests covering empty inputs, JSON parsing,
prose-wrapped JSON extraction, malformed JSON, API errors, array caps,
item-length trimming, snake_case fallback, non-string filtering.
Total tests: 78 (was 66). Bumps roadmap: Pillar 2 no longer deferred to v0.2.
After the first turn finished, typing was silently ignored: the prompt
box rendered fine but keystrokes didn't register. Cause: PromptInput
conditionally rendered TextInput based on the `disabled` flag. Mount/
unmount cycles dropped Ink's stdin raw-mode claim on some terminals, so
the freshly-mounted input wasn't receiving keystrokes.
Fix: keep TextInput mounted at all times; toggle its `focus` prop
instead of unmounting. useInput inside TextInput no-ops when focus=false,
but the raw-mode claim is preserved, so keystrokes land cleanly once we
re-enable focus.
Bumps to 0.0.3 for re-publish.
Previously, the CLI errored out on first run with 'Copy .env.example to
.env and fill it in' — a lousy welcome for anyone who did `npx reasonix
chat` expecting it to just work.
Now:
- chat command renders a Setup screen with masked-input TextInput if no
key is found. Key validated by format (sk- prefix + 16+ chars), saved
to ~/.reasonix/config.json with 0600 permissions.
- run command falls back to readline.question for the same flow when
stdout is a TTY; non-TTY still errors with a hint.
- Library users unaffected: DeepSeekClient still only reads
DEEPSEEK_API_KEY from env; the config file is a CLI convenience.
New module src/config.ts with readConfig / writeConfig / loadApiKey /
saveApiKey / isPlausibleKey / redactKey — all exported from the package
root so library users can opt in to the same storage.
9 new tests in tests/config.test.ts covering env-var precedence, file
fallback, format validation, and redaction. Total tests: 66.
Bumps version to 0.0.2 for re-publish.
Without this, `npm publish` silently strips the bin field, which would
leave `npx reasonix` broken for installed users even if the tarball
otherwise looks correct. Caught via `npm pkg fix` on the first publish
attempt.
- src/retry.ts: new fetchWithRetry wrapper. Retries on 408/429/500/502/503/504
and network errors (fetch throws). Does NOT retry on 4xx auth/bad-request
errors, aborts, or mid-stream body read failures (retrying would re-bill
and desync context). Honors Retry-After header, capped by maxBackoffMs.
Exponential backoff with 75-125% jitter to spread concurrent clients out.
- src/client.ts: DeepSeekClient.chat and .stream now go through fetchWithRetry.
New { retry } option on DeepSeekClientOptions; pass { maxAttempts: 1 } to
disable.
- tests/retry.test.ts: 11 tests covering retry/no-retry statuses, network
errors, maxAttempts exhaustion, abort handling, Retry-After, onRetry.
- tests/loop.test.ts: updated the failure-path test to use status 401
(non-retryable) so it completes instantly.
Total tests: 57 (was 46). This closes the #1 production risk before launch:
a single 503 during DeepSeek peak hours no longer kills the chat session.
- Markdown: outer container now uses gap={1}, adding a blank line
between each block-level element (paragraph / list / heading / code /
hr / inline display equation after LaTeX strip). Previously sections
like '步骤:' flowed into the list without visible separation.
- ReasoningBlock: cap reduced from 500 → 220 chars, rendered as a
single dim italic line ('↳ thinking: ...') instead of a 19-line
bordered block. Full reasoning still lands in --transcript.
Two follow-up issues from the R1 test:
1. Streaming view duplicated in scrollback
- Cause: during long streams, the dynamic render area grew past the
terminal viewport. When finalize committed the full Markdown-rendered
version via <Static>, the terminal could not erase the scrolled-up
frames of the previous streaming pass, so users saw both the raw
streaming text AND the formatted final output stacked.
- Fix: new <StreamingAssistant> view keeps the dynamic region to a
fixed 1–3 line footprint — 'assistant (streaming · 245 + think 88
chars)' with a single tail-preview line. No matter how long the
stream gets, the dynamic area stays in-viewport and Ink can clear
it cleanly on finalize.
2. LaTeX commands leaking through (\implies, \to, \quad, etc.)
- Fix: extended stripMath in markdown.tsx with the full set of
common commands — arrows (\to, \implies, \rightarrow), relations
(\leq, \geq, \neq, \approx), set membership (\in, \notin),
greek letters, operators (\cdot, \times, \div, \pm), spacing
(\quad, \qquad, \,, \;, \!), and line breaks (\). Also
collapses runs of whitespace that the strip can leave behind.
Two UX issues surfaced during real R1 usage:
1. UI flicker on long streaming outputs
- Cause: every DeepSeek token triggered a React state update, which
re-rendered the entire App subtree (StatsPanel + all events + input).
On a 1320-token answer that's ~1300 full-screen rewrites in seconds.
- Fix: split state into 'historical' (completed events) and 'streaming'
(current assistant turn). Historical goes inside Ink's <Static> which
renders each item exactly once — zero redraw for old messages.
Streaming deltas are buffered in refs and flushed at 16Hz (60ms
interval) instead of per-token. EventRow is React.memo'd for good
measure.
2. Markdown / LaTeX rendered as raw text
- Cause: assistant text was dropped into <Text>{text}</Text> so users
saw literal '\(', '\)', '**bold**', '# header', etc.
- Fix: new src/cli/ui/markdown.tsx — line-based MD parser producing
Ink elements. Handles ATX headings, ordered / unordered lists,
fenced code blocks, inline bold / italic / code, and strips the
LaTeX scaffolding (\(, \), \[, \], \boxed{...}, \cdot, etc.)
that terminals can't render anyway. Markdown is applied on finalize
only — during stream we keep raw text for speed.
- Bug: assistant_final dispatched mark_assistant_done which only set
streaming=false — ev.stats and ev.repair were dropped on the floor, so
the '↳ cache X% · tokens … · $…' line never rendered.
- Missing feature: reasoning_content streamed from deepseek-reasoner was
captured by the loop but never shown to the user.
Changes:
- EventLog: DisplayEvent gains a reasoning field; assistant row renders it
in a dim italic 'thinking ›' block above the final answer (capped at 500
chars preview).
- App.tsx: new reducer actions append_reasoning and finalize_assistant
(replacing mark_assistant_done); reasoning deltas are appended as they
stream; stats + repair note are attached atomically on assistant_final.
After this, Phase C (deepseek-reasoner) will show R1's thinking live above
the answer, and every assistant turn shows the per-turn cache hit stats.
- README: replace projected ranges with measured numbers from real API runs
- 5-turn Chinese chat: 85.2% cache hit, 93.9% savings vs Claude
- 2-turn calculator tool-use: 94.9% cache hit, 95.8% savings vs Claude
- tests/loop.test.ts: 5 integration tests for CacheFirstLoop using fake fetch
(single-turn, telemetry recording, tool dispatch, prefix stability, 5xx error)
- Total tests now 46 (was 41)
loadDotenv was only called inside CLI commands, so any direct script import
(examples/*, benchmarks/*) hit 'DEEPSEEK_API_KEY is not set' even when the
user had a valid .env file. Promote env.ts from cli/ to src/, export loadDotenv
from the library index, and call it at the top of every script entrypoint.
Target branch: 2.x features and fixes go to `studio`. 1.x takes bug fixes,
provider/API compatibility, release/updater, security and platform stability
only, on `main-v2`.
Pull requests are limited to maintainers and invited contributors; one from
anyone else is closed automatically. Open an issue instead.
-->
## Summary
-
## Cause
-
## Blast radius
-
## Neighbouring behaviours tested
-
## Why this layer
-
## UI changes
<!--
Delete this section if the PR touches nothing under `desktop/frontend-next/src`
or the website pages.
-->
- Screenshots, before and after: light and dark, a wide window and a phone-width one (about 390 px). Attach them to this description.
- Entries moved, hidden or removed: none / list each one.
- Hiding or removing a visible control needs a linked issue and a release-notes line naming it. Do not retire UI with `display: none !important` or a feature flag.
- If a row of `docs/STUDIO_PARITY.md` changes, update it here.
## Issues
<!--
If this resolves a report, put `Fixes #123` on its own line — GitHub only
auto-closes from a bare line, so `- Fixes #123` in a list does nothing and the
report stays open. If it only relates to one, use `Refs #123` instead: the
release workflow then asks that reporter to verify once the fix ships.
-->
## Verification
-
For a GSAP to WAAPI/CSS migration (or any cross-API replacement), document
the source-to-target contract here: easing syntax, time units, callbacks,
cancellation, reduced-motion behavior, and failure fallback. Verification must
assert that the target API was actually called; a mock that silently skips it
does not count.
## Disclosure
- [ ] AI assistance was used for this change (optional; for transparency only, it does not change how the change is reviewed)
# An unsigned package is not a lesser APK, it is an unusable one: Android's
# package manager rejects it outright rather than reporting a signature
# mismatch. Say so where the run summary can be read, instead of letting a
# green build imply a shippable artifact.
- name:Say what an unsigned build means
if:steps.key.outputs.signed != 'true'
run:|
echo "::warning::no signing key configured, so this APK is unsigned. Android refuses to install an unsigned package, so the release will carry no APK; the file stays a workflow artifact for whoever signs it."
{
echo "### No APK on this release"
echo ""
echo "The build produced an unsigned APK, which Android refuses to install."
echo "It is attached to this run as a workflow artifact only. Add the four"
Write-Output "::error title=studio-signing.unexpected-signer::STUDIO_SIGNING_SUBJECT is '$($env:EXPECTED_SUBJECT)' but $file is signed by '$($certificate.Subject)'"
$failed = $true
}
}
if ($failed) { exit 1 }
'Certum payload and installer signing, signer, trust and timestamps passed.' >> $env:GITHUB_STEP_SUMMARY
platform=$(git diff -z --name-only --no-renames "$BASE_SHA" HEAD | bash scripts/ci-platform-scope.sh)
if git diff --name-only --no-renames "$BASE_SHA" HEAD |
grep -qE '^(desktop/electron/|desktop/packaging/|desktop/cmd/update-helper/|desktop/cmd/studio-manifest/|desktop/go\.(mod|sum)$|cmd/reasonix-studio-host/|internal/platform/(update|appupdate)/|go\.(mod|sum)$|scripts/(linux-install-smoke|verify-linux-package|verify-linux-appimage|verify-studio-artifacts)\.sh$|scripts/(windows-signing-lib|verify-windows-package|verify-windows-authenticode|install-smoke)\.ps1$|\.github/workflows/(studio|release-studio)\.yml$)'; then
if ($run.ExitCode -eq 0) { throw 'the arm64 installer exited 0 on an x64 machine' }
if (@(Get-ChildItem -Recurse -Force $target -ErrorAction SilentlyContinue).Count -ne 0) { throw 'the arm64 installer wrote into the target on an x64 machine' }
- HTTP `serve` protections, including the default per-launch token, the launch
token every state-changing request requires when authentication is opted
out, localhost binding assumptions, JSON-only state-changing requests, and
CORS restrictions.
- Desktop and bot session isolation, including per-workspace session metadata
and configured bot allowlists.
- Updater, install, and release verification paths.
The following are normally treated as trusted local/operator-controlled inputs
unless another bug lets an untrusted actor supply them:
- CLI arguments and text typed directly by the local user.
- The user's own configuration under the Reasonix home directory.
- Explicit `@path` references supplied by the local user to attach local files.
- MCP servers, language servers, hooks, and slash commands installed, enabled,
or approved by the local user.
- Provider base URLs and model names configured by the local user.
The following can be security issues when reachable by an untrusted actor or
when they bypass the intended boundary:
- Reading or writing files outside the configured workspace without explicit
local-user intent.
- Following symlinks or path traversal to escape workspace confinement.
- Running shell commands or external tools without the required permission gate.
- Leaking credentials, environment variables, prompt history, local files, or bot
messages to logs, model providers, MCP servers, crash reports, or telemetry.
- Allowing a website to drive the local HTTP server through CSRF, CORS, or
content-type bypasses.
- Letting a bot user outside the configured allowlist submit prompts, approve
tools, or access a project workspace.
- Trusting unverified update artifacts, plugin definitions, or downloaded
binaries.
## Project Configuration
Files that arrive with a workspace are untrusted input: `reasonix.toml`,
`.reasonix/settings.json`, `.mcp.json` and the project `.env`. Cloning a
repository is not a decision to trust its author, so these files may narrow
what the user configured and never widen it.
| Setting | What a workspace file may do |
| --- | --- |
| `sandbox.bash` | Move `off` to `enforce`, never back |
| `sandbox.network` | Move `true` to `false`, never back |
| `sandbox.forbid_read`, `sandbox.denied_domains` | Add to the user's lists |
| `sandbox.allow_write`, `sandbox.workspace_root` | Apply only when they resolve inside the workspace, symlinks followed; `${VAR}` in any sandbox path expands from the process environment only |
| `sandbox.host_authorities`, a user's `sandbox.allowed_domains` | Nothing |
| `permissions.deny`, `permissions.ask` | Add to the user's rules |
| `[[providers]]`, `tools.system_one` endpoints | Declare them; they stay out of use until approved, and model settings naming them fall back to the user's |
An "always allow" answer, or extra write access, granted in a workspace is
stored under the Reasonix home, not in the workspace.
Programs a workspace names for the host to run stay off until the user
approves them for that workspace:
- Hooks, language server commands, `tools.search.rg_path`,
`tools.shell.path`, `[browser]` and `tools.system_one.laya.python` are
approved with `reasonix trust`, or for hooks by saving them from the hooks
editor.
- An approval is stored under the Reasonix home with a digest of the
declaration and of the workspace files it names; any change needs approval
again. Approvals and grants belong to one workspace folder.
- Hooks and language servers are checked against their approval again before
each start, and refused if a file they name changed, appeared or now
resolves elsewhere.
- A single program path (`tools.shell.path`, `tools.search.rg_path`,
`[browser]`, `laya.python`) may not point into the workspace, an
`allow_write` root, a temporary directory or a toolchain cache the bash jail
leaves writable, and may not climb with `..`; its approval covers the
program file's content.
-`tools.system_one.laya.local` is read from the user's configuration only.
- Without an interactive frontend they stay off.
- MCP servers a workspace declares stay off until the user enables them for
that workspace.
A project value that is not applied is reported as a load warning with the
reason. A way for workspace files to widen any of the above without the
user's approval is a security issue.
## `@` File References
Reasonix supports `@path` references so users can include local files and images
in a prompt. This is intentional local functionality, but implementations must
preserve these invariants:
- In workspace-scoped sessions, relative and absolute paths must resolve under
the active workspace root before file content is read or attached.
- Path traversal such as `..` must not escape the workspace root.
- Symlinks must not be usable to bypass the intended workspace boundary.
- Unscoped local CLI compatibility must not be exposed to remote, bot, or
browser-controlled inputs unless an equivalent workspace boundary is applied.
- File content should be size-limited and binary content should not be dumped as
prompt text.
Static analysis alerts about path expressions should be triaged against these
rules: user-controlled path data is expected, but the access must either stay
inside the configured workspace or be clearly limited to trusted local CLI use.
## Out of Scope
The following reports are usually out of scope unless they demonstrate a bypass
of one of the boundaries above:
- A local user intentionally asks Reasonix to read, edit, or send their own
files to a configured model provider.
- A local user installs or enables a malicious MCP server, hook, slash command,
language server, or shell command and then grants it permission.
- A configured model provider, proxy, or MCP server receives data the user
intentionally sent to it.
- Denial-of-service issues that only affect the local user's own session and do
not corrupt files, leak secrets, or bypass permissions.
- Issues requiring administrator/root access on the user's machine before
interacting with Reasonix.
- Vulnerabilities in third-party services, models, proxies, or plugins that are
not caused by Reasonix behavior.
## Coordinated Disclosure
This is a community-maintained project. Maintainers will make a best-effort
assessment, ask follow-up questions when needed, and coordinate fixes before
public disclosure for confirmed vulnerabilities.
Please give maintainers reasonable time to investigate and release a fix before
publishing exploit details. If you plan to disclose on a timeline, include that
`verify-page.sh` is the one to run after a change: it starts the kernel with the
same arguments `Kernel.kt` uses (`--auth token`, `--token-file`, `--port-file`,
`-page`) and checks that it binds a port and answers 200. Without a device, that
is as deep as the chain can be verified.
## Where the code is
| File | Owns |
| --- | --- |
| `MainActivity.kt` | The WebView, the back gesture, downloads, external links, renderer restart |
| `Kernel.kt` | Unpacking the page, starting and stopping the kernel, waiting for the port, health probes, logs, the workspace directory |
| `KernelService.kt` | The foreground service that keeps a long turn alive |
| `NativeBridge.kt` | `@JavascriptInterface`: what the page may ask the phone for |
| `BrowserShellServer.kt` | Loopback HTTP server the kernel's browser tools drive the overlay WebView through |
| `Downloader.kt` | Writing a kernel-produced file through the system document picker |
The page reaches the shell through `window.reasonixHost` and `ReasonixNative`,
defined in `desktop/frontend-next/src/port/host.ts` (`AndroidHost`).
**Phone and desktop share one page build.** What differs only on a phone is
decided at runtime, not by a second set of components. `phoneShell()` in
`src/port/host.ts` and the `[data-shell="android"]` selector in `mobile.css` both
read `<html data-shell="android">`, which `index.html` sets before the bundle
loads.
One attribute feeding both is what keeps style and components from disagreeing
about what a phone is.
## What the page may ask the phone for
`NativeBridge` is reachable from whatever document the WebView holds, so every
method that touches the device asks `trusted()` first.
The activity answers by comparing the **main frame's** origin against the
kernel's and against the one paired computer the person scanned a code for. A
page that navigated elsewhere is not trusted, even though it may still hold the
object.
Five methods answer without the check — `version`, `systemTheme`, `safeArea`,
`setLayerOpen`, `setRunning` — because they report back what the page already
knows about its own window and grant nothing.
`openInApp(url)` is the pairing decision, not a navigation one: it loads a URL in
this window only for the origin the scanner just returned, and only once.
Without that, any page holding the kernel origin could hand itself the bridge.
External links leave through the browser. A non-web scheme is routed to the
system only for `mailto:` and `tel:`; everything else is dropped, because an
`intent://` URL can start an arbitrary exported activity with caller-supplied
extras.
## Permissions, and what they cost
`MANAGE_EXTERNAL_STORAGE` — opening a folder on the phone as a workspace. The
kernel is a Go binary: it opens real paths with `open(2)`, and SAF hands back a
`content://` URI it cannot open.
Requested from the folder-picker action, never at launch. Android shows no dialog
for it and opens system settings instead.
**There is no OS-level sandbox around this kernel.** The PR sets the sandbox to
off on Android, so confining the agent to the chosen folder is Reasonix's own
write-root check and nothing else. A shell tool with all-files access can reach
all shared storage.
`REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` — Doze freezes the app group, which stops
a turn that is still running. Asked once when a turn actually runs, never at
launch, and the person can refuse. Refusing costs battery life during long turns
and nothing else.
**Google Play restricts this permission**: fine for a sideloaded build, a
store-policy risk if this is ever listed.
`FOREGROUND_SERVICE` / `FOREGROUND_SERVICE_DATA_SYNC` — keeping the kernel alive
while the screen is off. `dataSync` is capped per 24 hours from Android 15. It is
the closest honest description of "an agent is working".
`CAMERA` — reading the pairing code a computer shows. Requested when the person
asks to scan, never at launch. `ScanActivity` is not exported.
`READ_EXTERNAL_STORAGE` / `WRITE_EXTERNAL_STORAGE` — the same folder walk below
API 33. `maxSdkVersion`-gated; above 33 they are superseded by the permission
above.
`allowBackup=false` with explicit extraction rules, so a `keystore` or a token in
app storage never leaves the device in a cloud backup.
## Cleartext HTTP
The kernel serves its page on `127.0.0.1:<port>`, and a paired computer serves
the same page over its LAN address. Both are plain HTTP.
Neither address can be written into a `network-security-config`: the port is
chosen at start, the LAN address at scan time, and the format matches literals
and domains, not subnets.
So the config permits cleartext and the boundary is in the code instead.
`shouldOverrideUrlLoading` sends every other http(s) origin to the browser, and
the bridge answers only the kernel and the just-paired computer. A plaintext page
on the LAN cannot become the document holding the bridge.
## What goes into the APK
| Content | Size | Why it is shaped this way |
| --- | --- | --- |
| `lib/arm64-v8a/libreasonix.so` | 45 MB | Go static binary, stripped. It is a `.so` rather than a file in `assets/` because only `nativeLibraryDir` is guaranteed executable — a binary copied to app storage fails on a device whose data partition is mounted `noexec`. |
| `assets/page/` | 14 MB | The frontend build, including the Inter and Noto Sans SC fonts, `noCompress` |
| `assets/LICENSE` | 1 KB | The repository's MIT licence, verbatim. MIT requires the notice and the licence text to accompany a binary distribution. |
`assets/LICENSE` is generated by `sync-page.sh` from the repository's root
`LICENSE`, not committed a second time: a checked-in copy drifts when the root
file is updated.
It sits in `assets/` rather than `assets/page/` because that directory is removed
and rebuilt on every build.
A release APK is about 31 MB.
## Building
**The Gradle wrapper is committed**, jar and all. `build.sh` refuses to run
without `gradlew` rather than generating one from whatever `gradle` is on `PATH`:
the dependency versions are part of the build.
`gradle-wrapper.properties` pins `distributionSha256Sum`, so a mirror that serves
a different distribution zip fails verification instead of being unpacked and
run. Dependency repositories are the official ones only — a mirror belongs in a
user-level init script.
**Signing.** A release with no key configured comes out **unsigned**
(`app-release-unsigned.apk`) with a warning. It used to fall back to the debug
key, which produced an artifact that looked shippable and was signed by a
per-machine key nobody chose: it could not install over the previous build.
Point the build at a real key by writing `keystore/keystore.properties`
(`storeFile`, `storePassword`, `keyAlias`, and optionally `keyPassword`) or by
setting the matching `REASONIX_KEYSTORE*` environment variables. Key material
stays out of the repository and out of build logs.
Debug builds always use the debug key. Signing a debug build with the release key
would let anyone who can read the keystore produce a build that installs over the
shipped one under the same signature.
**Non-ASCII checkout paths.** AGP refuses to build under a path with non-ASCII
characters on Windows unless `android.overridePathCheck=true` is set. That is a
property of one machine's disk layout, not of this project, so it is not in the
repository's `gradle.properties`.
Set it in a user-level `~/.gradle/gradle.properties` or pass
// The extraction script: prefer article/main for content pages,
// fall back to body. innerText preserves visual line breaks. It
// also stamps a ref on every element a person could act on, so the
// kernel can name one in an act step the way the desktop backend
// names an accessibility node. A ref already on an element is kept,
// so it stays the same across snapshots of one document; a fresh
// document starts the numbering over, and the kernel only accepts a
// ref from the snapshot it last read.
valscript="""
(function(){
var seq = window.__rxRefSeq || 0;
var used = {};
var marked = document.querySelectorAll('[data-rx-ref]');
for (var i = 0; i < marked.length; i++) { used[marked[i].getAttribute('data-rx-ref')] = true; }
function roleOf(el) {
var tag = el.tagName.toLowerCase();
var role = (el.getAttribute('role') || '').toLowerCase();
if (role) return role;
if (tag === 'a') return 'link';
if (tag === 'button') return 'button';
if (tag === 'select') return 'combobox';
if (tag === 'textarea') return 'textbox';
if (tag === 'input') {
var t = (el.getAttribute('type') || 'text').toLowerCase();
if (t === 'checkbox' || t === 'radio' || t === 'submit' || t === 'button' || t === 'reset') return t;
return 'textbox';
}
return 'generic';
}
function nameOf(el) {
var n = el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.getAttribute('name') || '';
if (!n) { n = (el.innerText || el.textContent || '').trim(); }
return n.replace(/\s+/g, ' ').slice(0, 160);
}
var sel = 'a[href],button,input,select,textarea,[role=button],[role=link],[role=checkbox],[role=radio],[role=tab],[role=menuitem],[contenteditable=true]';
var els = document.querySelectorAll(sel);
var elements = [];
for (var j = 0; j < els.length; j++) {
var el = els[j];
var ref = el.getAttribute('data-rx-ref');
if (!ref) {
do { seq++; ref = 'e' + seq; } while (used[ref]);
el.setAttribute('data-rx-ref', ref);
used[ref] = true;
}
var raw = (el.value != null && String(el.value) !== '') ? String(el.value).slice(0, 160) : '';
echo"licence: app/src/main/assets/LICENSE (copied from the repository's LICENSE)"
Loaded 100 of 11106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.