Compare commits

..
551 Commits
Author SHA1 Message Date
YHH a5adca41ac chore(release): 0.27.3 (#315) 2026-05-06 01:12:27 -07:00
YHH aed4d431cb chore(ui): remove orphan ChromeBar.tsx (#314)
No live render path — `App.tsx` mounts `StatsPanel`, which has its own
`ChromeRow` that diverged from `ChromeBar` and is the bar users actually
see. Only references are a CHANGELOG history line and one test
description string ("'w \$0.91' style").

The two formatter helpers `ChromeBar` once owned (`formatBalance` /
`formatBalanceLabel`) already live in `theme/tokens.ts` after #272 / #313.
2026-05-06 01:06:20 -07:00
YHH 0acfcefb89 fix(ui): top bar cost + subagent end-cost follow wallet currency (#313)
After #272 fixed StatusRow / UsageCard / ChromeBar BalancePill, three
display sites still hardcoded `$` and ignored the wallet currency:

- StatsPanel.ChromeRow (the live top bar) — cost label `[$0.0058]`
- StatsPanel.ChromeRow — balance label inline-formatted, bypassing the
  shared formatBalance helper from #272
- useSubagent end-event summary — ` · $0.0123` cost suffix

Now all three route through formatCost / formatBalance and follow the
live wallet symbol. Render tests added in ui-stats-panel-currency.test.tsx
covering USD / CNY / no-wallet variants.

useSubagent gets a `getWalletCurrency` thunk (not a snapshot value)
because subagent runs can outlive a balance refresh — the thunk reads
the latest currency at end-event time.

Out of scope: ChromeBar.tsx (orphan, no live render path), DiffApp.tsx
(dev tool comparing historical USD numbers), BudgetRow (USD by definition,
user sets `--budget` in USD). SessionPicker tracked separately in #312.
2026-05-06 00:58:47 -07:00
Wesley Vianaandesengine 9cb0bdbc5f Fix: usd currency on status bar (#272)
* fix: Currency for USD wrong afeter TUI redesign.

* red: tests for the currency bug

* Fix implementation

* fixup: collapse tokens helpers + fix UsageCard cost bug

Addresses the two review comments on this PR:

1. Undefined-currency fallback now defaults to CNY for all three helpers
   (formatBalance, formatCost, balanceColor) — matches pre-fix unconditional ¥.
2. Seven helpers (formatCNY, formatBalance, formatBalanceLabel,
   formatWalletDisplay, formatCost, balanceColorCny, balanceColorForBalance)
   collapsed to three: formatBalance, formatCost, balanceColor.

Also fixes a separate bug surfaced while collapsing: UsageCard turn cost
(header) and session cost (body) used formatCNY, which was unconditional ¥
regardless of wallet currency. They now use formatCost(…, balanceCurrency)
and follow the wallet symbol like StatusRow does.

Render tests added for UsageCard turn/session cost in USD wallet mode.

---------

Co-authored-by: esengine <[email protected]>
2026-05-06 00:44:35 -07:00
YHH 2ca403670d refactor(loop): extract message builders, failure tracker, forced-summary helper (#311)
loop.ts 1331 → 1219 (−112). Three sibling files under src/loop/:
- messages.ts: pure ChatMessage builders (assistant + synthetic)
- turn-failure-tracker.ts: per-turn count/types + threshold tipping
- force-summary.ts: forced-summary generator behind a small DI context

Drops two now-unused imports (errorLabelFor, reasonPrefixFor) from loop.ts.
2026-05-06 00:06:31 -07:00
YHH c6e5bf4b02 refactor(loop): move LoopEvent / BranchSummary types + hook helpers out (#309)
PR2 under #307. Three more pieces that didn't depend on `this`:

- new `src/loop/types.ts` — `EventRole`, `BranchSummary`, `BranchProgress`,
  `LoopEvent`. The public-API re-export from `loop.ts` is preserved
  (`export type { ... } from "./loop/types.js"`), so consumers importing
  from `reasonix` see no change.
- new `src/loop/branch.ts` — `summarizeBranch` lives next to the types
  it produces.
- new `src/loop/hook-events.ts` — `safeParseToolArgs` + `hookWarnings`.
  These format hook outcomes as `LoopEvent`s and were the only callers
  of `formatHookOutcomeMessage` / `HookOutcome` from `./hooks.js`, so
  those imports leave `loop.ts` too.

`loop.ts`: 1414 → 1332 lines. No public API change. `npm run verify`
green (2336 pass / 1 skip).
2026-05-05 21:07:20 -07:00
YHH 08c7f2be81 refactor(loop): extract escalation marker + summary-reason helpers (#308)
PR1 under #307. Six functions and three constants that don't touch
`this` had no business living inside the `CacheFirstLoop` class file.

- new `src/loop/escalation.ts` — `parseEscalationMarker`,
  `isEscalationRequest`, `looksLikePartialEscalationMarker` plus
  `NEEDS_PRO_MARKER_PREFIX` / `NEEDS_PRO_MARKER_RE` /
  `NEEDS_PRO_BUFFER_CHARS`. The streaming chunk consumer + post-call
  retry path call these as plain functions now.
- `src/loop/errors.ts` gains `reasonPrefixFor` + `errorLabelFor` next
  to `formatLoopError`. They share the same `"budget" | "aborted" |
  "context-guard" | "stuck"` reason union and were the only callers.

`loop.ts`: 1463 → 1414 lines. No public API change — these were all
private / file-local. `npm run verify` green (2336 pass / 1 skip).
2026-05-05 21:02:53 -07:00
YHH 8befb44e5e fix(web): rewrite htmlToText with a real HTML parser (#306)
The chain-of-regex approach was tripping CodeQL across three rules
(bad-tag-filter, incomplete-multi-character-sanitization,
polynomial-redos) on the same set of patterns:

- `<tag[\s\S]*?</tag>` misses `</tag >` (whitespace before `>`) and
  re-exposes `<tag` after one removal pass on `<scr<tag>ipt>`-shaped
  input.
- `<[^>]+>` doesn't handle attribute values containing `>` (rare but
  legal in unquoted contexts) and is the canonical "incomplete
  sanitization" footgun.

Replaces both with a `node-html-parser` walk:

- `htmlToText` parses the input, removes `script / style / noscript /
  nav / footer / aside / svg` blocks via `querySelectorAll`, then
  walks the surviving tree and emits text with `\n` breaks at the
  block-level tags we care about (`p`, `div`, `br`, `h1-6`, `li`,
  `tr`, `section`, `article`).
- `stripHtml` (used by `parseMojeekResults`) becomes `parseHtml(s).text`.
- `decodeHtmlEntities` stays — kept for the post-parser pass since
  parser-decoded text can still contain numeric entities in edge
  attribute contexts.
- 5 MB input cap retained.

`node-html-parser` 7.x: 25 KB gzip, zero deps, ~30k packages
depend on it, active maintenance. Lighter than `parse5` for our
use case (we don't need full HTML5 conformance — just the tree).

21 web-tools tests pass unchanged; 2336 total tests green.
2026-05-05 20:38:23 -07:00
zerone0x b65ed747c9 fix(events): emit tool audit trail events (#260) (#304) 2026-05-05 20:28:24 -07:00
zerone0x 86be00299e fix(mcp): make inspect errors actionable (#101) (#303) 2026-05-05 20:24:10 -07:00
YHH b634b5e171 fix(codeql): drain 3 real bugs flagged by CodeQL (#305)
- src/cli/ui/Wizard.tsx — quoteIfNeeded escaped `"` but not `\`. A
  trailing backslash on the input would consume the closing quote
  when a downstream parser un-escaped the result. Escape `\` first
  (CodeQL js/incomplete-sanitization).
- src/cli/ui/clipboard.ts — temp filename was `reasonix-clip-${Date.now()}.txt`,
  predictable + collides under sub-millisecond bursts. Switched to
  `randomUUID()` (CodeQL js/insecure-temporary-file).
- tests/slash.test.ts — `/kb.example.com/` matched too broadly (`.`
  matched any char, no anchors). Tightened to
  `/\bkb\.example\.com\b/` (CodeQL js/incomplete-hostname-regexp +
  js/regex/missing-regexp-anchor).

136 wizard + slash tests pass unchanged.
2026-05-05 20:13:59 -07:00
YHH 3e91082456 fix(edit-blocks): close exists→write and read→write races (CodeQL) (#301)
Drains the last 2 file-system-race warnings in code/edit-blocks.ts.
Replaces the existsSync precheck + separate read/write pair with a
single fd-scoped flow:

- Try `openSync(path, "r+")` first. ENOENT → file doesn't exist:
  bail with `file-missing` (when SEARCH is non-empty) or fall through
  to atomic create.
- Atomic create is `openSync(path, "wx")` — fails on EEXIST so a
  concurrent writer that filled the slot between our `r+` ENOENT and
  our create can't be silently clobbered.
- Modify path keeps one fd open through fstat → read → ftruncate →
  write. ftruncate sets the new length first (so a shorter result
  doesn't leave stale tail bytes), then we overwrite from offset 0.

The 22 edit-blocks tests pass unchanged.

1 file-system-race warning still open (`usage.ts:103` compaction);
needs temp-file + rename, separate PR.
2026-05-05 20:01:04 -07:00
YHH 638eaeeb46 fix(memory): close exists→write race in hash-memory append (CodeQL) (#300)
Drains the last 2 file-system-race warnings in cli/ui that were
exists→write rather than stat→read.

The original `appendBulletToFile` had two races:

1. `existsSync(path)` then `writeFileSync(path, header)` — between the
   check and the write a concurrent appender could create the file,
   and our writeFileSync would clobber it with a fresh header (losing
   their bullet).
2. `readFileSync(path)` then `appendFileSync(path, …)` — peeking the
   trailing byte to decide whether we need a leading `\n`, then a
   separate append. A concurrent writer that added their own newline
   in between would cause us to insert a redundant blank line.

Fix:

- Atomic create-or-fail via `openSync(path, "ax")`. EEXIST means
  another process won the race; we fall through to the append branch
  rather than clobbering.
- For the append branch, open with `a+` once and do the trailing-byte
  peek + write on the same fd. `O_APPEND` means each `writeSync`
  atomically lands at end-of-file regardless of concurrent appenders.

20 hash-memory tests pass unchanged.

3 file-system-race warnings still open: edit-blocks.ts (×2) and
usage.ts:103. They need different surgery (`r+` + ftruncate /
read-modify-write or temp-file + rename); separate PR.
2026-05-05 20:01:00 -07:00
YHH 1a7b88c72f fix(fs): close 4 more stat→read TOCTOU races (CodeQL js/file-system-race) (#299)
Same fix shape as #298 — open once, do the size check and the read
against the same fd. The read on filtered semantic indexes also gets
to enforce its size threshold against the actual bytes we're about
to load, not a stat result that could be stale by the time we look.

- src/index/semantic/chunker.ts:209  per-file read in the indexer —
  re-checks `maxFileBytes` against `fh.stat()` before reading
- src/server/api/semantic.ts:200    `/api/semantic/status` index
  summariser — was `statSync().size` then `readFileSync`
- src/cli/ui/slash/handlers/semantic.ts:78  `/semantic` slash status —
  was `fs.stat` then `fs.readFile`; estimate fallback for >10MB stays
  the same, just bound to the fd's stat
- src/telemetry/usage.ts:74        compactUsageLogIfLarge — folds the
  separate stat / read try-blocks into one fd-scoped sequence

5 file-system-race warnings remain — those are exists→write or
read→write patterns (`hash-memory.ts`, `edit-blocks.ts`,
`usage.ts:103`); separate PR with `openSync(path, "ax" | "r+")`.
2026-05-05 20:00:55 -07:00
YHH 6ee2428802 fix(fs): close 3 stat→read TOCTOU races (CodeQL js/file-system-race) (#298)
Same fix shape across three files: open once, use fstat + read against
the same fd. The fd binding pins the inode for the lifetime of the
operation so a concurrent rename / replace / unlink during the call
can't desync the size or mtime we just observed from the bytes we're
about to read.

- src/tools/filesystem.ts:127  read_file body — was `fs.stat` then
  `fs.readFile`; switches to async `fs.open` + `fh.stat` + `fh.readFile`
- src/server/assets.ts:36      mtime-keyed asset cache — was `statSync`
  then `readFileSync`; switches to `openSync` + `fstatSync` + chunked
  `readSync`
- src/server/api/skills.ts:72  per-skill listing — same shape; also
  drops the redundant `existsSync` precheck that was a separate race
  in the same chain

9 file-system-race warnings remain — those are exists→write or
read→write patterns that need a different fix (open with `ax` / `r+`
flags); separate PR.
2026-05-05 19:28:21 -07:00
YHH febecb3d6f refactor(app): extract codeApply / codeDiscard into useCodeMode hook (#290) (#296)
Phase-2 PR under #290 (start of the feature-cluster phase). The
/apply and /discard slash callbacks move into one hook (93 lines).
The hook owns the partition / snapshot / save / sync sequence and
returns thin string-builders that AppInner forwards to its log.

Drops `partitionEdits` (unused after extraction) and `savePendingEdits`
(only used by the extracted callbacks) from App.tsx's imports.

App.tsx: 3361 → 3304 lines.
2026-05-05 19:18:08 -07:00
YHH 795a1e2f35 refactor(app): extract /loop machinery into useLoopMode hook (#290) (#295)
Phase-1 PR under #290 — biggest single extraction so far. The /loop
slash command's entire lifecycle moves into one hook:

- the activeLoop state + the four refs (mirror, timer handle, firing
  flag, and the timer scheduler effect itself)
- startLoop / stopLoop / getLoopStatus
- the timer scheduler useEffect (35 lines)

External consumers no longer poke at refs directly. The hook exposes:

- startLoop / stopLoop / getLoopStatus (forwarded to slash handlers)
- isLoopActive() — replaces all `activeLoopRef.current` checks (Esc
  handlers, apply-slash-result)
- isLoopFiring() / clearFiringFlag() — replace the cross-component
  `loopFiringRef.current` reads in handleSubmit's cancel guard
- activeLoop — reactive state for the LoopStatusRow render

apply-slash-result.ts's context shape switches `activeLoopRef:
MutableRefObject<...>` to `isLoopActive: () => boolean`. Cleaner —
slash handlers don't need to know about the ref shape.

App.tsx: 3499 → 3400 lines.
2026-05-05 19:07:11 -07:00
YHH 77cd4f7f66 refactor(app): extract quitProcess into useQuit hook (#290) (#293)
Phase-1 PR under #290. The Ctrl+C / SIGINT exit handler now lives in
its own hook: it returns the `quitProcess` callback and registers /
deregisters the SIGINT listener on its own. AppInner just calls
`useQuit(transcriptRef)` and forwards the returned function to the
slash dispatcher and Ctrl+C interceptor.

The "why process.exit, not Ink exit" rationale moves with the code
into the hook's docstring — that's the only place future callers
need to read it.

App.tsx: 3499 → 3483 lines.
2026-05-05 19:01:13 -07:00
YHH 3ec46356f5 refactor(app): extract writeTranscript into useTranscriptWriter hook (#290) (#294)
Phase-1 PR under #290. The transcript writer becomes its own hook —
takes the transcript ref + the model/prefix metadata it needs to
stamp on each record, returns the LoopEvent writer that AppInner
forwards into stream subscribers and slash handlers.

Drops `recordFromLoopEvent` + `writeRecord` from App.tsx's import
block since the hook now owns those.

App.tsx: 3499 → 3493 lines.
2026-05-05 18:58:53 -07:00
YHH 825c6e9608 refactor(app): extract input-recall into useInputRecall hook (#290) (#292)
First Phase-1 PR under #290. Lifts the bash-style ↑/↓ history recall
out of AppInner: the two `useRef`s (`promptHistory`, `historyCursor`)
and the two `useCallback`s (`recallPrev`, `recallNext`) are now
co-located in `src/cli/ui/hooks/useInputRecall.ts`.

The hook returns four functions — `recallPrev` / `recallNext` for
PromptInput, plus `pushHistory` (called on every successful turn) and
`resetCursor` (called once on submit). Existing callers that wrote
`promptHistory.current.push(text)` switch to `pushHistory(text)`;
`historyCursor.current = -1` becomes `resetCursor()`.

`apply-slash-result.ts` had the only out-of-component reference to
the ref — its context shape now accepts `pushHistory: (s: string)
=> void` instead of the raw `MutableRefObject`. Cleaner contract.

App.tsx: 3499 → 3479 lines.
2026-05-05 18:58:47 -07:00
YHH affa03b235 fix: drain CodeQL warnings — polynomial redos + web.ts htmlToText (#291)
* fix(redos): close polynomial backtracking in 4 regexes

CodeQL js/polynomial-redos flagged four regexes whose backtracking
shape is O(n²) on adversarial input. None are reachable from a real
attacker today (the inputs are model output / our own URL constants),
but the patterns are easy to fix and the alerts were noise.

- at-mentions.ts:319 — `/\.+$/` on path-like tokens. Loop-slice instead.
- client.ts:95 — `/\/+$/` on baseUrl. Loop-slice instead.
- scavenge.ts:67/75/86 — three DSML matchers (`<X>[\s\S]*?</X>` shape)
  on reasoning_content. Adds a 100 KB input cap with an early-bail
  note; the matchers themselves stay readable.

Per CodeQL's third remediation example, bounding the input length is
a valid fix when the regex is hard to rewrite — scavenge is best-effort
and the cap is well above any plausible legitimate reasoning_content.

* fix(web): drain CodeQL warnings on htmlToText

htmlToText leaned on a chain of regex replacements that CodeQL flagged
across six rules — bad-tag-filter, incomplete-multi-character-
sanitization, polynomial-redos (×2), double-escaping. None were
exploitable in our pipeline (output goes to the LLM, not a browser),
but the patterns had real correctness bugs visible to the model:

- `<script[\s\S]*?</script>` missed `</script >` (whitespace before
  `>`) and could leave `<script` behind on the second pass when an
  outer match revealed a previously-hidden inner opening.
- Chained `decodeHtmlEntities` replacements ran `&amp;` before `&lt;`,
  so `&amp;lt;` decoded to `<` instead of literal `&lt;`.

Rewrites both:

- `stripTagBlock(s, tag)` — indexOf-based scan with explicit tag-
  boundary check (avoids matching `<scriptfoo>`) and tolerant close
  matching (`</tag …>` with whitespace).
- `decodeHtmlEntities` — single regex pass with an entity map plus
  `&#nnn;` / `&#xHH;` numeric-entity handling. No more order bugs.
- 5 MB input cap on htmlToText so any residual quadratic patterns
  (e.g. the kept `<[^>]+>` strip) stay bounded.

21 web-tools tests still pass.
2026-05-05 18:58:43 -07:00
YHH 4ba0199c42 chore(tsconfig): add @/* path alias for src; migrate slash handlers (#289)
* chore(tsconfig): add @/* path alias for src; migrate slash handlers

The 16 files under src/cli/ui/slash/handlers/ sit four levels deep, so
every import to a top-level module read "../../../../i18n/index.js" or
the equivalent. The depth was load-bearing for nothing — it just made
moves and reviews painful. Adds a single \`@/* → src/*\` alias to
tsconfig.json and mirrors it in vitest.config.ts (esbuild via tsup
already picks up tsconfig paths transparently).

Migrates only the four-level offenders for now. Three-level imports
(siblings within cli/ that resolve to "@/cli/...") are left alone —
the relative form is arguably clearer when the import target is a
neighbour. A follow-up can tighten that if it's worth the churn.

Build, typecheck, and full test suite all pass on the migrated paths.

* fix(jobs): wait for actual close event after SIGKILL, not a fixed timer

stop() had two timing races. Both manifested as the same flake — the
returned snapshot's `running` flag could still be true even though the
test (and the user) just told us to stop the job.

1. SIGKILL phase used a fixed 800ms timer, then returned regardless of
   whether the OS had reaped the process tree. Under Windows scheduler
   load, taskkill /T /F on a 3-level tree (npm → node → vite) can take
   over a second to propagate before Node's `close` event fires.
2. SIGTERM phase awaited `readyPromise`, which is dual-purpose: it
   fires on either a startup ready-signal regex match OR child exit.
   If the job had already matched a ready signal, `readyPromise` was
   already resolved, so the SIGTERM grace race short-circuited
   immediately and we'd jump to SIGKILL with zero pause.

Adds `closedPromise` — fires only on close/error, never on ready
signal — and uses it for both the SIGTERM grace race and the post-
SIGKILL wait, with a 5s ceiling on the latter so a wedged kernel
can't hang us indefinitely.
2026-05-05 18:25:09 -07:00
YHH 5f80b252e8 refactor(filesystem): extract edit + search bodies into src/tools/fs/ (#287)
* refactor(filesystem): extract edit + search bodies into src/tools/fs/

filesystem.ts had grown to 681 lines, with three of the registered
tools — edit_file, search_files, search_content — carrying most of
the weight in their inline `fn:` bodies. The diff helpers (renderEditDiff,
lineDiff) were also trailing the registration code with no good reason
to live in the same file.

- src/tools/fs/edit.ts — applyEdit + lineDiff + renderEditDiff (the LCS-based diff renderer is now in the same file as its only caller).
- src/tools/fs/search.ts — searchFiles + searchContent share a SearchContext shape so each tool's `fn:` becomes a one-line dispatch.
- src/tools/filesystem.ts — registration entries kept; bodies are now thin pass-throughs.

`lineDiff` is re-exported from filesystem.ts so the existing test import
(`tests/filesystem-tools.test.ts`) doesn't move.

No public API change. No behavior change. filesystem.ts: 681 → 486 lines.

* fix(filesystem): close stat→read race in search_content (CodeQL)

Replaces the separate `fs.stat(full)` + `fs.readFile(full)` pair with a
single `fs.open` → `fh.stat` → `fh.readFile` sequence so the size check
and the actual read bind to the same fd / inode. No TOCTOU window.

Functionally equivalent: oversized files still skip cheaply (we never
read past the size check), small files still read in one shot.
2026-05-05 18:24:51 -07:00
YHH 4b77671103 refactor(shell): split tools/shell.ts into parse + exec submodules (#286)
shell.ts had grown to 847 lines, mixing three unrelated concerns:
allowlist parsing (which is pure string work and the security gate),
process spawning (which carries all the Windows / PowerShell / GBK
workarounds), and tool registration with the ToolRegistry. Each lives
in its own file now:

- src/tools/shell/parse.ts — tokenizer, allowlist, RISKY_ARGS demotion
- src/tools/shell/exec.ts — runCommand, prepareSpawn, killProcessTree, all the Windows quirks
- src/tools/shell.ts — registerShellTools, NeedsConfirmationError, format helpers, plus re-exports

No public API change — every name still importable from ./shell.js.
No behavior change. shell.ts: 847 → 304 lines.
2026-05-05 18:24:46 -07:00
YHH 900eae2a3a refactor(loop): extract heal/shrink/thinking/errors helpers into src/loop/ (#284)
loop.ts had grown to 1724 lines, mixing the CacheFirstLoop streaming
class with a dozen helper functions across four unrelated concerns:
message healing, oversized-result shrinking, thinking-mode flags, and
DeepSeek error formatting. Each concern now lives in its own module
under src/loop/, and loop.ts re-exports every public name so external
callers don't move.

No behavior change. loop.ts: 1724 → 1459 lines.
2026-05-05 18:24:42 -07:00
YHH 94047eadf3 fix(jobs): close stop() race condition; drop useless \$ escapes (#288)
* fix(benchmark): drop useless \$ escapes in tdd-eval prompt string

The h1 task description string used `\${file}::\${fullName}` inside a
regular `"..."` literal. The backslashes are no-ops (JS quietly drops
unrecognized escapes in regular strings) but trip CodeQL's
js/useless-regexp-character-escape rule. Identical resulting string,
cleaner source.

* fix(jobs): wait for actual close event after SIGKILL, not a fixed timer

stop() had two timing races. Both manifested as the same flake — the
returned snapshot's `running` flag could still be true even though the
test (and the user) just told us to stop the job.

1. SIGKILL phase used a fixed 800ms timer, then returned regardless of
   whether the OS had reaped the process tree. Under Windows scheduler
   load, taskkill /T /F on a 3-level tree (npm → node → vite) can take
   over a second to propagate before Node's `close` event fires.
2. SIGTERM phase awaited `readyPromise`, which is dual-purpose: it
   fires on either a startup ready-signal regex match OR child exit.
   If the job had already matched a ready signal, `readyPromise` was
   already resolved, so the SIGTERM grace race short-circuited
   immediately and we'd jump to SIGKILL with zero pause.

Adds `closedPromise` — fires only on close/error, never on ready
signal — and uses it for both the SIGTERM grace race and the post-
SIGKILL wait, with a 5s ceiling on the latter so a wedged kernel
can't hang us indefinitely.
2026-05-05 18:24:17 -07:00
YHH 0945a1189e test(comment-policy): ban bare TODO, FIXME, and translator notes (#285)
TODO/HACK markers without a (#nnn) issue anchor are debt leakage —
they accumulate without ever being tracked. Require the anchor; bare
markers fail the comment-policy gate.

FIXME is banned outright: either fix it now or open an issue and turn
it into a TODO(#nnn). The marker without follow-through is just noise.

Translator-note comments in i18n files ("english version", "中文版",
etc.) restate what the strings already say — i18n entries are
self-documenting.

src/ currently has zero violations of any of these rules, so this is a
floor-keeper, not a cleanup.
2026-05-05 18:24:13 -07:00
YHH bba8199ba4 chore(test): retry once on flaky tests (#282)
jobs.test.ts / loop.test.ts / bundle-smoke spawn real processes and
load the tokenizer cold; on Windows under load these intermittently
miss their wall-clock budget. One retry absorbs the scheduler
hiccup; a real failure still re-fails on the second run.
2026-05-05 16:05:58 -07:00
esengine fc8639a697 chore(release): 0.27.2 2026-05-05 15:51:25 -07:00
YHH 8c51dd6f0f fix(settings): preserve fields when settings POST writes more than one (#281)
handleSettings read cfg once up front, then per-field either called a
self-contained helper (setLanguage / saveApiKey / saveReasoningEffort)
or mutated the snapshot and called writeConfig — so a combined POST
like { lang, baseUrl } would write lang via the helper, then clobber
it with the stale snapshot in the writeConfig branch.

Single read up top, all field updates accumulate into one cfg, single
writeConfig at the end. Runtime side-effects (setLanguage,
applyPresetLive, applyEffortLive) fire after the disk write succeeds
so disk + runtime state can't diverge mid-request.

Closes #274
2026-05-05 15:48:51 -07:00
YHH 56f1cbb835 fix(filesystem): search_content.glob accepts real glob patterns (#280)
The `glob` arg was always a `name.toLowerCase().includes(...)` substring
filter, so `*.ts` matched the literal three-char filename instead of
TypeScript files. Param name advertised glob, behavior didn't.

Now glob via picomatch when the value contains `*`, `?`, `{`, or `[`;
case-insensitive substring otherwise so existing `.ts` / `test` callers
keep working. Patterns containing `/` match against the rel-path
(enabling `src/**/*.tsx`), basename otherwise.

Closes #273
2026-05-05 15:42:25 -07:00
YHH abb1b1ec7a fix(filesystem): search_files skips dependency/build dirs by default (#279)
Aligns search_files with search_content + directory_tree: skip the
existing SKIP_DIR_NAMES set (node_modules / .git / dist / build /
.next / target / .venv) by default, accept include_deps:true to opt
back into walking them. Fixes the surprising mismatch where
search_content("foo") and search_files("foo") had different default
scopes.

Closes #267
2026-05-05 15:32:18 -07:00
ctharveyandCharles H 4f1e65a629 fix(filesystem): slash-normalize tool output paths (#270)
Co-authored-by: Charles H <[email protected]>
2026-05-05 14:54:57 -07:00
ctharveyandCharles H 7096e43895 fix(shell): reject cd in parsed chains (#277)
Co-authored-by: Charles H <[email protected]>
2026-05-05 14:54:45 -07:00
esengine 8543c88034 chore(release): 0.27.1 2026-05-05 09:05:19 -07:00
YHH bdfb04c52b fix(shell): preserve Windows path backslashes inside quoted args (#266)
Inside `"..."` the parser treated any `\X` as a generic escape and
dropped the backslash, so `dir /b "C:\Users\foo\.bar"` ran against
`C:\Users\foo.bar`. Restrict the escape to `\"` and `\` only —
everything else stays literal so Windows path separators survive.

Single `isDqEscape` helper now shared by `tokenizeCommand`,
`detectShellOperator`, `splitOnChainOps`, and `parseSegment`.

Closes #265
2026-05-05 09:04:23 -07:00
esengine 207d55be52 chore(release): 0.27.0 2026-05-05 08:48:57 -07:00
YHH 1ab4ebe971 feat(mcp): registry-backed marketplace + CLI/Ink/dashboard surfaces (#264)
* feat(mcp): registry-backed marketplace + CLI/Ink/dashboard surfaces

Was: 5-entry hardcoded catalog. Now: live marketplace pulling from
registry.modelcontextprotocol.io (primary), smithery.ai (fallback),
bundled catalog (offline last-resort). 24h cache, schema v2, lazy
per-page loading so first list returns ~30 entries in ~1s.

CLI: `reasonix mcp {list,search,install,browse}` — browse is an Ink
TUI (type-to-filter, ↑↓ pick, Enter install, Tab load 5 more pages,
Esc quit).

Dashboard: MCP panel grows a "marketplace" chip beside all/live/
unbridged. New endpoints: GET /mcp/registry, POST /mcp/registry/install.
Install writes the spec to config.json (same path as manual /mcp/specs
POST).

Cache file moves to ~/.reasonix/mcp-registry-cache.json with a
schemaVersion gate; older blobs are silently rejected and refetched.
MCP_REGISTRY_PAGE_LIMIT env var caps how far an eager load walks
(rarely needed since pagination is now on demand).

* feat(mcp): smithery detail-fetch — install Smithery-only entries

Smithery's listing endpoint omits install metadata, so previously any
Smithery-sourced entry surfaced a "not yet supported" hint. Now `mcp install`
(CLI + dashboard) lazily fetches `/servers/<qualifiedName>` detail and
maps the connection to a runnable spec:

  http  → remote streamable-http with deploymentUrl
  stdio → npx -y @smithery/cli run <qualifiedName> (via new extraArgs
          field on RegistryInstall, threaded through specStringFor)

Verified live: `exa` → `exa=streamable+https://exa.run.tools`,
`hugeicons/mcp-server` → `mcp-server=npx -y @smithery/cli run hugeicons/mcp-server`.

Both CLI and dashboard install paths share the same lazy-detail fall-
through. 6 new tests cover http/stdio mapping, 404 fallback, and
extraArgs spec generation.

* test(shell): SpyGate denies instead of approving — kills 5s flake

The "passes the correct kind to the gate" test only asserts what the
gate received; it doesn't care whether the command runs. The old
SpyGate returned `run_once`, so the dispatch went on to spawn `npm i`
in an empty tmp dir. On Windows under concurrent load (full suite +
antivirus + npm cold start) the spawn could exceed the 5s test
timeout, then the afterEach `rmSync` hit EPERM because npm still had
the dir open.

Switching the gate's response to `deny` short-circuits the dispatch
before any spawn. Test runs in ~50ms instead of 1-5s, and the EPERM
failure mode goes away. The assertion (kind + payload were forwarded
correctly) is unchanged.

* test(mcp): anchor mock-URL prefixes with trailing slash

CodeQL flagged `url.startsWith("https://registry.modelcontextprotocol.io")`
in the test's inline fetch mock — without a trailing `/`, an attacker-
controlled URL like `https://registry.modelcontextprotocol.io.evil/`
would also match. Not actually exploitable since the URL is generated
by our own fetcher (the test mock just routes calls), but the rule is
correct in principle and trivial to satisfy.

Adds the trailing slash to every mockFetch host key plus the inline
matcher. All 34 tests still pass.

* feat(mcp): /mcp browse slash + dashboard cards/uninstall + iconUrl

Three improvements driven by user feedback after the marketplace v1:

1. **/mcp browse slash command** — opens an Ink marketplace modal inside
   the chat session. Type to filter, ↑↓ pick, Enter installs (or
   uninstalls if already present), Tab loads 5 more pages, Esc closes.
   No more "exit chat to run external `reasonix mcp` command" friction.

2. **Dashboard cards now show icons + installed-state badge**, and the
   detail pane gets: full description (no truncation), runtime/transport
   meta line + actual on-disk spec when installed, required-env card,
   homepage link, and an explicit "restart required" hint. Lift iconUrl
   out of the official registry's `icons[]` and Smithery's `iconUrl`.

3. **Uninstall button** — a marketplace entry whose spec already lives
   in config.mcp[] swaps Install → Uninstall (calls existing DELETE
   /mcp/specs). Detail pane carries the matching badge.

NOT in this PR: live hot-reload after install. `ctx.reloadMcp` was
declared but never wired in `chat.tsx`, so install/uninstall still
needs a `reasonix code` restart. Both UIs say so honestly. Real
hot-reload is a separate refactor.

* feat(mcp): hot-reload — install / uninstall now bridges live without restart

Closes the last gap in the marketplace flow: previously the user
installed an MCP server through the slash modal or dashboard, the spec
got written to config.json, and we had to tell them "restart `reasonix
code`". `ctx.reloadMcp` was declared on DashboardContext but never
wired in chat.tsx, so it was always undefined.

Refactor: chatCommand's inline MCP-init loop becomes an `McpRuntime`
object (createMcpRuntime in chat.tsx) with addSpec/removeSpec/
reloadFromConfig methods. The runtime owns:
  - clients, summaries, registered-tool-names per spec
  - hot-add path that calls loop.prefix.addTool for every newly
    bridged tool
  - hot-remove path that closes the client + unregisters tools +
    calls loop.prefix.removeTool

New on the supporting types:
  - ToolRegistry.unregister(name)
  - ImmutablePrefix.removeTool(name) — same cache-miss cost as addTool

Wiring:
  - chat.tsx passes runtime → Root → App → both modal/dashboard surfaces
  - SlashContext gets a `reloadMcp` field (for future slash handlers)
  - DashboardContext.reloadMcp is set by App.tsx
  - /mcp browse modal calls reloadMcp after install/uninstall;
    failure falls back to the old "restart required" message
  - POST /mcp/registry/install and POST/DELETE /mcp/specs all call
    ctx.reloadMcp() and surface bridged: true/false in the response
  - Dashboard panel shows "installed + bridged → spec" when hot-reload
    succeeded, falls back to plain "installed" otherwise

CLI `reasonix mcp install` still says "restart required" — it runs
in a separate process from any active chat session, so it can't reach
into a different process's runtime. The slash + dashboard surfaces
inside the same session do hot-reload.

* feat(mcp): unify /mcp into a single tabbed hub + cap dashboard list height

User feedback after the marketplace landed: the McpBrowser ("/mcp")
and the new McpMarketplace ("/mcp browse") felt like the same feature
because the visual style overlapped and the verb "browse" collided
with the existing component name "Browser".

Fix: wrap both in a single McpHub modal with two tabs.

  - `/mcp` → opens the hub on Live (or Marketplace if no servers attached)
  - `/mcp browse` (also `/mcp install`, `/mcp marketplace`) → opens on Marketplace
  - Tab key cycles tabs; the previously Tab-bound load-more in
    Marketplace moves to PgDn so the wrapper owns Tab cleanly
  - Slash result loses openMcpBrowser/openMcpMarketplace; gains
    openMcpHub: { tab: "live" | "marketplace" }
  - Tests in tests/slash.test.ts updated to match the new shape

Dashboard list height: `.sessions-grid` had `min-height: 540px` but
no ceiling, so a long marketplace list pushed the right detail pane
off-screen. Adds `max-height: calc(100vh - 140px)` so the list scrolls
internally (`.ssl-rows` already has overflow-y: auto). Affects all
panels using the grid (sessions, mcp, etc.); same UX win for any
long left-column list.

* fix(mcp): /mcp opens hub even with native tools (code mode)

In `reasonix code` mode, `tools` is seeded with native filesystem /
shell / memory / plan / choice tools, so `loop.prefix.toolSpecs` is
never empty. My earlier guard required all three (servers + specs +
toolSpecs) to be empty before opening the hub on the marketplace tab,
which meant `/mcp` in code mode silently fell through to the printed
fallback text dump — exactly what the user reported.

Simplified: interactive `/mcp` always opens the hub. Live tab when at
least one server is bridged, Marketplace tab otherwise. The text dump
is only reachable via `/mcp text` (replay / non-TTY scenarios).

Tests: renamed two assertions to `/mcp text`, added a new case that
exercises the code-mode regression directly (mcpSpecs present but
servers empty → opens hub on marketplace).

* fix(dashboard): cap marketplace list height — was still scrolling the page

The previous attempt added `max-height: calc(100vh - 140px)` to the
grid container, but CSS Grid items default to `min-height: auto` (which
means "content size"), so the children — `.sessions-list` (with the long
registry list) and `.sessions-detail` — grew past the grid's max-height
and dragged `.app-body`'s overflow-y along, pushing the right detail
pane below the fold. Symptom user reported: "I scroll to the bottom
and the right detail pane is gone."

Fix is the standard CSS Grid + inner-overflow recipe:

  - Add `grid-template-rows: minmax(0, 1fr)` so the row resolves to the
    grid's available height (capped by max-height) rather than to
    children's content size.
  - Add `min-height: 0; min-width: 0` to both grid items so they
    actually shrink to fit the track. With min-height: 0, their inner
    `.ssl-rows { overflow-y: auto }` and `.sessions-detail { overflow:
    auto }` rules finally take effect — list scrolls internally, detail
    pane stays visible at all viewport sizes.

Affects every panel using `.sessions-grid` (sessions, mcp, …) — same
UX win for any long left-column list.

* fix(mcp): load-more button — distinct exhausted state + lift hardcoded caps

Two bugs the user reported in the dashboard marketplace:

1. Click "load more" → no visible response. Cause: dashboard sent
   `limit=50` hardcoded, so even after the server walked more registry
   pages the response was sliced to the same top 50. Fix: track
   `displayLimit` in panel state, bump by 50 on each click, send as
   query param.

2. Server-side hardcoded caps (`pages` / `maxPages` clamped to 50,
   `limit` clamped to 200) hit a wall after a few clicks regardless
   of cache depth. Lifted to 200 / 200 / 1000.

3. When the registry is genuinely exhausted, the old footer just
   showed dim "all pages loaded" text — visually indistinguishable
   from a disabled button, so the user thought clicks weren't
   registering. New footer:
     - active: primary button with "load 50 more · showing X / Y"
       label so the count visibly grows after each click
     - exhausted: distinct success-tinted card with ✓ marker

Side effect: `q`-search now also benefits from raised caps. With
matchTarget early-stop the server still returns fast even when caps
are higher.

* fix(server): asset cache uses mtime, not "once per process"

Caused real friction during dashboard development: change panels source,
run `npm run build`, refresh browser → still see old UI because the
running reasonix server cached `dashboard/dist/app.js` in memory at
first read and never re-reads. Required a full restart to pick up any
dashboard rebuild.

Switched to mtime-keyed cache: re-stat each request, re-read body if
mtime advanced. `dashboard/dist/app.js` is ~800KB so the stat-then-
hit-cache path is microseconds. The previous "ONE read per process"
optimisation was guarding against ~zero cost.
2026-05-05 08:47:16 -07:00
esengine 767633d00e docs(readme): preview Reasonix Advocate badge in Community section
Show what the badge looks like before anyone has earned it, so
prospective advocates can see the target. Uses the for-the-badge
shields.io style in the project's lavender brand colour; metadata
badges at the top stay flat-square for information density.
2026-05-05 06:20:20 -07:00
esengine 10c7d45ac3 docs(readme): invite users to share advocacy in Show and tell
Point active users at the Show and tell discussion category and
preview a forthcoming Reasonix Advocate badge for sustained advocates.
Word of mouth is the only growth channel for a zero-marketing-budget
project, so make the ask explicit.
2026-05-05 06:05:02 -07:00
esengine b5f6e1e54c chore(release): 0.26.1 2026-05-05 04:26:11 -07:00
YHH 4e16baaa66 fix(shell): demote destructive flags on allowlisted commands (#258)
* fix(shell): demote destructive flags on allowlisted commands (#257)

Allowlist matched on leading tokens only, so `git branch -D`,
`find -delete`, `git diff --output=...`, `npx eslint --fix`, etc.
flowed through without confirmation. Add a per-prefix RISKY_ARGS
table that demotes specific tail tokens back to the confirm gate;
both `--flag value` and `--flag=value` forms are caught. Chains
inherit via the existing per-segment isAllowed call.

* fix(shell): also demote tree -o and find -fprint0 (#257)

Follow-up audit caught two more write-anywhere paths on otherwise-
allowlisted inspection tools: `tree -o FILE` writes the tree output,
and `find -fprint0 FILE` writes NUL-separated paths. Same risk class
as the `git diff --output=` family already covered.
2026-05-05 04:25:27 -07:00
esengine b85f1de3b1 docs(readme): switch star-history to /chart timeline + log-scale
The /svg?type=Date endpoint was returning empty for this repo (likely
because the cumulative-by-day shape needs more data points). /chart with
type=timeline + logscale renders correctly from day one and reads better
when the y-axis range is small.
2026-05-05 01:11:16 -07:00
esengine d35e27d193 test(jobs): poll runningCount after stop/shutdown to absorb taskkill async
The post-stop/shutdown asserts were racing Windows taskkill /T tree
propagation, occasionally catching a transient `runningCount === 1`
right after the stop promise resolved. Poll up to 2s for the value to
settle to 0 — distinguishes "persistently wrong" (real bug) from
"momentary race during reap" (not a bug).
2026-05-05 01:00:58 -07:00
esengine 835c6b8f23 docs(repo): improve passive-discovery surface
Add custom OG social card (1280×640), star-history chart in both READMEs,
FUNDING.yml so the Sponsor button shows up. Goal: when someone lands here
from a shared link or GitHub explore, the first impression and signal of
seriousness should be higher than a default-rendered repo page.
2026-05-05 00:37:56 -07:00
esengine 9b23390605 docs(web): full landing-page refresh — drop hardcoded numbers, refresh capabilities, add community section
The marketing site had drifted from the project. Bring it back in line with
the post-0.26 README:

- Hero: drop "Ink TUI" / "No LangChain" / "DeepSeek V4" pin; replace the
  three hardcoded-number stats (90.2% / ~98% / 100%) with qualitative tags
- Why Reasonix: reorganize the six cards as four architectural pillars
  (matching ARCHITECTURE.md) plus two community/positioning cards
- In the box: expand from six to twelve capabilities, matching the README's
  feature-grid.svg — adds plan mode, permissions, dashboard, sessions,
  semantic search, auto-checkpoints, /effort, replay, event log
- Benchmarks: remove the hardcoded-numbers table; keep methodology + repro
  command + link to the harness directory
- CLI: refresh command list and flags to current 0.26 surface
- New Community section with contrib.rocks wall + good-first-issue /
  discussions / contributing links
- Footer: drop Changelog (we don't keep one), add Releases / Benchmarks /
  Contributors links

i18n.js: rewrite both dicts; 118 keys × 2 with verified 1:1 parity. CSS:
new .community styles, .stat-num resized for qualitative tags, .feat-grid
responsive breakpoints expanded for the wider 12-card layout.
2026-05-05 00:14:32 -07:00
esengine ba58eceb3c docs(readme): SVG-rendered pillar + capability cards for proper visual hierarchy
GitHub strips CSS from HTML tables, so the previous <table>-based pillar
and capability sections rendered as plain rows. Move both to custom SVG
assets that match the existing hero-terminal.svg design language —
dark cards (#0a0c10), gradient icons (teal/blue/purple), Inter + JetBrains
Mono typography.

- pillars.svg / pillars.zh-CN.svg: new 2x2 grid of the four architectural
  pillars from ARCHITECTURE.md, with deep-link anchors below
- feature-grid.svg / feature-grid.zh-CN.svg: rewritten as a 3x4 grid of
  twelve concrete capabilities (was 6 cards with hardcoded "94% live cache
  hit" copy that violated the no-hardcoded-numbers rule)

README drops the HTML <table> markup, halving its line count.
2026-05-04 23:38:00 -07:00
esengine 18860ac28e docs(readme): redesign — terminal-aesthetic, four-pillar grid, capability list
Visual identity:
- Dark-themed shield badges matching terminal color palette
- <h3>-driven hero hierarchy in place of bold-paragraph tagline
- GitHub callouts (TIP / NOTE / IMPORTANT) as visual anchors

Information architecture:
- Four numbered pillar cards (2x2) mirroring ARCHITECTURE.md sections,
  each deep-linking into the relevant pillar
- Capability grid (3x4) surfacing twelve concrete features the previous
  README hid: cell-diff renderer, MCP, plan mode, permissions, dashboard,
  persistent sessions, hooks/skills/memory, semantic search, auto-checkpoints,
  /effort, transcript replay, event log
- Comparison table gains an "Open community development" row

EN and zh-CN kept structurally identical (same sections, same headings).
2026-05-04 23:02:26 -07:00
esengine 07a5f34d16 chore: sync package-lock to 0.26.0 2026-05-04 23:02:24 -07:00
esengine ee3f8c676c chore(release): 0.26.0 2026-05-04 22:38:51 -07:00
YHH cebe2c3ba8 fix(renderer): avoid \x1b[2J on resize so input bar stops duplicating on conhost (#249) (#255)
\x1b[2J on Windows PowerShell 5.1's legacy conhost scrolls the visible
viewport into scrollback rather than truly erasing it. Each terminal
resize was pushing the current input/toolbar into scrollback, and a
later grow-resize pulled those rows back into the viewport — visible
to the user as duplicated input bars.

Use the same rewind-and-clear pattern (\r\x1b[<N>A\x1b[J) already
used by commitScrollback / emitStatic. \x1b[J fills with spaces in
place, no scrollback push. Platform-neutral, no Windows branch.
2026-05-04 22:34:41 -07:00
YHH d24a6b5b38 refactor(cli): move /prune-sessions to reasonix prune-sessions CLI (#254)
The slash form didn't need any chat state — it just deleted idle session
files from disk. Belongs as a CLI subcommand. Adds --days and --dry-run
flags (the slash form had neither).

  reasonix prune-sessions               # default 90d, deletes
  reasonix prune-sessions --days 30
  reasonix prune-sessions --dry-run     # preview, no delete

Removed:
  - /prune-sessions slash handler + registry entry
  - pruneUsage / pruneNone / pruneInfo i18n strings (EN + zh-CN)
  - slash schema entries for "prune-sessions"
  - tests covering the slash form

Updated:
  - /doctor's stale-session warning now points at `reasonix prune-sessions`
  - i18n schema gains cli.pruneSessions, ui.pruneDaysHint, ui.pruneDryRunHint

Part of #243. /init stays slash (it leverages the live edit-gate;
not actually a CLI shape on closer look). /dashboard stays dual.
/clear rename pending RFC.

Tests: 2254 pass.
2026-05-04 22:09:43 -07:00
YHH 8c49b38732 refactor(slash): drop /setup — handler did nothing useful (#253)
/setup just printed a static "exit and run reasonix setup" reminder.
The actual `reasonix setup` CLI subcommand is unchanged; we just
removed the slash command that pointed at it.

Part of the #243 inventory cleanup. Net -5 LOC across handlers,
commands, i18n (EN + zh-CN), and tests.

Tests: 2254 pass.
2026-05-04 20:55:57 -07:00
Wesley Viana 32a4818d76 chore: test coverage and mutation test (#247)
* chore: test coverage and mutation test

* Increase mutation scope
2026-05-04 20:46:48 -07:00
Wesley Viana fe074942f4 fix: Model was still doing things while pending to approve (#237)
* fix: Model was still doing things while user was being prompt to accept tool call.

* Checkpoint feedback, remove dead code
2026-05-04 20:43:07 -07:00
YHH eb6291843a feat(loop): aggressive fold tier between 70% and 80% of ctxMax (#252)
PR-D from #244. Closes the gap between the normal-fold threshold (50%)
and the force-summary cliff (80%): when a turn lands in 70-85%, the
recent K turns alone are already big enough that a normal fold (tail =
20% of ctxMax) wouldn't buy meaningful headroom. The aggressive tier
shrinks the tail to 10% of ctxMax — sacrifices some recent context
for a real reset.

Decision matrix now:

  ratio > 0.8  → exit-with-summary
  ratio > 0.7  → fold (tail = 10% ctxMax)  [aggressive]
  ratio > 0.5  → fold (tail = 20% ctxMax)  [normal]
  else         → none

The status line and warning text both surface "aggressive" when that
tier fires, so users know why recent turns were trimmed harder than
usual.

Implementation:

  - PostUsageDecision now carries `tailBudget` and `aggressive` fields
    when kind === "fold". loop.ts passes tailBudget through to
    compactHistory (which already accepted keepRecentTokens).
  - decideAfterUsage hoists the alreadyFolded short-circuit above the
    fold-band checks so neither tier re-fires within a turn.

Tests: 2243 pass (was 2242; +1 covering the aggressive band yields a
warning matching `aggressively folded` and a status with `aggressive`).
2026-05-04 20:36:55 -07:00
ctharveyandCharles H 305bc641a2 refactor(mcp): extract server summary matching + replacement helpers (#250)
- Add sameMcpServerSummary(a, b) for logical identity (ref or label+spec).
- Add replaceMcpServerSummary(servers, target, updated) for immutable list update.
- Replace inline prev.map(...) in App.tsx with the helper call.

Co-authored-by: Charles H <[email protected]>
2026-05-04 20:19:20 -07:00
YHH 557cfc12c7 refactor(loop): /compact now folds (cache-safe), drop in-place mutation (#251)
PR-B from #244: closes the foot-gun left over from #238 / #241.

Before this PR, /compact called loop.compact() → ContextManager.inPlaceCompact(),
which mutated mid-history tool result bodies. Cache-aware analysis (#238) showed
that path costs more than it saves: shrinking 50% of prompt size while
invalidating 100% of cache from the mutation point on. The 95% preflight valve
was the second caller of the same path.

What changed:
  - /compact handler now calls loop.compactHistory() (the cache-safe fold from
    #241) via the existing async-via-postInfo pattern (mirrors /dashboard).
    Sync return is "folding…"; result lands as a follow-up info line.
  - 95% preflight: tries fold first (one summary call, append-only) instead of
    in-place compact. If fold can't shrink anything, surfaces the warning and
    lets the request go (the user can /clear).
  - loop.compact() public method removed. ContextManager.inPlaceCompact()
    removed. shrinkOversizedTool* helpers stay (still used by session
    heal-on-load and tests).
  - 80% force-summary warning text updated: now mentions /compact since the
    name is safe to recommend.

User-visible:
  - /compact name kept (muscle memory + short to type), behavior is now
    cache-safe fold. Old behavior is gone.
  - /help text updated to reflect the new semantics.
  - tests/preflight.test.ts: warnings now report fold result instead of
    pre-compacted tool count; the "nothing to fold" path replaces the old
    "nothing to auto-compact".

Tests: 2233 pass. Typecheck clean.

Closes #243's foot-gun deletion concerns.
2026-05-04 20:18:20 -07:00
ctharveyandCharles H 10f1866c02 refactor: make applyMcpAppend immutable — returns new McpServerSummary instead of mutating input (#248)
- applyMcpAppend() now returns a new McpServerSummary with updated
  report.tools.items and toolCount, built via object/array spreads.
- Original target object is never mutated.
- ApplyAppend type returns McpServerSummary instead of void.
- kickOffMcpReconnect captures the return value and updates its local target.
- App.tsx stores MCP servers in local state and immutably replaces the
  matching summary after append-drift.
- Both biome-ignore/noExplicitAny suppressions removed.

Co-authored-by: Charles H <[email protected]>
2026-05-04 19:45:32 -07:00
YHH d632755f43 refactor(loop): extract ContextManager — zero behavior change (#245)
Pulls the four ad-hoc compaction mechanisms behind one component
(see #244 for the full architectural rationale):

  - decideAfterUsage(usage, model, alreadyFoldedThisTurn) returns
    "fold" / "exit-with-summary" / "none" — the policy that used to
    live as inline if-blocks in step()
  - decidePreflight(messages, toolSpecs, model) is the local outgoing
    estimate gate (>95% of ctxMax)
  - fold(model, opts) replaces compactHistory's body
  - inPlaceCompact(maxTokens) replaces compact's body and is also
    what the 95% preflight calls — the one remaining cache-breaking
    path, marked for removal in PR-B
  - trimTrailingToolCalls() factors out the in-flight tool_calls tail
    drop used before forced-summary

loop.ts methods become thin delegators: compact / compactHistory keep
their public signatures (slash handlers and tests untouched);
forceSummaryAfterIterLimit stays in loop.ts because it's tightly
coupled to LoopEvent yielding.

All thresholds and the summary-marker constant moved to
context-manager.ts. No values changed.

Tests: 2235 pass (no test changes). Typecheck clean.
2026-05-04 19:38:29 -07:00
YHH ea37106e03 ci: add CodeQL security scanning workflow (#246)
Runs on push to main, every PR, and weekly cron. Uses the
javascript-typescript analyzer with security-extended queries.
2026-05-04 19:33:57 -07:00
ctharveyandCharles H eb7c9b5425 fix(mcp): prevent unhandled rejection during hung send timeout (#240)
Co-authored-by: Charles H <[email protected]>
2026-05-04 19:15:56 -07:00
YHH 8681d158aa feat(loop): append-only history fold at 50% of ctxMax (#241)
When a turn's response shows promptTokens > 50% of the model's context
window, replace the older portion of the log with a single synthesized
assistant summary and keep the trailing turns whose token weight fits
in 20% of ctxMax. One cache break per fold; cache rebuilds in ~1 turn,
then the conversation continues under the cap until the next fold.

Without this, append-only sessions grow unbounded — by the time
prompt > 80% of ctxMax, the existing force-summary path fires every
turn ($0.07/turn purgatory until /clear or /compact). Fold prevents
ever reaching that cliff.

Sized so:
  - tail budget = 0.2 * ctxMax → ~30% headroom before next fold
  - min savings fraction = 0.3 → no fold if head wouldn't shrink the
    log meaningfully (avoids re-fold thrash on stable post-fold logs)
  - summary call uses deepseek-v4-flash + high effort, ~$0.07 each

Validated on a real 20-turn DeepSeek session with ctxMax pinned at 50k
(scripts/probe-long-session.mts):
  turn 10: 52% trips → fold fires → 42 msgs → 19, prompt 25k → 13k
  turn 11: cache rebuilds to 84% within one turn
  turn 16: 51% trips again, fold fires
  total cost across 20 turns: $0.0381 (vs $0.0493 without fold)
  total mutations: 2 (= the 2 folds, nothing else)

Closes #236.
2026-05-04 19:03:32 -07:00
YHH a621f17294 perf(loop): drop in-place auto-compaction — was destroying prompt cache (#238)
* perf(loop): drop in-place auto-compaction — was destroying prompt cache

DeepSeek prompt cache is prefix-exact: mutating any byte of an old
message invalidates every cached token after that point. We were
calling compactInPlace() in five places (turn-end, post-tool-args,
40-80% proactive, 80% reactive, plus the slash command), which meant
long sessions repeatedly traded "smaller prompt" for "0% cache hit
on the rest" — net negative against DeepSeek's 4× cache discount.

Probed empirically (scripts/probe-cache.mjs):
  append-only:    98.6% cache hit
  one mutation:    0.0% cache hit, lost 4480 cached tokens
  long session:   ~91% sustained across turns after warmup

Removed the auto-trigger paths entirely. The 80% reactive block now
goes straight to forced-summary instead of trying to mutate-then-bail
(it was already falling through to summary in the common case). The
95% preflight emergency valve and the manual /compact slash command
are kept — they're explicit/last-resort and expected to break cache.

Refs #236

* test(loop): add end-to-end cache-hit probe driving real CacheFirstLoop

Complements scripts/probe-cache.mjs (which probes the API primitive).
This drives the actual loop through 6 real turns and asserts:
  - log.compactInPlace() is never called (append-only invariant)
  - warm-turn cache hit % stays above 80%

Measured against the live API after the auto-compaction removal:
  turn 0:  0.0% (cold cache, expected)
  turns 1-5: 99.0, 98.5, 98.0, 97.6, 97.1 — ~98% sustained
  total mutations: 0
2026-05-04 18:35:08 -07:00
esengine 4b446e8640 release: 0.25.1 — chain operators + file redirects in run_command
`run_command` learns the four common shell chain operators (`|`, `||`,
`&&`, `;`) and the seven file redirect operators (`>`, `>>`, `<`, `2>`,
`2>>`, `2>&1`, `&>`). Parsed and spawned natively — no shell is invoked,
so semantics are identical on Windows / macOS / Linux; PowerShell 5.1's
`&&` parse error and the object-vs-bytes pipe gap are sidestepped.

Each chain segment is allowlist-checked independently: `git status |
grep main` now auto-runs when both halves are individually allowed, the
granular-approval behaviour wviana asked for in discussion #231.

The chain parser stays consistent with the project's long-standing
lenient tokenizer — `cargo run -- --flag=1&2` and similar embedded-
operator args stay literal instead of getting POSIX-strict-rejected.
shell-quote is no longer a dependency; `splitOnChainOps` is whitespace-
bounded like the existing `detectShellOperator`.

Mid-pipe `2>&1` correctly merges stderr into the next segment's stdin
without truncating on stdout-end (counter-based close-when-both-ended).

Targets resolve relative to the project root. Heredoc `<<` and
background `&` remain explicitly rejected with clear errors. `\$VAR`
and `\$(...)` pass through as literal characters — no shell expansion.

Closes #232. Driven by discussion #231. PRs: #233 (chain ops), #234
(lenient-tokenizer regression fix), #235 (redirects + mid-pipe `2>&1`).
2026-05-04 17:56:30 -07:00
YHH 9443f50955 feat(shell): support file redirects in run_command (#235)
* feat(shell): support file redirects in run_command (`>`, `>>`, `<`, `2>`, `2>>`, `2>&1`, `&>`)

Phase 2 of the chain-aware run_command rewrite. Each segment now parses
trailing redirects via a single-pass walker (no shell), opens files with
fs.openSync, and hands the resulting fds to spawn's stdio array. Pipe
wiring still applies — `<` overrides pipe-stdin only when explicitly
present; `>`/`>>`/`&>` override the pipe-out / capture-buffer wiring.

Supported per segment (max one per fd):

- `>`   stdout truncate
- `>>`  stdout append
- `<`   stdin from file
- `2>`  stderr truncate
- `2>>` stderr append
- `2>&1` merge stderr → stdout (file fd, pipe, or our buffer, whatever stdout points to)
- `&>`  both → file (truncate)

Targets resolve relative to the chain's cwd. Multiple redirects to the
same fd are rejected with a clear conflict message.

ChainSegment now carries `redirects: Redirect[]` alongside `argv`. The
old `tokenizeCommand + detectShellOperator` per-segment combo is
replaced with `parseSegment`, a quote-aware single-pass walker that
emits both argv tokens and redirects at the same level — keeps the
lenient embedded-`&`/`|` handling intact (the `cmd1 ; cmd2 -flag=1&2`
regression fix from #234 still passes).

Heredoc `<<` is rejected explicitly. Background `&` is rejected
explicitly (use run_background, not run_command). `$VAR` and `$(…)`
pass through as literal characters — no shell expansion, matching the
existing single-command tokenizer.

Adds 30 new tests in tests/shell-redirects.test.ts covering parser
output and execution; updates the obsolete redirect-rejection tests
in tests/shell-tools.test.ts to cover the new rejection set
(background `&`, heredoc `<<`, missing target, multi-redirect-per-fd).

* fix(shell): hold child.stdin open until both prev streams end on mid-pipe `2>&1`

`cmd1 2>&1 | cmd2` was wiring prev.stdout into child.stdin with default
end-on-source-end, then piping prev.stderr in with `end: false`. When
stdout finished first, child.stdin closed and any subsequent stderr
writes hit a closed stream — output got truncated.

Both branches now pipe with `end: false` and a 2-counter closes stdin
only after both source streams emit `end`. Adds a test that pipes
stderr through to a downstream cat-like process and asserts both
streams reach the destination.
2026-05-04 17:29:08 -07:00
YHH 56b94d0677 fix(shell): drop shell-quote, hand-roll chain splitter to keep lenient tokenization (#234)
Phase 1 (#233) used shell-quote for chain segmentation, but its strict
POSIX tokenization split `--flag=1&2` into three tokens with `&` as a
background operator — a regression vs. pre-Phase-1 behavior, where the
existing lenient `tokenizeCommand` left embedded `&`/`|`/`;` chars as
literal bytes inside larger tokens.

Replace with a small whitespace-bounded chain splitter that matches the
existing `detectShellOperator` convention: chain ops only count when
they begin a whitespace-separated token. Each segment then runs through
the existing `tokenizeCommand` (lenient) and `detectShellOperator`
(rejects `>`, `<`, `&`, `2>&1`, `&>`).

Recovers:
- `cargo run -- --flag=1&2`           — runs (was rejected post-#233)
- `git status ; cargo run -- --flag=1&2` — chain runs, second segment keeps `&`

Drops:
- `git status|grep main` (no spaces) — never worked pre-Phase-1, was a
  shell-quote-only side effect; align with the project's
  whitespace-bounded operator convention.

Also drops `$VAR` / `$(...)` rejection — these now pass through as
literal arguments, matching the existing single-command tokenizer's
behavior. Models see the literal `$HOME` in echo's output and learn.
2026-05-04 17:10:13 -07:00
YHH 5ea5f76de6 feat(shell): support |, &&, ||, ; in run_command via split-and-spawn (#233)
Parse chain operators ourselves with shell-quote and spawn each segment
as a separate process — never invoke a system shell. Sidesteps PowerShell
5.1's `&&` parse error and the object-vs-bytes pipe semantics gap on
Windows. Each segment is allowlist-checked independently, so
`git status | grep main` runs when both halves are individually allowed.

Redirects (`>`, `<`, `2>&1`), background `&`, env-var expansion `$VAR`,
command substitution `$(…)`, and subshells `(…)` remain rejected up-front
with clear errors.

Tracks #232, addresses #231.
2026-05-04 16:56:38 -07:00
esengine 7526167d32 fix(setup): replace ink-text-input with MaskedInput, strip leaked paste markers
Two bugs in the Setup screen on Windows / cell-diff renderer:

1. ink-text-input bakes chalk-styled output into the text it returns.
   Our renderer strips the ESC byte but keeps the rest, so users saw
   literal `[7ms[27m[90mk-...[39m` in the input field. MaskedInput uses
   the renderer's <Text inverse> / <Text dimColor> primitives instead.

2. Windows ConPTY splits bracketed-paste wrappers across stdin chunks,
   so Ink's parser sees `\x1b[200~` / `\x1b[201~` as printable `[`,
   `2`, `0`, `0`, `~` and they leak into the buffer. Strip them at
   the input boundary and again at submit.

Also fixes a stale-closure bug where rapid keystrokes from a paste
burst all read the initial empty value, so only the last char survived.
A ref synced on every render lets each keystroke append onto the
latest accumulated value.
2026-05-04 09:55:43 -07:00
esengine 32126dece4 release: 0.25.0 — plan auto-execution, kill flicker root cause, prune demos
Plan execution is continuous after approval — `mark_step_complete` no
longer throws PlanCheckpointError; the model runs all steps in one turn.
Plan card commits to scrollback as the approved snapshot AND renders as
a fixed-height live strip (PlanLiveRow) docked above prompt input via
the windowed-5 step view.

Flicker root cause was orphan unsettled cards (aborted streams that
never fired their .end event) trapping every subsequent card in the
live region — Yoga re-measured the whole live tree on every chunk.
CardStream now allows only the LAST card to be live; earlier orphans
are force-committed to scrollback.

Streaming cards switch to a left ▎ stripe (Card.tsx). Round borders'
top/bottom rows orphaned under the cell-diff renderer's row-promotion
logic when content height changed mid-stream. Stripe rows always carry
both ▎ and content, so promotion is always atomic.

Active-tone color set (TONE_ACTIVE) lifts streaming/running cards one
shade brighter; settled tones unchanged. DiffCard tone bug fixed
(was warn, registry says ok). PlanCard wraps any plan length to a
fixed 5-step window with `✓ ⋯ N done` / `⋯ N upcoming` elision.

API surface: PlanCheckpointError + PlanCheckpointConfirm removed.
mark_step_complete returns the step_completed payload directly.
/stop slash command added (typed alternative to Esc abort).

Cleanup: removed all 7 demo CLI commands (banner / card / flicker /
preview / renderer / select / stress) and their 5 test files. They
duplicated production card components and drifted out of sync.
2026-05-04 09:29:48 -07:00
ctharvey 73000ce388 refactor(mcp): hide host client reads from browse UI (#227)
Refs #196.
2026-05-04 08:55:46 -07:00
ctharvey c86279a493 refactor(mcp): extract healthBadge to mcp-health.ts (#226)
Refs #196.
2026-05-04 08:54:14 -07:00
ctharvey fbcd82096c refactor(mcp): extract healthBadge to mcp-health.ts (#226)
Refs #196.
2026-05-04 08:51:37 -07:00
esengine 37b4cca4f6 refactor(ui): SubagentRow uses Card+CardHeader; drop CardRenderer's marginTop
Two related fixes:

1. SubagentRow was a hand-rolled 9-row block with ▎ left bar drawn on
   every row. User reported it didn't match the rest of the card pass —
   because it predates the Card primitive entirely. Rewritten on top of
   <Card> with round border + violet tone + CardHeader (titleBg pill +
   model pill + spinner in `right`). Body collapses from the 9-row
   stack into 3 lines (task / last / phase) inside the card. Row count
   is still fixed (no per-event growth) so flicker behavior is preserved.

2. CardRenderer had marginTop=1 on its outer wrapper, doubling the
   marginTop=1 the Card primitive already adds. Every static-emitted
   card carried 2 leading blank rows, accumulating noticeable gaps in
   scrollback between cards. Drop CardRenderer's mt; Card primitive
   alone owns inter-card spacing.
2026-05-04 07:11:02 -07:00
esengine 3d692ead01 feat(cards): tinted reasoning title + model pill on reasoning/streaming + subagent demo-style children
Three card-header upgrades the user asked for:

1. CardHeader gains an optional `titleBg` that paints the title as a
   colored chip — used by ReasoningCard so `reasoning` reads as a
   muted-purple block instead of plain bold text. (Borrowed from
   PILL_SECTION.reason — already in the theme.)

2. ReasoningCard + StreamingCard surface the snapshotted `card.model`
   as a Pill in the header `right` slot. v4-flash / v4-pro / r1 each
   get their own color via PILL_MODEL.

3. SubAgentCard children now match card-demo's row format:
   ▎ [status spinner|✓|✖] [kind glyph] [summary]

   Previously the row only had the kind glyph + content; now per-child
   running cards spin a tone-colored circle while done ones get a green
   ✓. Header switches the meta from a static status text to "N running"
   when active, mirroring the demo's runningCount.
2026-05-04 06:57:43 -07:00
esengine a9024a8d31 refactor(ui): soften ThinkingRow — italic + dim instead of bold blue block
Original was bold brand-blue spinner + bold brand-blue text + faint
duration with hardcoded `· ` separators. All three fields competed for
attention even though the row is just a "model is busy" hint.

Restraint: drop bold from spinner + label, switch label color to FG.sub
italic (semantic "thinking" via type, not color), accent-purple spinner
for a slower visual pulse, gap={1} for spacing instead of inline `· `
chunks. Reads as one sentence instead of three competing pills.
2026-05-04 06:52:39 -07:00
esengine a8e7ebeb47 fix(renderer): keep promotedRows across resize so scrollback isn't duplicated
mount.ts resize() reset promotedRows=0, which made the next commit's
commitScrollback see split.skipped > promotedRows and serialize every
already-scrolled-out row a second time. Each terminal resize stacked
another full copy of the overflowed history into scrollback — visible
as duplicate chrome bars / mode bars climbing up the scroll buffer.

Promoted rows live in the terminal's own scrollback, which the renderer
can't access — so resetting our counter is structurally wrong. Keep
promotedRows; with pendingClear handling the visible repaint, the new
layout's skipped count drives an honest newPromote (often 0 on resize,
since the layout's overflow boundary moves by 1-2 rows max under width
change, not by the entire history).

Also dedup same-dimension resize events — terminals fire 2-3× per
drag and each fires a full commit otherwise.
2026-05-04 06:43:16 -07:00
esengine 88e5becf06 Revert "fix(cards): pin flexShrink=0 on Card so settled bodies aren't squashed"
This reverts commit 8685215e23.
2026-05-04 06:27:42 -07:00
esengine 8685215e23 fix(cards): pin flexShrink=0 on Card so settled bodies aren't squashed
In `npm run dev` real ink (not the cell-diff renderer) drives layout,
and yoga defaults flex-shrink to 1. When a settled card lands inside
real ink's <Static> column, the box can be shrunk to fit even though no
explicit height is bound — UserCard's Markdown body and ReasoningCard's
SettledPreview both collapsed to 0 rows while the headers survived.

flexShrink=0 on both active and settled wrappers anchors each card to
its content height. The streaming reply was unaffected because its body
alone is already taller than terminal/2 so shrink wouldn't fire.
2026-05-04 06:25:11 -07:00
esengine 7b108cc2c0 fix(cards): drop paddingLeft from settled Card so bodies render
Adding paddingLeft={2} to the settled-mode wrapper collapsed the layout
so card bodies (UserCard's Markdown, ReasoningCard's BodyLines, etc.)
rendered as 0 rows — only the headers were visible. Card-demo's
StaticRow doesn't apply outer padding either; it pads body sub-Boxes
individually, which is the pattern the live cards used pre-refactor.

Settled mode now mirrors the original outer wrapper shape exactly:
`<Box flexDirection="column" marginTop={1}>`. Bodies render. Active
mode keeps the round border + paddingX=1 + width="100%".
2026-05-04 06:11:01 -07:00
esengine 948f361849 fix(cards): propagate ActiveCardContext into Static's off-tree render
CardStream previously wrapped <Static> in an ActiveCardContext.Provider,
but Static emits its items via bridge.emitStatic which renders them in
an off-tree reconciler — context from the live tree doesn't travel.
Settled cards still rendered with active=true (default) and kept their
borders.

Move the Provider inside the Static children function so it captures
into the per-item subtree that emitStatic actually serializes. Live
path drops its (now redundant) Provider since Card primitive defaults
to active=true.
2026-05-04 06:01:09 -07:00
esengine d65eeddac6 fix(cards): drop border on settled cards + stretch active borders to full width
Two visual bugs after the e78112b border roll-out:

1. Settled cards (in scrollback) carried borders too, but card-demo only
   borders the live/active cards — settled rows in demo are flat history
   text. Live chat now mirrors that: ActiveCardContext threads
   active=false through CardStream's <Static> path, and Card primitive
   renders a paddingLeft=2 flat block when not active.

2. Active card width was content-fit, so a narrow reasoning card and a
   wide reply card had different border widths in the same column. Adds
   width="100%" so every active card stretches to the full available
   width and the column reads as a uniform stack.

Also resolves the "reply bottom border missing" symptom — settled reply
cards no longer have a border at all, so the question doesn't arise.
2026-05-04 05:53:40 -07:00
esengine e78112bf4f feat(cards): wrap 16 cards in round-border Card primitive — port the demo look to live chat
card-demo had a polished round-border + paddingX=1 wrapper around each
card, but the live chat path (src/cli/ui/cards/*.tsx) never adopted it,
so the demo and the actual chat looked completely different. New
primitive `Card({tone, children})` ports that wrapper to the real cards.

Refactored cards now flow through `<Card tone={...}>` with their content
flush left inside the border (paddingX=1 on the wrapper provides the gap;
removed the per-body `paddingLeft={2}` that would have stacked).

Border tone tracks status:
- ok / running / settled — TONE.ok / brand / accent
- error / warn / abort  — TONE.err / warn
- meta-info             — FG.meta (usage / memory)

LiveCard skipped — it's a one-line transient toast and a 3-row border
would defeat the point. CompactUsageRow path also stays flat.

DEC 2026 sync from 0.24.1 means the border resizing for streaming
content (reasoning/tool/streaming card body growing) lands atomically
per frame; no flicker layered on top of what we already had.
2026-05-04 05:44:00 -07:00
esengine 51a5f9dd8e refactor(cards): unify card header via CardHeader primitive — drop CardBox
Every card had been hand-rolling its first row with the same
Box/Text/gap=1 incantation, so spacing and color hierarchy drifted
between cards. New CardHeader primitive accepts (glyph, tone, title,
optional titleColor / subtitle / meta / right) and gives 12 cards a
single source of truth:

- glyph + bold title in tone color (titleColor overrides for demoted
  cards like usage/memory/user where the bold reads as muted FG.sub)
- subtitle in FG.body (e.g. tool args summary, search query, task
  title, subagent name)
- meta items prefixed with `·` separator, joined by ` · `, faint by
  default; colored MetaItem variant carries diff +/- counts and
  retry/rejected badges without inline JSX clutter
- right slot for ad-hoc inline elements (streaming/reasoning/tool
  spinners)

Drops CardBox — it had a ▎ left-bar API but no card actually wrapped in
it (grep returned zero call sites); the inline ▎ each card showed was
hardcoded, and the redesign has no leading bar at all.

Cards converted: User, Streaming, Reasoning, Tool, Task, Plan, Diff,
Usage, Memory, Search, Branch, SubAgent. 12 files, net -55 lines.

Zero flicker risk — pure single-row replacement, same column width per
field. No row count changes.
2026-05-04 05:30:34 -07:00
esengine b5fd33700e feat(cards): visual audit pass — disambiguate streaming/task, demote usage, branch+ctx+doctor enter token table
The CARD constant was the source of truth on paper but most cards
hardcoded glyphs in JSX, so the table drifted from what's rendered.
This pass aligns intent and fixes the worst clashes:

- streaming and task were both `▶` brand-blue and visually
  indistinguishable when both surfaced in the same turn. Streaming now
  paints `◈` (paired with reasoning's `◆` for the thinking→speaking
  arc); task keeps `▶` but moves to TONE.warn so "doing work" reads
  separately from "model replying".
- usage is a turn-end summary, not active output — header demoted to
  FG.meta; bars + balance keep brand for information density.
- doctor's fail glyph `✗` aligned to error's `✖` for consistency.
- branch in-progress was reusing CARD.streaming.color (brand-blue);
  branching is orchestration, paired with subagent under TONE.violet.
- ctx, doctor, branch were absent from CARD; added so future cards have
  a token to anchor against. (Existing cards still hardcode glyphs;
  consolidation is a follow-up.)

Zero row-count or column-width changes — every replacement is a
single-cell glyph. No flicker risk on top of 0.24.1's sync wrap.
2026-05-04 05:14:47 -07:00
esengine b24d2350ed release: 0.24.1 — DEC 2026 sync to suppress flicker + marked v15 2026-05-04 04:55:46 -07:00
esengine 9f8df4da6b fix(deps): bump marked to v15 — v12 pre-escapes inline text to HTML entities
Marked v12's tokenizer ran inline text through HTML escape (& → &amp;,
< → &lt;, " → &quot;), which is correct for HTML output but wrong for a
TUI — both the user-input echo and assistant markdown rendered the raw
entities. v15 keeps token.text literal and only escapes at the HTML
renderer layer, which matches our actual rendering path. Also avoids the
miswidth where a 1-cell `<` was measured as 4 cells (`&lt;`) and clipped
content past the wrap edge.
2026-05-04 04:49:47 -07:00
esengine 6e2e869aaa fix(renderer): wrap commit writes in DEC 2026 sync to suppress flicker
Commit/static/resize paths buffered bytes into one write but the terminal
could still paint the cleared-then-repainted intermediate state. Wrapping
each frame in BSU/ESU (\x1b[?2026h…l) lets supporting terminals (Windows
Terminal ≥1.18, iTerm2, Kitty, Wezterm, alacritty, foot) swap the frame
atomically; others ignore the unknown CSI. Also folds resize's screen
clear into the next commit so clear+repaint is one sync block.
2026-05-04 04:49:32 -07:00
esengine ff6edff2f6 0.24.0 2026-05-04 04:04:48 -07:00
YHH 213b4ec198 Merge pull request #224 from esengine/fix/inkcompat-stdout-flicker
feat(renderer): yoga + 17/17 card migration + UX overhaul (#160)
2026-05-04 03:41:49 -07:00
esengine 5b5ff09088 feat: WelcomeBanner redesign + plan reject reason + prompt cursor + App cleanup (#160)
Five small, related UX improvements riding the yoga + card-migration train:

WelcomeBanner — REASONIX × 🐋 DeepSeek brand row (cyan brand + violet accent
+ whale emoji), tagline, slash-command hints. Drops the hand-painted box-
drawing borders that broke under CJK fonts; uses borderStyle="round" with
yoga's alignItems="center" so layout is correct in any font.

PlanRefineInput — new "reject" mode (red ✗ tone, error palette). The plan-
confirm picker's cancel branch now opens this input so users can attach a
reason like approve / refine already do. Empty Enter = same cancel synthetic
as before; with text = synthetic includes the user's reason. Symmetric with
the "Tab to add reason" pattern on tool-deny.

PromptInput — call useCursor({visible:false}) so the renderer hides the OS
cursor. PromptInput paints its own ▌ block; without this, the OS cursor
showed at screen-bottom too, doubling up.

App.tsx cleanup — dropped 8 unused imports / destructured fields (ApplyResult,
archivePlanState, ReasoningEffort, saveReasoningEffort, writeClipboard,
renderFrame, COLOR, updateAvailable). Flattened currentRootDir to a state
without setter (no caller).

flicker-demo.tsx — committed the previously-untracked debug demo command
(referenced from src/cli/index.ts).
2026-05-04 03:38:17 -07:00
esengine a92b3c042a feat(cards): migrate remaining 9 cards to flat card-demo style (#160)
Finishes the card-stream migration (now 17/17 = 100%). Each card replaces
CardHeader + BarRow with a flat layout: a row Box for the header glyph +
title + faint metadata, and paddingLeft={2} child rows for the body.

Cards in this commit:
- DiffCard, SubAgentCard, UsageCard, MemoryCard
- SearchCard, LiveCard, CtxCard, BranchCard, DoctorCard

Visual: tighter, no left bar gutter, headers read like one line of status.
Behavior: identical — just different layout primitive.
2026-05-04 03:37:42 -07:00
esengine a5abd9ef94 chore: drop v2 prompt path + Ink-era card primitives (#160)
The chat-v2 / SimplePromptInput stack was the migration test bed for the
cell-diff renderer. With yoga + isPrimaryRenderer in place, the production
chat path on the v1 PromptInput is the only supported entry point, so v2
is now dead weight.

Card primitives (BarRow / CardHeader / Card.tsx / glyphs.ts) became
unreferenced once every card finished migrating to the flat card-demo
style — yoga handles the alignment they were emulating.

Removed:
- src/cli/commands/chat-v2.tsx, input-demo.tsx
- src/cli/ui/chat-v2-slash.ts, loop-bridge.ts, prompt-input-v2.tsx, use-prompt-history.ts
- src/cli/ui/cards/{Card.tsx,CardHeader.tsx,glyphs.ts}
- src/cli/ui/primitives/BarRow.tsx
- tests/renderer/{chat-v2,chat-v2-slash,loop-bridge,prompt-input-v2,use-prompt-history}.test.tsx
- chat-v2 / input-demo command registrations from src/cli/index.ts

Added: src/cli/ui/primitives/CursorBlock.tsx (the only piece of BarRow.tsx
still needed by ReasoningCard, lifted to its own file).
2026-05-04 03:37:15 -07:00
esengine 38867e5c92 feat(renderer): integrate yoga-layout as the flexbox engine (#160)
Replaces our hand-written column/row flex math with Meta's yoga-layout
(WASM, used by real Ink and most React-based TUIs). Layout is now full-spec
flexbox with alignItems/Self/Content, flexShrink/Basis, flexWrap, margin,
min/max, columnGap/rowGap, percent widths.

Why now: the old engine had no cross-axis alignment, so every "center this"
required a nested row+justifyContent hack. With yoga, components describe
intent directly; banner / modal / input layouts collapse to a fraction of
the markup.

Scope:
- Add yoga-layout 3.2.1 dep
- New src/renderer/layout/yoga-layout.ts adapter (LayoutNode -> YogaNode + measure func)
- Rewrite layout.ts: drop layoutBox/Column/Row/intrinsicWidth, walk yoga's
  computed positions to populate LayoutRows
- Extend BoxNode + RsxBox + inkCompat.Box prop surface with the new flex props
- BoxSizing.BorderBox; default flex-shrink=1 (CSS, not yoga's 0); root margins
  reflected in total render bounds
- isPrimaryRenderer=true: only React renderer in this process, so context-stack
  collisions on re-entrant updateContainer go away
- emitStatic via queueMicrotask + reset reservedRows after static bytes -
  fixes resume-path layout collision
- Pin Block Elements (U+2580..U+259F) to width=1 alongside Box Drawing
- Per-edge borderColor props now forwarded through inkCompat
- render-to-bytes header trimmed to satisfy comment-policy

Tests: 2187/2187 pass. Two existing border/padding tests updated for yoga's
content-row reservation behavior (more correct than the old engine).
2026-05-04 03:36:44 -07:00
ctharveyandCharles H 99754672af fix(mcp): close client on handshake failure; swallow kill() errors on Windows (#216)
When mcp.initialize() rejects (timeout, bad spec, etc.), the catch
blocks in chat.tsx and run.ts never called mcp.close() — the child
process leaked, readLoop kept running, and on Node 24 the orphaned
rejection fired as an unhandled rejection.

- Lift mcp declaration before try so it's accessible in catch
- Call mcp?.close().catch(() => undefined) in both catch blocks
  (guard prevents cleanup masking the original bootstrap failure)
- StdioTransport.close(): child.kill("SIGTERM") throws EINVAL on
  Windows; use platform-conditional signal and try/catch to swallow
  both EINVAL and failed-spawn errors

Co-authored-by: Charles H <[email protected]>
2026-05-03 23:34:41 -07:00
esengine d5c02bfae2 fix(renderer): atomic frame writes in mount commit paths (#160)
commitScrollback / commitVirtual / emitStatic all made up to four
sequential opts.write() calls per frame: clear-promote header, promoted
bytes, reserve-grow prelude, and the actual diff patches. Between
writes the terminal could flush, briefly showing blank rows where
content was about to be painted — visible as flicker when ChoiceConfirm
mounts on top of an actively-streaming card (each chunk + the modal
mount each emitting their own multi-write commit).

Now each commit buffers everything into one string and issues a single
opts.write at the end. One terminal flush per frame, no in-between
blank state.

This stacks on top of the previous useStdout fix; the two together
should land the modal-mount flicker.
2026-05-03 22:24:31 -07:00
esengine b140d1c1fb fix(renderer): inkCompat.useStdout returns stable proxy — eliminates modal-mount flicker (#160)
Root cause of the flicker user reported when ChoiceConfirm (and other
modals) appears while a streaming card is still writing:

`inkCompat.useStdout` was returning `{ stdout: { columns, rows } }`,
a fresh object literal on every render with no `.on/.off/.isTTY/.write`.
viewport-budget.tsx (the row allocator the modal claims rows from)
runs `useEffect([stdout])` to register a "resize" listener — every
render produced a new stdout reference, so the effect re-fired every
render. Inside the effect, `stdout.on("resize", ...)` threw because
`.on` was undefined; throw skipped cleanup; cleanup never landed; the
listener that should have detached on next render never did. The
re-fire + throw + dispatch dance manifested as the flicker.

Fix:

1. New `StdoutContext` carries the real NodeJS.WriteStream (passed in
   via mount({stdout})).
2. `useStdout()` now `useMemo`-s the returned wrapper on
   (viewport.columns, viewport.rows, real stdout). Stable identity →
   downstream `useEffect([stdout])` doesn't re-fire on benign renders.
3. The wrapper exposes viewport-driven `columns`/`rows` (so layout
   still reflects the renderer's mounted size, not the host terminal),
   plus `.on/.off/.write/.isTTY` proxied to the real WriteStream.
4. `inkCompat.render` threads `opts.stdout` through to mount() so the
   chain is wired end to end.

All existing tests still pass (the live-banner-via-shim narrow-viewport
test, useStdout viewport tests, etc.).
2026-05-03 22:16:24 -07:00
YHH 3b070dce9c feat(cards): migrate PlanCard + TaskCard (#160) (#220)
PlanCard:
- Header: ⊞ {title} · 3/7 done
- Step rows: glyph + numbered title; running step bold + ← in progress

TaskCard:
- Header: glyph + step N/M + title · elapsed · status
- Step rows: glyph + bold tool name + step title + detail + elapsed

Drops CardHeader / BarRow chrome; both adopt the same flat layout
established for the other cards.
2026-05-03 21:42:07 -07:00
YHH 08e5ddd1f0 feat(cards): migrate ToolCard to card-demo style (#160) (#219)
Drops CardHeader / BarRow / CardBox chrome. Header is one row:
status-glyph + bold tool name + faint args + retry / rejected badges +
faint meta trail (size · elapsed · exit-code).

Status glyphs:
- ▢ running (alongside ⠋ braille spinner)
- ✓ ok
- ✗ rejected
- ✖ error (exit ≠ 0)
- ⊘ aborted

Output preview indented 2; long output keeps the `⋮ N earlier lines`
elision. Exit-code-non-zero output stays in error red, OK output dims.
2026-05-03 21:42:03 -07:00
YHH c3ab3fcb52 feat(cards): migrate ReasoningCard + StreamingCard (#160) (#218)
* feat(cards): migrate ErrorCard + WarnCard to card-demo style (#160)

Drops CardHeader + BarRow primitives. Both cards collapse to the same
flat header-row + indented body pattern that UserCard adopted in #214.

Error retains its retry meta + truncated stack-trace block (unchanged
behavior, lighter visual chrome). Warn keeps the optional detail meta
on the header line.

* feat(cards): migrate ReasoningCard + StreamingCard (#160)

The two most-visible cards in every chat turn drop CardBox + Pill
chrome and adopt the card-demo glyph + bold-title pattern.

ReasoningCard:
- Streaming: ◇ reasoning… · 234 tok ⠋ + italic preview tail (4 lines)
- Settled:   ◆ reasoning · 234 tok · 3¶ · 2.1s + tail (2 lines) + elision
- Aborted:   ◇ reasoning (aborted) in red

StreamingCard:
- Streaming: ▸ writing… ⠋ + clipped preview tail (4 lines)
- Done:      ‹ reply + full markdown body
- Aborted:   ‹ aborted (red) + clipped tail + [truncated by esc]

Spinner stays — liveness signal during streaming is real UX value.
Pills + CardBox left-bar removed.
2026-05-03 21:41:59 -07:00
YHH 4556fb0f09 feat(cards): migrate ErrorCard + WarnCard to card-demo style (#160) (#217)
Drops CardHeader + BarRow primitives. Both cards collapse to the same
flat header-row + indented body pattern that UserCard adopted in #214.

Error retains its retry meta + truncated stack-trace block (unchanged
behavior, lighter visual chrome). Warn keeps the optional detail meta
on the header line.
2026-05-03 21:41:55 -07:00
YHH c80be26517 feat(cards): migrate UserCard to card-demo style (#160) (#214)
* chore(deps): drop ink from runtime dependencies (#160)

The CLI bundle now inlines ink + ink-text-input via tsup's noExternal +
alias chain, so neither package needs to ship at runtime. ink and
ink-text-input move to devDependencies (kept for source resolution
during build / test), and ink-spinner is dropped outright (only ever
referenced in a comment).

vitest gets the same ink → inkCompat alias as tsup so the test suite
runs through the same renderer shim production ships, removing the
last divergence between the two paths.

bundle-smoke already asserts no `from "ink"` literal survives in
dist/cli/; the noExternal extension to ink-text-input means the
bundle has zero `from "ink-text-input"` references too, so a future
regression that breaks either alias fails CI.

* feat(cards): migrate UserCard to card-demo style (#160)

Drops the CardBox left-bar wrapper. The new layout matches card-demo's
flat row aesthetic — accent ›, bold "you", faint relative-time meta,
followed by the user's markdown body indented under it. No more border
or marginLeft offset; cards align to the page's left margin.

This is the first card in the visual migration sweep. Pattern is:
* drop CardBox
* marginTop={1} between cards (was implicit via CardBox)
* header row: glyph + bold word + faint meta
* body indented paddingLeft={2}

Each remaining card (reasoning / streaming / tool / plan / ...) lands
in its own follow-up so before/after diffs stay reviewable.
2026-05-03 20:55:35 -07:00
YHH 252e1258bd chore(deps): drop ink from runtime dependencies (#160) (#213)
The CLI bundle now inlines ink + ink-text-input via tsup's noExternal +
alias chain, so neither package needs to ship at runtime. ink and
ink-text-input move to devDependencies (kept for source resolution
during build / test), and ink-spinner is dropped outright (only ever
referenced in a comment).

vitest gets the same ink → inkCompat alias as tsup so the test suite
runs through the same renderer shim production ships, removing the
last divergence between the two paths.

bundle-smoke already asserts no `from "ink"` literal survives in
dist/cli/; the noExternal extension to ink-text-input means the
bundle has zero `from "ink-text-input"` references too, so a future
regression that breaks either alias fails CI.
2026-05-03 20:55:31 -07:00
YHH 5bd2678d51 feat(build): tsup alias 'ink' → inkCompat — chat now runs on cell-diff (#160) (#212)
Adds an esbuild alias on the CLI bundle that resolves every `import …
from "ink"` to src/renderer/ink-compat. Combined with noExternal:
["ink"] this forces the bundle to inline the shim instead of leaving
"ink" as a runtime external. The 3496-line App.tsx and every UI file
that imports Box / Text / Static / useApp / useInput / useStdout /
render now flow through the cell-diff renderer with zero source
changes.

Library + dashboard bundles are unchanged — only the CLI alias.

bundle-smoke gains an assertion that no `from "ink"` literal survives
in dist/cli/, so a future regression that breaks the alias fails the
build pipeline. Doctor command runs end-to-end through the aliased
path; help / version / non-interactive subcommands work.

Tests still resolve the real "ink" package (vitest doesn't go through
tsup), so unit tests stay on the existing path; the bundle test is the
production-correctness check.
2026-05-03 19:32:09 -07:00
YHH f01f12d0ae feat(renderer): inkCompat.render — Ink-shaped runtime over the cell-diff renderer (#160) (#211)
New render(element, opts) → { rerender, unmount, waitUntilExit, cleanup,
clear } that mirrors Ink's render API while mounting through the
cell-diff renderer's mount(). Wires resize, Ctrl+C handling
(default-on, opt-out via exitOnCtrlC: false), and useApp().exit()
integration so existing Ink-shaped apps drop in cleanly.

Foundation for the next step: a tsup alias 'ink' → inkCompat that lets
the existing reasonix chat (and its full 3496-line App.tsx) render
through cell-diff without any source changes — replacing the parallel
chat-v2 rebuild track.

7 new tests cover initial mount, waitUntilExit gating, rerender,
Ctrl+C exit, exitOnCtrlC: false, useApp().exit(), and useInput wiring.
2026-05-03 19:20:55 -07:00
YHH b4b196ea3a feat(renderer): chat-v2 — slash commands (/help /clear /cost /new /exit) (#160) (#210)
handleSubmit detects a leading / and routes to a pure handler map in
src/cli/ui/chat-v2-slash.ts instead of running a turn. Each handler
returns events to dispatch (synthetic user + canned reply, or a
session.reset, or a live.show error) plus an optional exit flag.

/help renders the command list as a regular streaming card so the
markdown view picks up the formatting; /cost reads from agentStore
state and shows current usage; /clear and /new both fire session.reset
which the existing reducer already handles. Unknown commands surface
as an err live card with the offending name.

10 new tests (7 unit + 3 integration through the chat-v2 shell).
2026-05-03 19:16:13 -07:00
YHH ada301ffce feat(renderer): chat-v2 — session persistence + resume (#160) (#209)
runChatV2 accepts session / forceNew / forceResume options; resolveSession
picks the actual name (timestamp suffix on --new, latest prefix on
--resume); CacheFirstLoop({session}) handles persistence so the running
transcript carries across launches.

Resumed sessions replay user-side history as user cards on mount via
AgentStoreProvider's initialCards seed. Assistant content isn't replayed
(no event log on disk yet); fresh turns stream into place.

CLI: `reasonix chat-v2 --session foo` resumes; `--new` forks a fresh
suffix; `--resume` walks to the latest matching prefix. Header shows
the resolved session name when one is active.
2026-05-03 18:54:00 -07:00
YHH 8f6a12767c feat(renderer): chat-v2 — wire web / memory / ask_choice tools (#160) (#208)
The real-loop runTurn now builds a ToolRegistry mirroring chatCommand:
web search/fetch (when searchEnabled()), memory tools (remember /
recall / forget), and ask_choice. The loop is constructed once per
chat session and reused across turns so cache state and the running
transcript carry over.

Tool events flow through the existing makeLoopBridge into tool.start /
tool.end card pairs, so the chat-v2 surface now shows real tool
activity inline (when DEEPSEEK_API_KEY is set). MCP / sessions /
slash commands are still deferred to 5d-23c-e.
2026-05-03 18:43:56 -07:00
YHH fb80b9cb38 feat(renderer): chat-v2 — real DeepSeek loop when API key is set (#160) (#207)
New makeLoopBridge() translates LoopEvents into the AgentStore event
shape: assistant_delta opens reasoning / streaming cards and emits
chunks; tool_start + tool produce paired cards with elapsedMs;
assistant_final and done close everything and stamp turn.end with
usage; error closes any open card with aborted=true and fires
turn.abort.

ChatV2Shell takes an injectable runTurn callback. runChatV2 builds the
real one (DeepSeekClient + ImmutablePrefix + CacheFirstLoop) when
DEEPSEEK_API_KEY is set; otherwise the canned demo path still runs so
the UI is explorable without an account.

11 new bridge unit tests; existing chat-v2 tests rewired to the new
runTurn injection point.
2026-05-03 18:36:55 -07:00
YHH ce01092f9c feat(renderer): chat-v2 — settled cards flow through Static (#160) (#206)
chat-v2 splits its card list into settled (user, finished reasoning,
finished tool, completed streaming) and in-flight at every render.
Settled cards go through inkCompat.Static so they emit to scrollback
once and never re-render; only the actively-streaming card stays in
the live region. The viewport's live region is now bounded by the size
of the in-flight card, not by the whole conversation.

MarkdownView drops its useMemo: Static's renderToBytes path uses a
one-shot tree walker without a React dispatcher, so any hook call
inside a Static-promoted subtree throws. Recomputing markdown lines
each render is allocation-light enough that the cache wasn't load-bearing.
2026-05-03 18:25:52 -07:00
YHH 0bd11e1e63 feat(renderer): bracketed paste + sentinels in SimplePromptInput (#160) (#205)
The keystroke parser now recognises ESC[200~...ESC[201~ wrappers and
emits the entire payload as a single keystroke, so multi-line pastes
hit processMultilineKey's pasteRequest branch. SimplePromptInput keeps
a per-instance paste registry; each burst gets one PUA sentinel in the
buffer + an inline `[paste #N · Ml · Nb]` placeholder. Submit expands
sentinels back to original content via expandPasteSentinels.

chat-v2 + input-demo enable bracketed-paste mode (ESC[?2004h) on entry
and disable on exit so the wrapper actually arrives.
2026-05-03 18:06:30 -07:00
YHH 42dba23bf7 feat(renderer): chat-v2 — submit history with ↑/↓ recall (#160) (#204)
usePromptHistory hook holds a FIFO of submitted entries. Up arrow on a
boundary saves the current draft, then walks back; down arrow walks
forward and restores the saved draft past the newest entry.
Duplicate-of-latest submissions are coalesced; entries past the cap
(default 100) drop from the front.

chat-v2 wires it into SimplePromptInput's onHistoryPrev / onHistoryNext.
2026-05-03 17:51:07 -07:00
YHH ea3bdbed4d feat(renderer): SimplePromptInput goes multi-line (#160) (#203)
Reuses processMultilineKey from src/cli/ui/multiline-keys.ts so chat-v2's
prompt input shares behavior with the live chat input: backslash line
continuation, ↑/↓ between logical lines, Ctrl+W word delete, Meta+B/F
word jump, Alt+Enter for newline, Enter to submit, history hooks at
buffer boundaries.

Renders each logical line as its own row; cursor lands on the right
(line, col) via useCursor's rowFromBottom. The keystroke parser also
learns Alt+Enter (\x1b\r → meta+return) so the multi-line reducer can
distinguish it from a bare Enter.
2026-05-03 17:41:56 -07:00
YHH 7cd9456440 feat(renderer): chat-v2 — live input replaces canned playback (#160) (#202)
chat-v2 now opens an empty conversation with SimplePromptInput at the
bottom. Each Enter dispatches user.submit and plays a stock canned reply
turn (reasoning + streaming + turn.end) — no real model is wired up yet,
but the seam from keystroke → reducer → cards → cell-diff renderer is
fully exercised end-to-end.

Esc on an empty prompt exits; Esc on a non-empty prompt clears (handled
by SimplePromptInput's onCancel semantics).
2026-05-03 17:27:00 -07:00
ctharveyandCharles H 9bf23b49ca refactor(mcp): move McpServerSummary out of UI slash types into src/mcp/summary.ts (#201)
- New src/mcp/summary.ts: canonical McpServerSummary interface + buildMcpServerSummary() builder
- slash/types.ts: import+re-export McpServerSummary from MCP layer, remove inline interface and unused inspect/registry imports
- chat.tsx: use buildMcpServerSummary() instead of inline object literal

Addresses issue #196 first boundary: relocation + builder, zero behavior change.

Co-authored-by: Charles H <[email protected]>
2026-05-03 17:23:31 -07:00
YHH e931db397e feat(renderer): SimplePromptInput — single-line input on cell-diff renderer (#160) (#200)
New SimplePromptInput component built on useCursor + useKeystroke. Handles
printable chars, backspace, delete, enter, ←→, home/end, ctrl+a/e/u/k,
escape (clear when non-empty, cancel when empty). Caret position published
through useCursor so the terminal cursor sits where the user expects.

`reasonix input-demo` exercises the component standalone — submitted
entries land in a Static history list above the prompt.
2026-05-03 17:17:16 -07:00
YHH 184a4a0366 feat(renderer): useCursor hook — React-driven terminal cursor positioning (#160) (#199)
Adds CursorContext + useCursor() in the renderer. Components register a
target { col, rowFromBottom?, visible? }; mount() reads the latest target
on every frame commit and feeds it into next.cursor.

Also adds a "cursorVisible" patch type so visibility transitions emit
ESC[?25h / ESC[?25l on the diff stream. Foundation for the chat-v2
PromptInput migration — single-line input lands next.
2026-05-03 17:04:26 -07:00
YHH 4d58eef324 feat(renderer): markdown pipeline — marked → MdLine[] → inkCompat (#160) (#198)
Splits markdown rendering into a pure parser (markdown-lines.ts) and a
cell-diff-renderer view (markdown-view.tsx). chat-v2's reasoning and
streaming card bodies now render proper headings, lists, code blocks,
blockquotes, and inline bold/italic/code instead of a single flat line.

`markdownToLines` is streaming-safe — partial input parses gracefully,
so the same call on every chunk yields a stable line tree.
2026-05-03 16:55:10 -07:00
YHH c2603a897e feat(renderer): chat-v2 — stripped-down App tree on cell-diff renderer (#160) (#197)
Mounts AgentStoreProvider through `mount()` instead of Ink's `render()`.
A canned event script drives the real reducer; CardRows read state via
`useAgentState`. No PromptInput yet — Esc / Ctrl+C exits.

Lays the seam for the chat App migration: events → reducer → useState
→ inkCompat tree → cell-diff renderer all proven end-to-end.
2026-05-03 16:42:21 -07:00
ctharveyandCharles H d9684bbff5 fix(tui): bound Markdown table rendering to card width with fallback key/value layout (#195)
- MarkdownWidthCtx + useWidth() propagate available column width into
  nested block renderers; width prop is body-width (no double subtraction)
- tableLayout() pure function decides columnar vs fallback layout
- FallbackTable wraps long values under their label; labelPad clamped to
  availableWidth-1 so label+value never exceeds card width
- ColumnarTable for tables that fit; HorizontalRule width-bounded
- plainText() exported for test access
- 18 tests: smoke (11), tableLayout fallback decision (2),
  FallbackTable width invariants (5 including narrow-width sweep)

Co-authored-by: Charles H <[email protected]>
2026-05-03 16:25:53 -07:00
YHH 02ce601ef2 feat(renderer): card-demo — full chat lifecycle reference (#160) (#191)
* feat(renderer): card-demo — full chat lifecycle reference

Demonstrates the design pattern for streaming-TUI cards: every card
type (user, reasoning, tool, plan, response, diff, error) has an
active form that lives in the live region, animating, and a settled
form (typically 1 line) that commits to terminal scrollback once
the underlying work completes.

Auto-replays a fake chat session: user message → reasoning →
shell tool with rolling output → plan with stepwise spinner →
diff → streaming response → error notice. Each card animates
in the live region, then collapses to a single-line summary in
the Static history above. The live region is bounded — at most
ONE active card plus status + prompt — so it never overflows
the viewport, native mouse scroll/select keep working.

This is the pattern Reasonix's actual chat App.tsx should adopt
when migrating to the cell-diff renderer: track in-flight work
in live state, commit completed work to Static. Mirrors how
Claude Code structures its CLI streaming.

Refs #160.

* feat(card-demo): full Reasonix card vocabulary + variants

After surveying src/cli/ui's actual card stream, expanded card-demo
from 7 stages to 13 covering every real card type and lifecycle
variant we ship today:

  user  → reasoning (R1) → read_file → bash → bash retry/error
       → plan (4 steps with embedded tool ops)
       → write_file rejected → diff → subagent (nested children)
       → streaming response → usage → warn → error

Card behavior matches the live App's CardStream conventions:

- reasoning: active spinner + last 4 token-streamed lines; settled
  keeps last 2 lines + "⋯ N ¶ · M tok · /reasoning last"
- tool: tone-colored glyph (▤ read, ▥ write, ▶ bash, ⊙ search,
  ⌬ fetch, ⊕ mcp); active rolling 5-line tail + elapsed; settled
  shows "⋮ N earlier lines" + tail (2-5 lines per tool tone);
  rejected = badge replaces body; retry/error = red + ↻ retry X/Y
- plan: ◯/▶/✓/✗/!/s glyphs + "← in progress" marker; settled
  keeps full step list (per #160 Plan never collapses to 1 line)
- response: active "writing…" spinner + last 4 lines; settled
  keeps full markdown body (or "(truncated by esc)" if aborted)
- diff: file header + first-N hunk preview; +/- coloring
- subagent: ⌬ + nested children with ▎ indent; child cards are
  single-line summaries with their own tone/glyph
- usage / warn / error: single-row badges

Wrap helper added so streaming text wraps at ~70 cols and the tail
is computed against actual visual rows.

Refs #160.

* fix(renderer): wide-char width compensation for Ambiguous glyphs

User repro: card-demo in Windows Terminal showed residue chars next to
glyphs like ↻ ▶ ⊞ ◆. East Asian Ambiguous width disagreement —
stringWidth reports 1, the terminal renders 2 (or vice versa on
Western terminals), so the diff cursor model gets out of sync with
where the terminal actually advanced. Subsequent cells land in the
wrong column → leftover chars from the previous frame appear next to
the new content.

Two-part fix:

1. Layout (string-width call site): treat ambiguous chars as wide
   (width 2) by default, so the layout reserves enough cells either
   way. Box-drawing block U+2500..U+257F is pinned to width 1
   explicitly because terminals never render those wide and our
   borders depend on it.

2. writeCell, when emitting a Wide cell, runs a leading-space + CHA
   compensation:
     CHA col+1     ← jump to the right-neighbor cell
     stdout ' '    ← pre-write a blank there (covered by wide
                     glyph if the terminal renders 2-wide; visible
                     as a clean space if the terminal renders 1-wide)
     CHA col       ← jump back to the original column
     stdout char   ← write the actual glyph
     cursor.x += 2 ← model advances 2 cells regardless
     CHA col+2     ← force the terminal cursor to col+2 so the next
                     cell write lands in the right spot

   ~4 extra escape sequences + 1 leading space per Wide cell, only
   fires when cell.width === Wide. Empty / narrow cells unaffected.

This is what was making \`↻ retry 1/3\` and \`0.4s\` run together
with stray chars between them, and what made the Plan card render
\`││\` on the right edge.

Refs #160.

* feat(card-demo): real-world plan execution + concurrent active cards

Restructure to match how a real session actually drives cards:

- active state is now an array. Multiple cards can be live at once
  (plan stays live while a tool runs below it; subagent stays live
  while children animate inline).

- Plan no longer appears all-done in one shot. Steps progress one
  at a time: each step starts running, a tool card appears below the
  plan card, the tool animates, settles to history, plan step flips
  to done, next step starts. Plan card itself never leaves live area
  until every step is in a terminal state.

- The fix-failing-test scene now exercises:
  * search step (grep) — short tool with rolling output
  * write_file rejected mid-plan → step gets blocked → plan retries
    via patch tool
  * bash test with retry chain (1/3 fails, 2/3 succeeds)
  * bash deploy (npm publish)
  * full plan settles, diff card pushed, markdown response
    streams (header + code block + bullet list)

- Subagent scene: ⌬ card stays live while 4 child rows animate
  in sequence (reasoning, grep, read, diff). Each child flips
  from running spinner to ✓ in place. CJK streaming response
  follows.

- Edge cases scene: aborted reasoning (settles with red glyph +
  "(aborted)" badge), MCP tool, web_fetch, compaction warn, rate
  limit error, final usage card.

Tools now have per-tone tail length (read/search/fetch = 2 lines,
bash/mcp = 5 lines) matching the real CardStream conventions.
ToolActive carries a `retry` field rendered as `R 1/3` next to the
elapsed timer.

Refs #160.
2026-05-03 16:23:14 -07:00
YHH 4ee324b02e feat(renderer): virtual viewport — full layout stays live, PgUp/PgDn scrolls (#160) (#190)
* feat(renderer): virtual viewport — full layout stays live, PgUp/PgDn scrolls

Adds a scroll: "virtual" mode to mount(). Rather than promoting overflow
rows to scrollback (where they freeze), the entire layout lives in
memory and the visible viewport-1 window slides over it. All animations
keep running for the full layout, even when the user has scrolled away
from the bottom.

mount opts.scroll defaults to "scrollback" — the existing behavior is
unchanged for chat / preview / banner-demo et al. Apps that want
dashboard-style live regions opt in.

Implementation:
  - renderVirtual returns the full layout with a windowAt(offset, h)
    slicer.
  - mount tracks scrollOffset + stickyBottom + lastTotalRows.
  - Each commit picks a window: stickyBottom or shrink → snap to
    bottom; otherwise hold the user's offset (clamped).
  - PgUp / PgDown scroll by viewport-1 rows. Home / End jump to
    extremes. After any scroll, stickyBottom re-evaluates against
    the new offset so resuming at the bottom auto-follows growth.

stress-demo opts into "virtual" — its 4 concurrent regions can now
exceed the viewport without freezing anything; user scrolls the
viewport over a still-live layout.

Tests: tests/renderer/virtual-viewport.test.tsx (6) — initial bottom
pin, PgUp older rows visible, Home/End jumps, growth-while-sticky
follows latest, growth-after-user-scroll holds position. Uses an
inline virtual-terminal byte parser to read final screen state past
cell-diff fragmentation.

Refs #160.

* feat(renderer): mouse wheel scrolls the virtual viewport

Mouse wheel was being consumed by the terminal's own scrollback and
landed on empty pre-mount terminal output instead of scrolling our
virtual layout.

Fix: enable SGR mouse mode (\x1b[?1000h\x1b[?1006h) on mount when
scroll: "virtual", disable on destroy. Keystroke parser recognizes
button 64 → wheelUp, button 65 → wheelDown. mount's scroll handler
maps wheel events to scrollBy(±3 rows).

Mouse capture is only enabled in virtual mode; scrollback mode
leaves text selection / native scrollback alone for chat-style
apps where the user expects normal terminal behavior.

Tests: keystroke parser cases for SGR `<64;X;YM`, `<65;X;Ym`. Two
virtual-viewport tests cover wheel scrolling and the enable/disable
escape sequences at mount/destroy.

Refs #160.

* fix(renderer): disable mouse mode on any exit path

The bug: enabling SGR mouse mode (\x1b[?1000h\x1b[?1006h) at mount
without disabling it on every exit path leaves the terminal stuck —
mouse clicks and selection get swallowed by escape sequences for
the now-dead process. User has to close the terminal window or
manually emit the disable bytes.

Fix: register `process.on("exit", ...)` to write DISABLE_MOUSE on
ANY process exit (normal, crash, parent-killed). Also intercept
SIGINT/SIGTERM with `process.exit(130)` so Ctrl+C funnels through
the same exit handler. destroy() unregisters these handlers when
mount tears down cleanly.

Idempotent disable: writing DISABLE_MOUSE twice (once from
destroy, once from exit handler) is safe — the disable sequence
just sets a flag in the terminal.

Refs #160.

* feat(renderer): virtual mode enters alt-screen — like the live chat

Aligned mount's virtual mode with src/cli/ui/alt-screen.ts: enter the
terminal's alternate buffer (1049h) so the renderer owns its own
viewport without polluting the user's main shell history. Use button-
event mouse mode (1002, not 1000) for press/drag/release tracking;
SGR coords (1006). Shift+drag still bypasses for native selection.

The escape sequence on enter is now:
  \x1b[?1049h\x1b[2J\x1b[H\x1b[?1002h\x1b[?1006h

On any exit (destroy, process.exit, SIGINT/SIGTERM):
  \x1b[?1006l\x1b[?1002l\x1b[?1000l\x1b[?1049l

The alt-screen toggle (1049l) automatically restores the user's
pre-mount terminal contents — npm wrapper output, prior shell prompts,
all visible again. No more polluted scrollback after stress-demo
exits, no more stuck mouse mode if the process crashes.

This is what the user meant by "fullscreen": the chat command and
stress-demo now both behave like vim/htop/less — own the viewport,
restore on exit. The scrollback mode (default for chat preview etc.)
keeps the inline behavior where output streams to the user's main
terminal buffer.

Refs #160.

* fix(stress-demo): inline mode + rolling Shell — like Claude Code

After studying claude-code-sourcemap: their CLI runs **inline** for
streaming output (no alt-screen, no mouse capture). Native mouse
selection and terminal scrollback work the user's whole life.
AlternateScreen wrapping is opt-in for explicit modal UIs (plan
mode, etc.) — not the default.

Reasonix stress-demo was wrong to opt into virtual mode. Reverting:

  - scroll: "virtual" removed → uses default "scrollback"
  - SHELL_WINDOW=5 rolling window restored so the layout fits a
    typical viewport (~22 rows)
  - alt-screen takeover gone → user keeps native mouse selection
    and terminal scrollback

Now matches Claude Code's pattern: streaming dashboards stay inline,
trade-off is older content goes to terminal scrollback frozen (which
is fine, that's how every TUI streaming app works).

Virtual mode stays in the renderer for genuine modal/fullscreen UIs
that explicitly opt in. Not the default.

Refs #160.
2026-05-03 08:45:27 -07:00
YHH fd64c2f8e5 feat(renderer): stress-demo — 4 concurrent live regions (#160) (#189)
* feat(renderer): stress-demo — 4 concurrent live regions

The simple-streaming preview wasn't a real test of the renderer's
value. Plain text streaming on its own is something Ink doesn't
struggle with too much. The actual jitter that #155 reports comes
from STACKED dynamic regions all updating concurrently — Plan card
on top with a spinner, shell command appending output rows below,
streaming response card on top of that, status header ticking, etc.

This subcommand mounts that exact scene:

  - status row (ticks every 100ms — elapsed time + cost)
  - Plan card (4 steps, step 2 has a spinner ticking every 80ms)
  - Shell card (npm test, output rows append every 250ms)
  - Response card (text reveals 4 chars every 33ms, wraps mid-phrase)
  - hint bar at bottom

All five regions update at independent rates. On Ink, every state
change in any of them re-emits the entire 20-row tree. On the new
renderer, each tick produces patches only for the cells that
actually changed — typically 1-3 cells per tick.

Three tests cover initial paint, ticked state after 1s
(verifying multiple regions are advancing), and ESC-to-exit.

Refs #160. Run `reasonix stress-demo` to see whether the original
jitter problem is actually fixed in the live terminal.

* fix(renderer): re-reserve vertical space when layout grows mid-session

stress-demo exposed a hard correctness bug: live repro showed
spinner glyphs scattered down the left margin overwriting npm dev
output, multiple stacked top borders, scrambled text everywhere.

Root cause: reservation only ran on the first paint. stress-demo's
layout grows over time (Shell card appends rows every 250ms,
Response card text wraps onto new rows as it streams). When the
new layout height exceeded the originally-reserved rows, each
overflowing row triggered a terminal scroll. The diff cursor model
didn't track scrolls, so subsequent relative cursor moves landed
in completely wrong positions — overwriting whatever was at those
real terminal coordinates, including pre-mount scrollback content.

Fix: track reservedRows. On every commit, if the new layout's
height exceeds reservedRows, emit `\n * delta + CSI <delta> A` to
reserve more rows (scrolling once if needed) and bring cursor
back to its model position. Subsequent diffs then use relative
moves within the now-larger reserved region — never past it,
never into pre-mount territory.

Also corrects the off-by-one math from 5d-13: each commit can
extend the reserved area incrementally as content grows.

Refs #160.

* fix(renderer): clip layout to viewport-1 + ink-compat Box default = row

Two fixes from running stress-demo to actual chaos in PowerShell.

1. Layout taller than viewport caused overflow rows to write past
   the reserved area, triggering scrolls the diff cursor model
   didn't track. Subsequent relative cursor moves landed in
   pre-mount terminal territory — Plan spinner cells overwrote
   npm dev output, top borders got clobbered by glyphs from
   later commits.

   Fix: renderToScreen takes an optional maxHeight. mount passes
   viewportHeight - 1. When the layout produces more rows than
   that, the SKIP rows come off the TOP — so the most recent
   streaming content stays visible while the older static chrome
   scrolls off the top of the live region.

2. inkCompat.Box defaulted flexDirection to undefined (which our
   native Box treats as column). Ink defaults to row. Real
   components like the live WelcomeBanner used <Box> for hint
   lines expecting row flow; the shim was stacking each Text
   on its own line, blowing the layout up to 19 rows.

   Fix: ink-compat Box defaults flexDirection to "row" when
   not explicitly set.

Refs #160.

* feat(renderer): promote overflow rows to scrollback when layout > viewport

Last fix clipped layout to viewport-1 to stop the diff from corrupting
pre-mount terminal content, but it also meant scrolled-off rows were
never preserved — user couldn't scroll up to see the older state.

Now when layout exceeds viewport-1, the top rows that get clipped are
EMITTED to scrollback explicitly:

  1. Track promotedRows — how many top rows have been committed.
  2. Each commit, if the new clip count exceeds promotedRows, emit
     bytes for those new rows via serializePromoted: clear the live
     area, write the promoted rows (cursor advances, they go into
     scrollback), reset frame, then repaint the live region below.
  3. promotedRows monotonically increases — once a row is promoted,
     it stays in scrollback at the state it had when promoted (its
     last-known content before scrolling off).

renderViewport replaces the renderToScreen call inside mount: it
returns the visible Screen + a serializer for the promoted slice
of the same layout pass (no double-layouting).

For status / spinner rows whose content keeps changing: when they
overflow, the snapshot at the moment of overflow is what scrollback
keeps. Subsequent commits stop touching those rows. UX-wise this is
similar to how a real terminal scroll preserves output history.

Refs #160.

* fix(stress-demo): rolling Shell window — keep all 4 regions in viewport

Reframing: terminal scrollback is write-once. Once a row scrolls off
the live region, terminals can't update it anymore — animations on
that row are necessarily frozen. The promote-to-scrollback path
preserves the row so users can scroll back, but it'll never re-animate.

The fix isn't more renderer plumbing — it's keeping the demo's layout
inside the viewport so nothing has to scroll off in the first place.

Shell card now shows the last 5 output rows; older rows roll out with
a "(+N earlier)" indicator next to the title. The card stays a
constant ~7 rows tall regardless of how many test lines have arrived.
Status + Plan + Shell + Response + hint now total ~22 rows — fits in
a typical 24-row terminal with all four regions live and animating.

Real chat use cases will use Static for committed messages (which
DOES belong in scrollback) and live region for the in-flight reply
(which fits the viewport). The promote path stays for those cases.

* fix(renderer): full reset on resize — no double-paint

Live repro: shrink the terminal while stress-demo is running. The Plan
card appears stacked twice — one frozen copy above, one live below.

Cause: resize re-rendered through the normal onCommit path, which
saw layout > new viewport-1 and ran promote-to-scrollback. The old
live frame's height (from the bigger viewport) was used to compute
how far up to clear with CSI nA — but CSI A clamps at viewport top,
so the clear missed pre-resize content. Then promoted bytes wrote
visibly into the cleared area, and the diff repainted the live
region below. Net effect: duplicate cards.

Fix: resize is a special event, not a normal commit. Reset frame,
reservedRows, promotedRows; emit `\x1b[2J\x1b[H` to wipe the
visible viewport (scrollback above is preserved by terminals);
then re-render through the normal first-paint path. Pre-resize
content stays in scrollback; current frame paints fresh in the
new viewport size.

Refs #160.
2026-05-03 07:47:48 -07:00
YHH a9df67102b feat(renderer): preview — incremental text reveal on the streaming row (#188)
Builds on the spinner state machine: instead of just spinning then
echoing, the response now reveals 3 chars per 33ms, growing in place
in the live area. Spinner glyph keeps ticking (80ms) while text grows.
When fully revealed, a 200ms pause, then the user line + complete
echo land in Static and the prompt comes back.

This is the workload that breaks Ink (#155): a streaming card whose
content grows mid-frame. Each reveal here is ~3 cell writes; the diff
layer doesn't repaint anything else (spinner cell, user line, hint
bar all stay frozen across the reveal). Real LLM streaming, when we
wire it in, slots into the same state — just replace the setInterval
that advances `revealed` with the token-arrival callback.

Response wraps at 60-col viewport — exercises the reveal-across-wrap
case where adding chars at end of one row spills onto the next.

Refs #160.
2026-05-03 07:07:43 -07:00
YHH a3b346848f feat(renderer): preview — streaming spinner state machine (#187)
Enter on a non-slash submission no longer echoes immediately. Shell
enters a "streaming" state: the user line and a Braille spinner row
('thinking…') render in the live area below the Static history,
ticking 80ms/frame. After 1500ms the streaming row commits both the
user line and the echo to Static and the prompt becomes available
again.

This is the core value-prop test for the cell-diff renderer: the
spinner ticks 18-ish times during the stream, each tick is a single
cell change, and the diff emits ~1 patch per frame instead of
re-painting the whole live region the way Ink does. No row-count
churn during the stream → no jitter.

Input is paused while inflight (keystrokes are dropped). The slash
fast-path (/help, /clear, /exit, /unknown) still works because slash
commands return synchronously without entering streaming.

Two new e2e tests in preview.test.tsx assert the spinner appears,
the echo lands after the timeout, and keystrokes during streaming
are dropped. The /clear test was rewritten to use /help submissions
(slash-only) to avoid streaming interference.

Refs #160.
2026-05-03 06:56:35 -07:00
YHH 966ddeac3b fix(renderer): reserve vertical space + slash commands in preview (#160) (#186)
* fix(renderer): anchor cursor to col 0 before the first paint

Bug surfaced live: typing into the preview shell wrote characters at
the wrong screen position because the very first frame's diff started
emitting cells from wherever the terminal cursor happened to sit at
mount time (often mid-line, after the npm dev wrapper output). The
moveTo no-op for (0,0)→(0,0) meant no \r got emitted, so the first
row landed in the column the shell had left the cursor at.

Fix: emit \r CSI J before the first reconciler commit. \r anchors the
cursor at column 0 of the current row; CSI J clears below so any
straggler text isn't visible underneath the live area. Subsequent
diffs already use \r on every row transition, so only row 0 of the
initial paint was vulnerable.

Adds reasonix preview slash commands (/help / /clear / /exit) on top
of 5d-12 since the user was testing them and surfaced the cursor bug.
Also fixes Static so that shrinking items[] resets lastIndex (without
this, a /clear followed by new items wouldn't emit the new ones).

Refs #160.

* fix(renderer): treat OOB cells as EMPTY_CELL in diffEach

Live repro from running reasonix preview:

  > 123 ▏         1 dev    <-- our prompt landed on the npm wrapper line
  > tsx src/cli/index.ts preview
  Enter submit · / for commands · Esc exit

Initial paint mounted on a 24-tall emptyFrame against a 6-row layout.
diffEach iterates the union (24 rows). For y=6..23 prev had EMPTY_CELL
(allocated by emptyFrame), next.cellAt returned undefined (OOB on the
shorter screen). The early-skip required BOTH non-undefined for
cellsEqual, so the OOB case fell through and emitted clear-patches —
~18 rows × viewportWidth cells of cursor moves + spaces. On a 24-row
terminal that ran the cursor past the bottom, scrolling the npm
output up; the header scrolled out of view and the prompt landed
where "> [email protected].1 dev" used to sit.

Fix: coalesce undefined to EMPTY_CELL on both sides before the equality
check. OOB-vs-EMPTY is now a no-op; populated-vs-OOB still emits a
clear (which is correct — the row really shrank).

Two regression tests in tests/renderer/diff.test.ts pin both legs.

* fix(renderer): reserve vertical rows + revert OOB coalesce

User-visible repro: reasonix renderer-demo (and preview) only showed
the bottom row of the layout in PowerShell. Header / prompt rows
appeared to be missing.

Two interacting bugs:

1. mount painted rows top-down using CSI nB cursor moves. When the
   shell left the cursor near the bottom of the viewport, every row
   transition past the visible region scrolled the terminal up,
   pushing earlier-painted rows off-screen. Only the LAST row written
   ended up still visible.

   Fix: before the first paint, emit `\r \n*(N-1) CSI <N-1>A` to
   pre-reserve N rows below the cursor (scrolling up once if needed)
   and return to the start. Subsequent moves stay within the reserved
   block — no more scrolls.

2. The earlier OOB-coalesce attempt in diffEach treated
   prev=undefined / next=EMPTY_CELL as equal, which silently dropped
   patches for spaces inside text content (since space cells share
   charId/style with EMPTY_CELL). "(none yet)" rendered with cursor
   gaps where its space should have been.

   Reverted to the original diff predicate. Initial paint now emits
   patches for every cell in the new screen (verbose, but correct);
   subsequent diffs still coalesce identical cells.

Reservation regression test in mount.test.tsx asserts the
\r\n*8\x1b[8A prelude for a 9-row layout.

Refs #160.

* fix(renderer): reserve N+1 rows so the final cursor park doesn't scroll

Off-by-one in the reservation prelude caused values to drift one row
up after the first paint when the live region used the bottom of the
viewport. Trace: 9-row content + final cursor parks at frame y=9
(one past the last content row). Old reservation only covered 9 rows
(R..R+8); the cursor's final move to R+9 hit the viewport bottom and
scrolled, shifting all painted content up by 1. Subsequent diffs
targeted the now-shifted rows correctly in their own model, but the
already-rendered content had drifted, so visually new values landed
one row above the row where the label sat.

Bump reserve to screen.height (was screen.height - 1) so the parking
row is also pre-allocated. seven-key-trace test confirms the byte
stream produces the right cells; mount.test.tsx regression updated
to assert the new prelude shape.

Refs #160.
2026-05-03 06:48:08 -07:00
YHH 9e206a14ad feat(renderer): reasonix preview — minimal chat shell on the cell-diff renderer (#185)
First user-facing surface that runs entirely on the new pipeline. Echo
mode for now: header, Static-emitted history, single-line input,
Enter to submit, Esc to exit. Composes everything 5d-2..5d-11 added
(useKeystroke, useApp.exit, Static scrollback, gap, hex colors,
marginTop, useState-driven draft).

State held in refs so a single push("abc\r") that fires four
keystrokes synchronously commits the right text — closure-captured
state would otherwise read pre-update values.

Subsequent PRs grow this shell toward feature parity with the live
chat: model badge, streaming card, tool result rows, slash-commands.
Once it catches up, the existing Ink-based App becomes the legacy
backend.

Refs #160.
2026-05-03 05:46:21 -07:00
YHH c557b9726b test(renderer): the live WelcomeBanner renders end-to-end via the shim (#184)
Mounts the actual src/cli/ui/WelcomeBanner.tsx — the component the
running app uses today — through our cell-diff renderer with **zero
source changes**. vi.mock substitutes "ink" with the ink-compat shim
at test time, so the production import paths stay intact.

Asserts the frame glyphs, REASONIX brand line, slash hints, in-code
mode tagline swap, dashboardUrl link line, and a narrow viewport
(cols=40). This is the first time a real production component renders
under the new pipeline without being copied or rewritten.

Refs #160. The path forward for full migration: add a runtime
"ink" → ink-compat alias when the new renderer is selected, and
existing components keep working.
2026-05-03 05:29:22 -07:00
YHH 5e040ad2e5 feat(renderer): wire useApp().exit() to a mount-level onExit hook (#183)
Previously useApp() returned a default {exit: noop}. Components inside
a mount tree could call exit() but nothing happened — the host had to
read the user's intent some other way (a Promise resolved from a
keystroke handler, etc.).

mount() now provides AppContext.Provider with a real exit fn. The fn
defers via queueMicrotask so it never fires synchronously inside a
render or effect — that would unmount the tree mid-commit. After
destroy, exit() becomes a no-op, so a stale ref can't fire onExit
later.

mount opt: onExit?: (error?: Error) => void. The host owns the actual
teardown; onExit is just the signal.

Refs #160. Smaller surface than full lifecycle plumbing — covers the
Ink useApp() pattern that DiffApp/ReplayApp/Setup/Wizard rely on.
2026-05-03 05:22:24 -07:00
YHH 0e893e1c0a feat(renderer): select-demo — arrow-nav SingleSelect via ink-compat (#182)
Reasonix select-demo subcommand mounts a faithful single-select list
through the cell-diff renderer: arrow nav, Enter to submit, Esc to
cancel, disabled rows skip + dim. Real-world pattern that combines
useKeystroke, useState-driven highlight, hex/named-color theming, and
nested column Boxes.

Five end-to-end tests cover initial paint, ArrowDown skipping a
disabled row, Enter on the initial active row, Esc cancel, and
ArrowUp wrap-around.

Refs #160. Together with banner-demo, this proves both static-shaped
content (banner) and interactive-shaped content (select) ride the new
pipeline cleanly.
2026-05-03 05:15:21 -07:00
Matt Van HornandMatt Van Horn d6fde1786d test(gitignore): add unit tests for src/gitignore.ts (#139) (#180)
Adds tests/gitignore.test.ts covering ignoredByLayers (empty layers,
literal dir match, intra-file negation, isDir toggle, out-of-scope
layer skip, fall-through, no-match) and loadGitignoreAt /
loadGitignoreAtSync (missing-file null path, working Ignore from a
real .gitignore in a tmpdir).

11 tests; vitest, lint, typecheck, and full suite (2064 tests) pass
locally. No source changes; no new dependencies.

Closes #139

Co-authored-by: Matt Van Horn <[email protected]>
2026-05-03 05:07:23 -07:00
YHH ac3e4f1d56 test(renderer): wide-char + emoji end-to-end through mount (#181)
Locks in the diff pipeline's behavior with CJK and emoji content:
both glyphs of a 4-cell CJK string land, replacing wide content with
narrow leaves no ghost half-cells, narrow→wide growth writes the new
wide char, multiple emoji in a row each appear, a styled CJK char
wraps in the right SGR open/close pair, and wrapping at the viewport
edge keeps the wide glyph intact on the next row.

Refs #160. The renderer's main correctness risk in real Reasonix usage
is wide chars across diffs (Chinese UI strings change between frames
constantly). These tests catch the SpacerTail-not-cleared regression
class up front.
2026-05-03 05:02:21 -07:00
YHH e250afc007 feat(renderer): gap on Box — column rows + row columns (#179)
Adds gap to BoxNode with the obvious semantics: in column flow it
inserts N empty rows between siblings; in row flow it reserves N cells
between siblings before flexGrow distribution.

Plumbed through native BoxProps + ink-compat Box. intrinsicWidth now
counts gap*N-1 for row-flow boxes so flex distribution is correct.
gap composes with justifyContent — extra slack from space-between is
added on top of the configured gap.

Refs #160. Used by markdown.tsx, etc.
2026-05-03 04:54:39 -07:00
YHH f28c67fddd feat(renderer): Static — emit settled rows to scrollback (#178)
Implements the "rendered once and never updated" semantic for
inkCompat.Static. Previously the shim just wrapped items in a column
Box, which left them subject to re-diff every frame.

Pipeline: when Static's items array grows, the new items are rendered
offline via renderToBytes and handed to the mount Handle's emitStatic.
emitStatic clears the previous live area, writes the static bytes
(advancing scrollback), and resets the prev frame so the next paint
starts fresh below.

renderToBytes is exposed publicly so apps can stage scrollback content
without React (e.g., a one-shot welcome banner emitted before the live
loop starts).

Refs #160.
2026-05-03 04:48:19 -07:00
YHH 3f15d000e8 feat(renderer): banner-demo — first real-app component via ink-compat (#177)
Reasonix banner-demo subcommand mounts a structurally faithful version
of the welcome banner — nested Box + marginY + marginTop +
justifyContent="center" + hex colors, useStdout for centering, useKeystroke
for ESC — entirely through the ink-compat shim onto the cell-diff
renderer.

Three end-to-end tests assert frame glyphs, brand line, hint row, ESC
exit, and resize re-paint. The Ink-flavored banner used by the live App
is left untouched on this branch; this is the first concrete proof that
a non-trivial component renders end-to-end through the new pipeline.

Refs #160.
2026-05-03 04:39:21 -07:00
YHH 19c33d1a9a feat(renderer): fixed width / height on Box (#176)
Adds width and height props to BoxNode + BoxProps + ink-compat. Width
overrides intrinsic size for row-flow allocation and clamps to the
parent's available width. Height pads with empty rows when content is
shorter and truncates when content is taller.

Unblocks the height={1} spacer-row pattern (4 components in src/cli/ui
use it) and width-constrained columns (sidebar, picker lists) that
need to land before the main App can migrate off Ink.

Refs #160.
2026-05-03 04:33:18 -07:00
YHH 25240984cb feat(renderer): justifyContent in row flow — flex-end / center / space-between (#175)
Wires Yoga-style row distribution into the layout engine. Default
(flex-start) preserves current behavior. flex-end pushes children to
the right edge, center splits slack evenly, space-between distributes
the gap between siblings. flexGrow children consume slack first, so
justifyContent silently degrades to flex-start when grow is present —
which matches CSS flexbox.

Plumbed through BoxNode → BoxProps → ink-compat Box so existing Ink
code reading `<Box justifyContent="space-between">` migrates with no
source changes. Three of four uses in the codebase already match this
shape.

Refs #160.
2026-05-03 04:24:19 -07:00
YHH e8594a973f feat(renderer): ink-compat shim — Box / Text / Spacer / Static / hooks (#174)
Lets components written against Ink's API render under the cell-diff
renderer with no source changes for the props we cover.

Box: padding{X,Y,Top,Bottom,Left,Right} pass through; margin{X,Y,Top,
Bottom,Left,Right,} translate to a wrapper Box's padding so empty rows
sit above/around the inner box (works in both column and row flow,
since the wrapper carries flexGrow on row participation). borderStyle
takes the string presets, borderColor takes color names + hex.

Text: color, backgroundColor, bold, dimColor, italic, underline,
strikethrough, inverse all stack into the StylePool entry.

Spacer is just <Box flexGrow={1}/>. Static is a flexDirection=column
wrapper — it doesn't yet implement Ink's "settled content stays in
place" semantic; that needs row-level commit isolation, deferred.

Hooks: useStdout reads {columns,rows} from a ViewportContext that
mount() now provides and re-publishes on resize(). useApp returns
{exit} from AppContext (host wires its own exit). useInput translates
each Keystroke to Ink's (input, key) callback shape, with isActive
gating.

Out of scope: width/height (need fixed-size layout), justifyContent,
alignItems, gap, useFocus, Transform, measureElement.

Refs #160.
2026-05-03 04:16:19 -07:00
YHH 35637b15aa feat(renderer): reasonix renderer-demo subcommand — end-to-end on real TTY (#173)
Lets us exercise the cell-diff renderer against real stdin/stdout
without touching the main Ink-based App. Counter + last-key display,
ESC to exit. Component-level tests cover initial paint, key handling,
and ESC-to-exit through a fake stdin and the test writer.

Refs #160.
2026-05-03 04:01:43 -07:00
YHH d0ab2cbd42 feat(renderer): stdin keystroke parser + useKeystroke hook (#172)
Adds the input side of the renderer pipeline so React components can
react to user keystrokes through the same provider/hook idiom they
already use for state.

Architecture:

- parseKeystrokes(chunk) is a pure ANSI escape-sequence parser. Plain
  ASCII passes through; \x01..\x1a become ctrl+letter; \r / \n
  return; \x7f / \x08 backspace; \t tab; \x1b alone escape; ESC +
  printable is meta+char; CSI A/B/C/D arrows; CSI 1;modifier <X>
  surfaces shift/meta/ctrl modifiers; CSI 3~ delete, 5~ pageUp,
  6~ pageDown, 1~/H home, 4~/F end.
- KeystrokeReader wraps a stdin-like stream (anything with on/off
  'data') and emits parsed Keystroke events to subscribers. Sets raw
  mode on construction, drops it on destroy.
- useKeystroke(handler) hook subscribes the calling component to the
  reader provided via KeystrokeContext.
- mount({ stdin }) constructs the reader, wraps the React tree in
  KeystrokeContext.Provider, and tears the reader down on destroy.

Tracking issue: #160.
2026-05-03 03:43:35 -07:00
YHH ed1ad08615 feat(renderer): react-reconciler integration — useState drives paints (#171)
useState / useEffect / re-render-on-state now drive paints without
the caller manually calling update(). React's reconciler maintains
the host node tree; on every commit we walk it to a LayoutNode tree,
hand it to the diff layer, and write only the changed bytes.

Surface:

  const handle = mount(<App />, { viewportWidth, viewportHeight, pools, write });
  // setState in App triggers a paint automatically.
  handle.update(<NewApp />);   // explicit replace also works
  handle.resize(cols, rows);
  handle.destroy();

Box and Text are now thin wrappers that emit string-typed JSX
intrinsics ('rsx-box' / 'rsx-text'). The reconciler matches the
strings in createInstance and instantiates host nodes; the existing
no-reconciler walker in react/render.ts matches the same strings.
Both code paths converge.

Adds react-reconciler + @types/react-reconciler as direct deps.

Tracking issue: #160.
2026-05-03 03:34:29 -07:00
YHH 40fe1dc546 feat(renderer): Renderer runtime — frame state + diff + write to a sink (#170)
Closes the offline pipeline of #160. Caller pushes a React tree at
the Renderer; it lays out, diffs against the previous frame, writes
only the changed bytes to the configured sink, and stashes the new
frame for the next call.

  const r = new Renderer({ viewportWidth, viewportHeight, pools, write });
  r.update(<App />);              // first paint — full screen
  r.update(<App />);              // identical tree — zero bytes
  r.update(<AppMutated />);       // only the diff
  r.resize(cols, rows);           // next update full-resets via clearTerminal
  r.destroy();                    // SGR reset + OSC 8 close

Sink is injected (write: (bytes: string) => void), so tests run
purely in memory via makeTestWriter() — no real stdout, no real
terminal. The same shape will plug into process.stdout.write in
the runtime integration step.

Doesn't yet:
- Drive re-renders from React state (the caller still has to call
  update; Phase 5b adds reconciler-driven re-renders).
- Read keystrokes (Phase 5c).
- Replace Ink in Reasonix's CLI (Phase 5d, behind a feature flag).

Tracking issue: #160.
2026-05-03 03:02:29 -07:00
YHH 266a4d509e feat(renderer): serialize Patch[] to ANSI byte stream (#169)
Closes the second-to-last layer of #160. Takes the Patch[] that
diffFrames returns and produces the actual bytes a terminal
understands.

  cursorMove → CSI A/B/C/D (vertical first, then horizontal)
  cursorTo   → CSI <col+1> G (CHA is 1-based)
  hyperlink  → OSC 8;;<uri> ST  (empty uri = close)
  clear      → \r + CSI <count> A + CSI J  (move up N rows, erase to end)
  clearTerminal → CSI 2J + CSI H

stdout / styleStr / carriageReturn pass through verbatim — they are
already terminal bytes by the time the diff layer puts them in the
patch list.

dx=0 and dy=0 cursor moves serialize to the empty string (no wasted
escapes), and an empty Patch[] serializes to '' so emitting a frame
with no diff is a no-op.

Tracking issue: #160.
2026-05-03 02:57:24 -07:00
YHH aa87a6d88b feat(renderer): cell-level diff between two Frames → Patch[] (#168)
Core of #160 — the algorithm that takes two Screen snapshots and
emits the minimal set of (cursorMove + styleStr + stdout + hyperlink)
patches needed to bring the terminal from the old state to the new.
This is what replaces Ink's bulk eraseLines: unchanged cells produce
zero bytes.

diffFrames(prev, next, pools) → Patch[]:

- viewport size differs → emit clearTerminal + write the full new
  screen. Resize is rare; predicting wrap on a different width is
  not worth the layout machinery.
- otherwise walk every (x, y) where the cells differ:
  - move the cursor there (\r if pending-wrap, then \r + dy + dx)
  - transition style if changed (StylePool.transition cached)
  - transition hyperlink if changed (OSC 8 open / close)
  - skip SpacerTail (the wide glyph already advanced the cursor)
  - write the char
- after all changes, restore cursor to next.cursor and reset style /
  hyperlink to none so anything we don't own renders cleanly.

Adjacent same-style writes ride on the terminal's natural cursor
advance — no inter-cell cursor moves, no inter-cell style emits.

Tracking issue: #160.
2026-05-03 02:39:13 -07:00
kabaka a6fd807b49 feat(i18n): Implement front-end and back-end language setting synchronization feature (#167)
Add back-end language setting support, including initializing language settings from the server and bidirectional synchronization functionality
Expand the language registry to support more languages, and improve language storage and error handling
Fix issue of returning to the chat page after refreshing
2026-05-03 02:38:21 -07:00
YHH 3634bdeca5 feat(renderer): Box borders — preset styles + custom glyph object + per-side colors (#166)
Closes the layout side of the renderer feature surface for #160.

Borders compose with padding by sitting outside it:

  border-top
    padding-top
      content (width = inner - borders - padding)
    padding-bottom
  border-bottom

Five preset styles ('single', 'double', 'round', 'bold', 'ascii')
or a fully custom { topLeft, top, topRight, ... } glyph object —
the latter is what Reasonix's CardBox uses today (whitespace
corners + a single glyph on the left for the accent bar).

Each side toggles independently via borderTop / Bottom / Left /
Right; default-on when borderStyle is set, default-off otherwise.
borderColor sets all four; per-side overrides (borderLeftColor
etc.) win.

intrinsicWidth now accounts for border + padding so flexDirection
row in a parent allocates the correct slot width to bordered
children.

Tracking issue: #160.
2026-05-03 02:29:06 -07:00
YHH 933d01060f feat(renderer): flexDirection row + flexGrow (#165)
Refactors layout from a linear TextRow stream to a 2D structure
where each visual row holds a list of x-positioned fragments.
Necessary for row direction — sibling children need to share rows
at different x offsets, which the previous one-fragment-per-row
shape couldn't express.

flexDirection='row' lays children left-to-right. Each child gets
min(intrinsicWidth, remaining) of the available width. When the
sum of intrinsics exceeds the container, allocations scale
proportionally and children's text wraps inside its narrower slot.
Children with different heights align at the top.

flexGrow distributes leftover width after intrinsics are honored.
The common case — Box flexGrow=1 as a flex spacer between fixed
content — yields '<L> <pad> <R>' style headers without manual
column math.

Default direction stays column.

Tracking issue: #160.
2026-05-03 02:20:57 -07:00
YHH 4026baa28c feat(renderer): Box padding (top / bottom / left / right + X/Y/all shorthands) (#164)
Padding shifts content inward without changing the Box's own width.
paddingTop / Bottom emit blank rows above / below children;
paddingLeft / Right reduce the inner width children lay out into,
and every emitted row carries a leftPad offset that the blit step
honours so writes start at the correct x.

paddingX / paddingY / padding shorthands compose with the side-
specific props — explicit side wins (paddingLeft beats paddingX
beats padding).

Tracking issue: #160.
2026-05-03 02:14:07 -07:00
YHH af4e9e33ef feat(renderer): React JSX entry — Box / Text / function components → LayoutNode (#163)
Lets callers write the renderer surface in JSX instead of building
LayoutNode trees by hand. Box and Text are exported as host markers
(throw if invoked directly); the render() entry walks the React
element tree, recognizes those markers, calls stateless function
components inline, and unwraps Fragments. Output is a Screen.

No reconciler yet — stateful components / hooks / re-render-on-state
don't drive output. The walker is enough for static JSX rendering
and for tests to use familiar JSX syntax. The reconciler comes when
we wire the renderer to actually drive a live UI.

Tracking issue: #160.
2026-05-03 02:06:54 -07:00
YHH eacb4e56d3 feat(renderer): vertical-stack layout from Box / Text nodes (#162)
Walks a tree of Box and Text nodes and lays them out into a Screen
of the given width. Children stack vertically; nested boxes flatten
in source order. Long text lines wrap at the cell boundary using
grapheme-aware width via Intl.Segmenter + string-width, so CJK and
emoji ZWJ count as one rendered glyph occupying the right number
of cells.

Style and hyperlink on a Text node are interned through the pools
and propagated to every cell the node produces — sets up the diff
layer to compare cells purely by integer ids.

Tracking issue: #160.
2026-05-03 01:59:57 -07:00
YHH c222808985 feat(renderer): cell-buffer foundation — Screen, Cell, intern pools (#161)
Lays down the data structures the cell-diff renderer will read from.
Pure values, no terminal IO; the diff layer (next) reads two Screen
snapshots and emits patches per cell that actually differs.

Three pools collapse high-cardinality runtime values to integer ids
so cell comparison stays in int-vs-int and per-frame allocation
stops being a GC problem at 5K+ cells.

Tracking issue: #160.
2026-05-03 01:51:44 -07:00
YHH 0b0e19fc7a feat: remove plan sidebar / docking entirely (#159)
Plan card now lives only as a regular inline card in the stream.
No right-side panel, no above-input pinning, no Ctrl+\ toggle.
Layout stayed in 'either-or' / 'both' / 'sometimes-pinned' uncertainty
across PR #127 → #156, and the docking machinery itself was a steady
source of layout instability that no amount of width-conditional
gating fully closed.

Removes:
- src/cli/ui/layout/SidebarPanel.tsx (file)
- tests/sidebar-panel.test.ts (file)
- App.tsx: activePlanCard / rawActivePlanCard / sidebarVisible
  derivation, the sidebarOpen state + Ctrl+\ keybind, the
  <SidebarPanel> mount, the modal-active gating that only mattered
  to suppress the sidebar
- viewport-budget.tsx: 'plan-card' ZoneId entry (no claimers left),
  useIsModalActive() hook (only consumer was sidebar)
- CardStream.tsx: excludeId prop (no callers left)
- config.ts: sidebarOpen field + load/save helpers

The plan card itself is unchanged — it's already a settled card
once all steps complete and renders as a regular inline card via
CardStream's existing plan->Static path. Inline plan card has
stable height (no windowing), so it doesn't suffer the live-region
height-flutter issue the sidebar's windowed PlanSection had.
2026-05-03 01:27:51 -07:00
YHH 0da4c78ca0 fix(sidebar): stabilize windowed plan-section height across step transitions (#158)
Root-cause fix for the up-down screen jitter dududarochadev reported
in #155 (and the same class of bug we previously masked with
cols-based sidebar gating).

When a plan has more steps than fit in the window (>11), the windowed
plan-section conditionally rendered '(N earlier hidden)' / '(N more)'
hint rows only when N>0. As the running step crossed the window
boundaries those flipped on/off, changing the live region's row count
and triggering Ink's erase-then-reprint to leak the previous frame.

Always render both indicator rows in windowed mode; show the count
when N>0, an empty 1-row placeholder otherwise. Total rendered height
of the windowed plan-section is now stable regardless of how the
running step moves through the plan.

Fix lives on the plan card itself, not behind a width gate, so the
narrow-screen inline-plan path benefits the same way once the same
windowing pattern lands there (currently inline PlanCard doesn't
window, so it's already stable for now).

This is the start of the broader 'live-region row stability' work I'll
track in a follow-up issue — streaming/reasoning preview cards have
the same shape of bug during their initial output ramp.
2026-05-03 01:04:31 -07:00
YHH 161e36a461 fix(layout): plan card lives in EITHER sidebar OR card stream, never both (#156)
Per RFC #20 thread, lamyc's ask was "task list collapsed INTO a
sidebar" on portrait/narrow setups. PR #127 shipped a sidebar but
also kept a pinned PlanCard above the input — so on wide screens the
plan rendered twice (sidebar + pinned), and on narrow screens (where
the sidebar refuses to render below 88 cols) the plan was pulled out
of the card stream and pinned above input alone, leaving no inline
plan card at all.

Single rule now:

  sidebarVisible = !PLAIN_UI && sidebarOpen && cols ≥ 88 && activePlanCard

  - sidebarVisible       → CardStream excludes plan; sidebar renders it
  - !sidebarVisible      → CardStream keeps plan inline; nothing pinned

Drop the pinned PlanCard above input entirely. Drop the unconditional
`excludeId` on CardStream. `PlanCard` is no longer imported in App.

This implements interpretation B+C from the layout discussion:
B) plan fully in sidebar when room exists, no duplicate
C) narrow / portrait → plan stays inline in stream, no sidebar
2026-05-03 00:37:02 -07:00
YHH 559e684784 fix(plan): gate sidebar + pinned plan card on modal-active, not step transition (#153)
#147 used "at least one step has left queued" as the proxy for
"plan has been approved". That breaks the post-accept window: once
the user accepts, plan steps may sit in `queued` for several seconds
before the model issues its first tool call — during which the sidebar
should be visible but isn't.

Right discriminator is the approval modal itself. `useIsModalActive()`
is true exactly while PlanConfirm (or any other modal-priority claim)
is up. Drop the "non-queued" check from findActivePlan and gate at
the call site:

  - SidebarPanel: `isModalActive ? null : findActivePlan(cards)`
  - App.tsx activePlanCard: same shape

findActivePlan stays pure (no hook usage) so it remains unit-testable.
The test that previously locked in "all-queued returns null" now
locks in "all-queued returns plan" — modal-gating is the caller's
contract.
2026-05-02 23:57:13 -07:00
YHH ea66fb4bf1 feat(cards): tool card 'rejected' state + input-size meta (#154)
Closes #150 (the user-facing half — bounce wording itself stays as-is).

The plan-mode bounce error and silent write_file are both fundamentally
visual problems: the gate runs before fs writes, but the spinner-then-
JSON-error sequence reads as 'wrote, then failed'; large write_file
content gives no progress signal because formatArgsSummary picks the
short path field.

A. Plan-mode rejection visual

ToolRegistry now adds rejectedReason: 'plan-mode' to the bounce JSON.
The reducer parses tool.end output, sets card.rejected on the marker.
ToolCard swaps the spinner for a red ✗ rejected badge in the trailing
slot and hides the verbose error body — one quick visual cue replaces
a faux-write spinner followed by a wall of JSON.

B. Input size in meta

ToolCard.formatMeta gains a leading '1.2 KB in' fragment when any
string field on args is at or above 1 KB. Generic — no per-tool
special case — so write_file (content), edit_file (long replace),
run_command (long stdin) all benefit. Below 1 KB, nothing shows;
small writes don't get noisy meta.

Tests:
- ui-reducer: tool.end with plan-mode marker flips rejected=true,
  regular errors don't trigger.
- tool-card-meta: largestStringInputBytes thresholding + multi-field
  selection.
2026-05-02 23:45:22 -07:00
YHH edf4233a60 feat(i18n): default to system locale when no explicit config (#151)
First-run users with a Chinese OS locale saw English by default —
the only signal was config.lang, which doesn't exist on first launch.
Add a third tier between config and the EN fallback: detectSystemLanguage()
reads Intl.DateTimeFormat().resolvedOptions().locale (cross-platform,
no env-var spelunking) and prefix-maps zh* → zh-CN, en* → EN, anything
else → null (falls through).

Priority: user-set config > system locale > EN.

The detection function takes the locale string as a parameter (defaulting
to Intl) so it stays unit-testable without mocking globals.
2026-05-02 21:21:47 -07:00
kabaka 4b4d125987 feat(i18n): add multi-language support (#149)
Add internationalization support for the dashboard, including English and Simplified Chinese.
- Create i18n module to manage language switching and translations
- Replace hardcoded text with translation keys in all panels
- Add language switching functionality to the settings panel
- Implement dynamic loading of translation content
- Update all UI components to use translation functions
2026-05-02 21:07:33 -07:00
kabaka 5631dafdde feat(i18n): add multi-language support (#144)
Implement runtime language switching, including:
- Add /language command for language switching
- Add Chinese/English translation framework
- Modify state management to support language change events
- Update tests to ensure correct functionality
- Adjust UI components to support internationalized text
2026-05-02 21:07:29 -07:00
YHH e11fd6c848 fix(plan): only treat plan as 'active' once execution has started (#147)
User reported the right-side plan sidebar appears during the
PlanConfirm approval modal, before the user has accepted. Same bug
also pinned the plan card above the input prematurely.

Both selectors (App.tsx:297 + SidebarPanel.tsx:39) used the same
predicate: variant === "active" + at-least-one-step-not-done. But
fresh plans have every step in `queued` — the predicate matched
immediately on creation, before approval triggered any state
transition.

Tighten the predicate: "active" now means execution has actually
started — at least one step has left `queued` AND not all steps
are done/skipped. Approval-pending plans (every step queued) and
finished plans (every step done/skipped) both correctly return null.

Exported findActivePlan and added 5 tests covering the regression
plus the surrounding boundaries (variant guards, latest-of-many).
2026-05-02 20:59:31 -07:00
YHH 11c7150ed1 fix(cards): drop fake key hints + CtxCard CardHeader + TaskCard meta tidy (#145)
Plan + Error cards advertised inline keybinds in their footers
(`[r] revise` / `[r] retry` etc.) but no handler was ever wired
to scrollback cards — the actual revise/retry flow runs through
PlanConfirm modals via arrow + Enter. Pressing the advertised key
did nothing. Removed the misleading footers; the modal flows are
unchanged.

CtxCard hand-rolled its own header instead of using CardHeader,
breaking the visual contract every other card follows. Routed it
through CardHeader with the same tone/glyph/meta shape.

TaskCard's `meta` ended in a trailing space (`X.Xs · `) and
CardHeader inserts its own space before the trailing badge, so the
rendered output had a double space before the status word.

Also collapsed a dead ternary branch in PlanCard step-color logic
where two arms produced the same value.
2026-05-02 20:31:41 -07:00
YHH 4a3f5f035b feat(cards): UserCard gets CardBox accent + drop dead approval-card type (#143)
UserCard was the only Markdown-rendering card without a CardBox bar —
long pasted prompts wrapped without a continuing accent, breaking the
visual rhythm against the now-accented streaming/reasoning cards.

Audit also turned up the `approval` card kind in cards.ts: declared
in the Card union but with zero producers in src/ or tests/. The
CardRenderer case for it just routed to FallbackCard ("not yet
migrated"). Removed the interface, the union member, and the orphan
case — default branch already catches anything unexpected.
2026-05-02 19:45:11 -07:00
ctharveyandCharles H 2ed06d4213 fix(code): adapt LF model output to target file line endings for SEARCH/REPLACE matching (#142)
applyEditBlock and edit_file both detect the target file's line ending
(CRLF vs LF) and adapt the model's search/replace text before matching.
Duplicate-match checks, replacement, and diff rendering use the adapted
text. CRLF files are preserved as CRLF; LF files stay LF.

Adds tests for both paths: SEARCH/REPLACE blocks (edit-blocks) and the
native edit_file tool (filesystem-tools), covering LF→CRLF matching,
LF preservation, multi-line CRLF matching, and duplicate-match refusal.

Co-authored-by: Charles H <[email protected]>
2026-05-02 19:26:07 -07:00
YHH e625e01e2e fix(cards): restore brand accent on done-state assistant reply (#140)
PR #126 (0.23.0) gave done assistant Markdown a brand-toned
borderLeft per lamyc's RFC #20 readability ask. The #136 card
redesign extracted CardBox but flipped the done-state color to
FG.faint, defeating the contrast that lets long replies stand
out in scrollback. Now matches the streaming-state color so the
bar reads continuously across the streaming → done flip.
Aborted state stays on FG.faint (correctly de-emphasized).
2026-05-02 19:22:45 -07:00
YHH b2c9d416d2 test(slash): silence MCP reconnect spawn stderr leak (#138)
The /mcp reconnect <name> test fired kickOffMcpReconnect with spec
"node nope", spawning Node against a missing 'nope' module. The
test passed (lifecycle line is returned synchronously) but Node's
MODULE_NOT_FOUND error leaked to stderr in the test runner output.

"node -e 0" exits 0 silently and is cross-platform.
2026-05-02 09:23:17 -07:00
YHH 7da04c615a release: 0.23.1 — reasoning/streaming card redesign + loop storm self-correct (#137) 2026-05-02 09:15:32 -07:00
YHH dfaee68b2d fix(tui): redesign reasoning + streaming cards (closes #133) (#136)
The Reasoning card had three rendering bugs that compounded into a
"feels broken" UX: only one preview line was visible, that line was
the head not the tail of the actual reasoning, and once content
overflowed the viewport the screen jittered on every chunk.

Root causes were three independent issues:

  1. The line-budget constant in StreamingCard / ToolCard was off by
     two cells, so rendered lines exceeded the terminal width by one
     and the terminal wrap-extended each row. Ink's eraseLines(N)
     then miscounted against the visible row count and left ghost
     rows behind on every render — the visible "jitter."

  2. The streaming live region grew row-by-row as text arrived.
     Each new line pushed everything below down by one row before
     the eraseLines miscount kicked in to make it worse.

  3. The settled body sliced last N lines, but reasoning is
     typically a single long paragraph — slice(-2) returned the
     whole one-line string, then clipToCells truncated from the
     head, so the user saw the first cells of the line instead of
     the last.

Fixes:

  - Wrap card content in `<Box borderLeft borderStyle={{left:"▎"}}>`
    via a new CardBox primitive — Ink renders the bar on every
    visual row including markdown wrap continuations.
  - Streaming preview is fixed at 4 visual rows (live region small
    enough that eraseLines miscount can't pile up). Settled
    reasoning collapses to last 2 visual rows.
  - Pre-wrap content via wrapToCells before slicing, so `slice(-N)`
    returns the true visual tail.
  - Drop the CardRenderer "yield to content" branch that hid
    reasoning entirely while output streamed.

Visual:

  - Section + model pills replace the `◆` glyph + emoji prefix.
    Model pill color signals model class (flash blue, pro purple,
    r1 violet).
  - Bar color dims to FG.faint once a card settles — running cards
    are accent-bright, done cards are grey.
  - Streaming header carries a braille spinner + "thinking…" /
    "writing…" status text.
  - Settled reasoning header shows duration on the right.
  - Settled cards above the tail-2 lines get a single elision row
    (`⋯ N ¶ · K tok above · /reasoning last`) instead of a full
    head+tail layout.
2026-05-02 08:50:24 -07:00
YHH c72fca8c6f fix(loop): self-correct on first repeat-loop storm before stopping (#134)
Closes #132.

Bad-args bugs (e.g. read_file({path:""})) and genuine stuck loops
both used to land in the same place: storm-breaker suppressed the
calls, the loop force-summarized, the turn ended with a loud yellow
"recent-repeat window" warning. Bad-args is the common case and would
self-correct if the model just saw the prior tool error — terminating
the turn forces a /retry that didn't need to happen.

Now the first all-suppressed storm in a turn rewrites the just-
persisted assistant message to preserve the original tool_calls,
stubs role:"tool" responses to honor DeepSeek's "every tool_call
needs a tool message" contract, yields a plain-language warning,
and continues the iter — model gets one shot at a different approach.
Only the second storm in the same turn falls through to the
forced-summary path.

Also softens user-facing copy: "storm-broken" / "recent-repeat
window" / "call-storm suppressed" jargon → "repeat-loop guard" /
"repeated tool call" / "stuck retry loop". Auto-escalation toast
now reads "4× repeat-loop" instead of "4× storm-broken".

Adds REASONIX_STORM_THRESHOLD / REASONIX_STORM_WINDOW env vars for
manual testing of the guard at lower thresholds.
2026-05-02 07:09:58 -07:00
YHH 58732cacf2 release: 0.23.0 — TUI quality-of-life pass (#130) 2026-05-02 06:32:17 -07:00
YHH fee58f13da fix(at-mention): nested .gitignore via shared util (#129)
@paulo70015 reported every @ query returning "no files match" on
Flutter projects. Diagnosis: the picker walker did not honor
.gitignore, so the 500-result cap filled with ios/Pods/ before the
alphabetical walk reached lib/.

Rather than grow the hardcoded ignore list per framework (Pods,
DerivedData, target, vendor, …), trust the project's own
.gitignore — same source of truth fzf, ripgrep, and the rest of
the ecosystem use.

  - new `src/gitignore.ts` lifts loadGitignoreAt + ignoredByLayers
    out of the semantic chunker, so the @ picker walker and the
    indexer share one nested-gitignore implementation
  - `listFilesWithStats(Sync|Async)` push a layer per directory's
    .gitignore as it descends; statBatch checks the merged layer
    set before stat'ing
  - default maxResults bumped 500 → 2000
  - opt-out via `respectGitignore: false` on ListFilesOptions
  - `chunker.ts` switches to the shared util — no behavior change

Tests cover root + nested .gitignore, negation (`!keep.log`),
opt-out, and the existing skip / cap / DFS-order contracts.
2026-05-02 06:26:38 -07:00
will 16024bbd15 test: add preset resolution and canonicalization coverage (#125) 2026-05-02 05:55:12 -07:00
YHH b6d4d9beab feat(tui): right-side context panel with Ctrl+\ toggle (#127)
* feat(tui): right-side context panel with Ctrl+\ toggle (#122)

Sidebar shows current plan steps, running tools, and last-turn
usage as a read-only HUD. Defaults open on cols ≥ 120, off below;
persisted in ~/.reasonix/config.json.sidebarOpen. Below 88 cols
total the panel hides regardless of preference.

Carries the StreamingCard hook-order fix from #126.

* fix(sidebar): hide entirely when no active plan

Empty sidebar default-on was visual noise — 28 cols of blank panel
on every fresh session. Now the panel returns null unless an active
plan exists. Drop the Usage section: same data already lives in the
inline UsageCard.

* fix(sidebar): hide on rejected plans (require actual progress)

submit_plan creates the plan card with all steps "queued" before
PlanConfirm even pops; cancelling the modal leaves the card behind
unchanged. Sidebar was treating "variant=active" as enough and
stayed mounted after rejection. Now also require at least one step
to have started — distinguishes pending-approval / cancelled
("all queued, forever") from running / partially-done plans.

* refactor(sidebar): divider uses borderTop instead of hardcoded char repeat

The divider rendered "─".repeat(SIDEBAR_WIDTH - 2), which would break
the moment the panel width or padding changed. An empty box with
borderTop lets Yoga compute the line width from the parent — adapts
automatically.

* fix(plan): drop the active plan card on PlanConfirm cancel

submit_plan creates the plan card up-front (variant=active, all
steps queued) before the user picks approve / cancel. On cancel
nothing was clearing the card, so the existing activePlanCard
selector + the new sidebar both kept it visible as if the plan was
running.

New plan.drop reducer action flips the latest active plan's variant
to "replay" (already-existing archive variant). Sidebar + bottom
PlanCard now honor cancel correctly. Approved-but-not-yet-started
plans render as before — variant is still "active", just with all
steps queued.
2026-05-02 05:38:18 -07:00
YHH 4f6e99e772 feat(cards): left accent bar on done assistant replies (#126)
* feat(cards): left accent bar on done assistant replies (#122)

Add a brand-toned borderLeft to the done-state Markdown so long
replies are visually distinguishable from tool/reasoning cards in
scrollback. Ink's <Box> doesn't accept backgroundColor; a left bar
is the terminal-native equivalent and works on light + dark themes.

* chore(tui): trim comment essays from layout migration

Comments added in the #120 migration violated CLAUDE.md: multi-paragraph
module headers, defensive justification, incident narrative ("lamyc-video
trigger"). Reduced to single lines where the why is genuinely non-obvious.
2026-05-02 05:35:36 -07:00
YHH 1ff2c7c7b9 fix(tui): single layout authority for viewport rows (#124)
* fix(tui): single layout authority for viewport rows (#120)

Streaming cards and approval modals each read stdout.rows and
computed their own row budget independently — the bottom-anchor
modal could claim rows the streaming card had already counted on
and vice versa, producing visible jitter when both rendered the
same frame (lamyc's video).

Replaces the scattered RESERVED_CHROME_ROWS / MODAL_OVERHEAD_ROWS
constants with a priority-greedy allocator. Each component declares
{ min, max } rows for its zone via useReserveRows; the provider
runs allocation and feeds back actual budgets so consumers stay
within the viewport.

Migrated zones, in priority order:
  modal       (EditConfirm, ShellConfirm, PlanConfirm,
               PlanCheckpointConfirm, ChoiceConfirm)
  status      — left for follow-up; already conditionally hidden
  input       (PromptInput multi-line)
  stream      (StreamingCard)
  safety      — reserved margin

Skipped this pass: PlanCard anchor, plan-card zone, status rows.
Those don't trigger the lamyc bug and can plug into the same API
when their behavior is reviewed.

* fix(viewport-budget): break infinite useEffect loop in useReserveRows

The hook had `ctx` in its effect deps, but the provider's context value
identity changes after every dispatch (the memo depends on `allocations`
which recomputes whenever `claims` changes). So claim → state update →
new ctx identity → effect re-fires (release + claim) → infinite loop.

Depend on `dispatch` (stable from useReducer) and the spec primitives
instead. Effect now fires once on mount, again only when min/max
actually change, and once on unmount.
2026-05-02 04:35:31 -07:00
YHH 08c14ad828 feat(prompt): Home/End/Ctrl+K/Alt-word shortcuts (#123)
Long-time CLI users reach for Home/End and Ctrl+K muscle-memory keys
that were never bound. Reuses the existing startOfLine/endOfLine
helpers and the previousWordStart helper used by Ctrl+W.

Ctrl+U keeps its non-standard "clear all" behavior — see comment.
2026-05-02 04:35:16 -07:00
YHH 82a7fd8b1e release: 0.22.0 — live MCP reconnect (identity + append) + d keybind (#119) 2026-05-02 03:10:03 -07:00
YHH ae6021ea29 feat(mcp): activate d-keybind in /mcp browser; share disable helper (#118)
Final stage of #105: wire McpBrowser modal's labelled-but-stub `d`
keybind to the same `mcpDisabled` config persistence the slash
already does. Removes the "(TBD)" label from the modal footer.

- New `src/cli/ui/mcp-disable.ts` exporting `toggleMcpDisabled`,
  the readConfig+writeConfig logic that was previously inlined in
  the slash handler.
- `src/cli/ui/slash/handlers/mcp.ts` — replaces the inline
  read/write block with a single call to `toggleMcpDisabled`.
  Unknown-name validation stays in the slash since it has access
  to mcpServers + mcpSpecs to build the "Known: …" hint.
- `src/cli/ui/McpBrowser.tsx` — `d` key handler persists
  `mcpDisabled` for the selected server and closes the modal.
  No need for the unknown-name check in the modal — the user
  picked from a live list, the name is always valid.
- Footer label updated.

Refs #105.
2026-05-02 03:03:34 -07:00
YHH c7298fec4e feat(mcp): append-drift mid-session reconnect (refs #110) (#117)
Stage E2 of the C2b follow-ups: when /mcp reconnect finds the server
added new tools at the END of its tool list, register them
mid-session and addTool the prefix instead of refusing.

Drift kinds the reconnect now accepts:

- identity → free swap, ~95% cache hit (was already shipped in #115)
- append → register new tools, ~95% cache hit (the new chunks land
  in cache too, per benchmarks/spike-mcp-reconnect data)
- edit / reorder / remove → still refused with "restart Reasonix"

Touch:

- src/mcp/registry.ts — extract `registerSingleMcpTool(mcpTool, env)`
  + new `BridgeEnv` type (resolved bridge environment captured at
  first-bridge time). bridgeMcpTools' return shape gains `env` so
  reconnect can re-use the same options.
- src/cli/ui/slash/types.ts — McpServerSummary gains `bridgeEnv:
  BridgeEnv` so the append handler has everything it needs to
  register a new tool without redoing the whole bridge.
- src/cli/commands/chat.tsx — captures bridge.env onto the summary.
- src/mcp/reconnect.ts — accepts identity (always) plus append (if
  caller passes accept: ["identity", "append"]). On append, returns
  addedTools so the caller can register them. Identity is forced-
  accepted regardless of `accept` because it's free.
- src/cli/ui/mcp-append.ts (new) — `applyMcpAppend(loop, target,
  addedTools)` calls registerSingleMcpTool + prefix.addTool +
  refreshes target.report. Accepted-tools-only counting handles the
  unnamed-tool defensive case.
- src/cli/ui/mcp-reconnect-kickoff.ts — gains optional `applyAppend`
  callback. When set, opts the reconnect into ["identity",
  "append"]; when missing, behaviour is unchanged from #115.
- src/cli/ui/slash/handlers/mcp.ts + src/cli/ui/McpBrowser.tsx +
  src/cli/ui/App.tsx — both surfaces wire applyMcpAppend through.
- tests/mcp-append.test.ts (new) — 4 cases: registry registration,
  fingerprint invalidation, summary refresh, defensive skip on
  unnamed tools.

Closes most of #110. Edit / reorder / remove mid-session remain as
follow-up issues — each requires new ImmutablePrefix API
(replaceTool / removeTool) + cache-reset announcement.
2026-05-02 02:48:56 -07:00
YHH d5d6032f83 feat(mcp): activate r-keybind in /mcp browser; share kickoff helper (#116)
Refs #110.

Stage E1 of the C2b follow-ups: wire the `/mcp` browser modal's
labelled-but-stub `r` keybind to the same reconnect flow the
`/mcp reconnect <name>` slash already uses.

- New `src/cli/ui/mcp-reconnect-kickoff.ts` exporting
  `kickOffMcpReconnect(target, postInfo) → string`. Returns the
  start-line, schedules the result line via postInfo. Both the
  slash handler and the modal now route through it.
- `src/cli/ui/McpBrowser.tsx` adds an `r` key handler that calls
  the kickoff against the currently-selected server, pushes the
  start-line via `postInfo`, then closes the modal so the line is
  visible immediately.
- `src/cli/ui/App.tsx` passes `log.pushInfo` into the modal.
- Footer label updated: `[r] reconnect (Stage C)` → `[r] reconnect`
  (the `[d] disable` slot stays labelled "(TBD)" — that ties to
  the registry-mutation work still pending).
- `src/cli/ui/slash/handlers/mcp.ts` reduces to a one-line call to
  the kickoff helper, dropping the inline async block.

No behaviour change for the slash; it produces the same lifecycle
lines via the shared helper. Modal is the new surface.
2026-05-02 02:34:16 -07:00
YHH 05d1efb4c9 feat(mcp): /mcp reconnect <name> for identity drift only (#115)
C2b implementation per RFC #110. Identity-drift only — append / edit /
reorder / remove drift cases surface a clear "restart Reasonix to apply"
message instead of mutating the registry or prefix mid-session. The
graduated permissive policy from the empirical spike (#113) needs API
work on `ImmutablePrefix` (replaceTool / removeTool) before the other
drift kinds can take effect mid-session; that's a follow-up PR.

Touch:

- `src/mcp/registry.ts`: new `McpClientHost = { client: McpClient }`
  indirection on BridgeOptions. Tool closures resolve the live client
  via `host.client` at call time, so reconnect can swap the underlying
  socket without re-bridging tools.
- `src/mcp/reconnect.ts` (new): `reconnectMcpServer({ host, spec,
  beforeTools })` re-handshakes a fresh transport, classifies drift,
  swaps `host.client` only on identity, closes the new client cleanly
  on refusal so the old one stays untouched.
- `src/cli/ui/slash/handlers/mcp.ts`: third subcommand `reconnect <name>`,
  fires async, reports via `ctx.postInfo` with the lifecycle
  `↻ reconnect…` / `✓ connected` / `✖ failed` formatter.
- `src/cli/ui/mcp-lifecycle.ts`: `reconnect` state added to the union.
- `src/cli/ui/slash/types.ts`: `McpServerSummary.client?` replaced by
  `host: McpClientHost`. `McpClient` import dropped (now via host).
- `src/cli/ui/mcp-browse.ts`: `/resource` and `/prompt` read through
  `server.host.client`. Disconnected-server warnings dropped — host
  always carries a client now.
- `src/cli/commands/chat.tsx`: builds the host at bridge time, stores
  it on the summary.

Tests:

- `tests/mcp-reconnect.test.ts`: 2 cases for spec_parse early returns.
- `tests/mcp-integration.test.ts`: live test that bridge + host
  indirection routes a swapped client correctly through registry.dispatch.
- `tests/slash.test.ts`: 3 cases for the slash dispatch (lifecycle line
  emission, unknown-name rejection with hint, no-arg usage).
- `tests/mcp-browse.test.ts`: server() helper updated to accept `client`
  and wrap in host shape.

Closes part of #110 (identity case only). Append/edit/reorder/remove
mid-session handling deferred — needs ImmutablePrefix surgery.
2026-05-02 02:22:26 -07:00
YHH 1920d90717 feat(mcp): tool-list drift classifier (groundwork for #110 C2b) (#114)
Pure function `classifyToolListDrift(before, after) → DriftReport`
encoding the cache-cost taxonomy validated by the live spike (#113):

- `identity`  — same names, same order, same content → free
- `append`    — every before-tool unchanged, new tools at the end → trivially cheap (94.8% hit observed)
- `edit`      — same names + positions, content of ≥1 tool changed → bounded loss past the divergence point
- `reorder`   — same set, different order, OR additions not at the end → catastrophic
- `remove`    — any before-tool missing from after → catastrophic; dominates even when other tools were added

Report carries `added` / `removed` / `edited` arrays so the policy
layer (next PR) can populate the warn line precisely.

Pure function, no I/O. 12 unit tests cover the matrix including
edge cases (empty before/after, remove-with-also-added).

Refs #110.
2026-05-02 02:03:02 -07:00
YHH d811f2d545 chore(spike): live DeepSeek run for RFC #110 cache-prefix question (#113)
Two-file spike under benchmarks/spike-mcp-reconnect/:

- runner.ts — 5 chat calls against live deepseek-chat with
  controlled tool-list drifts (identity, append, mid-stream edit)
- results.md — captured run + empirical findings

The headline result overturns the RFC body's "any drift = full
cache miss" claim. DeepSeek's prefix cache works at chunk
granularity (≈128 tokens), so the cost depends on WHERE the drift
falls:

- append a tool at the end → trivial cost (94.8% hit, even better
  than the no-drift 85% baseline because the new chunk gets cached)
- edit a tool's description in the middle → loses chunks past the
  edit (84.1% hit observed)
- replacing or reordering the tool list → effectively full miss

This nudges the C2b design call away from blanket "strict default"
toward graduated permissive: silent on appends, warn on mid-stream
edits, refuse on reorders / removals. `--strict` remains as an
explicit flag.

Refs #110.
2026-05-02 01:53:41 -07:00
YHH b9a97bb4b1 test(mcp): pin RFC #110's cache-prefix claims with 6 unit tests (#112)
The reconnect RFC's central claim — "re-bridging tools mid-session
breaks the prompt prefix when the new tool surface differs from the
old" — was so far an architecture-derived assertion, not an empirical
result. Cheap to lock down at the prefix-fingerprint layer.

`tests/mcp-reconnect-prefix-invariant.test.ts` covers six cases the
RFC directly references:

- identical tool list → fingerprint unchanged (the safe-reconnect case)
- one tool added → fingerprint changes
- one tool removed → fingerprint changes
- description-only edit on an existing tool → fingerprint changes
- parameter-schema edit → fingerprint changes
- same tools reordered → fingerprint changes (array order is part of
  the prefix bytes via JSON.stringify)

This gives RFC #110 a concrete reference to point at when weighing the
strict / permissive / `--force` approaches: any drift past the
"identical bytes" line is a guaranteed cache miss, full stop.

Refs #110.
2026-05-02 01:41:35 -07:00
YHH 5124024248 release: 0.21.0 — MCP CLI surfaces aligned with design doc (#111) 2026-05-02 01:31:56 -07:00
YHH b3a0fcd286 feat(mcp): p95 latency tracker + slow-server warn toast (#109)
Stage C2a of #105.

Per-server ring-buffered latency tracker; emits a one-line warn
toast (design §32) on p95 threshold cross. Idempotent within a
"slow window" — fires once when p95 transitions over the
threshold, again only after p95 dips below and crosses back.

Touch:

- New `src/mcp/latency.ts` — `LatencyTracker` with size-5 ring
  buffer + p95 helper. Tracks `wasOverThreshold` boolean so
  emission is gated on the transition, not on every over-cap call.
- `src/mcp/registry.ts` — `BridgeOptions` gains `serverName`,
  `slowThresholdMs`, `onSlow`. The bridged tool's `fn` records
  per-call elapsed time when a tracker is configured. Default
  threshold 4000ms.
- New `src/cli/ui/mcp-toast.ts` exporting `formatMcpSlowToast`
  that prints `⚠ MCP `<name>` slow · 8.4s p95 over the last 5
  calls` per design §32.
- `src/cli/commands/chat.tsx` + `src/cli/commands/run.ts` — wire
  `serverName` and `onSlow` callback so the warn line lands on
  stderr.
- `tests/mcp-latency.test.ts` — 9 cases covering buffer fill
  threshold, single-fire on cross, re-fire after dip-and-cross,
  default threshold, p95 math edges, and toast formatting.

Stage C2b (`/mcp reconnect <name>` with cache-prefix invariant
handling) is split out into a separate RFC — the live tool-list
swap raises a non-trivial design question (what if the
reconnected server's tool surface changed? cache prefix breaks).

Closes part of #105.
2026-05-02 00:22:45 -07:00
YHH 456cc3438b feat(mcp): /mcp disable / enable + disabled lifecycle event (#108)
Stage C1 of #105 (Stage C split into C1 = persistence side here, C2
= live reconnect + slow toast next).

Add a config-persisted disable list and the corresponding `○ disabled`
lifecycle line so users can keep a flaky server in their config but
skip it on launch.

Touch:

- `src/config.ts` — new `mcpDisabled?: string[]` on ReasonixConfig.
  Backwards-compatible: existing configs ignore it.
- `src/cli/ui/mcp-lifecycle.ts` — `disabled` state added to the
  formatter, prints `○ disabled     via /mcp disable <name>`.
- `src/cli/commands/chat.tsx` + `src/cli/commands/run.ts` — read the
  disabled set on startup; skip the bridge for matching named
  servers and emit the `disabled` lifecycle line in their place.
  Anonymous servers (no `name=`) are not toggleable, by design.
- `src/cli/ui/slash/handlers/mcp.ts` — first-arg dispatch:
  - `disable <name>` writes the name into `mcpDisabled`, idempotent
  - `enable <name>` removes from the array; deletes the field
    entirely when the last entry clears (keeps configs tidy)
  - `text` / no-arg paths unchanged
  Unknown names produce a "Known: …" hint listing the valid set
  (joined from live mcpServers labels + parsed config specs).
- `tests/mcp-lifecycle.test.ts` — disabled-state snapshot
- `tests/slash.test.ts` — six cases: persistence, idempotent
  disable, enable that empties the array, enable that clears the
  field, unknown-name rejection, missing-arg usage line. All
  isolated through `HOME=tmp` per the existing pattern.

Stage C2 (next PR): `/mcp reconnect <name>` (live teardown +
re-handshake), p95 latency tracker, slow-server warn toast.

Closes part of #105.
2026-05-02 00:13:40 -07:00
YHH 4d021dfd39 feat(mcp): /mcp opens an interactive browser modal (#107)
Stage B of #105.

Replace the `/mcp` text-dump with a keyboard-driven modal matching
`docs/design/agent-tui-terminal.html` §24. The text-dump path is kept
as `/mcp text` for non-TTY / replay contexts.

Modal shape per design:

  ◈ MCP browser  ·  ~/.reasonix/config.json  ·  4 servers

  ▸  notion          ● healthy · 142ms      12 tools · 8 resources · 0 prompts
                     tools/list  tools/call  resources/list  prompts/list

     linear          ◌ slow · 4.2s        7 tools · 3 resources · 0 prompts

     ...

  ↑↓ pick · [r] reconnect (Stage C) · [d] disable (Stage C) · esc quit

Touch:

- New `src/cli/ui/McpBrowser.tsx` — the modal component, manual row
  rendering (not Select.tsx) so we can put the per-row health badge
  in the right color and show a second-row capability list under
  the active server.
- `src/cli/ui/slash/types.ts` — add `openMcpBrowser?: boolean` to
  the SlashResult union, mirroring `openSessionsPicker`.
- `src/cli/ui/slash/handlers/mcp.ts` — return `{ openMcpBrowser: true }`
  in the rich-data path; `/mcp text` keeps the printed-card output.
- `src/cli/ui/App.tsx` — `pendingMcpBrowser` state, modal slot in the
  render tree, gates added to the eight conditional chains that
  already suppress prompt input while a modal is open.
- `tests/slash.test.ts` — split the existing `/mcp` test into one
  case asserting the modal flag fires and one asserting `/mcp text`
  still prints the card view.

Stage C will activate the `r` and `d` keybinds (currently labelled
"Stage C" in the footer).

Closes part of #105.
2026-05-02 00:05:30 -07:00
YHH 5e0cc49df5 release: 0.20.0 — drop Node 20, MCP fixes, README overhaul (#104) (#106) 2026-05-01 23:56:33 -07:00
YHH 96eeea23a0 release: 0.20.0 — drop Node 20, MCP fixes, README overhaul (#104) 2026-05-01 23:35:45 -07:00
YHH 7d88eb7591 feat(readme): visual polish — hero terminal · stats · feature grid (#102)
* feat(readme): hero terminal SVG matches design-doc aesthetic

Replace the plaintext code-fence demo of `reasonix code` with a
self-contained SVG that mirrors the design-doc terminal mockup
(`design/agent-tui-terminal.html`) and the website palette: dark
chrome, traffic-light dots, JetBrains Mono, ANSI-style color
roles (cyan prompt, purple `assistant`, amber path, coral SEARCH,
green REPLACE).

Bilingual: a separate zh-CN variant carries the Chinese user
message and the localized pending-edit footer.

* fix(readme): hero terminal shows unified diff, not raw SEARCH/REPLACE

The previous SVG painted the model's raw `<<<<<<< SEARCH` / `=======` /
`>>>>>>> REPLACE` markers, but those are an internal protocol — the TUI
actually renders pending edits via `formatPendingPreview` from
`src/cli/ui/edit-history.ts`, which produces a unified diff with `-`/`+`
prefixed lines and a `path  (-N +M lines)` file header.

Match that format faithfully; shrink the canvas to 880x360 since the
diff is more compact than the marker block was.

* docs(readme): tighten prose, replace feature wall with SVG grid

Two new design-token SVGs continue the hero-terminal aesthetic so the
README has consistent visual rhythm instead of a wall of `### heading`
subsections.

- Add `docs/hero-stats.svg` (+ zh): three gradient numbers (94% live
  cache hit · ~30× cheaper / task · MIT) below the hero tagline.
- Add `docs/feature-grid.svg` (+ zh): 6-card 3x2 grid replacing the
  eight `###` subsections that ran 25+ lines of wall text.

Prose cleanup:
- Drop the `--system-append` subsection; it's documented in
  `reasonix code --help`, doesn't belong in the hero quickstart.
- Drop the "Edits stay in memory..." line redundant with the
  terminal SVG that already shows the /apply gate.
- Drop the stale "1665 tests" count from the contributor snippet —
  the number drifts; "tests" alone is enough.

Net: 175 → 132 lines per README, four anchored visual blocks
(logo · stats · terminal · features).

* docs: publish design mockups under docs/design/ so links render

The README points at the dashboard and TUI design mockups, but the
links resolved to repo paths — GitHub serves `.html` files in repos
as syntax-highlighted source, never as a rendered page. Anyone
clicking through hit a wall of HTML instead of the intended preview.

Move the two mockups into `docs/design/` (already published via
GitHub Pages) and switch the README links to absolute
`https://esengine.github.io/reasonix/design/...` URLs. Now click-
throughs land on the rendered mockup, and the links work the same
on github.com, on the npm registry, and anywhere else the README
gets reposted.

`dashboard/app.css`'s "anchored to ..." comment updated to track
the new location.

* docs(readme): trim comparison table to differentiating rows only

Drop the 7 universally-yes rows (plan mode, edit review, MCP, skills,
hooks, sandbox, surface) and keep the 6 where Reasonix is actually
different from peers: backend, cost, license, cache-hit %, dashboard,
sessions.

Add a one-line note pointing at the feature grid for the rest, so the
information isn't lost — just reordered into the section that's
already explaining each feature in detail.

* docs(readme): unify hero block to a single centered column

Designer-pass cleanup. The hero used to fracture between centered
(logo, tagline, lang) and left-aligned (H1, badges, description),
making the eye jump as it scanned downward.

- Drop the redundant `# Reasonix` H1 — the wordmark in `logo.svg`
  already says it; the H1 was duplication, not hierarchy. Astro,
  Bun, Tailwind and similar polished READMEs do logo OR title,
  not both.
- Drop the `<em>` tagline; the description paragraph below
  conveyed 90% the same info more concretely. Pick one, not two.
- Center the badges and the description paragraph inside
  `<p align="center">` so logo → langs → badges → description →
  stats SVG all share one vertical axis.
- Quick start: drop the "First run: paste a key…" paragraph
  (the wizard prompts the user when they run it; pre-explaining
  was reading-overhead). Compact note inline as a `# comment`
  on the `npx reasonix code` line, plus an API-key link in the
  trailing requirements line.
- Contributing: drop the trailing `git clone … npm install …`
  snippet that duplicated CONTRIBUTING.md's setup section. The
  link above already says "read CONTRIBUTING.md" — trust it.

Net: 132 → 115 lines per README. Hero feels like one block.

* docs: drop "free credit on signup" — DeepSeek no longer offers it

Three places referenced free signup credit:

- README.md / README.zh-CN.md "Non-goals" bullet — rephrased as
  "needs a paid DeepSeek API key" so the air-gapped redirect to
  Aider+Ollama / Continue still makes sense
- docs/index.html + docs/i18n.js Quick start step 1 — "Sign up at
  ... and create a key" / "到 ... 注册并创建 Key"
- src/cli/ui/Setup.tsx + src/cli/ui/Wizard.tsx — drop "free credit
  on signup" hints from the key-paste prompt

* docs: contributor avatars, more badges, COC + SECURITY

README polish bundle:

- Add 2 badges: GitHub stars + Discussions count. Brings the row
  from 5 → 7 (still under the badge-spam threshold).
- Add a contrib.rocks contributor-avatar grid at the bottom of the
  Contributing section. Auto-updates from `git log` — no bot, no
  config file. Single `<img>`, fresh forever.
- Reference Code of Conduct + SECURITY.md from the Contributing
  blurb so first-time PR authors land on the right pages.

Project hygiene files:

- `CODE_OF_CONDUCT.md` — Contributor Covenant 2.1, fetched
  verbatim from the canonical EthicalSource repo, with the
  `[INSERT CONTACT METHOD]` placeholder filled in. GitHub's
  Insights → Community will now show the green check, and the
  repo nameplate gains a "Code of Conduct" link.
- `SECURITY.md` — private-disclosure policy, scope (in: package,
  dashboard, sandbox; out: third-party MCP servers, upstream
  Node, the user's own key handling), supported-versions note,
  and hardening reminders for users.
- `CONTRIBUTING.md` "Reporting security issues" reduced to a
  one-line pointer at SECURITY.md, eliminating the duplicate
  email address.

* docs: move README image assets into docs/assets/

The `docs/` directory was a mixed bag: GitHub Pages site source
(index.html, styles.css, i18n.js, term-anim.js, logo.svg, favicon.svg),
documentation pages (ARCHITECTURE.md), README image assets (six
hero / feature-grid / stats SVGs at root), and design mockups
(design/). Six SVGs cluttering the listing made it hard to tell
website-source from README-only-fixtures at a glance.

Move the README-only SVGs into `docs/assets/`:

- hero-stats.svg + .zh-CN.svg
- hero-terminal.svg + .zh-CN.svg
- feature-grid.svg + .zh-CN.svg

Update all 6 image references in README.md and README.zh-CN.md.
`logo.svg` stays at `docs/` root because it's used by both the
website (`docs/index.html` includes it) and the README — it's
genuinely a top-level brand asset, not an asset-folder fixture.
2026-05-01 23:16:25 -07:00
YHH 3c68fc5152 docs(readme): replace hardcoded good-first-issue list with label link (#99)
The hardcoded list (#15-#18) drifted: #18 closed but stayed listed, and
every closed ticket required a manual README edit. Point at the label
filter URL instead — always fresh, zero maintenance.

The line that already existed at the bottom ("Browse all good first
issue") was the better signal anyway; just promoted it.
2026-05-01 22:06:42 -07:00
48626d2df1 fix(mcp): allow hyphens in MCP spec name prefix regex (#96)
* fix(mcp): allow hyphens in MCP spec name prefix regex

The NAME_PREFIX regex excluded hyphens, so kebab-case server names like sage-wiki failed the prefix match. The entire string (including the =) was treated as a raw command path. One character added to the character class.

* test(mcp): cover kebab-case names in parseMcpSpec

---------

Co-authored-by: Charles H <[email protected]>
Co-authored-by: esengine <[email protected]>
2026-05-01 22:02:53 -07:00
YHH df258e9fc1 chore(ci): drop Node 20 from CI matrix; bump engines to >=22 (#98)
Node 20 reached end-of-life on 2026-04-30. The CI matrix kept it green
for users on the prior LTS; with EOL passed, the verification cost is
no longer paying back.

- engines.node: ">=20.10" -> ">=22"
- CI matrix: ["20", "22"] -> ["22"]
- tsup target: node20 -> node22
- README / README.zh-CN / CONTRIBUTING / REASONIX / docs: Node >= 22
2026-05-01 22:01:28 -07:00
ctharveyandCharles H 7b8e59f233 fix(code): bridge config.mcp servers in code mode (#91)
reasonix code now reads the mcp array from ~/.reasonix/config.json and passes it to chatCommand, which parses each spec and bridges the MCP server tools into the session. Previously only reasonix chat read config.mcp — reasonix code silently ignored it.

Co-authored-by: Charles H <[email protected]>
2026-05-01 21:47:37 -07:00
YHH 591c4e7f14 docs(contrib): drop CHANGELOG-per-PR rule (#94)
Three coupled changes:
  - CONTRIBUTING.md: replace 'update CHANGELOG.md under [Unreleased]'
    with 'don't touch CHANGELOG.md'. Releasing section now says the
    maintainer writes the notes from git log at release time.
  - PULL_REQUEST_TEMPLATE.md: replace the 'CHANGELOG updated' checkbox
    with the inverse — 'no edits to CHANGELOG.md'.
  - CHANGELOG.md: drop the lingering [Unreleased] section. The
    --system-append feature it described will land in the next
    versioned section, written by the maintainer.

Why: PR-time CHANGELOG entries had two failure modes — they piled up
in [Unreleased] when releases didn't roll them forward, and they
created soft conflicts between concurrent PRs. PR descriptions are
the authoritative record while work is in flight; release notes are
better written once with full context than in pieces during review.
2026-05-01 21:19:41 -07:00
YHH 7d5efb263f chore(quality): public API surface snapshot test (#93)
Locks the npm package's exported names to a recorded snapshot. When src/index.ts
gains or loses an export, this test fails with a clean diff and the maintainer
explicitly updates PUBLIC_API in the test file. Catches accidental ABI breakage
before a release ships.

Snapshot derived from the current 263-name surface. Future intentional changes
land via the same PR that touches src/index.ts: see test failure → update
PUBLIC_API → review the diff → merge.
2026-05-01 21:09:08 -07:00
YHH fc2f81c023 chore(quality): expand comment-policy scope + architecture invariants test (#92)
The comment-policy gate previously only walked src/. Tests, benchmarks,
scripts, and dashboard/src were left to convention — which meant that
multi-paragraph module-essay headers and stale phase-narrative comments
silently accumulated. Expand the test's roots to cover every code dir,
clean the 146 violations that surfaced, and gate them at pre-push.

The new tests/architecture-invariants.test.ts promotes two properties
from spike #87 (Exp 1) into permanent regression:
  - reducer projection determinism (identical events → byte-identical
    messages, regardless of timestamp / id / counter state)
  - message-level append-only across turn boundaries (every cut is a
    strict prefix of any later cut)

These are the load-bearing properties for the v0.14 event kernel and the
forkable-sessions RFC. Encoding them as tests means any reducer / event
schema change that violates them fails CI, not a future spike.

No behavior change in src/. Comment-policy expansion + invariants test
add about 18 new test assertions; full verify is unchanged at ~23s.
2026-05-01 21:09:04 -07:00
YHH 476b801c71 chore(code): drop unicode warning prefix + empty-catch comment (#88)
Followup to #86. The ▲ prefix has no precedent in other stderr writes
(run.ts / commit.ts / index.ts use plain text), and the empty-catch
note restates what the empty body already conveys.
2026-05-01 20:23:47 -07:00
ctharveyandCharles H 762b46c355 feat(code): --system-append / --system-append-file (#86)
Add two CLI options to reasonix code that let users layer personal workflow rules on top of the default Reasonix Code system prompt without replacing or weakening it.

--system-append <prompt>       inline string appended after the base prompt
--system-append-file <path>    UTF-8 file contents appended after the base prompt

Both may be used together. Inline text appears first, then file contents. Both are placed after the .gitignore section under a # User System Append heading. File read errors surface with the OS error code and exit cleanly.

Tests cover: absent by default, inline-only, file-only, combined ordering, placement relative to .gitignore, and base prompt preservation.

Co-authored-by: Charles H <[email protected]>
2026-05-01 20:19:01 -07:00
esengine 56ec0822a8 release: 0.19.0
Headline: complete dashboard refactor + design parity, plus a /cost
estimator and a wired-up cockpit.

## Dashboard
- 4768-line `dashboard/app.js` god file → 16 typed Preact panels +
  7 lib utilities under `dashboard/src/`.
- Vendor libs bundled locally via tsup. No more esm.sh runtime fetches.
- Drop the editor surface (CodeMirror) entirely; remove 20 unused devDeps.
- Drop `@ts-nocheck` everywhere — chat panel + chat-internals are now
  strict-typed.

## New panels / panel features
- **Overview cockpit** (#64): balance · tokens·7d · cache hit · tool calls·24h
  KPIs, current-session detail block, 14-day cost spark, recent plans rail,
  tool activity feed. Server-side aggregator with 30s TTL cache.
- **Chat side rail** (#69): Active plan card with step dots + Session card
  (turns / prompt tok / cost / cache hit) + Tool budget card (when /budget
  cap is set).
- **Chat composer popovers** (#81): / (slash command picker, filters
  SLASH_COMMANDS) and @ (project file picker, walks cwd ≤depth 4, caps 50).
  Keyboard-first: ↑↓ Tab Enter Esc.
- **Hooks event matrix** + **recent runs log** from `hook.fired` events.
- **MCP** filter chips (live / unbridged) + clickable unbridged rows with
  explanation card.
- **Skills** runs·7d count from cross-session usage log subagent rows;
  built-in skills clickable with read-only description.
- **Semantic** search bar + result cards (POST /api/semantic/search) +
  2-col layout with sidebar status/config cards; chip-based excludes
  editor matching design's index-config card.
- **Sessions** detail shows the resume command (mid-session swap requires
  restart).

## Slash
- `/cost <text>` (#63): pre-turn cost estimator with worst-case + likely
  (apply session cache hit) USD breakdown.

## CSS / layout fixes
- `.app { height: 100vh }` (was 640px from mockup) — kills page-level
  scrollbar; only chat-feed scrolls now.
- Mode picker active state restored (catch-all rule was overriding).
- Custom themed scrollbar instead of OS default.

Closes #28, #64, #69, #78, #81, #82.
2026-05-01 09:23:39 -07:00
YHH 628edd2b7e fix(dashboard): semantic excludes card matches design index-config (#85)
The Excludes section had its own ad-hoc layout with a toggle expander,
"excludes-card" / "excludes-grid" / "excludes-options" / "excludes-actions"
classes — none of which were in the design.

Restyled to match design §12's `index config` card:
- `.card` + `.card-h` with title and reset link in the header
- `.form-row` per category (lbl above, chip row below)
- Optional sub-label (e.g. "· glob") rendered dim
- `.checkbox-row` with `.box.on ✓` instead of native checkbox for gitignore
- `.input.mono` for max bytes; help text shows MiB equivalent
- `.btn.ghost` Preview + `.btn.primary` Save side-by-side, flex:1 each

Always visible — drops the toggle so the config is discoverable.
ChipExcludesField → ChipFormRow with the new design markup.
2026-05-01 09:21:43 -07:00
YHH 933e5b4c21 feat(dashboard): semantic 2-col layout + index meta fields (#82) (#84)
Server: /api/semantic GET now returns index meta when an index
exists — chunks, files (distinct paths), dim, sizeBytes, lastBuiltMs,
model. Reads index.meta.json + index.jsonl from .reasonix/semantic/.

UI: restructured the panel to design §12's 2-col layout:
- Left: chips + search section + ollama setup cards (when not ready) + job view
- Right (280px sidebar): "index status" card with the new rail-kv stack
  + Re-index/Rebuild/Stop buttons inline; "ollama" card with binary/daemon/model
  pills; existing "Excludes" card

Setup checklist (install / daemon / model pull) restyled as proper
.card blocks with .card-h headers instead of ad-hoc sections.

Closes #82.
2026-05-01 08:55:15 -07:00
YHH 4fe1faed27 feat(dashboard): chat composer popovers — slash + @ mention (#81) (#83)
Adds the floating popover from design §4 above the chat composer.

- **Slash popover** — fires when input matches `^/(\w*)$`. Filters
  the SLASH_COMMANDS catalog (fetched once via new GET /api/slash)
  by prefix, shows name + summary per row. Tab inserts; Enter
  inserts and submits. ↑/↓ navigate, Esc closes.

- **@ mention popover** — fires when input ends with `(?:^|\s)@(\S*)$`
  in attached mode. New POST /api/files walks cwd up to depth 4,
  caps at 50 results, skips node_modules / .git / common binary
  extensions. Tab inserts the relative path; Esc closes.

The popover degrades to no-op when slash commands fail to load or
in standalone mode (no cwd).

Closes #81.
2026-05-01 08:50:11 -07:00
YHH f463b798a5 fix(dashboard): skills create-row clipping + session resume hint (#80)
- Skills: + create button could be pushed off-screen because the new-name
  input had default min-width:auto. Added min-width:0 + flex-wrap so the
  controls stack at narrow widths instead of clipping.
- Sessions: detail header only had a "back" button — no way to actually
  resume a session from the dashboard. Added a copy-friendly card that
  shows the `reasonix chat --session <name>` command, matching how /resume
  surfaces it in the TUI (mid-session swap needs a restart).
2026-05-01 08:38:54 -07:00
YHH d9f147d988 feat(dashboard): semantic search bar + result cards (#78) (#79)
Adds the search functionality from design §12. Renders a search
input above the existing index admin sections (only when an index
is built). On Enter, POST /api/semantic/search → result cards with
path, line range, cosine score, snippet (capped at 8 lines).

Server-side: new POST /api/semantic/search endpoint reuses the
existing querySemantic() entry. Validates topK (1..16) + minScore
(0..1). Returns 503 in standalone mode, 404 when no index exists.

Closes #78.
2026-05-01 08:31:22 -07:00
KuaaMU adae0670d0 test: add unit tests for clipboard.ts (#62)
Closes #18
2026-05-01 08:29:36 -07:00
YHH 702ef26b97 fix(dashboard): clickable skill / MCP rows + unbridged UX (#77)
User-reported bugs:
- Builtin skills (explore / research) were marked cursor:default with
  no click handler — clicking did nothing. Now opens a read-only
  detail card with description + a hint that custom skills override.
- MCP unbridged config rows were also non-clickable, and the row
  preview showed the raw spec ("filesystem=npx -y @modelcontextprotocol/...")
  with no explanation. Now: rows show parsed `<label>` + `<command>`,
  click opens an explanation card noting that MCP attaches on
  reasonix-code start (the dashboard alone can't spawn the child).
2026-05-01 08:26:01 -07:00
YHH 0f14015dad feat(dashboard): semantic chip excludes editor (Stage 6 of #69) (#76)
Replaces the textarea-per-category excludes UI with the design's
chip editor — each entry renders as .chip-f with × delete, a
dashed-border input handles + add (Enter or blur to commit, dedupes
existing entries).

Drops the newline-serialize / line-split conversion in favor of
native arrays end-to-end (toDraft / fromDraft now identity-pass).

Closes #69.
2026-05-01 08:14:51 -07:00
YHH 95ba206856 feat(dashboard): skills usage metrics — runs · 7d (Stage 4 of #69) (#75)
Adds the "runs" column from the design's inventories pattern. Counts
subagent rows in the cross-session usage log filtered to last 7 days,
keys by `subagent.skillName`. Surfaces as `runs7d: number` per skill
on /api/skills, rendered in the skill list row meta only when > 0.

Closes part of #69.
2026-05-01 08:10:17 -07:00
YHH 6f22c95ff0 feat(dashboard): hooks recent runs log (Stage 5 of #69) (#74)
Surfaces the design's "Recent runs" section at the bottom of the
Hooks panel. Reads `hook.fired` events from up to 8 most-recent
session events.jsonl files, returns the 12 newest with phase /
outcome / hook name / when. Renders as a compact table with
ok/warn/err pill per row.

Refactored `recentEventFiles` out of cockpit-events.ts into
`adapters/event-source-jsonl.ts` for shared use across cockpit
+ hooks aggregators.

Closes part of #69.
2026-05-01 08:06:29 -07:00
YHH 6dad145d29 feat(dashboard): MCP filter chips (Stage 3 of #69) (#73)
Adds all / live / unbridged filter chips to the MCP panel header.
Live = bridged into the session, unbridged = in config but not yet
loaded. The chips drive a single setState filter that toggles which
groups render in the list.

(Errored / uptime tracking from the design left for later — needs
new server-side state.)

Closes part of #69.
2026-05-01 08:01:48 -07:00
YHH ac90a40fb9 feat(dashboard): chat active plan rail card (Stage 2b of #69) (#72)
Adds the third rail card from design §4 — Active plan. Reads
cockpit.recentPlans (already shipping on /api/overview), picks the
most recent plan with status === 'active', renders a step-dot
header (1 → N) plus title + progress count. Hides when no plan
is active.

Closes part of #69.
2026-05-01 07:59:13 -07:00
YHH ac3c1c51d8 feat(dashboard): chat side rail — Session + Tool budget (Stage 2a of #69) (#71)
* feat(dashboard): chat side rail — Session + Tool budget (Stage 2a of #69)

Wraps the chat composer + feed in a `.chat-body` grid with a 280px
right column for the design's chat-rail card stack. Two cards in v1:

- **Session** — turns, last-turn prompt tokens, total cost, cache
  hit ratio progress bar (tinted ok / warn by threshold). Reads
  from the existing `stats` poll.
- **Tool budget** — only renders when `loop.budgetUsd` is set;
  shows spent / cap as a single progress bar that turns warn at
  80%, err at 100%. Surfaced `budgetUsd` on `/api/overview`.

Active plan card + slash command popover follow in 2b.

Closes part of #69.

* chore: drop unrelated RFC #25 spike draft accidentally committed
2026-05-01 07:55:52 -07:00
YHH 00d5eab3e7 fix(dashboard): page-level scroll + chat input clipping (Stage 1 of #69) (#70)
`.app { height: 640px }` was a leftover from the design mockup's
fixed-height display box. At runtime it caused a page-level
scrollbar on viewports below 640px and dead space above. Switch
to `100vh` so the dashboard fills the viewport.

`.chat-shell` height was wrong by the chrome chrome — it was
`100vh - 56px` instead of subtracting the actual top (44) +
status (26) + body padding (24×2). Pin the math precisely so the
composer stays in view and only `.chat-feed` scrolls.

Add `min-height: 0` to `.chat-feed` for the flex shrink-to-zero
gotcha — without it `flex: 1` can't actually shrink to allow
internal overflow:auto to take effect.
2026-05-01 07:47:24 -07:00
YHH dc6067f5c3 feat(dashboard): cockpit rows 1-3 (Stage 2 of #64) (#68)
Renders the design §5 cockpit grid using the server-side fields
shipped in #65 / #67:

- Row 1 (KPIs): balance / tokens·7d / cache hit / tool calls·24h
- Row 2 (wide pair): current session detail + 14-day cost spark (inline SVG polyline)
- Row 3 (wide pair): recent plans rail + tool activity feed
- Row 4 (KPIs, kept): tools loaded / mcp servers / edit mode / version

Each widget degrades gracefully when its source field is null
(standalone mode, no usage history, no events). Adds fmtCompactNum
to format.ts for the KPI value formatting (994k, 1.5M).

Closes #64.
2026-05-01 07:37:05 -07:00
YHH 61efab31a6 feat(server): events.jsonl cockpit fields (Stage 1B of #64) (#67)
Adds the events-derived half of the design §5 cockpit:
toolCalls·24h with prior-window delta, recentPlans (4 most recent
with completion ratio + done/active status), toolActivity (6 most
recent tool calls with ok/warn/err level).

Reads up to 8 most-recently-modified `*.events.jsonl` files from
the sessions dir, skips files whose mtime is older than 30 days.
Plugs into the existing 30s TTL cache shared with Stage 1A.

Adds `sessionsDir?` to DashboardContext so tests can isolate from
the user's real `~/.reasonix/sessions`.

Closes part of #64.
2026-05-01 07:31:10 -07:00
YHH 3d76096bd4 fix(dashboard): mode picker active state + custom scrollbar (#66)
The catch-all `button:not(.primary):not(.danger):not(.btn)` rule had
specificity (0,3,1) — higher than `.mode-btn.active` (0,2,0) — so
the active sky-blue background was getting overridden by the generic
fallback's bg-elev-2. Result: every mode button looked identical
regardless of which was selected. Excluded the panel-specific button
classes from the catch-all instead of bumping selectors everywhere.

Also added a thin themed scrollbar so dark-mode panels don't fall
back to the default OS chrome.
2026-05-01 07:23:05 -07:00
YHH a7874a6689 feat(server): cockpit aggregator on /api/overview (Stage 1A of #64) (#65)
Adds the usage-log derived half of the design §5 cockpit:
balance, tokens·7d (with prior-week deltaPct), cache hit·7d (deltaPp),
14-day cost sparkline, current-session detail. Hot fields refresh
per-poll; warm (disk-read) fields are 30s-cached behind a TTL keyed
on usageLogPath so the 2.5s overview poll doesn't burn disk I/O.

Stage 1B (events.jsonl-derived: toolCalls·24h, recentPlans, toolActivity)
lands in a follow-up. Stage 2 wires the UI rows.

Closes part of #64.
2026-05-01 07:15:35 -07:00
YHH 733ba2fbc6 feat(slash): /cost <text> — pre-turn cost estimate (#63)
Closes the budget loop with /budget. Bare /cost still shows the last
turn's spend. With text args, tokenize the prospective prompt
(system + tools + log + msg), price it both worst-case (full miss)
and likely (apply session's running cache-hit ratio), and surface
output cost using the session's average completion length.
2026-05-01 06:51:56 -07:00
YHH 7ec1339271 refactor(dashboard): drop @ts-nocheck on Chat panel (#61)
Type the last bulk-migration escape hatch — useState generics,
api<T> calls, modal/event/setting handler signatures, helper props.
Also strip multi-paragraph essay comments per CLAUDE.md (default
is none, one line max if WHY is non-obvious).
2026-05-01 06:00:08 -07:00
esengine f6b3458259 feat(dashboard): Hooks event matrix (script × LoopEvent grid)
Adds the design §13 event matrix above the JSON editors.
Flattens hooks from `{ event: [{ command, matcher? }] }` into per-script
rows; cells render '✓' (or matcher glob in warning color) when the
script fires for that event, '—' otherwise.

Each row is keyed by (scope, command) so the same script in project
+ global show as separate rows with a small scope tag.

Implementation:
- buildMatrix(data) helper produces the 2D grid from the nested
  hook config.
- Inline grid-template-columns string scales with the event count
  (220px label + N event columns).
- Reuses the design's .matrix / .row / .cell.on/.off styles from
  app.css.

JSON editors below remain the source of truth for editing —
matrix is read-only at this point. Click-to-edit cells (design §13
mentions it) is a follow-up.
2026-05-01 05:49:32 -07:00
esengine be702cac46 chore(dashboard): drop unused legacy panel utilities + dead MetricCard
After all 14 panels migrated to design vocabulary, the legacy
bridge styles in app.css are mostly orphan. Audit found 0
references to: panel-header / panel-title / panel-subtitle /
section-title / metric-grid / numeric / pill-warn / pill-accent /
card-title / card-value / card-hint. Plus pill-dim was still
referenced twice in chat-internals — swept to plain .pill there.

Dropped from app.css:
- 11 selectors with zero remaining references
- the renamed Legacy panel utilities banner

Kept (still used):
- .boot / .empty / .notice / .notice.err / .notice.warn (shared
  loading / error states)
- .muted / .kv-key (chat / semantic interior)
- .pill-err / .pill-active (semantic + chat)
- generic button / input / select fallbacks (so panels that
  didn't bother adding .btn render passably)

Plus deleted dashboard/src/components/metric-card.ts — Overview
and System both migrated to .kpi / .health-item directly, so the
component had zero importers.
2026-05-01 05:46:23 -07:00
esengine e6f2b03d8f refactor(dashboard): Chat panel — restore chat-specific CSS, swap header to chips
The PR #44 Foundation replaced app.css wholesale with the design
mockup's <style>. That dropped ~1100 lines of chat-specific CSS
(chat-shell / chat-feed / chat-msg / mode-picker / composer /
modal-card / toast / tool-card / markdown blocks) which Chat,
Sessions, modal popups, and toast/error overlays all depend on.

This PR:
- Restores the chat-related CSS sections from pre-foundation
  app.css as a 'Chat-panel legacy CSS' block at the tail of
  app.css (~1100 LoC).
- Remaps all old token references inside that block to design
  tokens: --primary → --c-brand, --bg-2 → --bg-elev-2, --mono →
  --font-mono, --border → --bd, etc. So the visual still aligns
  with the design palette, just keeps the working selectors.
- Migrates the Chat panel's outer header from .panel-header /
  .panel-title to a small .chips badge.

What's deferred:
- Deep restyle of chat-feed / chat-msg / composer to match the
  design's §4 Chat mockup pixel-for-pixel. Currently functional
  with the same look as before the foundation flip, just retoned.
- Drop the @ts-nocheck pragma on chat.ts (700 LoC of useState +
  SSE handler typing). Tracked as a follow-up.
2026-05-01 05:22:52 -07:00
esengine 8db20a4645 refactor(dashboard): Overview panel → design vocabulary
Adopts the design's .cockpit grid + .kpi cards. Renders 8 KPIs
across two rows using only the data /api/overview already exposes:
model / edit mode / plan mode / pending edits / tools / mcp /
session / version. Working directory gets its own .card below.

Skipped from design §5 (need new API):
- balance / 7d tokens / cache hit % / 24h tool calls (would need
  /api/usage rolled in)
- current session widget with cost + latency stats (need session
  detail endpoint)
- 14d cost trend sparkline (need usage series here)
- recent plans + tool feed widgets
2026-05-01 05:18:13 -07:00
esengine ab1d6d06fe refactor(dashboard): Hooks panel → design vocabulary
Light migration: textarea editors stay (matrix UI from design §13
needs more than the current API exposes — script-level editing,
glob filters, per-event toggles). What changes:
- Header chips show resolved count + each event name as separate chips
- Section h3 helper consistent with Settings/Semantic
- Cards wrap each scope's textarea (project / global)
- .btn / .btn.primary / .btn.ghost replace legacy primary buttons
- Info / error use .pill ok / .card.accent-err

Deferred: full event matrix UI (script × LoopEvent grid, click-to-edit
cells). Tracked as a follow-up.
2026-05-01 05:15:50 -07:00
esengine 5df4dc0a2f refactor(dashboard): Semantic panel → design vocabulary
- Pill modifiers swap to design tokens: pill-ok/warn/err/active/dim
  → pill ok / warn / err / info / pill (no modifier).
- Header becomes .chips with index status + ready/setup-needed
  badge.
- Section headers use the inline h3 sectionH3 helper (font-mono
  uppercase + spacing) consistent with Settings/System.
- Loading / error / not-attached states use .card / .card.accent-err
  / .card-h structure instead of legacy .boot/.notice/.empty.
- .muted spans replaced with inline color:var(--fg-3).
- Adds .kv-key to legacy panel utilities to keep the existing
  kv block rendering until the deeper Semantic redesign (sidebar
  index status + index-config card per design §12) lands.
2026-05-01 05:13:32 -07:00
esengine 27aec538ad refactor(dashboard): Usage panel → design vocabulary
- Header chips replace panel-header — record count + log size.
- Chart sits in a .card with .card-h title.
- Tables get .tbl class, td.num for numeric cells, td.dim for the
  bucket-label column. Headers no longer use legacy 'numeric' class
  (drops the right-align since .tbl handles it via .num).
2026-05-01 05:07:42 -07:00
esengine c540da5116 refactor(dashboard): MCP panel → design vocabulary
.sessions-grid layout. Left list shows live-bridged servers + any
config-only specs (with inline remove button) merged into one
.ssl-rows feed. Add-spec form sits in the list head. Detail view
on the right has spec card + optional instructions + tools /
resources / prompts tables.
2026-05-01 04:59:56 -07:00
esengine aa0ae8df18 refactor(dashboard): Settings panel → design vocabulary
Form-based panel — three .card sections (DeepSeek API / Defaults /
Runtime), each with rows: 110px label gutter + control + optional
right-aligned note. Uses .btn / .btn.primary plus design's input /
select tokens. Saved feedback shown as a .pill.ok.
2026-05-01 04:57:29 -07:00
esengine 6a2ff94f06 refactor(dashboard): Skills panel → design vocabulary
.sessions-grid layout. Filter input + scope chips + create form
in the left list head. Builtin items render with cursor:default
since they're read-only. Editor on the right with save / delete /
back actions.
2026-05-01 04:55:10 -07:00
esengine 22b2c7b5f2 refactor(dashboard): Memory panel → design vocabulary
Same .sessions-grid pattern: file list on the left (project REASONIX.md
+ global + project-private all merged into one .ssl-rows feed with
scope tag in meta), editor on the right with .sessions-detail-h
title bar + Save button + char count.
2026-05-01 04:52:45 -07:00
esengine e7ef628416 refactor(dashboard): Sessions panel → design vocabulary
Same .sessions-grid pattern as Plans (#48). Filter input + .ssl-row
list on the left, transcript detail on the right with .sessions-detail-h
title bar and back button.
2026-05-01 04:50:32 -07:00
esengine 6e71ea9117 refactor(dashboard): Plans panel → design vocabulary
Adopts the design's two-column .sessions-grid layout:
- Left: .sessions-list with filter input, status chips, .ssl-row
  per plan (name + status pill + preview + meta).
- Right: .sessions-detail with title bar + horizontal
  .plan-timeline / .plan-step cards (done / active / pending
  variants).

Plus a filter input that searches session id and summary.
2026-05-01 04:48:20 -07:00
esengine 4589b44945 refactor(dashboard): Permissions panel → design vocabulary
- chips show project / builtin counts
- add prefix moves into a .card with title + meta + form row
- feedback rendered as a .pill (ok / err / warn) instead of a notice
- project allowlist becomes a .tbl inside .card
- builtin section becomes a .card with grouped verb pills
- YOLO banner becomes a .card.accent-warn

No behavior change — all CRUD paths preserved.
2026-05-01 04:45:05 -07:00
esengine a1c726abd8 refactor(dashboard): System panel → design vocabulary
Replaces the metric-grid + .card paths layout with the design's
.health-grid + .health-item pattern. Each health check is a
labeled card with state pill + value + meta line. The paths card
becomes a .card with a .tbl inside.

Skipped from the design mockup (need new data sources):
- Per-MCP-server / API health checks (need /api/mcp + ping data)
- Environment table (process.platform / node version / terminal)
- log-tail event stream (would need SSE)
2026-05-01 04:33:44 -07:00
esengine bb7840a3db refactor(dashboard): Tools panel → design vocabulary; legacy panel utils
Tools panel migrated to the design's class structure:

- .chips + .chip-f filter row (just `all` for now — category filtering
  is a follow-up that needs new API fields).
- .tbl inside a .card for the tools table; pill.ok / pill.acc /
  pill (default) for the read-only / write / flat flags.
- card.accent-warn / card.accent-err for error states; .card with
  muted fg for loading / empty.

The 13 panels that haven't been migrated yet still reference
class names from the old CSS that no longer exist (.panel-header,
.empty, .notice, .pill-ok, .metric-grid, etc.). Added a `Legacy
panel utilities` block at the tail of app.css mapping them to
design tokens so those panels keep rendering passably until each
gets its own design-aligned migration. Block gets removed in the
final cleanup PR.
2026-05-01 04:31:10 -07:00
esengine 8d6435afe0 refactor(dashboard): foundation — adopt design tokens + new app shell
PR 1 of the visual catch-up. Replaces dashboard/app.css wholesale
with the design mockup's CSS (extracted verbatim from the <style>
block in design/agent-dashboard.html), and rewrites the App
component's sidebar/shell HTML to use the new class structure.

What changes visually:
- Sidebar adopts the design's three-section grouping (workspace /
  observe / configure) with the new .app-side / .side-tab markup,
  proper glyph + label slots, brand block with version badge.
- Top bar (.app-top) and status bar (.app-status) frames added —
  empty placeholders for now; will fill with breadcrumbs / live
  meters in panel migrations.
- Whole layout grids on .app (sidebar | top / body / status).

What stays broken (intentionally, per the migration plan):
- Each panel's interior still uses the old class names. Until the
  per-panel migration PRs land, panel content will look unstyled
  inside the new shell. That's the visible cost of doing this in
  reviewable chunks instead of one giant PR.

Token rename map (current → design):
  --primary, --accent, --grad-1..8 → --c-brand, --c-accent,
  --s1..6, --fg-0..4, --bg / --bg-elev / --bg-elev-2 / --bg-input
  / --bg-code / --bg-hover, --bd / --bd-strong.

Live-mode override at the tail of app.css forces .app to fill
viewport (the mockup constrains it to a 640px tile inside the
docs page).

Build / typecheck / 1682 tests still green.
2026-05-01 04:26:23 -07:00
esengine c8f86d9ec4 fix(dashboard): chat panel missing imports — MODE / TOKEN / appBus / parseToolArgs
PR #39 (Chat migration) extracted ChatPanel into panels/chat.ts
with a `@ts-nocheck` pragma. Four references the original
function had via global lexical scope in app.js were silently
missed at extraction time:

- MODE                — used in the placeholder text at line 448
- TOKEN               — used to build the SSE EventSource URL at line 126
- appBus              — used in a navigate-tab dispatch at line 545
- parseToolArgs       — used in summarizeActiveTool at line 641

@ts-nocheck masked all four ("cannot find name" errors are
suppressed by the pragma), and tests don't load the bundled
dashboard, so it shipped. The runtime symptom is the error
overlay reproduced in the user's bug report:

  ReferenceError: MODE is not defined
    at ChatPanel ...

Restored as named imports from `../lib/api.js`, `../lib/bus.js`,
and `../components/chat-internals.js`. parseToolArgs was
previously a private helper inside chat-internals.ts; promoted
to a named export so panels/chat.ts can reach it.

Verified by temporarily removing the @ts-nocheck and running
typecheck — zero "Cannot find name" errors after this fix.
1682 tests still pass.
2026-05-01 04:13:50 -07:00
esengine 249f80a94d refactor(dashboard): tighten chat-internals types, drop its @ts-nocheck
Removes `@ts-nocheck` from `dashboard/src/components/chat-internals.ts`
(541 → 692 LoC after annotations). Adds:

- ChatRole / ChatMsg / OnResolve types exported for re-use.
- Per-modal payload interfaces (ShellModalSpec, ChoiceModalSpec,
  PlanModalSpec, EditReviewSpec, WorkspaceSpec, CheckpointSpec,
  RevisionSpec, plus ChoiceOption / RevisionStep) — every modal's
  props now have proper shape.
- DiffEntry / DiffPair for the LCS diff helpers; lineDiff and
  pairDiffRows now strict-typed end to end (noUncheckedIndexedAccess
  satisfied without `any`).
- ToolCard's `args` narrows from `Record<string, unknown> | null`
  via runtime `typeof` guards; the few cross-cuts where TS can't
  follow the narrowing use `as string` casts on already-validated
  fields.

`panels/chat.ts` keeps its `@ts-nocheck` for now — ChatPanel is
700+ LoC of interleaved useState / SSE handlers / refs, type
tightening tracked as a follow-up in #28. Annotated the pragma
with a one-liner so readers know it's intentional and where it's
tracked.

Build / typecheck / 1682 tests still green.
2026-05-01 04:08:57 -07:00
esengine 56deed139f chore(deps): drop 20 unused @codemirror/* devDependencies
Stage 2 (#31) removed the dashboard's editor surface — the
CodeMirror integration that was its only consumer. The 20
@codemirror/* packages have been dead weight in package-lock
since then.

Removed:
  @codemirror/autocomplete, commands, language, search, state,
  theme-one-dark, view, plus 13 lang-* grammars.

Build / typecheck / 1682 tests still green.
2026-05-01 04:01:11 -07:00
esengine 8cb0f47555 refactor(dashboard): bundle vendor libs locally, drop esm.sh runtime fetches
Until now the dashboard's runtime imports pointed at esm.sh URLs
(preact, htm, marked, highlight.js, uplot). Tsup kept them
external so the browser fetched them on every cold load. Three
real risks:

- esm.sh outage / route change → dashboard breaks.
- CSP-locked environments → dashboard can't load at all.
- First-paint latency on flaky networks.

Bundle everything locally instead. tsup already exists; this is
just removing the external escape hatch.

Changes:

- All `https://esm.sh/<pkg>@<ver>` imports across `dashboard/`
  (19 files, .ts/.tsx/.js) become bare specifiers (`preact`,
  `preact/hooks`, `htm`, `marked`, `highlight.js/lib/common`,
  `uplot`).
- `dashboard/src/types.d.ts` deleted — the URL module shims it
  contained are no longer needed; TS resolves bare specifiers
  against the npm packages directly.
- tsup config: drop `external: [/^https:\/\//]`, set
  `noExternal: [/.*/]` and `splitting: false`. Result is a
  single self-contained `dashboard/dist/app.js` (696 KB —
  was 123 KB at runtime + ~3 MB live-fetched from esm.sh).
- `dashboard/index.html` references local `/assets/vendor-uplot.css`
  and `/assets/vendor-hljs.css` (was esm.sh URLs).
- `scripts/copy-dashboard-vendor-css.mjs` (new) copies those two
  CSS files from `node_modules/{uplot,highlight.js}/...` into
  `dashboard/dist/` after each build.
- `package.json` `build` chains the copy step.
- `src/server/assets.ts` adds a vendor-CSS branch so the asset
  server can serve `/assets/vendor-{hljs,uplot}.css` from
  `dashboard/dist/`.
- `uplot` added to devDependencies.

Bundle output verified: zero `esm.sh` references in
`dashboard/dist/app.js`. 1682 tests pass.
2026-05-01 03:56:07 -07:00
esengine cc2b2ef520 refactor(dashboard): migrate Chat + Sessions + chat internals — app.js shrinks 1562 → 125 LoC
Stage 4 PR 4.6 from #28. The largest single migration: ChatPanel +
SessionsPanel + all 7 modals + ToolCard + ChatMessage + diff helpers
move out of app.js into typed modules.

- components/chat-internals.ts (541 LoC) — ROLE_GLYPH, ToolCard,
  ChatMessage, ModalCard, 7 modal components (ShellModal,
  ChoiceModal, PlanModal, EditReviewModal, WorkspaceModal,
  CheckpointModal, RevisionModal), plus lineDiff/pairDiffRows
  helpers used by EditReviewModal. Carries `// @ts-nocheck` for
  bulk migration; type tightening is a follow-up.
- panels/chat.ts (784 LoC) — ChatPanel + summarizeActiveTool +
  InFlightRow + ChatStatusBar. Same @ts-nocheck rationale.
- panels/sessions.ts (128 LoC) — SessionsPanel; depends on
  ChatMessage from chat-internals. Properly typed.

Bug fix: ROLE_GLYPH was accidentally dropped during PR 4.1 (small
panels) when the strip cut its definition along with the chat
banner comment. ChatMessage would have crashed at runtime with
ReferenceError on any chat / sessions render. Tests didn't catch
it because no test loads the bundled dashboard. Restored in
chat-internals.ts.

Cleanup: dashboard/app.js trimmed to a 125-line shell — imports +
TABS array + the App component (sidebar + tab routing + error
boundary + toast stack). The @ts-nocheck pragmas in chat-related
files are explicitly tagged "tighten in follow-up".

Bundle: 122 → 123 KB (ROLE_GLYPH restoration). 1682 tests pass.
2026-05-01 03:47:10 -07:00
esengine 911e841084 refactor(dashboard): migrate Semantic panel + helpers
Stage 4 PR 4.5 from #28. Largest single-panel migration so far — SemanticPanel + SemanticExcludesCard + ExcludesPreview + ExcludesField + SemanticJobView + SkipBucketsView + toDraft/fromDraft helpers all move to panels/semantic.ts (~530 LoC). dashboard/app.js drops the entire Semantic block.
2026-05-01 03:40:12 -07:00
esengine 82a1d2daaa refactor(dashboard): migrate System panel
Stage 4 PR 4.4 from #28. Tiny panel — health metric grid + paths card — moves to panels/system.ts (~62 LoC).
2026-05-01 03:35:41 -07:00
esengine 592356820e refactor(dashboard): migrate Usage panel + uPlot loader
Stage 4 PR 4.3 from #28. Usage panel pulls out with its uPlot
chart loader and the chart subcomponent.

- panels/usage.ts (231 LoC) — UsagePanel (renamed from
  UsageWithChart), UsageChart subcomponent, loadUPlot helper
  (private). Daily series chart, rolling-window table, top
  models — same as before.
- dashboard/app.js — drops the live UsageWithChart + UsageChart
  + loadUPlot (~210 LoC) AND the dead-code original UsagePanel
  (~85 LoC) that hadn't been wired since the chart rewrite.
  TABS entry points at the new UsagePanel symbol.

Net dashboard/app.js loses 295 LoC; bundle still ~122 KB. uPlot
import stays external (esm.sh URL preserved through tsup).
1682 tests still pass.
2026-05-01 03:32:37 -07:00
esengine ff23936fc5 refactor(dashboard): migrate medium panels — settings / memory / skills / mcp
Stage 4 PR 4.2 from #28. Four panels with bigger surfaces (forms,
detail views, mutation flows) move out of dashboard/app.js:

- panels/settings.ts (153 LoC) — config form (api key, base url,
  preset, effort, search, runtime info)
- panels/memory.ts (172 LoC) — REASONIX.md + global / project-mem
  list + textarea editor
- panels/skills.ts (185 LoC) — list + create + edit + delete
  across project / global / builtin scopes
- panels/mcp.ts (206 LoC) — bridged-server table, persisted-spec
  CRUD, server detail view (tools / resources / prompts)

dashboard/app.js loses 656 LoC. Bundle still ~122 KB; CDN
imports stay external. Typecheck + 1682 tests pass.

Sessions panel deferred — it depends on ChatMessage which lives
with the Chat panel migration (Stage 4 PR 4.6).
2026-05-01 03:28:20 -07:00
esengine 7ef321cef1 refactor(dashboard): migrate small panels — overview / tools / permissions / plans / hooks
Stage 4 PR 4.1 from #28. Five panels move out of dashboard/app.js:

- panels/overview.ts (53 LoC) — Live Cockpit metric grid
- panels/tools.ts (71 LoC) — registered-tools table
- panels/permissions.ts (169 LoC) — allowlist CRUD + builtin
  groupings; private groupByVerb helper folded in
- panels/plans.ts (104 LoC) — archived-plan browser + step view
- panels/hooks.ts (105 LoC) — JSON editor for project + global hooks

Plus shared pieces these panels need:

- components/metric-card.ts (23 LoC) — used by overview now and
  by system in a later PR
- lib/html.ts (4 LoC) — single htm.bind(h) export so panels
  don't each rebind

dashboard/app.js loses 419 LoC. Bundle holds at ~122 KB; CDN
imports stay external. Typecheck + lint + 1682 tests still
pass. No behavior change.
2026-05-01 03:21:08 -07:00
esengine 7e598db416 refactor(dashboard): extract usePoll / bus / error-boundary / markdown
Stage 3 PR (consolidated). Originally split across PRs 3.2–3.5 in #28
but each was a 30–60 line leaf extraction — not enough review value
for the PR overhead. Folded the four into one architectural slice.

New files under dashboard/src/lib/:

- use-poll.ts (45 LoC) — typed `usePoll<T>` hook over the api() wrapper.
- bus.ts (65 LoC) — appBus, toastBus, showToast, ToastStack, plus
  reportAppError and the two window error listeners (registered on
  module load, same as before).
- error-boundary.ts (159 LoC) — ErrorOverlay component, ErrorBoundary
  class, buildIssueBody helper. Both consumers of bus.ts.
- markdown.ts (169 LoC) — escapeHtml, SEARCH_REPLACE_RE,
  renderSearchReplace, renderUnifiedDiff, the marked renderer
  customisation, renderMarkdownToString (was inline in
  renderMessageBody), LANG_BY_EXT, langFromPath,
  renderHighlightedBlock, hlLine. Drops the unused previewMarked
  (was only for the Editor that #31 removed).

Other moves:

- types.d.ts — module shims so TypeScript resolves the CDN URL
  imports against npm types. Specific shims for preact, htm,
  marked, highlight.js; wildcard fallback for anything else.
- package.json — preact, htm, marked, highlight.js added as
  devDependencies (types only — runtime still loads from esm.sh,
  tsup keeps them external).
- dashboard/app.js — drops ~500 LoC of moved blocks. renderMessageBody
  stays as a thin wrapper around renderMarkdownToString since it
  needs the Preact-bound `html` template literal.

Bundle output verified: dashboard/dist/app.js still 121 KB, CDN
imports preserved external. 1682/1682 tests pass.
2026-05-01 03:15:01 -07:00
esengine a5f4c19156 refactor(dashboard): extract api()/TOKEN/MODE → src/lib/api.ts
Stage 3 of #28, PR 3.1. The fetch wrapper (token-on-url for reads,
header-too for mutations, JSON parsing, structured ApiError) was
the next leaf-y piece after the formatters. Used by every panel,
no Preact dependency, easy to type.

- dashboard/src/lib/api.ts (new) — typed exports: TOKEN, MODE
  ("standalone" | "attached"), ApiOptions, ApiError, api<T>().
- dashboard/app.js — drops the inline definitions (~30 lines),
  imports the named exports.

Bundle still passes through tsup unchanged at the byte level
(esbuild inlines the lib module into a single file as before).
1682/1682 tests still pass.
2026-05-01 03:04:15 -07:00
esengine 2ff2262c12 refactor(dashboard): drop the editor surface (Stage 2 of #28)
The design mockup deleted §7 Editor in #26 — Reasonix's value is the
agent loop, not a VSCode-in-a-tab. The code follows. Net −1535 LoC
across nine files; the dashboard bundle shrinks from 137 KB to 121 KB.

Removed:

- dashboard/app.js — EditorPanel + the lazy CodeMirror loader (~540
  lines), the editor drawer overlay in App, the `editor` entry in
  TABS, the `openFileInEditor` helper, the `open-file` event-bus
  path, and the four tool-card path-link click handlers (now plain
  code spans).
- dashboard/app.css — 590 lines of editor-drawer / file-tree /
  CodeMirror skin. The `.tool-card-path-link` hover treatment goes
  with the click handler.
- dashboard/codemirror.js — 36-line CDN loader stub, gone.
- scripts/bundle-codemirror.mjs — the build-time CodeMirror bundler,
  no longer needed.
- src/server/api/file.ts — the `/api/files` + `/api/file/<path>`
  endpoints had no consumer outside the editor panel.
- src/server/router.ts — drops the `files` / `file` route cases.
- src/server/assets.ts — drops the `codemirror.js` serving branch.
- package.json — drops `dashboard/codemirror.js` from the npm
  files list and removes the `build:cm` script.

Out of scope: the new §7 Edit review surface (Stage 4 PR 4.15)
will live in `dashboard/src/panels/edit-review.tsx` and replaces
this slot in the IA conceptually, but that's later in the rollout.
2026-05-01 03:01:15 -07:00
esengine c770550b82 refactor(dashboard): extract formatters → src/lib/format.ts
First real TS module after the build-infra PR. Moves the five pure
helpers (fmtUsd, fmtPct, fmtNum, fmtBytes, fmtRelativeTime) out of
the 4768-line god file and into a typed leaf module. They had no
dependencies and ~6 panel call-sites, so this validates the
extraction pattern without touching state, polling, or buses.

- dashboard/src/lib/format.ts (new) — five exports, fully typed.
- dashboard/app.js — drops 35 lines of inline definitions, imports
  from "./src/lib/format". File-header comment shrunk to one line
  and corrected (no longer claims "no build step").
- tests/dashboard-format.test.ts (new) — 17 cases covering the
  null/undefined branches, locale separators, byte-unit boundaries,
  and the time-band edges; mocks Date.now where needed.

Bundle output verified: format functions appear once each in
dashboard/dist/app.js, CDN imports stay external. 1682/1682 tests
pass (was 1665; +17 from this PR).
2026-05-01 02:52:14 -07:00
esengine 63b023a54b build(dashboard): bundle via tsup so refactor can use TypeScript modules
The dashboard refactor (#28) needs to extract panels into typed
modules. Plain ESM-from-CDN can't follow `import` paths to local
sibling files at request time, so app.js has to go through a
bundler before it lands on the browser. Reusing the existing tsup
toolchain keeps build infra consistent with src/.

- tsup.config.ts adds a third entry: `dashboard/app.js` →
  `dashboard/dist/app.js`. Browser target, externals match
  `^https://` so esm.sh imports stay as live URLs in the output.
- dashboard/tsconfig.json extends the root config, swaps Node
  types for DOM, allowJs so the legacy app.js compiles unmodified
  while new TS modules under dashboard/src/ get strict checks.
- src/server/assets.ts reads app.js from `dashboard/dist/`; new
  branch serves the sourcemap.
- typecheck script chains both root + dashboard projects; verify
  now runs build first (matches the bundle-smoke pattern that
  already assumes CI builds before tests).
- package.json files: ship `dashboard/dist/` instead of the raw
  source app.js for npm consumers.
- Asset test that touches /assets/app.js skips when
  `dashboard/dist/app.js` is missing — same convention as the
  existing tests/bundle-smoke.test.ts.

No behavioral change at the dashboard level — esbuild passes the
source through; CDN imports stay external. First real TS module
extraction follows in a separate PR.
2026-05-01 02:45:11 -07:00
esengine c926d68f8c docs(rfc-25): land spike artifacts referenced from RFC #25
The four feasibility experiments for the kernel-level red-green
TDD invariant (RFC #25) produced reports, raw data, and reproducer
scripts. The RFC body and its summary comment cite paths under
benchmarks/spike-tdd-kernel/; without these files the references
are dead links.

Contents:
- latency.md / latency.json / bench-latency.mjs       (Exp 4)
- test-id-spec.md                                     (Exp 2)
- tdd-eval.md / tdd-eval.json / tdd-eval.mjs          (Exp 3)
- cost-results.md / cost-results.json / cost.mjs      (Exp 1)
- work-estimate.md                                    (3-stage plan)

All reports include their own pass thresholds, decisions, and
RFC-text-change implications. Reproducer scripts read the project
.env and run against deepseek-v4-flash / deepseek-chat; total
cost was ~$0.001 for the original spike pass.

Local-only tracking-issue-draft.md is intentionally excluded —
it gets posted as a real GitHub issue once the FCP closes.
2026-05-01 02:21:43 -07:00
esengine 385831db2d design(dashboard): drop editor, add edit-review, expand semantic config
Mockup prep ahead of the dashboard code refactor — current
dashboard/app.js is a 4768-line single-file Preact SPA with no
clear state boundaries, and the refactor needs an updated target.

- Remove §7 Editor entirely. Reasonix's value is the agent loop,
  not a VSCode-in-a-tab. Sidebar mockups (11 pages + collapsed
  variant) and the glyph palette drop the corresponding entries.

- Add §7 Edit review (reclaiming the slot). GitHub-style
  multi-file diff: aggregator header with stat + mode toggle +
  bulk apply, per-file collapsible cards with approve/reject,
  expand-context chevrons, intra-line word diff, unified ↔ split
  modes, plus empty / applied / test-failed states. §3 inline
  diff picks up syntax highlighting and a word-rem demo.

- §12 Semantic gains a real config card. The backend exposes
  6 fields (excludeDirs / excludeFiles / excludeExts /
  excludePatterns / respectGitignore / maxFileBytes); the mockup
  previously showed one as a read-only list. New card has
  editable chip lists, toggle, number input, and a Preview
  action, plus a Config preview subsec demonstrating the dry-run
  output of /api/index-config/preview.
2026-05-01 02:21:38 -07:00
esengine 6e2d3b4132 fix(docs): README pointed at CLAUDE.md (not in repo) instead of CONTRIBUTING.md
CLAUDE.md is local-only project guidance — never committed. The
public-facing rules entry is CONTRIBUTING.md (added in 4bf0abe). My
README rewrite (#23) linked to CLAUDE.md, which 404s for anyone
viewing the repo on GitHub.

Both English and Chinese READMEs updated to point at CONTRIBUTING.md
with a slightly fuller description (the rules cover comments, error
handling, and libraries-over-hand-rolled, not just comments).
2026-04-30 22:33:49 -07:00
esengine 89587ab9ea docs(zh-CN): mirror the trimmed English README · 894 → 169 lines 2026-04-30 22:29:39 -07:00
esengine 4749cc904f docs: trim README from 977 → 169 lines, refresh feature comparison
The previous README accumulated three years of "Risks", "Notes for
Reasonix", deep CLI reference, and library-usage walkthroughs that
belong on the website / in dedicated docs. Trim to the surface a new
visitor actually needs in 60 seconds.

Changes
- Single comparison table (was duplicated as "At a glance" + "Why Reasonix?")
- Drop stale `change_workspace` / `/cwd` row — both removed in 0.18
- Add per-workspace sessions row (new in 0.18)
- Cache-economics section condensed and tucked under <details>
- Feature highlights compressed to one paragraph each, link out for depth
- Contributing section front-and-centre with all four good-first-issues + the three open Discussions
- Non-goals retained (project-defining)
- Cut: long Risks essay, "Notes for Reasonix" prose, deep CLI reference,
  library-usage walkthrough, MCP transport tutorial, web-search internals
- Link-only references to architecture doc, design mockups, benchmarks dir

Stats updated to 1665 tests (was 1482).
2026-04-30 22:29:39 -07:00
esengine 7bfd68e3e6 docs: add Contributing section to README + dashboard design mockup
- README: link the four good-first-issues (#15-18) and the Discussions page;
  bump test count to 1665
- design/agent-dashboard.html: web-companion mockup, sibling to agent-tui-terminal.html.
  14 sections (tokens, shell, components incl. progress, chat with composer + slash
  popover + approval modal, overview cockpit, sessions, editor, plans, usage, inventories,
  system, semantic, hooks/settings). Anchor for the upcoming dashboard framework rewrite.
2026-04-30 22:17:00 -07:00
esengine 9de1ab9592 release: 0.18.1 (0.18.0 had ghost-frame bug, deprecated) 2026-04-30 20:34:39 -07:00
esengine 4807ccef13 fix(tui): drop ink debug:true — was leaving a ghost-frame trail per keystroke
`debug:true` does NOT force full-frame writes — Ink's docs are explicit that
each update is rendered as a SEPARATE output without overwriting the previous
one. Every keystroke triggered a React rerender → a fresh frame appended to
scrollback. After a session, dozens of stale PromptInput frames remained
above; relaunching reasonix made the new session's typing look like it was
"syncing" with the ghost frames above.

The original justification ("log-update drops frames on Windows ConPTY") was
my speculative misread — never seen in practice. Default log-update diff
mode is correct here.
2026-04-30 20:29:15 -07:00
YHH a8d42f87ec Merge pull request #13 from esengine/feat/tui-card-stream
TUI card-stream migration + drop change_workspace tool
2026-04-30 20:18:53 -07:00
esengine ba7666c1df feat(tui): mid-chat session switch + composer Esc-cancels picker
- chat.tsx: SessionPicker outcomes now drive state, parent re-renders App with `key={session}` so the new session gets a fresh transcript / scrollback / store; ink `debug:true` forces full-frame writes (log-update's diff dropped frames on Windows ConPTY)
- App.tsx: hydrate cards from `loadSessionMessages` on mount so resumed sessions render their history; expose `onSwitchSession` so the picker actually switches instead of printing a "quit and rerun" hint; conditional render of SlashSuggestions / AtMentionSuggestions only when matches !== null
- composer Esc: dismiss slash / @ / slash-arg pickers by clearing input — picker footers already advertise "esc cancel"
- state/{provider,state,store}: thread an optional `initialCards` through createStore; provider captures it in a ref so re-renders don't reset the store
- SessionPicker: rename starts with empty buffer (was pre-filled with old name — typo-prone)
- PromptInput: placeholder uses words "slash"/"at-sign" instead of `/`/`@` glyphs (read as residual typed input on dim-poor terminals)
- hydrate: new module rebuilds Card[] from ChatMessage[] (user → UserCard, assistant text → StreamingCard, reasoning_content → ReasoningCard, tool_calls + tool messages → ToolCard pairs)
2026-04-30 20:11:39 -07:00
esengine a1856a7dbc chore(session): events.jsonl sidecar lifecycle + strict workspace match
- listSessions: filter out *.events.jsonl — they share the .jsonl suffix and were polluting the picker as phantom sessions
- listSessionsForWorkspace: strict equality on meta.workspace; legacy untagged sessions no longer leak into every workspace's picker (resume-by-name still works)
- rename / delete: also move/remove the .events.jsonl sidecar so /forget and /rename leave no orphans
- JsonlEventSink: skip model.delta — recoverable from model.final.text and would balloon the sidecar with token-by-token frames
2026-04-30 20:11:15 -07:00
esengine f5bfcc5ce5 chore(tui): tighten PromptInput keystroke-ref comment per project style 2026-04-30 19:18:22 -07:00
esengine fb1b306f6d refactor: remove change_workspace tool and mid-session cwd switch
Mid-session re-rooting was a footgun: the message log still referenced old paths after a switch, and any tool call dispatched in the same parallel batch as `change_workspace` ran against the pre-switch sandbox before the user had approved. Both the deferred-batch workaround (loop.ts) and the modal/UI plumbing exist only to paper over those races. Cheaper to pin workspace at launch and tell the user to relaunch.

- delete src/tools/workspace.ts and tests/workspace-tool.test.ts
- delete src/cli/ui/WorkspaceConfirm.tsx
- loop: drop workspaceSwitchPending gate (no batch can target a pending switch anymore)
- server: drop "workspace" ActiveModal kind + resolveWorkspaceConfirm + the modal route
- slash: drop /cwd command, handler, and setCwd context callback
- code/prompt: rewrite the "switch project" section to tell the model the workspace is pinned
- tests/loop + tests/server-dashboard: drop the corresponding cases
2026-04-30 19:14:37 -07:00
esengine 73850eeb31 refactor(tools): harden child-process abort + subagent streaming
- shell: kill the whole process tree on timeout/abort (Windows taskkill /T, Unix process-group SIGKILL with leader fallback) — long-running shells were leaking children when the parent loop aborted
- shell + jobs: synchronously check signal.aborted before attaching the listener; AbortSignal addEventListener with `once:true` never fires if the signal already aborted, so child ran unbounded
- subagent: turn on streaming + emit `inner` and `phase` SubagentEvent variants so the parent UI can render child loop activity and flip "summarising" the moment the model starts the final answer
- skills: thread parent abort signal through SubagentRunner so subagent skill invocations cancel cleanly
- tests/subagent: extend fake fetch to serve SSE frames when stream:true
2026-04-30 19:14:01 -07:00
esengine 60c7000755 feat(tui): finalize card-stream migration
- App.tsx: drop legacy workspace-switch modal + registerWorkspaceTool wiring; surface active PlanCard via useAgentState selector
- handle-tool-event: remove change_workspace branch (the tool itself leaves in a follow-up)
- chat.tsx: pin session listing to the launch workspace via listSessionsForWorkspace
- PlanConfirm: route through ApprovalCard with metaRightColor; drop unused summary prop
- PromptInput: mirror value/cursor in refs so multi-event stdin chunks see the latest state (fixes a fast `/`+Backspace race that left the slash stuck)
- LiveRows / CardStream / BarRow / cards/{Approval,SubAgent}: layout polish for the card stream
- useSubagent: child-event subscription for the new SubAgent card
2026-04-30 19:13:20 -07:00
esengine b7b9b48ea2 chore(post-merge): trim PR #12 narrative comments to project style
CLAUDE.md forbids conversation history / incident narrative / stream-of-
consciousness debug traces in committed code. Cleanups on the just-merged
PR #12 contributions:

- session.ts: drop bogus "Priority order in description.md" reference;
  replace with a concise dispatch summary on resolveSession. Trim
  findSessionsByPrefix JSDoc to a single line.
- tests/session.test.ts: replace the 17-line "Wait — let's trace..."
  inner-monologue with one explanatory line. Trim 6-line ASCII-sort
  essay to 2 lines. Drop "Regression:" incident narrative and a few
  inline play-by-play comments on test setup.
- tests/plan-store.test.ts: replace the 8-line "Bug:" narrative with
  a test name that documents the invariant directly.
2026-04-30 19:02:41 -07:00
esengine c2d95cc0c9 Merge main: timestamped sessions + .plan.json sidecar cleanup
Integrates PR #12 onto feat/tui-card-stream:

- Use resolveSession() in chatCommand for --session paths so --new
  generates a timestamped name instead of truncating, and --resume
  picks the latest prefixed session. The full-list SessionPicker
  (this branch) covers the no-session launch path; the legacy
  resume/new modal from PR #12 is dropped (full-list is strictly
  more capable).
- Drop the baseSession Root prop and effectiveSession state — only
  used by the dropped legacy modal.
- session.ts deleteSession sidecar list keeps .meta.json (this
  branch had it; PR #12 didn't).
- App.tsx loop.resumedMessageCount > 0 guard from PR #12 lands as-is
  (auto-merged).
2026-04-30 18:56:24 -07:00
Wesley Viana 34464ff4e7 fix(session): preserve old sessions on "new"; clean .plan.json sidecars (#12)
Round 1 — sidecar cleanup:
- deleteSession() also removes the .plan.json sidecar
- App.tsx skips plan restoration when loop.resumedMessageCount === 0

Round 2 — timestamped sessions:
- New helpers: timestampSuffix(), findSessionsByPrefix(), resolveSession()
- "Start new" generates code-reasonix-YYYYMMDDHHmm instead of truncating
- --resume <name> resolves to the latest prefixed timestamped session
- Old session files preserved on disk

Tests: deleteSession sidecar regression, resolveSession + findSessionsByPrefix coverage.

Co-authored-by: wviana <[email protected]>
2026-04-30 18:51:20 -07:00
esengine dcad238c94 feat(tui): terminal-faithful redesign — cards, composer, status row, sessions
Massive batch implementing design/agent-tui-terminal.html across the TUI.
Major surfaces:

- Card system: shared CardHeader (▎ accent bar + glyph + title + meta),
  migrated Reasoning / Tool / Task / Plan / Diff / Error / Warn / Usage /
  Memory / Search / SubAgent / Branch + new DoctorCard. Drop the
  collapse arrows (terminal has no expand interaction).
- Layout: cost-ticker StatusRow above the prompt (turn ¥ · session ¥ ·
  wallet ¥ with threshold colors · cache %), separator now terminal-width
  responsive. Mode pills ●/◐/⊞/± with mode colors; verbose network state
  when offline; auto-confirm Countdown; REC pill placeholder.
- Modals: ApprovalCard with band header + footer separator. Deny modal
  per §m-deny. PlanConfirm + new PlanReviseEditor (↑↓/space/k+j/⏎).
  PlanCheckpoint auto file-snapshot via createCheckpoint on continue.
- Composer: PromptInput hint shows shift/alt+⏎. Paste sentinels render
  on their own row as a chip (┌ 📋 pasted · N lines · X · type ┐) with
  brand-bg highlight when focused. Empty-buffer ↑↓ recalls history.
- Markdown: marked + cli-highlight; styling matches dashboard/app.css.
  Tables drop ┌─┐ box and use header + ─ separator. File:line + @mention
  inline post-process (sky / amber underline + OSC-8).
- Sessions: SessionPicker rewritten as full sorted list with [n]/[d]/[r]/⏎
  keys + inline rename input. New .meta.json sidecar (branch / summary /
  cost / turn count) drives row content. /sessions slash opens picker
  mid-chat. /rename + /resume + renameSession() added.
- Slash: /cost auto-emit per turn (compact) + verbose via /cost; /doctor
  pushes structured DoctorCard via postDoctor; /context always emits
  CtxCard (footer retired).
- Stdin: Alt+Enter (ESC+CR/LF) → return+meta as universal newline; both
  shift/alt-Enter insert newline in multiline-keys.
- Bug fixes: ToastRail effect deps no longer churn every frame; Shift+Tab
  edit-mode cycle moved log.pushInfo out of setState updater (was firing
  store dispatch during render → "update CardStream while rendering
  AppInner" warning); same fix for stopLoop.
- Drop dead code: CtxFooter, EventLog, LiveRows old, ModalCard,
  log-frame, log-rows, markdown-frame and their tests.
- New deps: marked, cli-highlight; markdown.tsx 1612→227 lines.

Tests: 1646 pass; comment-policy gate stays green.
2026-04-30 08:57:00 -07:00
Wesley Viana ad3d97e189 fix(ui) Rendering inline formating deletes prefixed spaces. (#8)
* fix(ui) Rendering inline formating deletes prefixed spaces.

* Add falling unit tests for missing space before inline bold, code and others.

* Fix implementation
2026-04-30 06:09:00 -07:00
esengine 37dabbe395 fix(dashboard): editor mode toggle crashed Preact reconciler — 0.17.1
CodeMirror injects DOM into its container; the markdown preview uses
dangerouslySetInnerHTML. Toggling Edit / Split / Preview re-shaped the
DOM around both, so Preact tried to insertBefore against anchors that
were never its own children — observed as "render: Failed to execute
'insertBefore' on 'Node'" in the dashboard error overlay.

The editor stage now keeps both panes rendered at stable vnode
positions; data-mode on one wrapper drives CSS visibility instead of
restructuring the tree. CM stays mounted across toggles and gets a
requestMeasure when it returns from display:none.
2026-04-29 21:28:56 -07:00
esengine ec2b3c761e chore(release): 0.17.0 — config-driven index excludes + .gitignore
Minor bump. New feature surface: ReasonixConfig.index block fully
replaces the previously-hardcoded skip lists in chunker.ts (and the
duplicated copy in directory_tree). .gitignore is honoured by default,
nested per-dir. Dashboard Semantic tab grows an Excludes card with
Save / Preview / Reset that round-trips through GET/POST
/api/index-config and POST /api/index-config/preview.

Defaults are the union superset of the previous two lists, so existing
installs keep current behaviour without touching config.

Landed via PR #10 (closes #9).
2026-04-29 18:42:48 -07:00
esengine 4190a4b805 fix(dashboard): style the Excludes card properly
Earlier change used inline styles + abused .section-title for the
toggle header, leaving the card visually inconsistent with the rest of
the dashboard: bare textareas with no border, an unstyled number
input that fell back to browser defaults against the dark background,
and details/summary blocks rendered as raw HTML.

This adds:
- input[type="number"] grouped with text/search so it picks up the
  same bg-2 / border / padding / font as the other inputs.
- textarea gets the missing border / radius / padding / font-size /
  resize:vertical (was background+color+font-family only).
- New .excludes-* classes for the toggle header, two-column field
  grid, options row, action row, and the dry-walk preview drilldown.

The JS swaps every inline style on the Excludes card for a class.
2026-04-29 18:38:54 -07:00
esengine 38dd8f4861 docs(changelog): unreleased — config-driven index excludes 2026-04-29 18:38:54 -07:00
esengine 834ef31aae feat(server,dashboard): index-config endpoints + Settings card
GET /api/index-config returns user, resolved, and defaults so the SPA
can render a "reset" affordance without re-implementing them. POST
persists into ~/.reasonix/config.json via the existing writeConfig
path. POST /api/index-config/preview dry-walks the project root with
a draft config (without saving) and returns sample included paths
plus per-reason skip buckets — lets users see the impact before
committing the change.

Dashboard Semantic tab gets a collapsible "Excludes" card with
editable lists, gitignore toggle, max-file-size input, and Save /
Preview / Reset buttons. The job result panel now shows per-reason
skip bucket counts when a build finishes.

semantic.ts is wired to load the resolved config so dashboard-
triggered indexing honours the same excludes as the CLI.
2026-04-29 18:38:54 -07:00
esengine 903c10e83f feat(index): config-driven excludes + nested .gitignore
Pulls SKIP_DIRS / SKIP_FILES / BINARY_EXTS / maxFileBytes out of
chunker.ts (and the duplicate copy in directory_tree) into a single
src/index/config.ts. ReasonixConfig gains an optional `index` block
where any field present fully replaces the default for that field.

walkChunks now takes a ResolvedIndexConfig and an onSkip callback,
honours .gitignore by default (nested per-dir, scoped to the dir the
file lives in), and supports picomatch globs via excludePatterns.
buildIndex aggregates the callback into a per-reason skipBuckets map
that the CLI surfaces in its success line.

directory_tree no longer carries its own list — both code paths share
DEFAULT_INDEX_EXCLUDES, eliminating the drift the comment at
chunker.ts:29 had been warning about.

scripts/smoke-index-config.mjs is a tsx one-shot for verifying the
walker + .gitignore + glob behaviour against a real repo without
needing Ollama.
2026-04-29 18:38:54 -07:00
esengine bb7c245c9a chore(release): 0.16.1 — fix V4 deepseek-chat reasoning_content round-trip
Patch release. 0.16.0 has a real production-affecting bug: any tool
loop on the default deepseek-chat model 400s on the second turn with
"reasoning_content in the thinking mode must be passed back to the
API." DeepSeek's V4 rollout means deepseek-chat now emits non-empty
reasoning_content even with thinking disabled, and the whitelist-by-
model logic in assistantMessage() was dropping it.

Fixed in a27d46f, regression test in a5ffa0b, full τ-bench re-run
(100% pass · 90.2% cache hit) in f77e8f2.
2026-04-29 09:41:59 -07:00
esengine 3a04d6ab55 docs(numbers): refresh README + site to fresh v0.16 τ-bench numbers
Sweep the cached 94.4% / 46.6% / $0.001579 / $0.002599 numbers (from
the v0.2.1-era bench) and replace with the v0.16 re-run published in
f77e8f2:

- cache hit:       baseline 32.8%  · reasonix 90.2%  (+57.4pp)
- cost / task:     baseline $0.000992 · reasonix $0.000593 (-40%)
- pass rate:       100% on both
- vs Sonnet 4.6:   ~98% cheaper (was ~96%)

Touches: at-a-glance table, "why reasonix" prose, full benchmark table,
site hero stats + bench table + meta description + ctab.sub.
2026-04-29 09:40:46 -07:00
esengine f77e8f2951 bench(tau): refresh to v0.16 — 100% pass · 90.2% cache hit · $0.000593/task
Re-ran the full τ-bench-lite suite (8 tasks × 3 repeats × 2 modes = 48
runs) on v0.16.0 against deepseek-chat. Numbers vs the v0.2.1 snapshot:

| metric          | v0.2.1 reasonix | v0.16 reasonix | delta |
|---|---:|---:|---:|
| pass rate       | 100% (24/24) | 100% (24/24) | — |
| cache hit       | 94.4%        | 90.2%        | -4.2pp |
| mean cost/task  | $0.001579    | $0.000593    | -62%  |

Cost drop is mostly DeepSeek's price moves; cache-hit dip is small and
within run-to-run variance — the loop is still operating in the
prefix-stable regime (vs baseline's 32.8%, +57.4pp delta).

Also: runner.ts now reads VERSION live from src/index.ts instead of
the hardcoded 0.2.2 — every future re-run stamps the right version.

Refreshed transcripts (committed) carry per-turn usage/cost/prefixHash
so anyone can re-render the report locally without burning API credit.
2026-04-29 09:37:03 -07:00
esengine a5ffa0bbda test(loop): regression for V4 deepseek-chat reasoning_content preservation
New case alongside the existing R1 round-trip tests: when deepseek-chat
returns a non-empty reasoning_content (V4-era behavior), the next
request's assistant message must carry it back. Without the loop fix
in a27d46f the API 400s on the round-trip.
2026-04-29 09:21:00 -07:00
esengine a27d46fe48 fix(loop): preserve reasoning_content on V4 deepseek-chat round-trips
V4-era deepseek-chat now returns non-empty `reasoning_content` even
with `extra_body.thinking.type = "disabled"`. The API then rejects
round-trips that drop the field with "reasoning_content in the thinking
mode must be passed back".

The whitelist in `isThinkingModeModel` was too narrow — it only tagged
deepseek-reasoner / v4-flash / v4-pro. `assistantMessage()` now also
preserves reasoning_content whenever the producer emitted any non-empty
content, regardless of model name. The whitelist still applies to
synthetic messages where reasoningContent is empty (so they get an
empty string stamp for thinking-mode endpoints).

Caught by tau-bench (24/24 reasonix runs were failing on the kernel
HEAD; same test on v0.2.1 passed 100%). Single-task verify now hits
92.3% cache and passes.
2026-04-29 09:19:25 -07:00
esengine b3c602c112 docs(landing): collapse deep-dive sections into <details> for shorter top scroll
README and zh-CN README: wrap four reference-heavy sections in
<details>/<summary> blocks so the visible flow on GitHub stays around
half its previous height while keeping every word findable via Ctrl-F
and clickable expansion.

- Why-Reasonix tail (Pick something else / DeepSeek-Anthropic-compat /
  Aider-Cline-Continue): collapsed
- Slash-command reference inside "Commands inside the session": collapsed
- CLI reference (commands + flags + env vars): collapsed
- Library usage: collapsed

Comparison table, walkthroughs, plan mode, and benchmarks remain
visible — those are the parts a new reader actually reads.
2026-04-29 08:55:11 -07:00
esengine 1c2df7ef84 docs(landing): At-a-glance comparison block · drop dated 0.X tags · v0.16 site fallback
README / README.zh: pull a focused 7-row comparison table to right
after Quick start (was buried inside the 'Why' prose section). Headline
numbers + "see full comparison below" pointer. Trim a couple casual
asides ("watch your bill not happen") and remove version-specific tags
that aged out (`(new in 0.12)`, "since 0.5.14").

docs/: bump VERSION_FALLBACK and the static hero badge from 0.6/0.12
to 0.16. The site fetches latest from npm at runtime; the fallback
just covers offline-first-visit.
2026-04-29 08:34:54 -07:00
esengine 4bf0abefc1 docs(contrib): CONTRIBUTING.md + PR / feature-request templates · refresh REASONIX.md layout
CONTRIBUTING.md is the human-facing rules entry on GitHub (CLAUDE.md
stays as the AI-agent entry). Code rules previously only in CLAUDE.md
are now inlined here so contributors actually see them.

REASONIX.md layout table catches up to the recent structure refactor —
adds core/, ports/, adapters/, frame/, memory/, transcript/, telemetry/,
server/, code/ which had drifted off the doc.
2026-04-29 08:26:55 -07:00
esengine 146ddb0658 chore(release): 0.16.0 — drag-select with auto-scroll · /copy retired
feat(ui): plain mouse drag in the log now paints a reverse-video
selection, dragging past the viewport edge auto-scrolls the log, and
releasing copies the selected text to the system clipboard via OSC 52
+ tempfile fallback. Shift+drag still bypasses tracking for native
terminal selection.

chore(ui): the old /copy slash command, copyMode lifecycle, and
mouse-tracking helpers are gone — the new flow stays inside
alt-screen so there's no main-buffer dump to manage.
2026-04-29 08:10:50 -07:00
esengine 0620c8ee4e fix(ui): correct mouse→abs-row math when content is shorter than viewport
The old mouseToAbsRow assumed log content always started at the top of
the box. Two cases broke that:
1. ChromeBar is 2 rows (pills + ChromeRule), not 1 — log starts at row 3.
2. At logScrollOffset=0, the inner Box uses justifyContent="flex-end",
   so when totalRows < available the content is bottom-anchored and the
   top of the box is empty — clicks there were mapping to row 0.

Now the geometry IIFE computes contentTopRow / contentBottomRow per
render based on the actual layout (scrolled vs latest, BottomHint
present vs not), and mouseToAbsRow uses those instead of guessing from
logTopRow. Auto-scroll edge triggers use the real content edges too.
2026-04-29 08:10:09 -07:00
esengine 13a15bb665 feat(ui): native drag-select with auto-scroll at edge — replaces /copy
App now owns mouse selection. Plain drag in the log paints a reverse-
video selection highlight; dragging past the top/bottom edge of the
viewport auto-scrolls one row every 60ms; releasing copies the selected
text via OSC 52 to the system clipboard plus a tempfile fallback for
terminals that don't honor it. Shift+drag still bypasses tracking for
native terminal selection.

stdin-reader surfaces mouseDrag (SGR btn=32) and mouseRelease (tail='m')
events; alt-screen switches from mode 1000 (press only) to 1002
(button-event tracking with drag motion); log-frame extends AtomViewport
with firstRowAbs and adds extractSelection() to pull plain text out of
the selected absolute-row range.

Old /copy slash command, copyMode lifecycle, and the
isMouseTrackingOn / setMouseTracking helpers are removed — the new
flow stays inside alt-screen the whole time so there's no main-buffer
dump to manage.
2026-04-29 08:02:21 -07:00
esengine ef787f8eba fix(benchmarks): point harvest/tau runners at src/transcript/log.js
The structure refactor (3b0dd73) moved src/transcript.ts under
src/transcript/, but the two benchmark runners kept the old import
path and tripped CI's tau-bench dry-run.
2026-04-29 07:53:48 -07:00
esengine 3b0dd73d31 fix(tests): de-flake jobs read test under CPU load
read(jobId) test fired fixed 300ms sleeps after child spawn; under
parallel-suite contention the child hadn't printed yet and the
"contains 'a'" assertion failed. Replace fixed waits with a 100ms × 20
poll loop. Same shape as the `since` test below it.
2026-04-29 07:43:35 -07:00
esengine d84de144b7 refactor(structure): consolidate root scatter into memory/ telemetry/ transcript/
The root of src/ had 25 top-level *.ts files mixed with subdirs, including
several that map directly to architectural layers in design/architecture.md.

- memory pyramid → src/memory/{runtime,session,project,user}.ts
- telemetry      → src/telemetry/{stats,usage}.ts
- transcript     → src/transcript/{log,replay,diff}.ts

git mv preserves history. Internal cross-imports updated (siblings drop
the prefix; references to non-moved root files gain `../`). Public barrel
in src/index.ts and all consumers (~50 sites in src + 18 test files)
retargeted. Behavior is unchanged; verify (lint + typecheck + tests) green.
2026-04-29 07:40:58 -07:00
esengine a47f457ef2 chore(release): 0.15.0 — event-log replay · deny-with-context · comment-policy gate
feat(core): replay() reads events.jsonl sidecar and runs the same
pure reducers as in-process apply() — first deterministic proof of
the v0.14 projection layer.
feat(cli): reasonix events <name> for inspecting any session's event
stream from the command line.
feat(ui): deny-with-context shipped via PR #1 (@wviana) — Tab on a
tool-confirm modal opens inline reason entry, forwarded to the model
so it knows *why* the user refused.
chore: tests/comment-policy.test.ts enforces CLAUDE.md rules under
npm run verify; companion sweep removed 6.3k LoC of dead-weight
comments across 148 files.
2026-04-29 07:24:33 -07:00
esengine 9a5bbcc0e8 chore(comments): enforce CLAUDE.md no-essay rule via vitest + sweep -6.3k LoC
tests/comment-policy.test.ts pins six rules: ≤2-line module headers, no
Phase-N narrative, no version refs in comments, no incident history, no
banner separators, ≤3-line block comments. Runs under `npm run verify`
so pre-push catches new violations.

148 src files touched: 116 module-essay headers compressed to one line,
577 over-long block comments distilled or deleted, 44 banner separators
stripped, all v0.x / Phase-N / "user reported" / "fix for #N" narrative
removed. Net -6367 LoC of dead-weight comments. No behavior change;
1759/1759 tests, lint, typecheck pass.
2026-04-29 07:13:40 -07:00
esengine a1dd12008d chore(ui): trim deny-with-context comments to one-liners
Multi-paragraph docstrings + restated-what comments shipped via PR #1
trimmed back per CLAUDE.md.
2026-04-29 06:21:12 -07:00
Wesley Viana 622d5f89bb feat(ui): allow user to add context when denying a tool call
Pressing Tab on a Deny item (or n on edit-review) opens an inline input so the user can tell the model *why* they refused. Context is forwarded into the synthetic message and the historical log.

Also: stdin-reader.ts now probes setRawMode directly so bun (where isTTY is undefined) can still go interactive; useKeystroke falls back to Ink useInput when no KeystrokeProvider is mounted.

Closes #1
2026-04-29 06:14:21 -07:00
esengine f29eb405e6 feat(cli): reasonix events <name> + sweep dead comments off the kernel
reasonix events <name> pretty-prints the event-log sidecar — the first
user-facing consumer of events.jsonl. Renders one line per event with
per-type detail synopses; --type / --since / --tail filters; --json
for jq pipelines; --projection dumps the reduced ProjectionSet. Closes
the v0.14 kernel loop: events get written by every session, and now
there's a tool to read them.

Sweep pass: trimmed verbose jsdoc / restated-the-code comments off
eventize.ts, event-sink-jsonl.ts, event-source-jsonl.ts, and the
tests. ~80 lines of comment cruft gone, no logic changed.

- src/cli/commands/events.ts: command formatter + per-event detail
  table covering all 25 Event variants
- src/cli/index.ts: command registration with commander, help text
- tests/events-command.test.ts: 6 tests pinning the formatter + each
  flag (type filter, tail, json passthrough, projection, missing
  session error path)

1753 tests pass (was 1747 + 6 new).
2026-04-29 06:01:21 -07:00
esengine d3613ddb18 feat(core): event-log replay — first consumer reads sidecar + projects
Closes the loop on the v0.14 kernel architecture: the events.jsonl
sidecar from the prior commit is now demonstrably reduceable into a
useful projection. Synthetic LoopEvents → Eventizer → JsonlEventSink
→ disk → JsonlEventSource → reducers.replay() → ProjectionSet round-
trips correctly, conversation messages reconstructed in order, tool
result correlation preserved, replay() deterministic across runs.

This is the architecture-value tipping point: events are no longer
just write-only artifacts, they're the source of truth a consumer
can rebuild state from. Future work — UI re-rendering from a
projection, time-travel, multi-agent event trees — has a working
foundation.

- src/adapters/event-source-jsonl.ts: EventSource port impl. Pure
  read side: parses jsonl, skips malformed lines silently (best-
  effort replay over a possibly-truncated live writer).
- tests/event-sink-jsonl.test.ts: 5 tests pinning the sink mechanics
  (append-per-line round-trip, re-open on existing file, parent dir
  creation, flush no-op, port-shape conformance).
- tests/event-replay.test.ts: 5 tests pinning the architecture
  promise — synthetic LoopEvents reduce to expected projections,
  error-shaped tool results land with ok=false, replay determinism,
  missing-file safety, malformed-line tolerance.

1747 tests pass (was 1737 + 10 new). Zero touches to existing
production code.
2026-04-29 05:48:15 -07:00
esengine f36282d258 feat(core): event-log sidecar — kernel artifact alongside LoopEvent
Adds a new durable artifact: every session now writes a typed Event
log to ~/.reasonix/sessions/<name>.events.jsonl as a sidecar to the
existing ChatMessage / transcript files. Foundation for future
replay / projection / multi-agent consumers reading kernel events
instead of LoopEvent.

Architecturally a pure addition: no edits to loop.ts, transcript.ts,
EventLog, log-frame, replay, dashboard server, or any existing test.
LoopEvent stays as the internal protocol between loop and immediate
consumers — events.jsonl is a parallel kernel artifact, not a
migration target.

- src/core/eventize.ts: pure stateful translator. Holds monotonic
  event id seq, last-turn tracker (synthesizes model.turn.started),
  and a callId stack (correlates tool.intent → tool.dispatched →
  tool.result chains since LoopEvent.tool_start doesn't carry
  call.id).
- src/adapters/event-sink-jsonl.ts: concrete EventSink port impl —
  append-only JSONL with append/flush/close lifecycle. eventLogPath
  helper derives the sidecar path from a session name (mirrors
  src/session.ts:sessionPath).
- src/cli/ui/App.tsx: ~30 lines additive — refs for sink + eventizer
  opened on session mount (skipped for ephemeral sessions), pipe
  attached inside the existing for-await consumer alongside
  writeTranscript, sink.close on unmount, session.opened emitted at
  open time.
- tests/eventize.test.ts: 11 unit tests pinning the mapper —
  turn-start synthesis, delta channel split, tool callId
  correlation, error detection, warning categorization, control-
  marker passthrough.

1737 tests pass (was 1726 + 11 new). Zero existing-test edits.
2026-04-29 05:48:15 -07:00
esengine 33a3a7fd49 chore(release): 0.14.0 — abort-race fix · /copy mode · ctx footer · primitives
fix(loop): streaming-abort path resets _turnAbort before returning,
so a queued-submit triggered by ShellConfirm "run once" no longer
trips a spurious "aborted at iter 0/64" on the next user message.
fix(tui): edit_file interceptor reads root via currentRootDirRef so
post-workspace-switch writes don't go to the stale root while
read_file looks at the new one.

feat(tui): /copy exits alt-screen and dumps the rendered log to
main screen, returning on any keystroke — native scrollback + drag
select work on the dump.
feat(tui): always-on context-pressure footer above the prompt
(`ctx ▰▱… 14K/977K · 1% · sys 5.8K · tools 6.1K · log 0`); /context
toggles visibility, full breakdown panel still pushed to scrollback
for headless / replay.
feat(tui): chrome bar drops the cols<120 hard cutoff in favor of
width-aware shed by priority (balance > cache > session > update);
cache pill default-on with cold-start dim treatment.

refactor(ui): Bar / formatTokens / ChromeRule / ContextCell promoted
to primitives.tsx; CtxBreakdownBlock + computeCtxBreakdown share a
single compute path; StatsPanel shrunk 769 → ~280 lines (dead
chrome-redesign helpers removed).

feat(core): v0.14 architecture scaffold — Event log + pure-reducer
projections (core/) and 6 ports (ports/). Types only, zero behavior
change. 19 new reducer tests pin the projections + prove replay
determinism.
2026-04-29 04:56:45 -07:00
esengine 535a8ebb3b chore(release): 0.13.5 — TUI overhaul (chrome / streaming / scroll progress)
* chrome → native Ink Box+flexGrow (Phase 6a Frame-compiler path
  was clipping pills on Windows Terminal / ConPTY); preset pill
  replaces edit-mode pill; CNY balance uses ¥; cost includes
  inline budget when set
* streaming: full body text streams in (was 140-char tail) with a
  ▌ cursor blink and design-matching ░▒▓█▓▒ marquee row
* scroll: drop vertical ScrollBar (column alignment unreliable
  while legacy LogBlock atoms exist); chrome shows [↑ N%] when
  scrolled, BottomHint shows ↑ N · ▕──●──▏ X% · ↓ M · End
* frame/width: delegate to string-width package; hand-rolled
  width tables removed
* chore: project CLAUDE.md codifies code/comment conventions
2026-04-29 02:16:05 -07:00
esengine 8860cedc2a fix(frame): unify viewport-row math across log slicer + scrollbar (off-by-one)
Three places were computing 'rows the log can use' with subtly
different formulas:

  · slicer:         max(8, rows - 10)
  · scrollbar bar:  max(5, rows - 9)
  · scrollbar math: max(8, rows - 10)

Bar height (the cell count) and thumb math (the divisor) didn't
match — thumb was computed for a 20-row viewport but rendered into
21 cells, so thumb position drifted vs. the actually-rendered log
slice. User reported visual oddness consistent with this drift.

Unify on  (the parent log column's true height)
for both bar and thumb math. Slicer subtracts 1 when BottomHint
is active so the slicer doesn't claim the row the hint occupies —
the bar mirrors the same conditional so position stays in sync.

Tests: 1732/1732 pass.
2026-04-28 23:40:37 -07:00
esengine 98d6021ba9 fix(frame): restore 1-cell side padding to chrome (matches StatsPanel paddingX) + revert kitty keyboard protocol
Two reverts after the user reported chrome truncating worse than
before (only `[$` visible) and scrollbar display issues:

  · The Phase 6a chrome migration removed the legacy
    `paddingX={1}` from the StatsPanel outer Box but didn't
    restore the equivalent inner-width budget. Inner content
    rendered at full `cols` width, where on terminals that
    reserve their last column for cursor/scrollbar (Windows
    Terminal in some configs, ConPTY) the rightmost pill got
    clipped mid-glyph. Restore: build chrome at `width - 2` and
    wrap with 1-cell SPACE padding on each side so the visual
    matches the legacy chrome and the right-edge pill is safely
    inside the visible area.

  · The Phase 8 kitty keyboard protocol push (`\x1b[>1u`) was
    too aggressive — terminals without protocol support sometimes
    displayed the unrecognized CSI as visible chars, distorting
    the chrome layout. Revert until we wire feature detection
    (DA1/DA2 query response) before pushing the flag. The
    setImmediate-based ESC ambiguity timer in stdin-reader keeps
    handling the bogus-Esc bug class for now.

The earlier 1-cell safety margin (`width - 1` in App.tsx) is
removed since the new `paddingX`-equivalent already provides
the right-edge buffer.

Tests: 1732/1732 pass. Lint clean. Typecheck clean.
2026-04-28 23:37:52 -07:00
esengine 3e71089068 fix(frame): leave 1-cell right-edge margin for chrome to avoid terminal clipping
User reported wallet pill still clipped at "[w" even after the
appendCells / composeRow fixes. Reproduction confirmed our Frame
output is correct (full 120-col row, all cells styled, ANSI bytes
intact) — the clipping happens at the Ink/terminal layer.

Most likely culprit: terminals that reserve their rightmost column
for the cursor or a scrollbar (some Windows Terminal / ConPTY
configurations report 120 cols but only render 119 visibly), or
Ink miscounting our SGR-rich row width.

Cheapest fix: build chrome at stdout.columns - 1, leaving a 1-cell
safety margin. The cost is one column of empty space at the right
edge; the gain is the wallet / cache pills survive on every
terminal we've seen.

Tests: 1732/1732 still pass.
2026-04-28 23:29:22 -07:00
esengine 7a5ef3b163 fix(frame): wallet pill truncation + composeRow overflow handling in chrome
User reported the wallet pill at the top wasn't displaying fully.
Two bugs in `chrome-frame.ts`:

1. `appendCells` was padding to a generous width then stripping
   trailing-space-with-no-style cells. That stripped REAL spaces
   the caller had explicitly added as inter-pill separators
   (`appendCells(right, "  ")`), collapsing pills into each other
   visually. Fix: pass the EXACT visual width of the input string
   to `text()` so no padding is added in the first place.

2. `composeRow` only handled "left+right combined exceeds width"
   by truncating left. When `right alone` exceeded width, cells
   were appended past the row budget — Frame width invariant
   violated, terminal showed pills cut off mid-glyph. Fix: add a
   case-3 branch that truncates from the LEFT EDGE of the right
   group (drop update / mode / pro pills first; cost / balance /
   cache live at the rightmost end and survive longest), so the
   wallet pill stays visible even on terminals where every
   optional pill is active.

Three new tests:
  · wallet preserved when right side overflows (case 2)
  · width invariant holds when right alone exceeds width (case 3)
  · inter-pill spacer is NOT collapsed (the appendCells regression)

Tests: 1732/1732 pass (1729 prior + 3 new). Lint clean.
2026-04-28 23:20:28 -07:00
esengine 28b3f40b9e feat(frame): Phase 6a — StatsPanel chrome → Frame; generic frame-render helper
Chrome row + horizontal rule + optional budget row now compile to
a single Frame via `chromeFrame()` in `src/cli/ui/chrome-frame.ts`.
App.tsx renders it via the new generic `renderFrame(f, keyPrefix)`
helper in `src/cli/ui/frame-render.tsx`, which wraps each Frame
row in `<Box height={1}><Text>{ansi}</Text></Box>` — same
single-row-Box translation the log path uses.

  · `chromeFrame(props)` composes:
      · brand wordmark + project crumb (left)
      · status pills — update, mode, pro, cost, balance, cache —
        (right, with truncate-on-narrow rules)
      · 1-row dim ─ rule
      · optional budget row (`budget  $X / $Y  (Z%)` with amber
        at 80% / red at 100%)

  · `renderFrame(f, keyPrefix)` is generic — log atoms, chrome,
    and future modals/prompt all flow through it. Phase 7's
    direct-stdout paint layer will replace this helper without
    touching call sites.

  · App.tsx no longer imports `<StatsPanel>`. The legacy file is
    untouched (tests/observability still reference some helpers)
    and can be deleted in a follow-up once the dashboard panel
    confirms it's unused too.

Tests: 1729/1729 pass (1714 prior + 15 new chrome-frame tests
covering brand / project crumb / narrow truncation / cost / mode /
pro / update / balance / cold-start cache / rule / budget / row-
width invariant under all configurations). Lint clean. Typecheck clean.

Phase 6 progress:
  · 6a chrome  ← this commit
  · 6b modals  (next: ModalCard + EditConfirm + ShellConfirm + …)
  · 6c prompt  (PromptInput + suggestion area)
2026-04-28 23:13:54 -07:00
esengine efb0a77648 feat(frame): Phase 5 — markdown → Frame compiler, restores rich text styling on assistant / plan bodies
Reuses the existing block-level parser (`parseBlocks` from
markdown.tsx) and adds a per-block Frame compiler in
`src/cli/ui/markdown-frame.ts`. Closes the visual regression
introduced in Phase 4 where assistant body / plan body fell back
to plain text in exchange for row-level scrolling.

Coverage in this first pass — most common 90% of model output:
  · paragraphs with inline markup (bold, italic, code, link, strike)
  · headings (H1–H6, bold + tone keys off level)
  · bullet lists (`- ` / `* ` / `1. `) including GFM task items
                  with `[x]` / `[ ]` indicators
  · fenced code blocks with bg tint per line
  · blockquotes (left-border + dim text, recursive on children)
  · horizontal rule

Inline parser:
  · regex shared with `markdown.tsx`'s INLINE_RE so styling
    matches the legacy renderer for the same input
  · soft-wrap at last whitespace; hard-wrap as fallback when a
    single token exceeds line budget
  · 2-wide CJK / emoji handled via the Phase-1 width module

Wiring:
  · `simpleAssistantFrame` and `complexAssistantFrame` body now
    flow through `markdownToFrame()`; empty body still falls back
    to the dim "(empty body — likely tool-call only)" placeholder
  · `planFrame` body is markdown-compiled

Deferred (still plain-text fall-back inside the markdown pipeline):
  · tables                → header row + dim body rows for now
  · Aider edit-blocks     → SEARCH/REPLACE summary as plain text
  · citation validation   → URL passes through unchanged

Also tweaks `markdown.tsx` to export the `Block` AST union so the
Frame compiler can consume it without re-defining the type.

Tests: 1714/1714 pass (1699 prior + 15 new markdown-frame tests
covering paragraphs / inline / headings / lists / task items /
code / blockquote / hr / wrap / row-width invariant / links /
strike-through). Lint clean. Typecheck clean.
2026-04-28 22:49:11 -07:00
esengine 70dcad6401 feat(frame): Phase 4 — reasoning / branch / planState / ctx-breakdown / complex assistant / plan to Frame
Migrate the remaining "complex" event roles off the ink-atom
fallback. Each sub-block has been ported from its Ink component to
a Frame builder using Phase-1 primitives, then composed into the
parent role's frame.

  · reasoningFrame      "R1 ↯ reasoning · ~Nk tok · /think for full"
                         header + violet-bordered preview body (last
                         260 chars of reasoning, italic dim).

  · branchFrame         "⎇ BRANCH ×N picked #M" pill + per-branch
                         uncertainty list with the chosen one called
                         out in cyan bold.

  · planStateFrame      One row per non-empty TypedPlanState field
                         (subgoals / hypotheses / uncertainties /
                         rejected) with its bold colored label,
                         count, and items joined by " · ".

  · ctxBreakdownFrame   `/context` 4-color stacked char-bar across
                         48 cells + legend with token counts. Used
                         to be `<CtxBreakdownBlock>`.

  · complexAssistantFrame  Composes branch / reasoning / planState /
                            body / stats / repair into one
                            assistant-accent bordered column. Body
                            is plain-text for now (markdown→Frame
                            is deferred to a future phase) — code
                            blocks / bold spans render unstyled but
                            scrolling works row-by-row.

  · planFrame           "📋 plan proposed" header + plain-text body.
                         Markdown rendering deferred (same as
                         complex assistant body).

Dispatch updated:
  · plan / ctx-breakdown / assistant-with-reasoning|branch|planState
    now produce frame atoms
  · ink fallback shrinks to: streaming assistant (transient),
    plan-replay, plan-resumed (rare turn-state events)

Tests: 1699/1699 pass (1696 prior + 3 new). Lint clean. Typecheck clean.

Visible regressions on the migrated paths:
  · markdown formatting (bold / italic / code spans / lists / code
    blocks) is rendered as plain text. The original formatted text
    still lives in `~/.reasonix/sessions/<name>.jsonl`. This is the
    last remaining trade-off; closing it requires a markdown→Frame
    compiler which is the next phase.

What's next:
  · markdown → Frame  (preserves bold / code / lists in frames)
  · frame-based ScrollBar / BottomHint  (sibling components) so the
    log-rows.tsx file can be deleted entirely
  · streaming assistant migration (live atomic frame updates as
    chunks arrive)
2026-04-28 22:42:12 -07:00
esengine 3e6fdac9c0 feat(frame): Phase 3 — user / tool compact / edit_file diff to Frame
Three more roles migrated off the ink-atom fallback. Each is now
composed from Frame primitives — no Ink layout, no flex-engine
quirks, deterministic row count.

  · userFrame   — `◇ ` glyph header + cyan accent-bar body. Wraps
                   long text across rows, accent bar continues down
                   every row. Conditional turn-separator (gradient
                   rule with centered `◆` brand mark) above when
                   `event.leadSeparator` is set.

  · toolCompactFrame — `[bar] ▣ name [duration] [summary] /tool N`,
                        single-row, color tone keys off whether the
                        result starts with `ERROR:` (red pill +
                        accent vs. cyan pill + tool-yellow accent).

  · editFileDiffFrame — multi-row block:
                          1) `▣ edit_file   diff:` header
                          2) status header line (`edited X (A→B chars)`)
                          3) magenta-pill hunk header (`@@ -N,M +N,M @@`)
                          4) body — each line gutter-glyphed and
                             tinted (`−` red for removals, `+` green
                             for additions, `  ` dim for context)

  · turnSeparatorFrame — gradient `─` rule with centered `◆` mark,
                          composed from `gradientCells()` cells.

  · rowFrame helper — concat-cells-and-pad-to-width for layouts
                       conceptually one line of mixed-style segments
                       (tool pills, header rows). Truncates if too
                       wide, right-pads if too narrow.

Tests: 1696/1696 pass (1690 prior + 6 new). Lint clean. Typecheck clean.

Remaining ink-atom escape hatch (next):
  · plan / plan-replay / plan-resumed  (uses Markdown renderer —
                                        either render markdown to
                                        Frame OR keep markdown as
                                        ink for now)
  · ctx-breakdown                       (4-color stacked char-bar)
  · assistant with branch / reasoning /
    non-empty planState                 (rich sub-blocks)
2026-04-28 22:35:58 -07:00
esengine 5ec643033c feat(frame): Phase 2 — EventLog → Frame compiler, atom slicer
Migrate the log rendering path off the hand-rolled `log-rows.tsx`
LogRow/LogBlock pipeline onto the Frame primitives from Phase 1.

  · src/cli/ui/log-frame.tsx — new module:
      · `eventToAtom(e, projectRoot, width): LogAtom` — produces
        a `frame` atom for migrated roles (info, warning, error,
        step-progress, simple finished assistant turns) and an
        `ink` atom (legacy `<EventRow>` + estimated row count) for
        roles still pending migration (user, tool, plan / replay /
        resumed, ctx-breakdown, assistant-with-reasoning/branch).
      · `viewportLog(atoms, scrollOffset, available)` — slicer that
        operates on cumulative-row coordinates and returns
        `{ atoms, topSkip, bottomSkip, totalRows, maxScrollRows }`.
        Frame atoms support row-precise clip via `topSkip`/
        `bottomSkip`; ink atoms snap (no partial rendering).
      · `renderViewport(v)` — emits each visible row of a frame
        atom as `<Box height={1}><Text>{ansi}</Text></Box>`, and
        each ink atom as its legacy ReactElement directly.

  · App.tsx wiring:
      · imports `eventsToAtoms` / `viewportLog` / `renderViewport`
        from log-frame; keeps `ScrollBar` / `BottomHint` from
        log-rows (they're orthogonal to the slicer)
      · the renderer's IIFE replaces `eventToItems` + `sliceLogItems`
        + `slice.items.map(renderLogItem)` with the new pipeline;
        `scrollMaxRowsRef` / `lastTotalRowsRef` are filled the same
        way so the keystroke handler + scrollbar still work
      · the append-anchor effect (`historical` grows while user is
        scrolled up) sums `frame.rows.length` for frame atoms and
        `atom.rows` for ink atoms — exact for migrated roles.

  · Frame composition for these 5 roles uses primitives:
      · info / warning / error → accentFrame() = vstack(per-line
        rows of indent+body) → borderLeft for the colored bar
      · step-progress → vstack(spacer, header, optional body /
        note rows). Pill is bg-styled cells via `text()`.
      · simple assistant → vstack(spacer, header w/ optional model
        badge, borderLeft+padded body, optional repair / stats
        lines)

The OLD log-rows.tsx is no longer imported for slicing; only
ScrollBar / BottomHint remain in use. It can be deleted in a
follow-up once we're confident the new path covers every scenario.

Why this is the right shape:
  · Width invariant of every Frame is asserted by the Phase-1
    tests, so cross-event row arithmetic CAN'T drift
  · Topmost / bottommost frame atom in the viewport gets row-
    precise clip — a long summary you've scrolled past now still
    contributes its lower rows correctly, no more "long entry
    disappears when scrolling up" (user complaint that originally
    motivated this whole migration)
  · Frame data is pure → tests like log-frame.test.ts (17 cases,
    added this commit) can assert exact slice behaviour without
    spinning up Ink

Tests: 1690/1690 pass (1673 prior + 17 new). Lint clean. Typecheck clean.

Phase 3 next: migrate user / tool / plan / ctx-breakdown to
Frame builders, shrinking the ink-atom escape hatch toward zero.
Once it's empty the entire log becomes one big composable Frame.
2026-04-28 22:30:01 -07:00
esengine 7f20ccf6ac feat(frame): Phase 1 — Frame primitives, width, ANSI serializer (0.13.4)
Phase 1 of the long-term Frame-compiler architecture. New
`src/frame/` module replaces the runtime dependency on Ink's
layout engine for the log region (Phase 2 next). All pure
functions over a single immutable `Frame` data type — no React,
no Yoga, no estimates.

  · types.ts        Cell + Frame types. Each Cell carries its own
                     visual width (1 or 2) and an optional `tail`
                     marker for the second half of CJK / emoji /
                     fullwidth graphemes. The row-width invariant
                     (sum of non-tail widths == Frame.width) is
                     what every primitive guarantees.

  · width.ts        Grapheme cluster aware via `Intl.Segmenter`,
                     so ZWJ emoji like 👨‍👩‍👧 count as one cell.
                     Custom char-width tables for East Asian Wide
                     ranges (Hangul, CJK Unified Ideographs A-G,
                     Hiragana, Katakana, Fullwidth, common emoji
                     blocks). Replaces the `string-width` npm
                     dependency, which Ink uses but which was the
                     cause of the dashboard-pill OSC-8 width bug.

  · frame.ts        Primitives: empty, blank, text, vstack, hstack,
                     pad, borderLeft, slice, bottom, viewport,
                     overlay, fitWidth. All composable, all
                     deterministic. `viewport(stack, offset, height)`
                     is the slicer that future log rendering will
                     use — clamps offset, never returns empty for
                     non-empty input.

  · ansi.ts         Frame → ANSI string. Style-run batching so we
                     emit ONE SGR escape per consecutive same-style
                     run instead of per-cell. Plain-text mode for
                     snapshot tests; OSC-8 hyperlink open/close
                     bracketed around linked cells.

  · index.ts        Public surface for downstream phases.

48 new tests in `tests/frame.test.ts` covering:
  · grapheme width for ASCII / CJK / emoji / combining marks / ZWJ
  · text wrapping at width boundary, hard-break on \n,
    style propagation to every cell
  · vstack / hstack with mixed widths and heights
  · pad / borderLeft / slice / viewport / overlay / fitWidth
  · the row-width invariant, asserted on every composition output
  · ANSI serialization: style runs, OSC-8 hyperlinks, plain mode
  · CJK split-clip handling in fitWidth (replace orphan head with
    space when truncation would split a 2-wide grapheme)

Tests: 1673/1673 pass (1625 prior + 48 new). Lint clean. Typecheck clean.

Phase 2 (next): convert one EventLog role at a time to produce
Frames instead of JSX, replace `log-rows.tsx`'s row pipeline with
the Frame compiler. The current `LogRow`/`LogBlock` distinction
goes away — every event compiles to a Frame, slicer is just
`viewport(vstack(...frames), offset, height)`.
2026-04-28 22:22:56 -07:00
esengine fd26900d48 chore(infra): pre-commit + pre-push git hooks via simple-git-hooks (0.13.3)
Phase 0 of the long-term Frame-compiler architecture migration:
foundation infrastructure to make sure the rest of the migration
can't accidentally ship broken.

  · pre-commit  → npm run lint     (fast, enforces format + style
                                     before staging)
  · pre-push    → npm run verify   (lint + typecheck + test, full
                                     gate before anything reaches
                                     origin)

`simple-git-hooks` chosen over husky for zero runtime overhead and
no shell-script generation magic — the hooks live as 2-line shell
files in .git/hooks/, installed by `prepare` on every npm install
so a fresh clone gets them automatically.

`verify` script added so CI / contributors can run the same gate
locally without remembering the three sub-commands.

This replaces "remember to run lint before push", which 0.13.0
demonstrated is unreliable (CI failed on 23 Biome diagnostics
because it was forgotten). Foundation for Phase 1 (Frame primitives)
which will land next.

Tests: 1625/1625 pass. Lint clean. Typecheck clean.
2026-04-28 22:15:01 -07:00
esengine baedbf7292 feat(tui): row-granular log scroll + scrollbar + bogus-Esc fix (0.13.2)
Three significant fixes / additions on top of 0.13.1:

1. **Row-granular scrolling.** `sliceVisibleEvents` is replaced by a
   pre-flattened row pipeline in `log-rows.tsx`. Each migrated event
   role decomposes into one or more `LogRow`s (each ≈ one terminal
   line); unmigrated roles fall back to a multi-row `LogBlock` that
   wraps the legacy `<EventRow>` component. Migrated this commit:
     · info / warning / error / step-progress
     · finished assistant turns (header + body lines + stats line)
   The slicer picks items by ROW range, the renderer wraps each item
   in `<Box height={1}>`, and `overflow="hidden"` + `justifyContent`
   handle clipping. Wheel = 3 rows / tick, PgUp/Dn = ~viewport.
   Append-anchor sums row counts (not event counts) so the user's
   logical scroll position is preserved exactly when content arrives.

   The earlier negative-marginTop attempt is gone — Ink's overflow=
   hidden does NOT reliably clip negative-margin children (verified
   empirically), which let log content bleed up into the chrome and
   hide the cost / cache pills. The pre-flatten approach avoids the
   layout fight entirely.

2. **Vertical scrollbar + bottom-hint.** A 1-cell column on the
   right of the log viewport renders a brand-colored thumb whose
   position and size track the visible row range. Hidden when
   `totalRows <= viewportRows`. The scrollbar component clamps its
   own offset internally so a momentarily-stale `logScrollOffset`
   can't make the thumb shrink toward zero in "scrolling into
   emptiness" territory. Paired with a `BottomHint` row that surfaces
   "↓ N rows below — End to jump" whenever the user is scrolled up,
   so newly-arrived content at the bottom is never silently missed.

3. **No more bogus "aborted by user (Esc)".** When the event loop
   was blocked >250ms (heavy Ink render on a long log), a
   multi-byte sequence like `\x1b` + `[A` (Up arrow) split across
   chunks would dispatch as `escape` THEN `upArrow` because the
   `setTimeout`-based ESC ambiguity timer fires in the timers phase
   ahead of the poll phase where stdin data events queue. The
   spurious `escape` triggered `loop.abort()`, killing the running
   turn — the same thing the PR #1 author reported as "sometimes
   it's saying the user had aborted by pressing esc when I didn't".
   Fix: defer the timer's dispatch via `setImmediate`, which runs in
   the CHECK phase after POLL — giving any queued data events a
   chance to consume the rest of the sequence first. The chunk
   handler's `cancelEscTimer` already cancels both the timeout and
   the immediate, so a real follow-up byte still wins.

Other polish:
   · `maxScrollRows = totalRows - viewportRows` (was `totalRows - 1`)
     so Home / max scroll lands on a fully-populated viewport showing
     the start of the log instead of one row visible and the rest
     empty.
   · `useEffect` clamp on `logScrollOffset` snaps it back to
     `scrollMaxRowsRef.current` when role-rendering height drifts
     mid-stream — keeps the thumb in sync with reality.

Tests: 1625/1625 pass. Lint clean. Typecheck clean.
2026-04-28 21:39:23 -07:00
esengine d82aa833c9 fix(tui): mouse wheel + bottom-anchor long events + 0.13.0 lint cleanup (0.13.1)
Three issues from 0.13.0:

  · Mouse wheel didn't scroll at all — `useAltScreen` enabled the alt
    buffer without enabling mouse tracking, so SGR wheel events from
    `stdin-reader` were never produced. The `mouseScrollUp/Down`
    handlers in App.tsx were dead.

  · A tall LATEST event clipped its bottom rows behind
    `overflow="hidden"`, so the user couldn't see the end of long
    assistant replies / big diffs. The earlier attempt used negative
    `marginTop` for row-granular scrolling, but Ink's overflow=hidden
    doesn't reliably clip negative-margin children — content bled up
    into the chrome region, hiding the cost / cache / balance pills.

  · 0.13.0 was pushed without `npm run lint`, so CI failed on 23
    Biome diagnostics (format / organizeImports / useImportType / a
    missing useCallback dep).

Mouse tracking:
  · `useAltScreen` now turns on mode 1000 + 1006 (basic button + SGR
    coords) on mount and disables on unmount / SIGINT / SIGTERM.
    Mode 1000 captures press/release only — wheel arrives as buttons
    64/65 — without intercepting drag, so terminals that honor
    `Shift + drag` for native cell selection (Windows Terminal,
    iTerm2, WezTerm, gnome-terminal, kitty, alacritty, VS Code) still
    let the user copy/paste cleanly. `/mouse off` is the escape hatch
    for terminals that don't bypass on shift.

Long-event bottom-anchoring:
  · The middle-region Box now sets `justifyContent="flex-end"` when
    `logScrollOffset === 0` so the latest event's BOTTOM aligns with
    the bottom of the viewport. A tall final entry's overflow then
    clips at the TOP — the user sees the END of the just-produced
    content, which is what they want at the "newest" anchor.
  · Scrolling up (offset > 0) flips back to `flex-start` (top-anchored)
    so reading older content starts from the slice's top edge —
    natural "scrolling back through history" mode.
  · Row-level scrolling within a single tall event is deferred — it
    needs every event role to expose a row-list representation, which
    is a larger refactor tracked separately. Until then, offset=0 +
    flex-end gives both ends of long content via offset-mode switching.

Lint/typecheck cleanup (none change behavior):
  · `import type React` reverted to `import React` (with biome-ignore)
    in `SplitDiff.tsx` and `char-bar.tsx` — JSX in classic-transform
    mode needs React in value scope.
  · `App.tsx` adds `touchedPaths` to handleSubmit's dep array.
  · `WelcomeBanner` drops a stale biome-ignore + uses `letter` as
    React.Fragment key on the wordmark (REASONIX letters are unique
    + array is fixed, so no array-index-key concern).
  · Test teardown for `process.env.HOME` keeps `delete` with a scoped
    biome-ignore — assigning `undefined` would set the literal string.
  · 16 files auto-fixed by `biome check --write` (format + import order).

Tests: 1625/1625 pass. Lint clean. Typecheck clean.
2026-04-28 21:05:51 -07:00
esengine 937b9797aa feat(tui): 0.13.0 redesign — alt-screen layout, sticky chrome, /checkpoint, side-by-side diff (0.13.0)
Breaking: TUI now takes over the alternate screen buffer (\x1b[?1049h),
which means session output is no longer captured in the user's terminal
scrollback after exit. The transcript file (~/.reasonix/sessions/<name>.jsonl)
is the durable record. Trade-off accepted in exchange for a real fixed-
header / scrollable-middle / fixed-footer layout.

Visual:
  · single-row chrome: brand + project crumb + pills (mode, cost, balance, cache)
  · WelcomeBanner: gradient REASONIX wordmark + 5 quick-start cards + live
    web-UI URL when the embedded dashboard is up
  · EventLog: ▎ accent bar on every role; ToolPill / ReasoningBlock /
    StreamingAssistant rebuilt as bracket text with phase verbs and a
    trailing ▌ blinking cursor while streaming
  · PlanStepList: tree-style ┣/┗ rows with status icons + char progress bar
  · ModalCard: full borderStyle="round" + header rule + footer slot;
    every confirm modal (Shell / Plan / Choice / Workspace / Walk / Refine)
    inherits the bordered card
  · /context now renders a 4-color stacked char-bar via a new
    ctx-breakdown DisplayRole

Behavior:
  · /checkpoint <name> + /restore — Cursor-style session-scoped snapshot
    store at ~/.reasonix/sessions/<root>/checkpoints/, replaces the
    rejected auto-commit feature
  · EditConfirm uses side-by-side diff (left old / right new)
  · /mouse [on|off] runtime toggle; mouse tracking OFF by default so
    native shift-drag selection still works
  · Idle ticker gate — when nothing is streaming or busy, the 8Hz/1Hz
    heartbeats pause so terminal text selection survives
  · Dashboard: auto-starts on launch (configurable via --no-dashboard);
    URL surfaces on the WelcomeBanner instead of a chrome pill that was
    unreliable across terminals; concurrent startDashboard() calls now
    de-dupe via an in-flight Promise ref so we don't leak listeners
  · /jobs: 5-col table with port detection from job stdout
  · /status enriched with cost / cache / budget / dashboard rows

New components:
  · SplitDiff.tsx — side-by-side diff renderer with paired cells
  · alt-screen.ts — useAltScreen hook with SIGINT/SIGTERM/exit restore
  · char-bar.tsx — CharBar / StackedCharBar reusable progress bars
  · src/code/checkpoints.ts — snapshot CRUD (15 tests)

Tests: 1625/1625 pass. Build + typecheck clean.
2026-04-28 20:14:06 -07:00
esengine 32cccfaeca feat: reasonix commit — draft commit messages from staged diff (0.12.22)
Reads `git diff --staged`, falls back to working-tree diff (with a
warning + refuses to actually commit when source is working tree),
samples the last 10 commits as a style reference, and asks DeepSeek
v4-flash to draft a message that matches the project's existing
voice. The diff IS the spec; the log is the voice.

UX:
- Print draft inside ─── separators
- [a]ccept / [r]egenerate / [e]dit (in $EDITOR) / [c]ancel prompt
- `-y / --yes` skips the prompt (CI / scripted use)
- Multi-line bodies survive: `git commit -F -` reads the message
  from stdin, no shell quoting concerns
- Pre-commit hook output / git's confirmation are inherited so the
  user sees the same final commit screen they'd see from `git commit`

Safety:
- Fails fast when not in a git repo
- Refuses to commit a working-tree-derived draft (staging area is
  empty so `git commit` would fail anyway) — prints draft for the
  user to copy after `git add`
- Caps diff at 80KB (head + tail with truncation marker) so a giant
  refactor doesn't blow the model's prompt budget; warns the user
  the resulting draft will likely be vague

Default model is v4-flash — drafting a commit message doesn't need
pro. `-m` overrides for cases where flash undercooks the message.
2026-04-28 08:45:37 -07:00
esengine c1288d3a66 feat: reasonix doctor — one-command health check (0.12.21)
When a user reports "Reasonix is broken", the support flow has been:
"check API key, try a chat, look at config.json, check Ollama if you
use semantic, …" — now `reasonix doctor` runs all of that in one go.

8 checks, run in parallel (api-reach has an 8s timeout, the rest are
local + sub-millisecond). Each returns ok / warn / fail; the summary
line counts them. Exit 1 on any fail so CI / install scripts can
fast-fail on misconfiguration; warn → exit 0.

Checks:
- api key       env DEEPSEEK_API_KEY → config.apiKey → fail
- config        ~/.reasonix/config.json present + parseable + key fields
- api reach     /user/balance reachable + balance reported
- tokenizer     data/deepseek-tokenizer.json.gz on disk + readable
- sessions      session count + total bytes + flag stale ≥90d
- hooks         global + project hook count, parse-clean
- ollama        skipped when no semantic index built; otherwise
                binary on PATH + daemon up + embed model pulled
- project       cwd has any of .git / REASONIX.md / package.json / pyproject.toml /
                Cargo.toml / go.mod — heuristic for "is this a project root?"

Plain text output (no Ink) so it works even when Ink can't mount —
the case this command is most useful in. ANSI color when stdout is
TTY, gracefully bare on TERM=dumb / piped.
2026-04-28 08:39:20 -07:00
esengine e0cdb7e7bb feat: session USD budget cap — opt-in soft circuit breaker (0.12.20)
Off by default — Reasonix's cost story is 'cheap by design,' adding a
silent cap at install would just confuse new users.

Opt in via:
- CLI flag: `reasonix chat --budget 5`, same on `code` / `run`
- Slash mid-session: `/budget 5` to set, `/budget off` to clear,
  `/budget` alone to show current spend / cap / percentage
- Config-file equivalent: not added yet; per-session override is the
  primary surface

Loop semantics (src/loop.ts):
- step() opens with a budget gate that runs BEFORE any state mutation,
  so a refusal leaves the loop unchanged — user corrects the cap and
  re-issues the same prompt cleanly.
- spent ≥ cap → yields an `error` event with a clear hint about
  /budget, returns immediately. Turn counter doesn't advance.
- spent crosses 80% of cap (one-shot, sticky via _budgetWarned) →
  yields a `warning` event noting how close the next turn is.
- setBudget(usd|null) is the mutator that resets the sticky flag so a
  user who bumps the cap mid-session sees a fresh threshold message.

UI (src/cli/ui/StatsPanel.tsx):
- One-row `budget  .XXXX / .YY  (Z%)` indicator below the metrics
  block, hidden when `budgetUsd === null`. Color: dim under 80%,
  amber 80-99%, red ≥100%.

Tests: 6 new cases in tests/loop.test.ts covering default off-state,
80% one-shot warn, no-repeat warn, refusal at cap, setBudget(null)
unblocks, setBudget(usd) re-arms warning. 1610 pass.
2026-04-28 08:24:04 -07:00
esengine bf1bb778aa fix: jobs O(N²) ready-detect + web_fetch body byte cap (0.12.19)
jobs.ts:
- ready-signal regex used to test against the FULL job.output buffer
  on every chunk, then ALSO against the chunk. With 9 regexes ×
  growing buffer × per-chunk dispatch, that's quadratic CPU during
  startup of a chatty dev server. Replace with a 1KB sliding window
  for cross-chunk matching — bounded cost regardless of total output.

web.ts:
- webFetch had no upper bound on response body size. `await resp.text()`
  pulls the entire body into memory before applying the 32K char cap;
  pointing the model at a 50MB changelog or a runaway server with no
  Content-Length pegged the heap. Now:
  - 10MB hard cap on raw body bytes
  - pre-flight check against Content-Length when the server provides it
  - streaming reader for chunked / undeclared-length responses, aborts
    cleanly once total bytes cross the cap

Tests: +2 web cases (declared-length refusal, mid-stream cap). 1604 pass.
2026-04-28 07:55:30 -07:00
esengine 0c1d80fec9 fix(hooks): cap stdout/stderr at 256KB so a runaway hook can't OOM the loop (0.12.18)
The default spawner appended every chunk into a JS string with no
upper bound. A buggy or runaway hook (`cat largefile`, infinite
`yes`, etc.) accumulated unbounded into Reasonix's heap until its
timeout fired — 5s for blocking events, 30s for logging hooks, plenty
to push the heap past comfortable limits.

Now:
- per-stream byte cap of 256KB (matches what hooks are actually for —
  short error messages, validator stderr, `git status --short`)
- raw Buffer collection + decode-once-at-close, mirroring shell.ts —
  protects against multi-byte UTF-8 sequences split across chunks
- HookSpawnResult / HookOutcome carry an optional `truncated` flag
- formatHookOutcomeMessage suffixes "(output truncated at 256KB)"
  so users know the loop didn't see the full output

Tests:
- truncation flag propagates from spawner → outcome
- format message surfaces the truncation tag
- existing 26 hook tests all pass unchanged

1602 tests pass (+3).
2026-04-28 07:47:54 -07:00
esengine 9ba7fbdf86 style: biome lint/format follow-up to 0.12.17
CI failed on lint after the 0.12.17 push:
- src/memory.ts: collapse multi-line string concat into one template
  literal (lint/style/useTemplate)
- src/usage.ts, tests/memory.test.ts, tests/session.test.ts: biome
  formatter line-width preferences (auto-fixed via npm run lint:fix)

No behavior change. 1599 tests still pass.
2026-04-28 07:43:17 -07:00
esengine 1e58cf3e4b chore: project-wide cleanup pass — MCP version, async FS walk, GC, prefix audit (0.12.17)
P0 — true bugs:
- mcp/client: clientInfo.version was hardcoded "0.3.0-dev"; now imports
  VERSION so MCP servers see the real client version

P1 — user-facing improvements:
- at-mentions: new listFilesWithStatsAsync — TUI mount no longer blocks
  on hundreds of synchronous statSync calls; picker fills in once the
  async walk completes (typically <200ms)
- usage.jsonl: auto-compaction past 5MB drops records older than 365d
  so heavy users don't accumulate unbounded telemetry on disk
- session: pruneStaleSessions() helper + new /prune-sessions slash
  command; /sessions listing flags entries idle ≥90d
- ImmutablePrefix: fingerprint is now cached + invalidated only by
  addTool. Cuts the per-render JSON.stringify+sha256 cost AND adds
  a verifyFingerprint() drift detector for catching future mutations
  that bypass addTool — Reasonix's prefix-cache hit ratio is the
  central KPI; silent prefix churn was the largest unguarded risk

UX polish:
- streaming row: "(no content)" → "(empty body — likely tool-call only)"

Tests:
- memory: fingerprint cache + dedup behavior + drift detection (5 new)
- at-mentions: listFilesWithStatsAsync mirrors sync contract (5 new)
- usage: compaction triggers past threshold, drops only old records
- session: pruneStaleSessions semantics + cutoff arg
- new tests/event-log-streaming.test.ts: lastLine bounded slicing

Total: 1599 tests pass (+20).
2026-04-28 06:59:40 -07:00
esengine 2dbf8bf723 perf(tui): streaming smoothness pass — 30Hz throttle, tick split, citation cache (0.12.16)
- FLUSH_INTERVAL_MS 100→33ms (≈30Hz) + REASONIX_FLUSH_MS env override
- lastLine bounded to tail*4 chars (was O(N) regex on full streaming buffer)
- phase pill padEnd(8) so WAITING/THINKING/DISPATCH/WRITING transitions
  don't reflow the row
- ticker: split fast(120ms) + slow(1000ms) contexts; useElapsedSeconds /
  UndoBanner countdown / ModeStatusBar jobs poller move to slow tick
- streaming row: drop the ◆/◇ pulse animation, single braille spinner
  carries the liveness signal — one less Text node + one less fast-tick
  subscriber
- citation validateCitation: mtime-keyed lineCount cache (256 LRU) so
  repeated cites of the same file skip readFileSync
2026-04-28 06:32:41 -07:00
esengine c225dad853 chore: rename preset vocabulary fast/smart/max → auto/flash/pro across user-facing surface (0.12.15)
Every user-facing string that still said fast/smart/max now says
auto/flash/pro — the canonical names presets have used since the
autoEscalate split. Touches CLI flag descriptions (chat/run/code),
/help's preset table, /preset's argHint/completer, the slash
handler's usage line.

Old config.json files keep working: resolvePreset still maps
fast → flash·effort=high, smart → auto, max → pro. What changed
is the interactive surface — /preset fast now prints usage instead
of silently doing the right thing, so the in-chat vocabulary
matches what's documented.
2026-04-28 05:55:39 -07:00
esengine a52f8facb4 feat: dashboard mirrors workspace/checkpoint/revision modals + parallel-tool deferral (0.12.14)
Three TUI confirmations the dashboard couldn't see — change_workspace,
plan checkpoints, plan revisions — now mirror to the web modal layer
with the same Switch/Deny/Continue/Revise/Stop/Accept/Reject choices
the terminal exposes.

Loop fix: when DeepSeek emitted change_workspace + write_file in one
parallel batch, the write was firing against the OLD sandbox before
the user could approve the modal — silent data loss into the wrong
project. Subsequent calls in the same batch now get a synthetic
"deferred — re-issue next turn" result; tool_call ↔ tool pairing stays
valid for DeepSeek's next-turn validator. Test in tests/loop.test.ts.

Dashboard polish:
- In-flight row shows the active tool + key args (path / command /
  char count) once tool_start fires, so write_file no longer feels hung.
- ErrorBoundary stops auto-recovering after 3 catches and renders a
  manual "Try again" button — no more silent flickering loop.
- .modal-cmd gets overflow + max-height + word-break so a pathological
  multi-kilobyte command can't push the rest of the panel offscreen.
2026-04-28 05:55:02 -07:00
esengine fed2a515be fix: scroll-up sticks during streaming (0.12.13)
Two stacked bugs let the auto-scroll keep yanking the user back
to bottom on every delta:

1. The "are they scrolled up?" listener attached via
   document.querySelector(".chat-feed") on mount — but the feed
   was conditionally rendered (only after the first message), so
   on a fresh session the listener never attached and the
   shouldAutoScroll flag was never flipped to false.

2. The auto-scroll's own scrollTop = scrollHeight write triggers
   a scroll event, which the listener was treating as a user
   scroll and snapping back to "at bottom".

Fixes:
- .chat-feed always rendered (empty state moved inside) + ref
  attaches the scroll listener on first paint.
- autoScrollInFlight ref gates the listener so only genuine
  user wheel/drag flips the guard.
2026-04-28 04:49:50 -07:00
esengine 067fcc21a4 feat: live semantic_search registration + chat banner (0.12.12)
Two questions from the user:
  - "after index ends, does it auto-register so chat can use it?"
  - "no index → put a dismissible warning at top of Chat?"

Both yes now.

Loop / prefix
- ImmutablePrefix.addTool(spec) appends to a (now-mutable) backing
  array, exposed through a readonly getter. Cost: one cache miss
  on the next turn after a tool's added; cheaper than restart.
- DashboardContext.addToolToPrefix wired from App.tsx.

Server
- runIndex on success: registerSemanticSearchTool + addToolToPrefix
- /api/overview returns semanticIndexExists (cheap stat)

Dashboard
- Top-of-Chat banner when no index, with "Build it →" (navigates
  to Semantic tab via appBus) + dismiss × (persists in localStorage)
2026-04-28 04:45:54 -07:00
esengine 957fc34c9b feat: Semantic panel guides users through missing Ollama (0.12.11)
Previously the panel just said "not reachable" with a copy-paste
command list. Now it distinguishes the three failure modes and
offers a one-click action for the two that we can resolve:

- binary missing  → Install Ollama card (macOS / Windows / Linux)
- daemon down     → "Start daemon" button (ollama serve, detached)
- model missing   → "Pull <model>" button with live progress
- all ready       → Index buttons enable

Server adds:
- GET /api/semantic returns the full checkOllamaStatus shape
- POST /api/semantic/ollama/start
- POST /api/semantic/ollama/pull (fire-and-forget; PULLS map
  carries status + last log line; SPA polls /api/semantic)
2026-04-28 04:34:06 -07:00
esengine e0e7bb91f2 feat: in-flight row at the bottom + live char counters (0.12.10)
The "turn in flight" row used to sit at the top of the chat panel,
far from the user's eyes (which are at the input). Move it to a
proper InFlightRow above the ChatStatusBar, and fill it with the
live signals the TUI showed but the web didn't:

  ⠋ thinking · 2.3s · reasoning 1,204 ch · out 0 ch · [Abort]

- Phase: thinking / streaming / waiting based on which streaming
  channel is growing
- Elapsed seconds tick every 500ms so motion is visible even
  through long deltas
- Character counts derived from the existing `streaming` state
2026-04-28 04:27:11 -07:00
esengine efd6d64176 feat: dashboard Semantic panel — index in background with live progress (0.12.9)
Previously building the index meant exiting the TUI to run
`reasonix index`. Now the dashboard has a Semantic tab that
kicks off `buildIndex` in-process and streams progress to the
SPA so users can keep coding while it runs.

Server
- src/server/api/semantic.ts — GET status / POST start / POST stop
- Per-root JobRecord captures BuildProgress via onProgress
- Wired into the /api router

Dashboard
- New Semantic sidebar tab; polls every 1.2s while running
- Shows Ollama reachability, index existence, live phase + counters
  + percentage bar + elapsed time
- Index / Rebuild / Stop buttons with appropriate disabled states
- Standalone (non-attached) dashboards explain why the panel is empty
2026-04-28 04:16:01 -07:00
esengine 44f309509e fix: split dashboard URL onto its own row (0.12.8)
0.12.7 put the URL + description on the same Ink row. On terminals
that hide the OSC 8 escape, Ink miscounts the escape bytes as visible
width — the description wrapped right through the middle of the URL.

Two stacked rows now:

  ◇ web   open the dashboard in a browser (chat · files · stats · settings)
          http://127.0.0.1:NNNN/?token=...

The URL is the only content on its line, so even a bad width
measurement can't collide with anything.
2026-04-28 04:08:18 -07:00
esengine 546e587a1e feat: auto-start dashboard + URL row in status panel (0.12.7)
Most users never discovered /dashboard existed. Now the URL is in the
status panel from the first turn, on its own row with a description.

- App auto-calls startDashboard() on mount; --no-dashboard opts out
- StatsPanel renders a dedicated row:
    ◇ web   http://127.0.0.1:NNNN/?token=...   open the dashboard
    in a browser (chat · files · stats · settings)
- URL wrapped in an OSC 8 hyperlink — clickable in iTerm2 / WezTerm /
  Windows Terminal / VS Code / recent gnome-terminal; copy-pasteable
  in older ones
- noDashboard prop threaded through App + chatCommand + codeCommand
2026-04-28 04:04:31 -07:00
esengine d58861e0d6 docs: refresh README + dynamic version on landing site
Site
- Hero badge + term-anim header now read the live npm version. i18n.js
  fetches https://registry.npmjs.org/reasonix/latest on init, caches
  it in localStorage, exposes Reasonix.version() / onVersionChange().
- term-anim subscribes and patches the .tw-ver pill in place when the
  fetch resolves, so we don't have to rerun the whole animation.
- Hardcoded "v0.6" / "v0.6.0" replaced with a {version} token in the
  translation strings; only fallback constant left to bump on major
  cuts (and the npm fetch overrides it on every visit).

README (en + zh)
- New Web dashboard section right after Quick start (0.12 headline).
- /preset and --preset references switched from the dropped legacy
  fast/smart/max vocabulary to the current auto/flash/pro.
- Stale `Reasonix v0.5.21 · ...` example refreshed to the 0.12-era
  panel header.
2026-04-28 03:52:54 -07:00
esengine c9369d7532 chore: add .gitattributes to force LF (unblocks publish on Windows)
Without this, a Windows checkout with autocrlf=true lands the working
tree with CRLF even though the repo stores LF. Biome rejects CRLF, so
prepublishOnly's `npm run lint` step fails on tests/resolve.test.ts.
Pinning eol=lf for all text files makes the working copy match what
Biome expects and what the repo stores, on every platform.
2026-04-28 03:38:19 -07:00
esengine 78e6df6a4d feat: editor polish + CI fixes + storm breaker via registry (0.12.6)
Editor
- Side-by-side diff in the edit-pending-review modal (red/green tint,
  hljs syntax highlighting, paired LCS rows). Modal payload gained
  `search`/`replace` fields (the truncated `preview` stays for old
  clients).
- Local CodeMirror bundle (`dashboard/codemirror.js`, ~937 KB) via
  scripts/bundle-codemirror.mjs — replaces 21 esm.sh imports. Server
  serves it through `serveAsset`.
- Markdown view modes: Edit / Split / Preview segmented control;
  separate Marked instance for preview so chat-renderer customizations
  don't run on user files.
- Sidebar collapses to icons (52px), persisted in localStorage.

CI / regression fixes
- Restore legacy preset migration (fast → flash+high, smart → auto,
  max → pro) so `tests/resolve.test.ts` passes again.
- Storm breaker no longer hardcodes a mutating-tools list. It accepts
  an `isMutating` predicate; `loop.ts` wires it from the existing
  ToolRegistry `readOnly` / `readOnlyCheck` flags. Buffer entries are
  tagged read-only vs mutating: a mutating call drops prior reads
  (read→edit→verify cycles no longer trip), but identical mutator
  calls still suppress on the threshold.

1571/1571 tests pass.
2026-04-28 03:26:53 -07:00
esengine 9f88f3b330 fix: highlighting + md preview (0.12.4)
- Pin @lezer/highlight and @lezer/common in esm.sh ?deps= so all
  CodeMirror packages share one copy. Previously each pack pulled
  its own, so highlight tags compared by identity stopped matching
  and oneDark silently produced no colors.
- Add markdown preview button (Edit/Preview toggle, only on .md tabs)
- Use a separate Marked instance for the preview so chat-specific
  diff/SEARCH-REPLACE code handling doesn't run on user files
2026-04-28 02:58:10 -07:00
esengine 72326254b6 feat: editor as a sidebar tab (0.12.3)
- New Editor tab in the sidebar, mounts full-width inside .main
- main-editor modifier strips panel padding so editor fills viewport
- Drawer entry still works for "click path in chat" deep-link
2026-04-28 02:45:20 -07:00
esengine baece15b65 feat: editor polish — top tabs, highlight, gutter, autocomplete (0.12.2)
- Tabs lifted out of editor-main into a full-width bar (VS Code style)
- oneDark + defaultHighlightStyle reorder so colors actually show
- Gutter restyled (dark bg, dim numbers, active-line highlight)
- foldGutter + highlightActiveLineGutter added
- autocompletion(activateOnTyping: true) + completionKeymap
- Autocomplete popup styled to dark theme
2026-04-28 02:43:11 -07:00
esengine fe9ad209eb feat: editor v2 — file tree + collapsible side (0.12.1)
- Recursive folder tree replaces flat path list (folders first, alpha)
- Collapsible side panel (◀ to hide, ▶ to restore)
- Drawer width 50% → 65% (min 360 → 420)
- Filter mode keeps the flat path list
2026-04-28 02:37:11 -07:00
esengine be7daa017c feat: web dashboard + auto/flash/pro preset rework (0.12.0)
Web dashboard at /dashboard slash — 12 panels, modal mirroring back to
the live TUI, bidirectional chat. 127.0.0.1 only, ephemeral token,
CSRF on every mutation. Preact + HTM SPA, no build step. Drawer-style
CodeMirror editor (click any path in chat tool cards).

- src/server/ — HTTP server, 16 endpoints, SSE event stream
- dashboard/ — embedded SPA (3 files, ~1600 LOC)
- src/cli/ui/slash/handlers/dashboard.ts — /dashboard slash entry
- src/cli/ui/App.tsx — broadcast hooks for events / modals / stats

Preset semantics rework: auto / flash / pro replaces fast / smart / max.
- auto: flash baseline + auto-escalate (current behavior, default)
- flash: lock to flash, no escalation
- pro: lock to pro, no downgrade
- loop.autoEscalate flag gates NEEDS_PRO marker + failure-threshold paths
- applyPresetLive callback flips loop.model + autoEscalate live (no
  session restart needed — closes the "switched to max but still on
  flash" gap the user reported)

Other:
- cacheSavingsUsd telemetry helper + UsageBucket field, surfaced in
  /stats dashboard + web Usage chart
- BUILTIN_ALLOWLIST exported, removeProjectShellAllowed +
  clearProjectShellAllowed in src/config.ts (powers Permissions panel)
- marked v12 renderer hardened (token-vs-positional + null text coerce)
- CodeMirror multi-instance bug fixed via esm.sh ?deps= pinning

1568 tests pass. Lint / typecheck / build clean.
2026-04-28 02:29:39 -07:00
esengine c594ad71f7 feat: /permissions slash + MCP Streamable HTTP transport
- /permissions list/add/remove/clear — per-project shell allowlist
  audit + edit from inside the TUI; surfaces edit-mode banner
  (yolo bypasses allowlist), refuses to clobber the read-only
  builtin list, alias /perms.
- removeProjectShellAllowed + clearProjectShellAllowed in config.ts
  for the slash to call (literal-only match, scoped per project).
- StreamableHttpTransport (MCP 2025-03-26): single endpoint, handles
  202 / application/json / text/event-stream responses, captures
  Mcp-Session-Id and echoes on subsequent POSTs, surfaces session
  expiry as a clear error.
- Spec parser: streamable+http(s):// prefix routes to the new
  transport; plain http(s):// stays SSE for back-compat. Wired
  through chat / run / mcp inspect.

1521 tests pass (+24). Lint / typecheck / build clean.
2026-04-27 22:02:18 -07:00
esengine 23c81e6f11 chore(release): 0.11.2
Split /init into its own patch release. /init landed after the
0.11.1 commit, and it's a small but distinct addition (no fix /
no behavioral change to existing flows), so a separate version
makes the changelog story cleaner: 0.11.1 is the workspace-switching
release, 0.11.2 is the project-init release.
2026-04-27 07:23:48 -07:00
esengine 0d0cdfc54a docs: fold /init into 0.11.1 changelog, restore missing 0.11.0 header
Two CHANGELOG fixes ahead of publishing 0.11.1:

1. Add a bullet for /init under 0.11.1 Added. /init was committed
   after the 0.11.1 version bump but before publication, so the
   shipped 0.11.1 actually includes it. Update the headline to
   acknowledge the addition.

2. Restore the '## [0.11.0] — 2026-04-27' header that was clobbered
   when the 0.11.1 entry was inserted earlier — the 0.11.0 content
   was orphaned without a heading.
2026-04-27 07:20:11 -07:00
esengine 60c598527d feat: /init — model-driven REASONIX.md generator
New slash command that asks the model to scan the project and write a
concise REASONIX.md baseline, removing the friction of having to
hand-author one. The file is auto-pinned into the system prompt every
launch, so a good baseline pays back on every subsequent turn.

Mechanism: handler emits a structured user-turn prompt via `resubmit`
that hard-constrains the model to a fact-only document with sections
for Stack / Layout / Commands / Conventions / Watch out for. The
"output ≤ 80 lines / 3KB" cap and "STOP after writing" line are
load-bearing — without the cap REASONIX.md would burn cache budget
every turn; without STOP flash chains follow-up suggestions and
wastes tokens.

Reuses existing filesystem tools (read_file / directory_tree /
edit_file / write_file) — no new tool, no new pipeline. The
generated content lands as a pending edit in the normal review queue,
so the user audits it via /apply before disk writes.

Edge cases:
- Outside code mode: handler returns "/init only works in code mode"
  with the `reasonix code` invocation hint.
- REASONIX.md already exists: refused, points at `/init force` to
  regenerate. Force matching is case-insensitive.

Five tests covering: refuse outside code mode, fresh-init resubmit
shape (verifies length cap + STOP marker survive future tightenings),
existing-file refusal, force override, force case-insensitivity.

1487 tests passing.
2026-04-27 06:55:20 -07:00
esengine 494c62ef60 docs: rebuild Claude-Code-on-DeepSeek section around cache_control
DeepSeek now ships an official Anthropic-compatible endpoint at
api.deepseek.com/anthropic, so the previous 'Claude Code can't run
DeepSeek' framing is factually wrong: Claude Code talks to it
unmodified.

The defense moves from 'protocol incompatible' to 'cache mechanic
incompatible':

- Anthropic native cache is marker-based: cache_control on a message
  caches up-to-this-marker as a content-addressed unit. Claude Code's
  loop is designed around this — markers compensate for an otherwise
  non-stable prefix.
- DeepSeek's auto-cache is byte-stable: it fingerprints the literal
  byte stream from 0. No markers.
- DeepSeek's compat endpoint IGNORES cache_control. Claude Code's
  main caching strategy disappears; auto-cache misses because the
  prefix wasn't byte-stable to begin with.

Reasonix's loop was designed around byte-stable prefix from line one
(append-only invariant). That's why 94.4% on the same workload
where a cache-hostile baseline lands at 46.6%.

Restructure the section into two subheaders:
- 'But DeepSeek now has an Anthropic-compatible API...' — handles
  the Claude Code case head-on with DeepSeek's compat table and the
  marker-vs-byte-stable contrast
- 'What about Aider / Cline / Continue?' — handles the natively-
  DeepSeek tools, keeps the existing 5-row DeepSeek-specific quirks
  table (R1 thinking leak, schema flatten, repair, effort, tail-only
  compaction)

Mirror everything in README.zh-CN.md.
2026-04-27 06:37:15 -07:00
esengine c43ada74e2 docs: handle 'just point Claude Code / Aider at DeepSeek' objection
The 'Why Reasonix?' section explained why we beat generic competitors,
but didn't cover the sharper rebuttal: 'I'll just point Claude Code
(or Aider, Cline, Continue) at DeepSeek and get the same economics
without your tool.' Without an answer prospects bounce silently.

Add a third subsection to 'Why Reasonix?' that handles it head-on:

- Claude Code: not really. It's hard-bound to Anthropic's API —
  auth, tool-schema shape, <thinking> parsing all assume Claude.
  A translation proxy (claude-code-router) gets you protocol
  compatibility but every Anthropic-tuning becomes overhead and
  every DeepSeek-tuning is unreachable.
- Aider / Cline / Continue: yes, they support DeepSeek and you get
  the cheap token price. What you don't get is the DeepSeek-
  specific loop work, captured in a 6-row table contrasting how
  each layer (cache markers, reasoning blocks, tool schemas,
  malformed JSON, reasoning-effort, compaction) differs between
  Anthropic/OpenAI assumptions and DeepSeek reality, with what
  Reasonix does about each.

Then drive the cache-stability claim home with concrete numbers:
generic harnesses land at 40-60% cache hit on DeepSeek vs 94.4% for
Reasonix on the same workload, which at DeepSeek's pricing is ~2.5×
on input cost alone.

Mirror in README.zh-CN.md.
2026-04-27 06:22:26 -07:00
esengine 18b8d0d8df docs: add 'Why Reasonix?' positioning section to README
The README read like a feature manual — "here's everything we have"
without ever telling a new visitor why they'd pick Reasonix over
Cursor / Claude Code / Cline / Aider. Most prospects bounce because
the unique value (DeepSeek's price × cache-first prefix engineering)
isn't visible above the fold.

Insert a "Why Reasonix?" section between Quick start and the code-
mode walkthrough, with three pieces:

1. Three short pitches: cost economics that actually land in your
   bill (~30× cheaper than Claude Sonnet, with 94% live cache hit
   verified in benchmarks/), terminal-native (no Electron / IDE
   plugin), MIT-licensed and hackable end-to-end.
2. A side-by-side comparison table — Reasonix vs the four
   alternatives, on backend / cost / runtime / license /
   cache-hit / MCP / plan mode / skills / edit review / workspace
   switch / cost dashboard / sandbox enforcement.
3. An honest "Pick something else when" section pointing at Aider,
   Cline, Cursor, and Claude Code's IDE mode for the cases where
   Reasonix's tradeoffs don't fit (multi-provider, IDE integration,
   PhD-level reasoning benchmarks, fully-local).

Also tighten the subtitle under # Reasonix to lead with the cost
angle instead of "no LangChain" (audience-correct, but doesn't
help conversion). Mirror everything in README.zh-CN.md. Bump the
test-count claim in Development from 1007 to 1482.
2026-04-27 04:37:38 -07:00
esengine 855b91c7ed feat: workspace switching (/cwd + change_workspace) + 4 fixes
Add two ways to pivot to another project mid-session:
- /cwd <path> — user-typed slash; validates target, applies via
  applyCwdChange (re-registers filesystem/shell/memory tools,
  reloads hooks, syncs loop.hookCwd, re-registers run_skill).
  MCP servers stay on the launch root (no reconnect handshake).
- change_workspace tool — model-callable, gated on a
  WorkspaceConfirm modal. Tool fn always throws
  WorkspaceConfirmationError; App detects the marker, mounts
  Switch/Deny modal; approval drives the same applyCwdChange path.
  No always-allow option — switches are per-target.

Fixes that surfaced from real-use workspace-switching attempts:
- loop: reset _turnAbort after Esc-abort branch returns. Prior
  carry-abort logic re-aborted at iter 0 on every subsequent
  step(), poisoning the session until restart.
- shell: collect Buffer chunks instead of decoding per-chunk;
  smartDecodeOutput tries strict UTF-8, falls back to GB18030 on
  Windows when invalid sequences detected. Fixes mojibake on
  Chinese-Windows cmd.exe error messages (chcp 65001 doesn't
  cover them — they come from a localized resource DLL).
- markdown: gate stripMath pipeline on a math-marker pre-check.
  The catch-all \[a-zA-Z]+ → "" had been wiping \TEST out of
  Windows paths like F:\TEST1, rendering them as F:1.
- prompt: tell the model to call change_workspace (or surface
  /cwd) when the user asks to change projects, instead of
  fumbling with cd /d / pushd / 2>&1 shell hacks.

Bump 0.11.0 → 0.11.1, CHANGELOG entry covers all four fixes plus
the two new entry points. 1482 tests passing.
2026-04-27 04:29:31 -07:00
esengine efcab7d141 chore(release): 0.11.0 2026-04-26 21:02:32 -07:00
esengine ca1406d864 feat: local semantic_search index + Ollama launcher + i18n; fix subagent abort races
Pillar 1 — semantic search (opt-in, local):
- src/index/semantic/{embedding,chunker,store,builder,tool,preflight,
  ollama-launcher,i18n}.ts — Ollama-backed local embedding index for
  the project. Cosine search over Float32 JSONL store, mtime-based
  incremental rebuild, fault-tolerant per-chunk embedding so a single
  oversized file doesn't kill the whole build.
- New CLI: `reasonix index [--rebuild --model --ollama-url --yes]`
  with TTY-aware Braille spinner + elapsed-time + phase labels (no
  more "stuck on building…"). Non-TTY path still emits one line per
  phase for CI logs.
- Preflight checks Ollama binary / daemon / model and prompts (or
  --yes auto) to fix what's missing. All user-facing strings route
  through src/index/semantic/i18n.ts (zh/en, system-locale auto-detect
  via REASONIX_LANG → LANG/LC_ALL → Intl.DateTimeFormat).
- `/semantic` slash inside reasonix code shows status + how to enable.
  No startup auto-prompt — opt-in via the explicit shell command,
  same pattern /setup and /update use.
- semantic_search tool registers only when an index exists.
- code-mode system prompt gets a routing fragment when the tool is
  registered, telling the model to prefer semantic_search for
  descriptive queries and fall back to grep for exact tokens.

Pillar 2 — fix subagent Esc race:
- DOM addEventListener("abort", …) doesn't fire for already-aborted
  signals. If the parent aborted before the listener attached, the
  child ran free until iter budget. Sync-check .aborted at attach.
- loop.ts step() reassigning _turnAbort lost prior aborted state.
  Forward the carry-over so abort() called before step() runs still
  kills it at iter 0.
- subagent treated forcedSummary assistant_final events as success,
  so /skill claimed an aborted run finished normally. Now surfaces
  forcedSummary as an error → success: false.

Tests (+27): chunker (incl. window-split + hard-truncate-overlong-line),
store roundtrip, embedAll null-slot fault tolerance, i18n locale
detection + EN/ZH dicts, /semantic slash status renderer, bootstrap
contract (no startup prompt), prompt routing fragment, and a regression
test for subagent already-aborted signal handling.
2026-04-26 20:56:53 -07:00
esengine 477e710ad6 docs: bilingual landing site + Chinese README
- docs/ landing page for GitHub Pages with i18n auto-switch (en/zh
  via navigator.language → localStorage), terminal-themed dark UI,
  hero animation that mirrors the real TUI rendering primitives
  (◇/◆ role glyphs, yellow tool pills, rounded cyan EditBlockRow
  with - red / + green diff lines, info-row pending/applied status)
- README.zh-CN.md mirroring the English README structure
- Language switcher header on README.md → zh-CN + website
2026-04-26 18:47:25 -07:00
esengine 30ee7cd818 feat: /loop interval auto-resubmit + /walk per-block edit walkthrough
- /loop <interval> <prompt> repeats the prompt every <interval> (5s..6h
  bounds, fractional + s/m/h units). One active loop per session — re-
  issuing replaces it. Cancellation: /loop stop, Esc, /clear, /new, exit,
  any user-typed prompt (loop-fired submits set a ref-flag so the timer's
  own re-submit doesn't self-cancel). LoopStatusRow ticks the countdown
  every second under the modeline. Skips a tick (re-arm in 1s) when busy
  rather than queueing duplicate submits.
- /walk steps through the pending-edits queue one block at a time using
  the existing EditConfirm modal (per-block scrollable diff). y apply ·
  n reject · a apply rest · A flip AUTO · Esc cancels (keeps remaining
  queued). Each pick mutates pendingEdits via the existing /apply [N]
  partial-apply path, then advances to the new "first" block.
2026-04-26 08:57:59 -07:00
esengine 72eb3a2a39 feat: more codex/cc/cursor parity — security-review, /test, #g, @url, yolo mode
- `/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.
2026-04-26 08:44:15 -07:00
esengine 8780dae388 chore(release): 0.8.0 2026-04-26 08:11:56 -07:00
esengine c9f3e733fa feat: codex/claudecode/cursor catch-up — #memory, -c, /review, per-hunk /apply
- `#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.
2026-04-26 08:11:45 -07:00
esengine bf9bed64e8 fix(ui): drop startup viewport clear too — VSCode wheel scroll dies on \x1b[2J
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.
2026-04-26 02:23:04 -07:00
esengine 02fcadf9e8 fix(ui): stop erasing scrollback on resize / startup so VSCode wheel-scroll works
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.
2026-04-26 00:26:39 -07:00
esengine 9254d3ae87 fix(ui): unbind history recall from arrow keys; use Ctrl+P / Ctrl+N
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.
2026-04-25 23:36:24 -07:00
esengine 1d3b9e9c77 fix(ui): revert alt-screen so mouse wheel scrolls again, restore main-screen + resize clear
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.
2026-04-25 23:13:52 -07:00
esengine 8694f7767e fix(ui): switch TUI to alternate screen buffer, fix .ts↔.tsx citation typos
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.
2026-04-25 23:04:57 -07:00
esengine 6fb3de2261 fix(ui): kill animations + gradient bars to root-cause the resize ghost stacking
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.
2026-04-25 22:41:44 -07:00
esengine f5df1f9f5f fix(ui): freeze ticker during resize bursts so animations stop ghosting
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.
2026-04-25 22:25:20 -07:00
esengine 73660729ab chore(release): 0.7.5
Visual overhaul wave on top of 0.7.4. Highlights:

  - theme module: brand teal→fuchsia gradient, semantic palette, glyph
    set + gradientCells helper used across every animated surface.
  - StatsPanel: gradient header/footer rules, neon-flowing wordmark,
    threshold-colored ▰▰▰▱ context bar, icon-prefixed metric cells.
    Animations gate at cols ≥ 100 to avoid Ink eraseLines miscount.
  - PromptInput: animated left bar (vertical gradient flow), blinking
    cursor, fuchsia-bg paste sentinels, [Ctrl+J] newline hint.
  - EventLog: full-height role bands on user + assistant + edit-file
    diffs, gradient turn separators, role-pilled headers (model in
    bg-green pill, tools in yellow/red bg pill), violet bg-pill for
    reasoning previews + diff hunks, pill-ified branch/plan-state/
    stats/step-progress/plan-resumed/plan-replay rows, semantic info
    icons (▸/▲/✓/✗/↻ auto-detected from text).
  - Markdown: H1 cyan / H2 violet / H3 fuchsia bg-pill headings,
    round-bordered code blocks with language pill, brand-color
    blockquote bar.
  - Modals: shared ModalCard frame across choice / plan / shell /
    edit / checkpoint / revise / refine — each with its own accent
    so the user learns by sight.
  - LiveRows: solid-bg pill ModeStatusBar (vim modeline feel),
    streaming phase pills (WAITING/THINKING/DISPATCH/WRITING),
    UndoBanner + SubagentRow + OngoingToolRow + StatusRow all
    pill-ified.
  - Welcome card: gradient rules + sectioned hint card on first run.
  - Misc: clear viewport + scrollback at startup, fix WelcomeBanner
    gate (was never showing because the session info row already
    populated history), markdown headings drop literal '###'.
2026-04-25 22:06:48 -07:00
esengine 701dbcc32b feat(ui): clear terminal viewport + scrollback at startup
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.
2026-04-25 22:05:37 -07:00
esengine 1603479a3d fix(ui): gate animations + secondary pills on cols≥100 to stop narrow-term flashing
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.
2026-04-25 22:01:06 -07:00
esengine d263068bb2 fix(ui): markdown headings — drop literal '###', H3 gets fuchsia pill
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.
2026-04-25 21:55:59 -07:00
esengine 83768b92e4 feat(ui): diff hunk pill, brand-color blockquote bar, paste sentinel pill
- 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.
2026-04-25 21:53:35 -07:00
esengine 9174c1ba59 feat(ui): cursor blinks, refine input wrapped in ModalCard with mode-aware accent
- 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.
2026-04-25 21:50:22 -07:00
esengine 95c978722a feat(ui): plan-resumed/replay/step badges, error/warn pills, modal frames everywhere
- 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.
2026-04-25 21:45:38 -07:00
esengine 37e741afa1 feat(ui): plan state pills, branch block redesign, semantic info icons
- 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.
2026-04-25 21:40:56 -07:00
esengine 526e3edc97 feat(ui): plan-step status pills, streaming phase pills, undo + subagent badges
- 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.
2026-04-25 21:33:14 -07:00
esengine 60024a5223 feat(ui): markdown headings get bg pills, modals share a card frame
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).
2026-04-25 21:27:33 -07:00
esengine e463fe7518 feat(ui): animated prompt bar, user-msg band, reasoning pill, pickers polished
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.
2026-04-25 21:21:13 -07:00
esengine 53ab16bab4 feat(ui): wordmark + gradient rules now flow — colors travel each tick
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.'
2026-04-25 21:05:49 -07:00
esengine 4b2f2bf183 feat(ui): full-height role bands, code block cards, modeline divider
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.
2026-04-25 20:57:02 -07:00
esengine 9d775acb94 feat(ui): theme module + gradient bars, gradient turn separator, polished metrics
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.
2026-04-25 20:50:53 -07:00
esengine 70bffed518 feat(ui): visual upgrade — pills, card-style welcome, status bar weight
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.
2026-04-25 20:41:52 -07:00
esengine 77285a251c fix(ui): WelcomeBanner gated on real conversation, not historical.length
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.
2026-04-25 20:36:19 -07:00
esengine 7f7b48021e fix(lint): biome wants the long Text body wrapped 2026-04-25 20:33:04 -07:00
esengine 732593e4ed chore(release): 0.7.4 2026-04-25 20:29:46 -07:00
esengine d4662df023 fix(input): hoist KeystrokeProvider above App; restore Ctrl+C/J + Shift+Enter
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.
2026-04-25 20:29:38 -07:00
esengine 06f4716e17 feat(ui): welcome banner on the empty session
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.
2026-04-25 18:38:17 -07:00
esengine 49d4648b07 refactor(input): replace Ink useInput with our own stdin reader
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.
2026-04-25 10:50:08 -07:00
esengine 634f8e6028 refactor(input): centralise CSI recovery in key-normalize boundary
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.
2026-04-25 09:28:44 -07:00
esengine 9d09a14f91 fix(prompt): ESC-stripped arrow keys (Windows ConPTY) move the cursor
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.
2026-04-25 09:11:00 -07:00
esengine 1c023126d9 fix(prompt): handle ESC-less bracketed-paste markers
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.
2026-04-25 09:06:21 -07:00
esengine 87d87c8f47 feat(ui): drop bordered Boxes throughout the live region
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.
2026-04-25 09:01:59 -07:00
esengine 50c757d203 fix(prompt): pin PromptInput Box to width=cols, fold Esc hint inside
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.
2026-04-25 08:34:19 -07:00
esengine 50670ee41b chore(release): 0.7.2
UX polish + two small fixes since 0.7.1:

- pickers / narrow-term reflow / multi-line indent (d6bb405)
- Wizard + SessionPicker keybinding hint unification (98f19d1)
- tool-summary suffix-match for MCP-bridged tools + write_file branch (1de2349)
- replay: align multi-line user msg under the prefix in RecordView (70e0ad1)

Tests 1264 → 1267, lint + typecheck + build clean.
2026-04-25 08:00:30 -07:00
esengine 70e0ad1aba fix(replay): align multi-line user msg under the prefix in RecordView
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.
2026-04-25 06:44:11 -07:00
esengine 1de2349350 fix(ui): tool-summary suffix-match bridges MCP-prefixed names
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.
2026-04-25 06:21:57 -07:00
esengine 98f19d1d47 chore(ui): unify keybinding hints in Wizard + SessionPicker
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.
2026-04-25 06:18:19 -07:00
esengine d6bb4054dc feat(ui): polish pickers, narrow-term reflow, multi-line indent
- ShellConfirm border yellow→red (highest-risk gate distinct from review)
- EditConfirm border cyan→yellow (decouple from PlanConfirm cyan)
- PromptInput: extract [Esc]-to-stop into separate dim row; narrow mode
  (≤90 cols) condenses prefix `you ›`→`›` with proportional indent
- EventLog: user/warning/error multi-line text now aligns under glyph
  via indentContinuationLines helper
- Slash/At/SlashArg suggestion overlays: marginTop separates from scrollback
2026-04-25 06:15:33 -07:00
esengine 9e3c62ed1e chore(release): 0.7.1 2026-04-25 04:47:34 -07:00
esengine ee274035c6 fix(loop,prompt): storm recovery, PYTHONUTF8, recency rule
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.
2026-04-25 04:47:27 -07:00
esengine 500868b490 fix(ui,prompt): paste sentinels, hard /clear, multi-line nav
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.
2026-04-25 04:47:05 -07:00
esengine 7aa71324c4 feat(md): extended markdown rendering
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).
2026-04-25 04:45:21 -07:00
esengine e530cab7a7 chore(release): 0.7.0 2026-04-24 20:14:25 -07:00
esengine bf45687414 chore(models): retire deepseek-chat/-reasoner defaults, name v4 directly
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.
2026-04-24 20:14:20 -07:00
esengine f28d27290c fix(r1): unify reasoning_content round-trip around producing model
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.
2026-04-24 20:14:05 -07:00
esengine 5453fc6dc3 refactor(plan): finish the split model started — types out, explicit barrel, per-tool helpers
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.
2026-04-24 19:55:39 -07:00
esengine 94a3c9d56e fix(choice): rewrite ask_choice guidance as one principle, not pattern list
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.
2026-04-24 19:28:50 -07:00
esengine 4cb445b280 feat(plan): /replay — Time Travel canvas for archived plans
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.
2026-04-24 19:16:18 -07:00
esengine 918ed2ca50 feat(plan): persist markdown body + add human summary field
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.
2026-04-24 19:06:43 -07:00
esengine ebc967be35 feat(plan): /plans slash — list active + archived plans for the session
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.
2026-04-24 18:55:42 -07:00
esengine 2e64d63c8b feat(plan): auto-archive completed plans for the artifact trail
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.
2026-04-24 18:50:30 -07:00
esengine 6d8a2c596c feat(loop): visible reasons for auto-escalation decisions
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).
2026-04-24 18:45:27 -07:00
esengine f6931481ba feat(plan): render full step list on resume, not just a one-liner
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).
2026-04-24 18:21:04 -07:00
esengine 15b0cfc894 feat(plan): persist structured plan state across session restarts
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.
2026-04-24 18:16:05 -07:00
esengine 331e01fda1 feat(ui): tool duration + /tool N hint on compact rows
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.
2026-04-24 18:04:07 -07:00
esengine 877a9ee03b feat(ui): compact one-line tool rendering with smart per-tool summary
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`.
2026-04-24 17:58:42 -07:00
esengine a4ff99236b feat(plan): revise_plan tool — surgical mid-flight plan edits with diff picker
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.
2026-04-24 17:38:53 -07:00
esengine c3d327e27f feat(plan): risk gutter + structured step list in plan pickers
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.
2026-04-24 10:14:48 -07:00
esengine acb3a3ffee fix(choice): make ask_choice reliably fire via tool desc + system prompt
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).
2026-04-24 09:15:28 -07:00
esengine 7e1695f945 feat(choice): ask_choice primitive for A/B/C branching decisions
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.
2026-04-24 08:44:45 -07:00
esengine 248dd134ba fix(plan): forbid submit_plan from presenting A/B/C option menus
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.
2026-04-24 08:17:02 -07:00
esengine e5a75119cb feat(plan): mid-execution checkpoints — Continue / Revise / Stop
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.
2026-04-24 08:10:56 -07:00
esengine 11155add8a feat(plan): structured steps + mark_step_complete progress rows
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.
2026-04-24 08:02:36 -07:00
esengine f82f93559b chore(release): 0.6.0
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.
2026-04-24 07:26:40 -07:00
esengine 5a7d16c24f fix(ui,prompt): dedupe edit_file result display; teach run_command its shell limits upfront
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.
2026-04-24 07:12:14 -07:00
esengine 292e51f0c2 fix(plan): render full plan body in scrollback, shrink PlanConfirm to picker only
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.
2026-04-24 07:05:40 -07:00
esengine c5b0906576 fix(skill): run_skill accepts decorated names; index uses trailing [🧬 subagent] tag
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.
2026-04-24 06:55:07 -07:00
esengine 30ca814809 feat(cost): model self-report escalation — flash emits <<<NEEDS_PRO>>>, loop retries on pro
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.
2026-04-24 06:47:31 -07:00
esengine 000e7c3ac0 docs(architecture): rewrite for v0.6 — four pillars, flash-first, new module layout
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.
2026-04-24 06:32:00 -07:00
esengine a22355a2ab feat(cost): per-turn cost badge in StatsPanel + pro armed/escalated pills
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.
2026-04-24 06:27:23 -07:00
esengine 39a4e137dc feat(cost): /pro single-turn arming + auto-escalate on repeated flash failures
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.
2026-04-24 05:51:24 -07:00
esengine 0383255de2 feat(cost): auto-compact tool results at turn end + lower proactive threshold
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.
2026-04-24 05:22:32 -07:00
esengine b2a50d50f5 feat(cost): cheap defaults everywhere — flash-first, pro opt-in, no auto-branch/harvest
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.
2026-04-24 04:59:15 -07:00
esengine e486a8e23a refactor(prompt): share TUI formatting + negative-claim rules across prompts
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.
2026-04-24 04:38:56 -07:00
esengine a4c1e9b478 refactor(ui): split slash.ts into per-topic handler modules
slash.ts had 1786 lines: types + SLASH_COMMANDS spec + parse
helpers + a ~800-line handleSlash switch + five private feature
handlers + utility helpers. Adding a command meant editing a
monolith; tests had to load the whole thing just to call one
handler. Layout:

    slash.ts                   20-line barrel (re-exports only)
    slash/types.ts             SlashResult / SlashContext / ...
    slash/commands.ts          SLASH_COMMANDS + parse functions
    slash/helpers.ts           git/memory/token/MCP utilities
    slash/dispatch.ts          SlashHandler type + registry +
                               handleSlash lookup
    slash/handlers/
      basic.ts     exit/clear/new/keys/help/setup/retry
      mcp.ts       mcp
      memory.ts    memory family
      skill.ts     skill/skills
      admin.ts     hooks/update/stats
      observability.ts   think/tool/context/status/compact
      edits.ts     undo/history/show/apply/discard/plan/mode/commit
      jobs.ts      jobs/kill/logs
      sessions.ts  sessions/forget
      model.ts     model/models/harvest/preset/branch/effort

Each handler is a plain (args, loop, ctx) => SlashResult function;
aliases (exit/quit, new/reset, skill/skills, apply-plan/applyplan,
hook/hooks, think/reasoning, help/?) are just duplicate keys in
the per-module handlers bag. The public import surface is
preserved via the barrel so App.tsx, tests, and sibling
components keep their existing imports.

Result: slash.ts 1786 -> 20 lines, fanned out into 13 focused
files each under 265 lines. Typecheck + biome + 1055 tests green.
2026-04-24 04:28:52 -07:00
esengine 9fdbdf738b refactor(ui): extract hooks + live components from App.tsx
App.tsx had grown to 2931 lines: streaming state, edit history,
pending-edits, shell/plan/edit confirm, @-picker, slash pickers,
subagent sink, hooks live-reload and cursor tracking all in one
function body. Split the cohesive clusters into dedicated modules
with no behavior change:

- LiveRows.tsx      StatusRow / ModeStatusBar / UndoBanner /
                    SubagentRow / OngoingToolRow + summarizeToolArgs
- edit-history.ts   EditHistoryEntry type + isEntryFullyUndone /
                    entryStatus / format{EditResults,PendingPreview,
                    UndoRows} / describeRepair
- useEditHistory    session-scoped /undo /history /show machinery
- useCompletionPickers  slash-name, @-mention, slash-arg pickers
- useSessionInfo    mount-time fetch of balance / models /
                    latestVersion + refresh callbacks
- useSubagent       subagent sink ref + live activity row

Also drops two dead helpers (formatQueuedEditPreview,
formatUndoResults) that had no callers.

Result: App.tsx 2931 -> 1984 lines (-32%). Typecheck + biome +
1055 tests green.
2026-04-24 04:28:33 -07:00
esengine f3f844b3dc fix(lint): pass biome check for 0.5.24 (format + unused template + exhaustive deps + comma/assign)
- 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.
2026-04-24 02:23:37 -07:00
esengine d65ca4f67f feat(code): review/auto edit gate, background jobs, context hygiene (0.5.24)
- 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)
2026-04-24 02:17:34 -07:00
esengine ee577995d0 fix(errors): actionable messages for 401/402/422 + V4 context-overflow hint (0.5.23)
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.
2026-04-23 21:22:14 -07:00
esengine e3d6fe3a86 fix(client): bump default timeout past DeepSeek's 10-min queue cap (0.5.22)
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.
2026-04-23 21:17:04 -07:00
esengine bfc4cd38ee docs(readme): update for V4 models, /effort, /resource, /prompt, 1M context, !/@ shortcuts
- 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.
2026-04-23 21:13:00 -07:00
esengine 0ccc419d0d feat(v4): integrate DeepSeek V4 — models, pricing, thinking toggle, effort control (0.5.21)
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.
2026-04-23 21:10:13 -07:00
esengine 7542aca687 feat(ui): show "N ready · building call M" during multi-tool turns (0.5.19)
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.
2026-04-23 20:18:10 -07:00
esengine 1e906bb577 fix(r1): round-trip reasoning_content on EVERY reasoner assistant turn (0.5.18)
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.
2026-04-23 20:03:06 -07:00
esengine a8c367ad0c fix(citation): leading / resolves to project root, not filesystem root (0.5.17)
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.
2026-04-23 19:57:49 -07:00
esengine 2d35cab39e fix(plan): actually stop the flicker — pause ticker, tighten clamp, stabilize onChoose (0.5.16)
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.
2026-04-23 19:54:19 -07:00
esengine 874d7df2f7 fix(r1): round-trip reasoning_content through tool loop (0.5.15)
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.
2026-04-23 19:50:18 -07:00
esengine 4d39744d99 feat(0.5.14): visible/durable/reachable + plan-flicker + pending-edit persistence
- !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.
2026-04-23 19:44:28 -07:00
esengine 74da4f2a92 revert /edit slash + fix picker blocking Enter on exact match (still 0.5.13)
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.
2026-04-23 19:08:14 -07:00
esengine 36f6d245f9 feat(ui): argument-level pickers for slash commands (0.5.13)
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.
2026-04-23 19:02:38 -07:00
esengine a44c23c0a8 feat(ui): @-picker recency ranking + /keys cheatsheet (0.5.12)
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.
2026-04-23 18:54:04 -07:00
esengine 337ded3839 feat(code): unified-diff preview for pending edit blocks (0.5.11)
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.
2026-04-23 18:47:01 -07:00
esengine 8ec6c630bd feat(slash): /edit <file> <instruction> — one-shot surgical edit (0.5.10)
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.
2026-04-23 18:41:12 -07:00
esengine a787272ceb feat(ui): collapse large user pastes in Historical display (0.5.9)
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.
2026-04-23 18:37:26 -07:00
esengine 0ca16d6e2d feat(ui): !cmd bash-mode prefix — user-typed shell passthrough (0.5.8)
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.
2026-04-23 18:31:30 -07:00
esengine ecf2ea372b feat(ui): @mentions picker + post-build bundle smoke test (0.5.7)
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.
2026-04-23 18:14:46 -07:00
esengine 335de43db5 fix(tokenizer): resolve data-file path in bundled builds (0.5.6)
**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.
2026-04-23 17:58:35 -07:00
esengine af077ddb24 feat: @file mentions in code mode + session-load heal → tokens (0.5.5)
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.
2026-04-23 17:48:50 -07:00
esengine 84ea648c84 feat(loop): preflight context-size check before each request (0.5.4)
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.
2026-04-23 17:32:09 -07:00
esengine 2d95c5787d feat(loop): token-aware /compact + auto-compact (0.5.3)
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.
2026-04-23 17:21:02 -07:00
esengine 19a2b8d2be feat(tools): token-aware tool-result truncation at dispatch (0.5.2)
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.
2026-04-23 16:52:23 -07:00
esengine ca27ca50bf fix(shell): reject shell operators (|, >, <, &, &&, ||, 2>) with a clear error (0.5.1)
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).
2026-04-23 16:38:27 -07:00
esengine d4615d6e76 chore(0.5.0): fix CI + add animated SVG logo
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.
2026-04-23 09:34:25 -07:00
esengine 9eff2e2cfc feat(0.5.0): Reasonix visual identity + DeepSeek tokenizer + models/pricing/context
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.
2026-04-23 09:28:40 -07:00
esengine c2f8e9b734 feat(0.4.28): reasonix code defaults harvest OFF — opt in via --harvest
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.
2026-04-23 05:13:20 -07:00
esengine d52599ec44 feat(0.4.27): citation-first answers — validated [text](path:line) links + broken-citation surface
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.
2026-04-23 04:47:10 -07:00
esengine 3c8669577d feat(0.4.26): subagents-via-Skills + search_content + render/shell/sandbox fixes
- 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.
2026-04-23 02:30:15 -07:00
esengine 3fee4e6883 feat: reasonix stats — cross-session cost dashboard + /stats slash (0.4.24)
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.
2026-04-22 22:24:59 -07:00
esengine 41d21f7cea feat(slash): /update shows current vs latest + shell command (0.4.23)
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.
2026-04-22 22:13:32 -07:00
esengine 715d8b5950 feat: hooks — user-defined automation at PreToolUse / PostToolUse / UserPromptSubmit / Stop (0.4.23)
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.
2026-04-22 22:06:29 -07:00
esengine 911f043db8 feat: version display in TUI header + reasonix update self-upgrade (0.4.22)
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.
2026-04-22 21:34:11 -07:00
esengine ce85319c9b docs(readme): promote reasonix code to the hero section, document skills
- 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.
2026-04-22 19:07:44 -07:00
esengine 2a9a9b386b feat: skills — project/global SKILL.md packs pinned into the prefix + shell fixes (0.4.21)
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.
2026-04-22 18:58:48 -07:00
esengine e3cfbb58dd feat: user memory — ~/.reasonix/memory/ pinned into the immutable prefix · remember/forget/recall tools · prompt cleanup (0.4.20)
- 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.
2026-04-22 17:30:26 -07:00
esengine becaf487e8 fix(shell): use path.win32.join so CI tests with platform:win32 pass on Linux
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.
2026-04-22 06:38:41 -07:00
esengine 6111d8f621 fix(loop): surface StormBreaker suppression as a visible warning + reset on user turn
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.
2026-04-22 06:35:13 -07:00
esengine d8ba9f9669 fix(shell): Windows — PATHEXT resolution + cmd.exe wrapping for .cmd/.bat (0.4.19)
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.
2026-04-22 06:09:11 -07:00
esengine e409e9d8d9 feat: Plan Mode — autonomous plan proposals + /plan gate + answer-questions flow (0.4.18)
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.
2026-04-22 05:50:28 -07:00
esengine 4d21ca4c4c feat: project memory — REASONIX.md pinned into the immutable prefix (0.4.17)
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.
2026-04-22 04:55:06 -07:00
esengine 1ccc1d7e67 feat: run_command shell tool · session picker · ShellConfirm picker · backspace/markdown fixes (0.4.16) 2026-04-22 04:43:17 -07:00
esengine fd344986e8 feat: web_search via Mojeek · cursor editing in prompt · REASONIX_UI=plain · ticker consolidation (0.4.15) 2026-04-22 04:05:25 -07:00
esengine 6ceb73d367 fix(ui): consolidate timers · patchConsole:false · REASONIX_UI=plain opt-out (0.4.14) 2026-04-22 02:35:02 -07:00
esengine dee96f66a2 fix(ui): tool_call_delta progress · reset streamRef per iter · expanded README (0.4.13) 2026-04-22 01:59:44 -07:00
esengine 6b4d8652e4 fix(loop): full tool_calls↔tool pairing validator + auto-compact on context-guard (0.4.12)
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).
2026-04-22 01:07:07 -07:00
esengine 5f7d8f238a feat: git-diff edit_file · /new clears context · clearer phase labels (0.4.11)
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).
2026-04-22 00:52:13 -07:00
esengine dc38c765e8 feat: status indicators · live stats · balance · in/out cost split · edit_file diff · GFM tables (0.4.10)
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).
2026-04-22 00:39:07 -07:00
esengine 59bd38b1aa feat: Esc cancels immediately · native fs tools · cursor fix · slow_count demo (0.4.9)
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).
2026-04-22 00:14:56 -07:00
esengine 3484c04133 feat(mcp): progress notifications — live progress bar in spinner (0.4.8)
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).
2026-04-21 23:54:11 -07:00
esengine 7075608ddc feat(ux): multi-line prompt input — Ctrl+J · Shift+Enter · '\<Enter>' (0.4.7)
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).
2026-04-21 23:47:04 -07:00
esengine 27a32b7b94 feat(ux+mcp): slash autocomplete · drop footer · /mcp rich view · mcp inspect CLI (0.4.6)
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).
2026-04-21 23:39:48 -07:00
esengine 1391534f6c feat(repair+mcp): DSML scavenge + MCP resources/prompts (0.4.5)
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).
2026-04-21 22:13:43 -07:00
esengine 169d66d46a feat(ux): /tool slash — inspect untruncated tool output (0.4.4)
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).
2026-04-21 21:41:30 -07:00
esengine 2836b5d406 fix(loop): Esc abort no longer blocks for 30-90s + bump to 0.4.3
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.
2026-04-21 21:31:59 -07:00
esengine d0bd6852c1 feat(ux): /retry · /status rich · /think · ↑↓ history · y/n · red errors · tool-row elapsed · reasoning tail · DSML strip (0.4.2)
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.
2026-04-21 21:26:42 -07:00
esengine cb2f2a550b feat(ux): tool-row elapsed + args · reasoning tail · /think (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.
2026-04-21 21:05:44 -07:00
esengine e472f4cb79 feat(code): /apply gate + /undo + /commit + .gitignore + better UX signals (0.4.1)
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.
2026-04-21 20:53:53 -07:00
esengine 14887264bb feat(code): reasonix code — SEARCH/REPLACE editing as a first-class mode (0.4.0)
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).
2026-04-21 20:05:45 -07:00
esengine 63ced2fa5b feat: Esc to abort + 70% budget warning + README refresh (0.3.2)
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.
2026-04-21 19:50:52 -07:00
esengine 461e736cbc fix(loop): force summary when maxToolIters is reached (0.3.1)
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.
2026-04-21 19:40:15 -07:00
esengine d932c50ab3 release: v0.3.0 — context gauge + /compact + stable graduation
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.
2026-04-21 19:35:36 -07:00
esengine b4c461c6ad fix(mcp): cap tool-result size + annotate context-overflow errors
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.
2026-04-21 19:22:58 -07:00
esengine 2f4e28b7cb feat(ux): setup wizard + config defaults — reasonix with no args just works
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.
2026-04-21 19:14:59 -07:00
esengine 5f715d05ee feat(mcp): SSE transport — remote/hosted servers via --mcp "https://…"
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.
2026-04-21 18:55:06 -07:00
esengine b662c63894 data(mcp): multi-server live run — 2 subprocesses, 1 prefix hash,
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).
2026-04-21 18:41:29 -07:00
esengineandClaude Opus 4.7 e793c7d59d chore(release): v0.3.0-alpha.3 — multi-server MCP + mcp list discovery
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]>
2026-04-21 18:31:33 -07:00
esengineandClaude Opus 4.7 7cd862194a feat(mcp): multi-server support — repeatable --mcp with per-server names
`--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]>
2026-04-21 18:22:53 -07:00
esengineandClaude Opus 4.7 407793c99e chore(release): v0.3.0-alpha.2
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]>
2026-04-21 18:08:27 -07:00
esengineandClaude Opus 4.7 5e124cec36 feat(mcp): cross-platform shell fix + second live data point via
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]>
2026-04-21 18:04:09 -07:00
esengineandClaude Opus 4.7 7fce6e650c chore(release): v0.3.0-alpha.1 — MCP client + first live run
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]>
2026-04-21 17:52:54 -07:00
esengineandClaude Opus 4.7 5941043489 feat(mcp): CLI --mcp flag + bundled demo server + subprocess integration test
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]>
2026-04-21 17:30:33 -07:00
esengineandClaude Opus 4.7 f142f8874d feat(mcp): v0.3 foundation — stdio client + ToolRegistry bridge
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]>
2026-04-21 17:04:16 -07:00
esengineandClaude Opus 4.7 fb5977743c data(harvest-bench): 18-run set + honest findings — harvest doesn't
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]>
2026-04-21 09:47:01 -07:00
esengineandClaude Opus 4.7 26b50e9242 feat(harvest-bench): 3 hard tasks + --timeout flag
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]>
2026-04-21 09:16:18 -07:00
esengineandClaude Opus 4.7 7233eddced data(harvest-bench): first 9-run live data + honest findings
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]>
2026-04-21 09:09:34 -07:00
esengineandClaude Opus 4.7 3a92ba2787 feat(bench): harvest eval harness — Pillar 2 scaffold
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]>
2026-04-21 08:53:01 -07:00
esengineandClaude Opus 4.7 6307b92af2 feat(cli): reasonix sessions — list + inspect saved chats
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]>
2026-04-21 08:39:14 -07:00
esengineandClaude Opus 4.7 2e42ae53aa feat(diff): show harvest-signal deltas in summary + markdown
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]>
2026-04-21 08:36:38 -07:00
esengineandClaude Opus 4.7 5ff0ef4535 chore(ci+examples): bench dry-run in CI + programmatic replay/diff example
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]>
2026-04-21 08:32:51 -07:00
esengineandClaude Opus 4.7 ce963be2e2 fix(ui): plan state colors — semantic + readable on dark terminals
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]>
2026-04-21 08:28:17 -07:00
esengineandClaude Opus 4.7 e5357f0df5 feat(cli): reasonix run gains --harvest / --branch / --transcript
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]>
2026-04-21 08:15:40 -07:00
esengineandClaude Opus 4.7 c148b342fc feat(harvest): thread planState through transcripts + replay UIs
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]>
2026-04-21 08:11:01 -07:00
esengineandClaude Opus 4.7 74e796b1c6 chore(release): v0.2.2 — 48-run bench, 100% reasonix pass rate
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]>
2026-04-21 08:00:47 -07:00
esengineandClaude Opus 4.7 c1965b1d1e fix(bench): relax t05 predicate — cancelled is an acceptable alternative to refused
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]>
2026-04-21 07:16:12 -07:00
esengineandClaude Opus 4.7 725cb16ff8 chore(release): v0.2.1
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]>
2026-04-21 07:11:26 -07:00
esengineandClaude Opus 4.7 ceb4840a63 feat(diff): split-pane Ink TUI with n/N divergence jump
`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]>
2026-04-21 07:01:41 -07:00
esengineandClaude Opus 4.7 4bca4cedd8 feat(replay): Ink TUI for transcript browsing
`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]>
2026-04-21 06:53:50 -07:00
esengineandClaude Opus 4.7 736611293f chore(release): v0.2.0
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]>
2026-04-21 06:44:37 -07:00
esengineandClaude Opus 4.7 dc5a65b02b fix(bench+diff): per-sub-call baseline transcripts + clearer labels + reference artifacts
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]>
2026-04-21 06:25:02 -07:00
esengineandClaude Opus 4.7 a930d1818a feat(v0.2 MVP): transcript replay + diff — offline cache/cost auditing
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]>
2026-04-21 06:11:15 -07:00
esengineandClaude Opus 4.7 7fed18fc47 feat(bench): τ-bench-lite harness + v0.1 validation data
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]>
2026-04-21 05:36:39 -07:00
esengine cc53474d56 feat(cli): session-by-default + /forget command
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).
2026-04-21 04:24:14 -07:00
esengine 359bd6bba3 feat(session): named session persistence — resume prior chats
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.
2026-04-21 04:19:56 -07:00
esengine ff91ff91f0 fix(markdown): belt-and-braces LaTeX stripping + regression tests
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.
2026-04-21 04:13:56 -07:00
esengine c72b429d82 fix(markdown): cover \dfrac/\tfrac/\binom + Unicode subscripts/superscripts
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.
2026-04-21 04:07:29 -07:00
esengine 989d8b33d8 style: biome formatter cleanup 2026-04-21 04:03:41 -07:00
esengine c40afe5caf fix(branch): show progress state + elapsed timer from second 0
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.
2026-04-21 04:03:07 -07:00
esengine 30ebd1353a feat(tui): /preset one-tap configs + persistent command strip
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.
2026-04-21 03:58:58 -07:00
esengine ffc872ae12 fix(branch): live progress feedback + correct cost aggregation across all samples
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.
2026-04-21 03:55:50 -07:00
esengine c04e71ee9b feat(cli): slash commands — toggle model/harvest/branch inside the TUI
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).
2026-04-21 03:47:31 -07:00
esengine 2169ad233f feat(consistency): self-consistency branching + major README refresh
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.
2026-04-21 03:42:48 -07:00
esengine 8c426595fa feat(pillar3): auto-flatten deep/wide tool schemas in ToolRegistry
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.
2026-04-21 03:36:02 -07:00
esengine 2e3c479402 feat(pillar2): R1 Thought Harvesting MVP (opt-in)
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.
2026-04-21 03:22:43 -07:00
esengine c4dd646642 fix(tui): keep TextInput mounted across turns to retain stdin raw mode
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.
2026-04-21 03:17:31 -07:00
esengine c0bc69e879 feat(cli): first-run setup prompts for API key, saves to ~/.reasonix/config.json
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.
2026-04-21 03:12:11 -07:00
esengine 437e5cc41f fix(pkg): drop leading ./ from bin path so npm keeps the entry
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.
2026-04-21 03:02:56 -07:00
esengine f1b740596c feat(client): exponential-backoff retry for transient API failures
- 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.
2026-04-21 02:15:50 -07:00
esengine d626b639fa style(tui): add blank line between reasoning preview and answer body 2026-04-21 02:10:54 -07:00
esengine f413c4dc6c style(tui): space out markdown blocks + compact reasoning preview
- 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.
2026-04-21 02:06:54 -07:00
esengine 2199a21c4d fix(tui): eliminate streaming/final duplicate + broader LaTeX strip
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.
2026-04-21 02:03:27 -07:00
esengine b7f29c384a fix(tui): eliminate flicker + render Markdown properly
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.
2026-04-21 01:59:09 -07:00
esengine 0f0a44a00c fix(tui): surface per-turn stats and R1 reasoning in the chat UI
- 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.
2026-04-21 01:44:01 -07:00
esengine 214dc13a38 feat(validation): bake measured DeepSeek API numbers into README + loop integration tests
- 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)
2026-04-21 01:42:34 -07:00
esengine 785f4d65c8 chore: ignore *.jsonl transcripts (accidental session.jsonl leak) 2026-04-21 01:34:21 -07:00
esengine 05298c0faf fix: load .env in examples and benchmark entrypoints
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.
2026-04-21 01:33:47 -07:00
esengine cc3d2bfcb1 chore: satisfy biome lint (rename shadowed globals, add missing hook dep) 2026-04-21 01:28:42 -07:00
esengine e9e7ccc622 Initial commit: Reasonix v0.0.1 — DeepSeek-native agent framework
Three-pillar design optimized for DeepSeek's economic and behavioral profile:
  - Pillar 1: Cache-First Loop (immutable prefix + append-only log + volatile scratch)
  - Pillar 2: R1 Thought Harvesting (stub surface, full impl in v0.2)
  - Pillar 3: Tool-Call Repair (scavenge + truncation + storm + flatten — complete)

Stack: TypeScript / Node 20+ / ESM. Ink + React TUI with live cache-hit and
cost panel. Streaming via SSE. Vitest (41 passing tests), tsup, biome.
2026-04-21 01:25:12 -07:00
11523 changed files with 124736 additions and 1366306 deletions

No files matched your search

+4 -5
View File
@@ -1,5 +1,4 @@
# Copy to .env and fill in. Only secrets belong here — a provider's base_url and
# model are configured in reasonix.toml, where api_key_env points at these variables.
DEEPSEEK_API_KEY=
MIMO_API_KEY=
DEEPSEEK_API_KEY=sk-your-key-here
DEEPSEEK_BASE_URL=https://api.deepseek.com
REASONIX_LOG_LEVEL=INFO
REASONIX_TRANSCRIPT_DIR=./transcripts
+11 -33
View File
@@ -1,33 +1,11 @@
.gitattributes text eol=lf
.gitignore text eol=lf
.npmrc text eol=lf
*.astro text eol=lf
*.bat text eol=crlf
*.css text eol=lf
*.go text eol=lf
*.golden text eol=lf
*.html text eol=lf
*.js text eol=lf
*.json text eol=lf
*.md text eol=lf
*.mjs text eol=lf
*.mod text eol=lf
*.nsi text eol=lf
*.plist text eol=lf
*.py text eol=lf
*.rs text eol=lf
*.sh text eol=lf
*.sql text eol=lf
*.sum text eol=lf
*.toml text eol=lf
*.ts text eol=lf
*.tsx text eol=lf
*.txt text eol=lf
*.xml text eol=lf
*.yaml text eol=lf
*.yml text eol=lf
Makefile text eol=lf
.githooks/** text eol=lf
benchmarks/**/*.sh text eol=lf
internal/runtime/agent/testdata/perseveration/** -text
desktop/frontend-next/perf/media/delivery.pdf binary
# Force LF line endings on every checkout, regardless of platform.
# Biome's formatter is strict about CRLF — without this, a Windows clone
# with autocrlf=true will land with CRLF in the working tree even though
# the repo stores LF, and `npm run lint` (and prepublishOnly with it)
# fails. See docs/style.md if you ever add binary types here.
* text=auto eol=lf
# Lockfiles + the codemirror bundle are generated; treat them as
# auto-detected text but never coerce.
package-lock.json text eol=lf
dashboard/codemirror.js text eol=lf
-6
View File
@@ -1,6 +0,0 @@
#!/bin/sh
# Go-native pre-push gate replacing the retired v1 npm hook (install: make hooks).
# Full tests run in CI; vet is the fast, cross-platform local check.
set -e
go vet ./...
go run ./tools/repolint
-44
View File
@@ -1,44 +0,0 @@
# Ownership for the studio line. Standard: docs/DOCS_STANDARD.md.
#
# Each rule lists exactly two owners: primary first, backup second.
# GitHub requests review from both. The last matching rule wins.
# repolint (codeowners, doc-owner) fails a rule for a missing path, a rule
# without a backup, and a document header that names different owners.
# Default: kernel, Studio shell, tooling, standing instructions.
* @esengine @SivanCola
# User-facing guides and references.
/docs/ @SivanCola @esengine
/docs/THEME_AUTHOR_GUIDE.md @esengine @SivanCola
/sdk/ @SivanCola @esengine
/README.md @SivanCola @esengine
/README.zh-CN.md @SivanCola @esengine
/SECURITY.md @SivanCola @esengine
# Contracts and processes the Studio line runs on.
/docs/DOCS_STANDARD.md @esengine @SivanCola
/docs/STUDIO_*.md @esengine @SivanCola
/docs/SESSION_MEMORY_RETRIEVAL.md @esengine @SivanCola
/docs/*_CONTRACT.md @esengine @SivanCola
/docs/TOOL_APPROVAL_MODES.md @esengine @SivanCola
/docs/CAPABILITY_DIAGNOSTICS.md @esengine @SivanCola
/docs/CHECKPOINTS.md @esengine @SivanCola
/docs/EXTENSION_*.md @esengine @SivanCola
/docs/SUBAGENT_*.md @esengine @SivanCola
/docs/ROADMAP.md @esengine @SivanCola
/docs/MIGRATING.md @esengine @SivanCola
/docs/design/ @esengine @SivanCola
/release-notes/ @esengine @SivanCola
# Release signing: provider policy, its contract and the workflow that uses it.
/.signpath/ @esengine @SivanCola
/.github/workflows/release-studio.yml @esengine @SivanCola
/.github/workflows/studio-certum-signing-smoke.yml @esengine @SivanCola
/.github/actions/setup-certum/ @esengine @SivanCola
/cmd/signpath-contract/ @esengine @SivanCola
/scripts/install-smoke.ps1 @esengine @SivanCola
/scripts/sign-certum.ps1 @esengine @SivanCola
/scripts/verify-windows-authenticode.ps1 @esengine @SivanCola
/scripts/verify-windows-package.ps1 @esengine @SivanCola
/scripts/windows-signing-lib.ps1 @esengine @SivanCola
+1
View File
@@ -0,0 +1 @@
github: esengine
+23
View File
@@ -0,0 +1,23 @@
---
name: Bug report
about: Something is broken
labels: bug
---
**What happened**
A clear and concise description.
**Expected**
What you expected to happen.
**Reproduction**
Steps or minimal code that reproduces it.
**Environment**
- Reasonix version:
- Node version:
- OS:
- DeepSeek model (e.g. `deepseek-chat`, `deepseek-reasoner`):
**Logs / transcript**
If using the CLI, attach the relevant chunk of `--transcript`.
-62
View File
@@ -1,62 +0,0 @@
name: Bug report
description: Report a bug in DeepSeek-Reasonix
title: "[Bug]: "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Thanks for filing a bug. Pick which version line you're on below — it gets
labeled automatically, no maintainer action needed. Not sure which line
you run? See the [version roadmap](https://github.com/esengine/DeepSeek-Reasonix/discussions/10748).
- type: dropdown
id: version-line
attributes:
label: Version line
description: Which line are you running?
options:
- "2.x — Reasonix Studio, studio branch (active development)"
- "1.x — main-v2 branch (maintenance / stable)"
- "0.x — legacy TypeScript (maintenance only)"
validations:
required: true
- type: input
id: version
attributes:
label: Exact version
description: Output of `reasonix --version`, or the version shown in Studio's settings.
placeholder: e.g. 2.20.0 or 1.39.0
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: What happened?
description: A clear description of the bug, and what you expected instead.
validations:
required: true
- type: textarea
id: repro
attributes:
label: Steps to reproduce
placeholder: |
1. ...
2. ...
3. ...
validations:
required: true
- type: input
id: os
attributes:
label: OS / platform
placeholder: e.g. macOS 15.3 (arm64), Ubuntu 24.04, Windows 11
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant logs or output
description: Paste any error output. Automatically formatted as code.
render: shell
validations:
required: false
-14
View File
@@ -1,14 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Version roadmap (1.x / 2.x)
url: https://github.com/esengine/DeepSeek-Reasonix/discussions/10748
about: Which line to use, which branch takes which changes, and where Reasonix is heading.
- name: Questions & discussions
url: https://github.com/esengine/DeepSeek-Reasonix/discussions
about: For usage questions, ideas, and general discussion — please use Discussions instead of opening an issue.
- name: Discord
url: https://discord.gg/XF78rEME2D
about: Bilingual community chat for setup help, workflow showcases, and feature ideas.
- name: QQ group (DeepSeek-Reasonix官方群, 1093562660)
url: https://qm.qq.com/q/i59b0z2R8s
about: Chinese-language community chat for setup help and everyday questions.
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Propose a new behavior or enhancement
labels: enhancement
---
**Problem**
What real problem does this solve? Who hits it?
**Proposed change**
What you'd like reasonix to do differently. Include a sketch of the
UX or API if relevant.
**Alternatives considered**
What else you tried or thought about. "I just want it" is not an
alternative.
**Scope check**
- [ ] This belongs in core reasonix (not better as a separate npm package)
- [ ] I've read CLAUDE.md and CONTRIBUTING.md
@@ -1,30 +0,0 @@
name: Feature request
description: Suggest an idea or improvement
title: "[Feature]: "
labels: ["enhancement"]
body:
- type: dropdown
id: version-line
attributes:
label: Version line
description: Which line is this for?
options:
- "2.x — Reasonix Studio, studio branch (active development)"
- "1.x — main-v2 branch (maintenance / stable)"
- "0.x — legacy TypeScript (maintenance only)"
validations:
required: true
- type: textarea
id: problem
attributes:
label: What problem does this solve?
description: What are you trying to do, and what gets in the way today?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: How would you like it to work?
validations:
required: false
+20
View File
@@ -0,0 +1,20 @@
<!-- Read CONTRIBUTING.md first if this is your first PR. -->
## What
<!-- One paragraph: what does this change? -->
## Why
<!-- Bug fix? Pre-existing issue? Linked discussion? -->
## How to verify
<!-- Steps the reviewer can run. `npm run verify` is assumed. -->
## Checklist
- [ ] `npm run verify` passes locally (lint + typecheck + tests + comment-policy gate)
- [ ] No `Co-Authored-By: Claude` trailer in commits
- [ ] Comments follow CONTRIBUTING.md (no module-essay headers, no incident history)
- [ ] No edits to `CHANGELOG.md` — release notes are maintainer-written at release time
-35
View File
@@ -1,35 +0,0 @@
name: Connect to Certum cloud signing
description: Verify the pinned SimplySign installer and connect to the configured certificate.
inputs:
username:
required: true
description: SimplySign account
otp-uri:
required: true
description: TOTP provisioning URI
thumbprint:
required: true
description: Expected SHA-1 certificate thumbprint
runs:
using: composite
steps:
- name: Verify SimplySign installer
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
Invoke-WebRequest 'https://files.certum.eu/software/SimplySignDesktop/Windows/9.4.3.90/SimplySignDesktop-9.4.3.90-64-bit-en.msi' -OutFile SimplySignDesktop.msi
$hash = (Get-FileHash -Algorithm SHA256 SimplySignDesktop.msi).Hash
if ($hash -ne 'CE2B38EF0124A574BC08E5558726099CAAC79A7C58B8D3D712F629371FE1BCB7') {
throw "SimplySign installer SHA-256 $hash does not match the pinned 9.4.3.90 build"
}
$signature = Get-AuthenticodeSignature SimplySignDesktop.msi
if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'Asseco Data Systems') {
throw 'SimplySign installer signature or publisher verification failed'
}
- name: Authenticate cloud certificate
uses: dismine/windows-app-signing-setup-action@89ae3b032d4bc7a5b98d1a42a34e61ecb6faad64
with:
certum-username: ${{ inputs.username }}
certum-otp-uri: ${{ inputs.otp-uri }}
certum-key-id: ${{ inputs.thumbprint }}
capture-diagnostics: 'false'
-108
View File
@@ -1,108 +0,0 @@
version: 2
updates:
# 2.x (studio): the development line.
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
groups:
go:
patterns: ["*"]
update-types: ["minor", "patch"]
- package-ecosystem: "gomod"
directory: "/desktop"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
groups:
go:
patterns: ["*"]
update-types: ["minor", "patch"]
- package-ecosystem: "npm"
directory: "/desktop/frontend-next"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
groups:
npm:
patterns: ["*"]
update-types: ["minor", "patch"]
- package-ecosystem: "npm"
directory: "/desktop/electron"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
groups:
npm:
patterns: ["*"]
update-types: ["minor", "patch"]
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
groups:
actions:
patterns: ["*"]
# 1.x (main-v2): maintenance. Dependabot reads this file from the default
# branch only, so the 1.x line is named here; it takes patch updates alone.
- package-ecosystem: "gomod"
directory: "/"
target-branch: "main-v2"
schedule:
interval: "weekly"
open-pull-requests-limit: 3
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor"]
groups:
go-1x:
patterns: ["*"]
update-types: ["patch"]
- package-ecosystem: "gomod"
directory: "/desktop"
target-branch: "main-v2"
schedule:
interval: "weekly"
open-pull-requests-limit: 3
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor"]
groups:
go-1x:
patterns: ["*"]
update-types: ["patch"]
- package-ecosystem: "npm"
directory: "/desktop/frontend"
target-branch: "main-v2"
schedule:
interval: "weekly"
open-pull-requests-limit: 3
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor"]
groups:
npm-1x:
patterns: ["*"]
update-types: ["patch"]
- package-ecosystem: "npm"
directory: "/site"
target-branch: "main-v2"
schedule:
interval: "weekly"
open-pull-requests-limit: 3
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor"]
groups:
npm-1x:
patterns: ["*"]
update-types: ["patch"]
-51
View File
@@ -1,51 +0,0 @@
# Area labels auto-applied to PRs by .github/workflows/pr-auto-label.yml
# (actions/labeler), based on the changed file paths. Keep the area set in sync
# with issue-auto-label.yml. severity/platform are issue-only — a PR is a change,
# not a bug report — and v1/v2 are handled by pr-version-label.yml.
agent:
- changed-files:
- any-glob-to-any-file:
- 'internal/runtime/agent/**'
- 'internal/session/control/**'
mcp:
- changed-files:
- any-glob-to-any-file:
- 'internal/ext/plugin/**'
- 'internal/codegraph/**'
config:
- changed-files:
- any-glob-to-any-file:
- 'internal/contract/config/**'
- 'internal/assembly/boot/**'
provider:
- changed-files:
- any-glob-to-any-file:
- 'internal/contract/provider/**'
skills:
- changed-files:
- any-glob-to-any-file:
- 'internal/ext/skill/**'
- 'internal/contract/tool/**'
tui:
- changed-files:
- any-glob-to-any-file:
- 'internal/frontend/cli/**'
desktop:
- changed-files:
- any-glob-to-any-file:
- 'desktop/**'
updater:
- changed-files:
- any-glob-to-any-file:
- 'desktop/cmd/sign/**'
- 'desktop/updater*.go'
- 'scripts/desktop-build.sh'
- '.github/workflows/release*.yml'
-7
View File
@@ -1,7 +0,0 @@
# Logins allowed to open pull requests, one per line, matched case-insensitively.
# Repository owners, members and collaborators, and bots, are always allowed.
lancy69
chuiwenwei
xxoingr
kevin9327
imcreazy
-63
View File
@@ -1,63 +0,0 @@
<!--
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)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

-19
View File
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="_图层_2" data-name="图层 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 145.55 113.29">
<defs>
<style>
.cls-1 {
fill: #ffffff;
stroke: #ffffff;
stroke-miterlimit: 10;
}
</style>
</defs>
<g id="_图层_1-2" data-name="图层 1">
<g>
<path class="cls-1" d="M144.68,38.49l-.06-.23c-.88-3.28-2.5-5.94-4.58-8.06.14,5.65-2.96,11.02-6.22,16.66l-.39.68c-2.26,3.91-4.66,7.94-6.57,11.1l-.86,1.38c-3.36,5.44-6.27,10.14-12.18,14.18-8.34,5.87-18.2,5.81-26.92,5.76-2.81-.02-5.48-.03-7.95.14l-.35.02c-3.22.06-5.96,1.57-8.17,4.49l-.14.18c-.86,1.06-1.7,2.26-2.58,3.54-3.43,4.92-7.69,11.04-16.17,12.42-4.37.86-9.98.84-14.94.83h-1.95c-.52,0-1.06,0-1.61,0-6.95,0-16.08-.89-21.94-6.55-.15-.15-.3-.3-.44-.45.5,4.73,2.33,8.64,5.44,11.65,5.86,5.66,14.98,6.55,21.94,6.55.55,0,1.09,0,1.61-.01h1.93c4.96.02,10.58.04,14.96-.83,8.48-1.37,12.74-7.5,16.17-12.42.88-1.27,1.72-2.48,2.58-3.54l.14-.18c2.21-2.92,4.95-4.43,8.17-4.49l.35-.02c2.47-.17,5.13-.16,7.95-.14,8.72.05,18.58.11,26.91-5.76,5.92-4.03,8.82-8.73,12.19-14.17l.86-1.39c1.91-3.15,4.3-7.18,6.57-11.09l.39-.69c3.81-6.6,7.41-12.84,5.86-19.57ZM120.9,23.02c-.28,0-.56,0-.83,0-9.68-.19-24.03-.09-35.57-.01l-2.04.02c-.93.01-1.82.02-2.67.03-8.36.08-14.4.13-23.33,3.82l-.27.12c-10.76,4.68-16.91,12.16-22.83,21.95-5.53,8.76-12.62,20.57-16.32,26.79-.41.69-.77,1.3-1.09,1.84l-.49.84c-1.49,2.53-3.23,5.49-4.21,8.95,3.98,1.9,8.52,2.65,12.71,2.91.27-.77.64-1.56,1.07-2.38.48-.94,1.05-1.9,1.63-2.89l.49-.84c.96-1.62,2.38-3.99,4.05-6.78,3.82-6.36,8.98-14.88,13.19-21.55l.07-.11c5.02-8.31,9.2-13.45,16.91-16.81l.11-.05c6.57-2.7,10.54-2.74,18.43-2.81.87-.01,1.78-.02,2.69-.03l1.99-.02c9.17-.06,20.13-.14,29.01-.07,2.26.01,4.39.04,6.32.08h.12s.11,0,.11,0c1.25-.01,2.91.11,4.61.46,1.03.22,2.08.52,3.05.93.21-.35.41-.71.62-1.06l.39-.68c1.92-3.33,3.79-6.57,4.97-9.82-4.08-1.92-8.7-2.76-12.89-2.82Z"/>
<path class="cls-1" d="M115.07,11.81c-9.7-.19-24.07-.09-35.62-.01h-1.99c-.93.03-1.82.04-2.67.04-8.36.08-14.4.14-23.33,3.83l-.27.12c-10.76,4.67-16.91,12.16-22.83,21.95-6.13,9.71-14.19,23.21-17.41,28.63l-.5.84c-2.08,3.55-4.68,7.97-4.94,13.39v.2s0,.21,0,.21c.01.81.06,1.61.15,2.38.14.15.29.3.44.45,1.53,1.47,3.28,2.63,5.15,3.52,3.98,1.9,8.52,2.65,12.71,2.91,1.41.09,2.78.12,4.08.12.55,0,1.09-.01,1.61-.01h1.95c4.95.01,10.57.03,14.94-.83,8.48-1.38,12.74-7.5,16.17-12.42.88-1.28,1.72-2.48,2.58-3.54l.14-.18c2.21-2.92,4.95-4.44,8.17-4.49l.35-.02c2.47-.17,5.14-.16,7.95-.14,8.71.05,18.58.1,26.92-5.76,5.91-4.04,8.82-8.74,12.18-14.18l.86-1.39c1.74-2.86,3.87-6.45,5.95-10.03.21-.35.41-.71.62-1.06l.39-.68c1.92-3.33,3.79-6.57,4.97-9.82.82-2.26,1.31-4.53,1.25-6.84-5.18-5.29-13.22-7.25-19.97-7.19ZM122.56,40.37l-.39.67c-2.21,3.81-4.55,7.77-6.39,10.79l-.84,1.36c-3.01,4.87-4.83,7.81-8.48,10.29l-.1.07c-4.94,3.49-11.95,3.45-19.38,3.41-2.88-.02-5.87-.04-8.79.16-7.1.19-13.51,3.58-18.07,9.57-1.13,1.4-2.12,2.83-3.08,4.21-2.92,4.18-4.71,6.57-7.64,7.02l-.31.06c-3.09.63-8.28.61-12.45.6h-2.16c-3.85.07-7.01-.16-9.45-.69-2.24-.48-3.87-1.22-4.89-2.2-.66-.64-1.54-1.81-1.63-4.65.11-1.35.71-2.82,1.52-4.35.48-.94,1.05-1.9,1.63-2.89l.49-.84c3.17-5.33,11.19-18.75,17.24-28.33l.07-.11c5.02-8.32,9.2-13.45,16.92-16.81l.1-.05c6.57-2.7,10.54-2.74,18.43-2.82.87,0,1.78,0,2.69-.03h1.94c11.52-.09,25.86-.19,35.38,0h.23c1.25-.01,2.92.11,4.61.46,3.15.66,6.4,2.12,7.27,5.02.2,1.2-.89,3.62-2.27,6.18-.7,1.31-1.48,2.65-2.2,3.9ZM120.07,23.01c-9.68-.19-24.03-.09-35.57-.01l-2.04.02c-.93.01-1.82.02-2.67.03-8.36.08-14.4.13-23.33,3.82l-.27.12c-10.76,4.68-16.91,12.16-22.83,21.95-5.53,8.76-12.62,20.57-16.32,26.79-.78-.35-1.41-.77-1.9-1.24-.66-.64-1.54-1.81-1.63-4.65.18-2.18,1.62-4.64,3.15-7.25l.49-.83c3.17-5.32,11.18-18.73,17.24-28.33l.07-.12c5.02-8.31,9.2-13.45,16.92-16.81l.1-.04c6.57-2.7,10.54-2.74,18.43-2.82.87-.01,1.78-.01,2.69-.03h1.99c11.5-.09,25.82-.19,35.33,0h.23c3.57-.04,10.55,1.02,11.88,5.48.14.84-.35,2.27-1.13,3.93-.28,0-.56,0-.83,0Z"/>
<path class="cls-1" d="M134.68,16.09l-.06-.23c-3.07-11.45-15.08-15.33-24.55-15.25-9.68-.19-24.03-.09-35.57-.01h-2.04c-.93.03-1.82.04-2.67.04-8.36.08-14.4.14-23.33,3.83l-.27.12c-10.76,4.67-16.91,12.16-22.83,21.95-6.14,9.73-14.2,23.22-17.41,28.62l-.49.85c-2.09,3.55-4.69,7.96-4.95,13.39v.2s0,.21,0,.21c.09,5.57,1.82,10.13,5.15,13.58.14.15.29.3.44.45,1.53,1.47,3.28,2.63,5.15,3.52,3.98,1.9,8.52,2.65,12.71,2.91,1.41.09,2.78.12,4.08.12.55,0,1.09-.01,1.61-.01h1.95c4.95.01,10.57.03,14.94-.83,8.48-1.38,12.74-7.5,16.17-12.42.88-1.28,1.72-2.48,2.58-3.54l.14-.18c2.21-2.92,4.95-4.44,8.17-4.49l.35-.02c2.47-.17,5.14-.16,7.95-.14,8.71.05,18.58.1,26.92-5.76,5.91-4.04,8.82-8.74,12.18-14.18l.86-1.39c1.74-2.86,3.87-6.45,5.95-10.03.21-.35.41-.71.62-1.06l.39-.68c1.92-3.33,3.79-6.57,4.97-9.82.82-2.26,1.31-4.53,1.25-6.84-.02-.96-.14-1.93-.36-2.91ZM119.76,25.27c-.7,1.31-1.48,2.65-2.2,3.9l-.39.67c-1.19,2.04-2.41,4.13-3.57,6.09-1.01,1.7-1.97,3.31-2.82,4.7l-.84,1.36c-3.01,4.87-4.83,7.81-8.48,10.29l-.1.07c-4.94,3.49-11.96,3.45-19.38,3.41-2.89-.02-5.87-.04-8.79.16-7.1.18-13.51,3.58-18.07,9.57-1.13,1.4-2.12,2.83-3.08,4.21-2.92,4.18-4.71,6.57-7.64,7.02l-.31.06c-3.09.63-8.27.61-12.45.6h-2.16c-3.85.07-7.01-.16-9.45-.69-1.16-.25-2.16-.57-2.99-.96-.78-.35-1.41-.77-1.9-1.24-.66-.64-1.54-1.81-1.63-4.65.18-2.18,1.62-4.64,3.15-7.25l.49-.83c3.17-5.32,11.18-18.73,17.24-28.33l.07-.12c5.02-8.31,9.2-13.45,16.92-16.81l.1-.04c6.57-2.7,10.54-2.74,18.43-2.82.87-.01,1.78-.01,2.69-.03h1.99c11.5-.09,25.82-.19,35.33,0h.23c3.57-.04,10.55,1.02,11.88,5.48.14.84-.35,2.27-1.13,3.93-.34.72-.73,1.48-1.14,2.25Z"/>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 5.4 KiB

-19
View File
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="_图层_2" data-name="图层 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 145.55 113.29">
<defs>
<style>
.cls-1 {
fill: #111111;
stroke: #111111;
stroke-miterlimit: 10;
}
</style>
</defs>
<g id="_图层_1-2" data-name="图层 1">
<g>
<path class="cls-1" d="M144.68,38.49l-.06-.23c-.88-3.28-2.5-5.94-4.58-8.06.14,5.65-2.96,11.02-6.22,16.66l-.39.68c-2.26,3.91-4.66,7.94-6.57,11.1l-.86,1.38c-3.36,5.44-6.27,10.14-12.18,14.18-8.34,5.87-18.2,5.81-26.92,5.76-2.81-.02-5.48-.03-7.95.14l-.35.02c-3.22.06-5.96,1.57-8.17,4.49l-.14.18c-.86,1.06-1.7,2.26-2.58,3.54-3.43,4.92-7.69,11.04-16.17,12.42-4.37.86-9.98.84-14.94.83h-1.95c-.52,0-1.06,0-1.61,0-6.95,0-16.08-.89-21.94-6.55-.15-.15-.3-.3-.44-.45.5,4.73,2.33,8.64,5.44,11.65,5.86,5.66,14.98,6.55,21.94,6.55.55,0,1.09,0,1.61-.01h1.93c4.96.02,10.58.04,14.96-.83,8.48-1.37,12.74-7.5,16.17-12.42.88-1.27,1.72-2.48,2.58-3.54l.14-.18c2.21-2.92,4.95-4.43,8.17-4.49l.35-.02c2.47-.17,5.13-.16,7.95-.14,8.72.05,18.58.11,26.91-5.76,5.92-4.03,8.82-8.73,12.19-14.17l.86-1.39c1.91-3.15,4.3-7.18,6.57-11.09l.39-.69c3.81-6.6,7.41-12.84,5.86-19.57ZM120.9,23.02c-.28,0-.56,0-.83,0-9.68-.19-24.03-.09-35.57-.01l-2.04.02c-.93.01-1.82.02-2.67.03-8.36.08-14.4.13-23.33,3.82l-.27.12c-10.76,4.68-16.91,12.16-22.83,21.95-5.53,8.76-12.62,20.57-16.32,26.79-.41.69-.77,1.3-1.09,1.84l-.49.84c-1.49,2.53-3.23,5.49-4.21,8.95,3.98,1.9,8.52,2.65,12.71,2.91.27-.77.64-1.56,1.07-2.38.48-.94,1.05-1.9,1.63-2.89l.49-.84c.96-1.62,2.38-3.99,4.05-6.78,3.82-6.36,8.98-14.88,13.19-21.55l.07-.11c5.02-8.31,9.2-13.45,16.91-16.81l.11-.05c6.57-2.7,10.54-2.74,18.43-2.81.87-.01,1.78-.02,2.69-.03l1.99-.02c9.17-.06,20.13-.14,29.01-.07,2.26.01,4.39.04,6.32.08h.12s.11,0,.11,0c1.25-.01,2.91.11,4.61.46,1.03.22,2.08.52,3.05.93.21-.35.41-.71.62-1.06l.39-.68c1.92-3.33,3.79-6.57,4.97-9.82-4.08-1.92-8.7-2.76-12.89-2.82Z"/>
<path class="cls-1" d="M115.07,11.81c-9.7-.19-24.07-.09-35.62-.01h-1.99c-.93.03-1.82.04-2.67.04-8.36.08-14.4.14-23.33,3.83l-.27.12c-10.76,4.67-16.91,12.16-22.83,21.95-6.13,9.71-14.19,23.21-17.41,28.63l-.5.84c-2.08,3.55-4.68,7.97-4.94,13.39v.2s0,.21,0,.21c.01.81.06,1.61.15,2.38.14.15.29.3.44.45,1.53,1.47,3.28,2.63,5.15,3.52,3.98,1.9,8.52,2.65,12.71,2.91,1.41.09,2.78.12,4.08.12.55,0,1.09-.01,1.61-.01h1.95c4.95.01,10.57.03,14.94-.83,8.48-1.38,12.74-7.5,16.17-12.42.88-1.28,1.72-2.48,2.58-3.54l.14-.18c2.21-2.92,4.95-4.44,8.17-4.49l.35-.02c2.47-.17,5.14-.16,7.95-.14,8.71.05,18.58.1,26.92-5.76,5.91-4.04,8.82-8.74,12.18-14.18l.86-1.39c1.74-2.86,3.87-6.45,5.95-10.03.21-.35.41-.71.62-1.06l.39-.68c1.92-3.33,3.79-6.57,4.97-9.82.82-2.26,1.31-4.53,1.25-6.84-5.18-5.29-13.22-7.25-19.97-7.19ZM122.56,40.37l-.39.67c-2.21,3.81-4.55,7.77-6.39,10.79l-.84,1.36c-3.01,4.87-4.83,7.81-8.48,10.29l-.1.07c-4.94,3.49-11.95,3.45-19.38,3.41-2.88-.02-5.87-.04-8.79.16-7.1.19-13.51,3.58-18.07,9.57-1.13,1.4-2.12,2.83-3.08,4.21-2.92,4.18-4.71,6.57-7.64,7.02l-.31.06c-3.09.63-8.28.61-12.45.6h-2.16c-3.85.07-7.01-.16-9.45-.69-2.24-.48-3.87-1.22-4.89-2.2-.66-.64-1.54-1.81-1.63-4.65.11-1.35.71-2.82,1.52-4.35.48-.94,1.05-1.9,1.63-2.89l.49-.84c3.17-5.33,11.19-18.75,17.24-28.33l.07-.11c5.02-8.32,9.2-13.45,16.92-16.81l.1-.05c6.57-2.7,10.54-2.74,18.43-2.82.87,0,1.78,0,2.69-.03h1.94c11.52-.09,25.86-.19,35.38,0h.23c1.25-.01,2.92.11,4.61.46,3.15.66,6.4,2.12,7.27,5.02.2,1.2-.89,3.62-2.27,6.18-.7,1.31-1.48,2.65-2.2,3.9ZM120.07,23.01c-9.68-.19-24.03-.09-35.57-.01l-2.04.02c-.93.01-1.82.02-2.67.03-8.36.08-14.4.13-23.33,3.82l-.27.12c-10.76,4.68-16.91,12.16-22.83,21.95-5.53,8.76-12.62,20.57-16.32,26.79-.78-.35-1.41-.77-1.9-1.24-.66-.64-1.54-1.81-1.63-4.65.18-2.18,1.62-4.64,3.15-7.25l.49-.83c3.17-5.32,11.18-18.73,17.24-28.33l.07-.12c5.02-8.31,9.2-13.45,16.92-16.81l.1-.04c6.57-2.7,10.54-2.74,18.43-2.82.87-.01,1.78-.01,2.69-.03h1.99c11.5-.09,25.82-.19,35.33,0h.23c3.57-.04,10.55,1.02,11.88,5.48.14.84-.35,2.27-1.13,3.93-.28,0-.56,0-.83,0Z"/>
<path class="cls-1" d="M134.68,16.09l-.06-.23c-3.07-11.45-15.08-15.33-24.55-15.25-9.68-.19-24.03-.09-35.57-.01h-2.04c-.93.03-1.82.04-2.67.04-8.36.08-14.4.14-23.33,3.83l-.27.12c-10.76,4.67-16.91,12.16-22.83,21.95-6.14,9.73-14.2,23.22-17.41,28.62l-.49.85c-2.09,3.55-4.69,7.96-4.95,13.39v.2s0,.21,0,.21c.09,5.57,1.82,10.13,5.15,13.58.14.15.29.3.44.45,1.53,1.47,3.28,2.63,5.15,3.52,3.98,1.9,8.52,2.65,12.71,2.91,1.41.09,2.78.12,4.08.12.55,0,1.09-.01,1.61-.01h1.95c4.95.01,10.57.03,14.94-.83,8.48-1.38,12.74-7.5,16.17-12.42.88-1.28,1.72-2.48,2.58-3.54l.14-.18c2.21-2.92,4.95-4.44,8.17-4.49l.35-.02c2.47-.17,5.14-.16,7.95-.14,8.71.05,18.58.1,26.92-5.76,5.91-4.04,8.82-8.74,12.18-14.18l.86-1.39c1.74-2.86,3.87-6.45,5.95-10.03.21-.35.41-.71.62-1.06l.39-.68c1.92-3.33,3.79-6.57,4.97-9.82.82-2.26,1.31-4.53,1.25-6.84-.02-.96-.14-1.93-.36-2.91ZM119.76,25.27c-.7,1.31-1.48,2.65-2.2,3.9l-.39.67c-1.19,2.04-2.41,4.13-3.57,6.09-1.01,1.7-1.97,3.31-2.82,4.7l-.84,1.36c-3.01,4.87-4.83,7.81-8.48,10.29l-.1.07c-4.94,3.49-11.96,3.45-19.38,3.41-2.89-.02-5.87-.04-8.79.16-7.1.18-13.51,3.58-18.07,9.57-1.13,1.4-2.12,2.83-3.08,4.21-2.92,4.18-4.71,6.57-7.64,7.02l-.31.06c-3.09.63-8.27.61-12.45.6h-2.16c-3.85.07-7.01-.16-9.45-.69-1.16-.25-2.16-.57-2.99-.96-.78-.35-1.41-.77-1.9-1.24-.66-.64-1.54-1.81-1.63-4.65.18-2.18,1.62-4.64,3.15-7.25l.49-.83c3.17-5.32,11.18-18.73,17.24-28.33l.07-.12c5.02-8.31,9.2-13.45,16.92-16.81l.1-.04c6.57-2.7,10.54-2.74,18.43-2.82.87-.01,1.78-.01,2.69-.03h1.99c11.5-.09,25.82-.19,35.33,0h.23c3.57-.04,10.55,1.02,11.88,5.48.14.84-.35,2.27-1.13,3.93-.34.72-.73,1.48-1.14,2.25Z"/>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

-37
View File
@@ -1,37 +0,0 @@
name: acp-conformance
# The agent is driven over stdio by the official ACP TypeScript SDK, and every
# message it writes is held to the schema that SDK ships. Not a required check:
# it runs when the ACP frontend or the harness changes, and on request.
on:
pull_request:
branches: [main-v2, studio]
paths:
- "internal/frontend/acp/**"
- "tools/acp-conformance/**"
- ".github/workflows/acp-conformance.yml"
workflow_dispatch:
permissions:
contents: read
concurrency:
group: acp-conformance-${{ github.ref }}
cancel-in-progress: true
jobs:
conformance:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
with:
go-version-file: go.mod
cache: true
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "22"
- run: make acp-conformance
-293
View File
@@ -1,293 +0,0 @@
name: Android
# The Android shell under `android/` ships from the same tag the desktop line
# publishes, and lands on the same release page.
#
# It is a separate workflow rather than a job inside release-studio.yml for two
# reasons. The toolchains share nothing — Go, the Android SDK, a Gradle wrapper —
# so a runner carrying both would install three toolchains to build one artifact.
# And `signing-contract` pins which workflows may reach the SignPath credentials;
# this one never touches them, and keeping it out of that graph is what keeps the
# fingerprint stable.
#
# A failure here does not hold back the desktop release: the two are independent
# by construction, and an APK is worth less than the desktop builds it sits
# beside.
on:
push:
tags: ['studio-v*']
workflow_dispatch:
inputs:
tag:
description: "Existing studio tag to build for and attach to (for example studio-v2.51.0)"
required: false
type: string
ref:
description: "A branch to build as a trial run of this workflow; nothing is attached to any release"
required: false
type: string
permissions:
contents: write # upload the APK to the release the tag belongs to
concurrency:
group: android-${{ inputs.tag || inputs.ref || github.ref_name }}
cancel-in-progress: false
jobs:
resolve:
name: resolve the tag
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
tag: ${{ steps.release.outputs.tag }}
version: ${{ steps.release.outputs.version }}
sha: ${{ steps.release.outputs.sha }}
candidate: ${{ steps.release.outputs.candidate }}
publish: ${{ steps.release.outputs.publish }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
persist-credentials: false
# The same tag grammar release-studio.yml enforces, spelled the same way:
# two workflows that disagree about which tags name a release would publish
# one artifact for a tag the other refused.
- name: Resolve tag and version
id: release
env:
IN_TAG: ${{ inputs.tag }}
IN_REF: ${{ inputs.ref }}
REF_NAME: ${{ github.ref_name }}
run: |
# A trial run builds a branch as a throwaway version and publishes nothing.
if [ -n "$IN_REF" ] && [ -z "$IN_TAG" ]; then
sha="$(git rev-parse --verify "origin/$IN_REF^{commit}")"
{ echo "tag="; echo "version=v0.0.0-dev.${sha:0:7}"; echo "sha=$sha"
echo "candidate=false"; echo "publish=false"; } >> "$GITHUB_OUTPUT"
echo "trial build of $IN_REF at $sha"
exit 0
fi
tag="${IN_TAG:-$REF_NAME}"
semver='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-([0-9A-Za-z-]+)(\.[0-9A-Za-z-]+)*)?$'
if [[ ! "$tag" =~ ^studio-v(.+)$ ]] || [[ ! "${BASH_REMATCH[1]}" =~ $semver ]]; then
echo "::error::studio release tag must be studio-vMAJOR.MINOR.PATCH[-PRERELEASE], got: $tag"
exit 1
fi
sha="$(git rev-parse --verify "refs/tags/$tag^{commit}")"
if ! git merge-base --is-ancestor "$sha" origin/studio; then
echo "::error::$tag is not on studio history"
exit 1
fi
version="${tag#studio-}"
candidate=false
if [[ "${version#v}" =~ $semver ]] && [ -n "${BASH_REMATCH[4]}" ]; then
candidate=true
fi
{ echo "tag=$tag"; echo "version=$version"; echo "sha=$sha"
echo "candidate=$candidate"; echo "publish=true"; } >> "$GITHUB_OUTPUT"
echo "resolved $tag -> $version at $sha (candidate=$candidate)"
build:
name: build the APK
needs: resolve
runs-on: ubuntu-latest
permissions:
contents: read
# `publish` decides whether to attach anything, and the only honest answer to
# "will this APK install" is whether a key was restored.
outputs:
signed: ${{ steps.key.outputs.signed }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ needs.resolve.outputs.sha }}
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
with:
go-version-file: go.mod
cache: true
cache-dependency-path: go.sum
# pnpm first: setup-node's pnpm cache needs the executable to exist.
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v4
with:
version: 10
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
cache: pnpm
cache-dependency-path: desktop/frontend-next/pnpm-lock.yaml
- uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
with:
distribution: temurin
java-version: "21"
cache: gradle
# The SDK is the one thing nothing sets for you, per android/README.md. The
# runner image carries one; this asserts the two pieces the build names
# rather than re-installing them, so a missing package fails here by name
# instead of surfacing later as an unresolved compileSdk.
- name: Provide the Android SDK
run: |
if [ -z "${ANDROID_HOME:-}" ]; then
echo "::error::ANDROID_HOME is unset; the runner image is expected to provide the Android SDK"
exit 1
fi
for piece in "platforms/android-35" "build-tools/35.0.0"; do
if [ ! -d "$ANDROID_HOME/$piece" ]; then
echo "::error::the Android SDK at $ANDROID_HOME has no $piece; android/README.md names it as a requirement"
exit 1
fi
done
echo "ANDROID_SDK_ROOT=$ANDROID_HOME" >> "$GITHUB_ENV"
# A key that exists signs; a key that does not leaves the artifact
# unsigned, which is what a release with no key has always produced. The
# decision is the repository's, not this workflow's: it reads the four
# secrets android/README.md already names.
- name: Restore the signing key
id: key
env:
KEYSTORE_BASE64: ${{ secrets.REASONIX_KEYSTORE_BASE64 }}
STORE_PASSWORD: ${{ secrets.REASONIX_KEYSTORE_PASSWORD }}
KEY_PASSWORD: ${{ secrets.REASONIX_KEY_PASSWORD }}
KEY_ALIAS: ${{ secrets.REASONIX_KEY_ALIAS }}
run: |
if [ -z "$KEYSTORE_BASE64" ] || [ -z "$STORE_PASSWORD" ] || [ -z "$KEY_ALIAS" ]; then
echo "signed=false" >> "$GITHUB_OUTPUT"
echo "no signing key configured: the APK will be unsigned"
exit 0
fi
mkdir -p android/keystore
printf '%s' "$KEYSTORE_BASE64" | base64 --decode > android/keystore/release.jks
{
echo "storeFile=keystore/release.jks"
echo "storePassword=${STORE_PASSWORD}"
echo "keyAlias=${KEY_ALIAS}"
# PKCS#12 keystores use one password for both; only write the second
# when it is genuinely a different fact.
[ -n "$KEY_PASSWORD" ] && echo "keyPassword=${KEY_PASSWORD}"
} > android/keystore/keystore.properties
chmod 600 android/keystore/*
echo "signed=true" >> "$GITHUB_OUTPUT"
echo "signing key restored"
- name: Build the kernel and the page
working-directory: android
env:
VERSION: ${{ needs.resolve.outputs.version }}
run: |
export REASONIX_APP_VERSION="${VERSION#v}"
bash ./scripts/build-kernel.sh
bash ./scripts/sync-page.sh
# The one end-to-end check that needs no phone: the kernel the shell starts,
# serving the page the APK carries. Running it here means an APK that would
# open blank fails the build instead of the install.
- name: Verify the packaged page
working-directory: android
run: |
(cd .. && go build -o reasonix-verify ./cmd/reasonix)
KERNEL_BIN="$PWD/../reasonix-verify" bash ./scripts/verify-page.sh
- name: Assemble
working-directory: android
env:
VERSION: ${{ needs.resolve.outputs.version }}
run: |
# The version comes from the tag, so the About screen and the update
# check name this release. versionCode keeps its existing shape, which
# is why the build digit stays 1: it is a single decimal place, and a
# number that grows past it would collide with the next patch.
./gradlew assembleRelease --no-daemon "-PreasonixVersion=${VERSION#v}"
- name: Name the artifact
id: apk
working-directory: android/app/build/outputs/apk/release
run: |
src="$(ls ./*.apk | head -n 1)"
if [ -z "$src" ]; then
echo "::error::assembleRelease produced no APK"
exit 1
fi
case "$src" in
*-unsigned.apk) name="ReasonixMobile-${{ needs.resolve.outputs.version }}-unsigned.apk" ;;
*) name="ReasonixMobile-${{ needs.resolve.outputs.version }}.apk" ;;
esac
mv "$src" "$name"
sha256sum "$name" > "$name.sha256"
{
echo "path=$PWD/$name"
echo "name=$name"
} >> "$GITHUB_OUTPUT"
ls -l "$name" "$name.sha256"
# 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"
echo "signing secrets to publish one."
} >> "$GITHUB_STEP_SUMMARY"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v8
with:
name: android-apk
path: |
android/app/build/outputs/apk/release/*.apk
android/app/build/outputs/apk/release/*.sha256
if-no-files-found: error
publish:
name: attach the APK
needs: [resolve, build]
# Nothing to attach unless the build was signed. Skipping is the honest
# outcome: a release page with an APK nobody can install is worse than a
# release page without one.
if: needs.build.outputs.signed == 'true' && needs.resolve.outputs.publish == 'true'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: android-apk
path: dist
# The release itself belongs to release-studio.yml, which creates it and
# owns its notes. This waits for it rather than creating a second one: two
# jobs racing to define a release is how a page ends up with the wrong body.
- name: Attach to the release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.resolve.outputs.tag }}
REPO: ${{ github.repository }}
run: |
# 90 minutes: on the last Studio release the page appeared about 40
# minutes after the tag run started, and the APK build spends part of
# that before this wait begins.
for _ in $(seq 1 360); do
if gh release view "$TAG" --repo "$REPO" >/dev/null 2>&1; then
gh release upload "$TAG" dist/*.apk dist/*.sha256 --repo "$REPO" --clobber
echo "attached to $TAG"
exit 0
fi
sleep 15
done
echo "::error::release $TAG did not appear within 90 minutes; the APK was built but not published"
exit 1
+31 -1178
View File
File diff suppressed because it is too large. Load diff
-35
View File
@@ -1,35 +0,0 @@
name: Close linked issues
# GitHub closes an issue named by "Fixes #N" only when the pull request merges
# into the default branch. This does the same for the 1.x line. It reads the
# merged pull request's description and never checks out its code.
on:
pull_request_target:
types: [closed]
branches: [main-v2]
permissions:
issues: write
jobs:
close:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
with:
script: |
const pr = context.payload.pull_request;
const { owner, repo } = context.repo;
// GitHub's own closing-keyword grammar, applied to this repository's issues only.
const keyword = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*:?\s+#(\d+)\b/gi;
const numbers = [...new Set([...(pr.body ?? '').matchAll(keyword)].map((m) => Number(m[1])))];
const sha = (pr.merge_commit_sha ?? '').slice(0, 9);
for (const issue_number of numbers) {
const { data } = await github.rest.issues.get({ owner, repo, issue_number });
if (data.pull_request || data.state !== 'open') continue;
await github.rest.issues.createComment({ owner, repo, issue_number,
body: `Fixed on the 1.x line by #${pr.number} (${sha}). It ships in the next 1.x release.` });
await github.rest.issues.update({ owner, repo, issue_number, state: 'closed', state_reason: 'completed' });
core.info(`closed #${issue_number}`);
}
+16 -41
View File
@@ -1,63 +1,38 @@
name: CodeQL
on:
# Docs/release-notes/root-Markdown changes carry no analyzable code; the
# weekly cron keeps the full scan cadence regardless.
push:
branches: ["main-v2", "studio"]
paths-ignore:
- 'docs/**'
- 'release-notes/**'
- '*.md'
branches: [main]
pull_request:
branches: ["main-v2", "studio"]
paths-ignore:
- 'docs/**'
- 'release-notes/**'
- '*.md'
# A schedule runs only from the default branch, so the weekly scan checks out
# both lines itself: 1.x is in maintenance, and security is part of it.
branches: [main]
schedule:
- cron: "27 3 * * 1"
- cron: "0 6 * * 1"
jobs:
analyze:
name: Analyze (${{ matrix.language }}${{ matrix.branch && format(', {0}', matrix.branch) || '' }})
name: analyze (${{ matrix.language }})
runs-on: ubuntu-latest
permissions:
security-events: write
packages: read
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [go, javascript-typescript, actions]
# Empty means "the ref this event is about"; a scheduled run names each line.
branch: ${{ fromJSON(github.event_name == 'schedule' && '["main-v2", "studio"]' || '[""]') }}
language: [javascript-typescript]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ matrix.branch }}
- id: head
if: matrix.branch != ''
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.language == 'go' && 'autobuild' || 'none' }}
- name: Perform CodeQL Analysis
if: matrix.branch == ''
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
queries: security-extended
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Analyze
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{ matrix.language }}"
# Results from a checked-out line are filed under that line's ref, not the
# default branch the schedule happened to run from.
- name: Perform CodeQL Analysis (${{ matrix.branch }})
if: matrix.branch != ''
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
category: "/language:${{ matrix.language }}"
ref: refs/heads/${{ matrix.branch }}
sha: ${{ steps.head.outputs.sha }}
@@ -1,51 +0,0 @@
name: Deploy accounts worker
on:
push:
branches: [main-v2]
paths:
- 'workers/accounts/**'
- '.github/workflows/deploy-accounts-worker.yml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: deploy-accounts-worker
cancel-in-progress: false
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
version: 10
run_install: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
cache: pnpm
cache-dependency-path: workers/accounts/pnpm-lock.yaml
- name: Deploy
working-directory: workers/accounts
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
run: |
pnpm install --frozen-lockfile
pnpm test
pnpm typecheck
npx wrangler deploy
- name: Sync RESEND_API_KEY to the worker
working-directory: workers/accounts
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }}
run: |
if [ -n "$RESEND_API_KEY" ]; then
printf '%s' "$RESEND_API_KEY" | npx wrangler secret put RESEND_API_KEY
else
echo "RESEND_API_KEY not set in repo secrets; skipping (worker stays in stub email mode)."
fi
-60
View File
@@ -1,60 +0,0 @@
name: Deploy crash worker
on:
push:
branches: [main-v2]
paths:
- 'workers/crash-report/**'
- '.github/workflows/deploy-crash-worker.yml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: deploy-crash-worker
cancel-in-progress: false
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '22'
cache: npm
cache-dependency-path: workers/crash-report/package-lock.json
- name: Validate
working-directory: workers/crash-report
run: |
npm ci
npm run typecheck
npm test
- name: Apply and verify diagnostics v2 D1 migration
working-directory: workers/crash-report
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
run: npm run migrate:diagnostics-v2
- name: Deploy
working-directory: workers/crash-report
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
run: |
npx wrangler deploy
# Mirrors the ALERT_WEBHOOK repo secret into the worker so the ingest
# sentinel can push alerts (see runIngestSentinel). Managed here so
# nobody needs local Cloudflare credentials; when the repo secret is
# unset the sentinel stays log-only.
- name: Sync alert webhook secret
working-directory: workers/crash-report
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
ALERT_WEBHOOK: ${{ secrets.ALERT_WEBHOOK }}
run: |
if [ -z "$ALERT_WEBHOOK" ]; then
echo "ALERT_WEBHOOK repo secret not set; removing any existing worker secret."
printf '{"ALERT_WEBHOOK":null}' | npx wrangler secret bulk
exit 0
fi
printf '%s' "$ALERT_WEBHOOK" | npx wrangler secret put ALERT_WEBHOOK
-40
View File
@@ -1,40 +0,0 @@
name: Deploy forum worker
on:
push:
branches: [main-v2]
paths:
- 'workers/forum/**'
- '.github/workflows/deploy-forum-worker.yml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: deploy-forum-worker
cancel-in-progress: false
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
version: 10
run_install: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
cache: pnpm
cache-dependency-path: workers/forum/pnpm-lock.yaml
- name: Deploy
working-directory: workers/forum
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
run: |
pnpm install --frozen-lockfile
pnpm test
pnpm typecheck
npx wrangler deploy
-44
View File
@@ -1,44 +0,0 @@
name: Deploy ops events relay
on:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: deploy-ops-events
cancel-in-progress: false
jobs:
deploy:
if: github.ref == 'refs/heads/platform'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '22'
cache: npm
cache-dependency-path: workers/ops-events/package-lock.json
- name: Validate
working-directory: workers/ops-events
run: |
npm ci
npm run typecheck
npm test
- name: Deploy
working-directory: workers/ops-events
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
run: npx wrangler deploy
- name: Sync secrets
working-directory: workers/ops-events
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
GITHUB_WEBHOOK_SECRET: ${{ secrets.OPS_GITHUB_WEBHOOK_SECRET }}
OPS_LISTEN_TOKEN: ${{ secrets.OPS_LISTEN_TOKEN }}
OPS_EMIT_TOKEN: ${{ secrets.OPS_EMIT_TOKEN }}
run: |
node -e 'process.stdout.write(JSON.stringify({GITHUB_WEBHOOK_SECRET:process.env.GITHUB_WEBHOOK_SECRET||null,OPS_LISTEN_TOKEN:process.env.OPS_LISTEN_TOKEN||null,OPS_EMIT_TOKEN:process.env.OPS_EMIT_TOKEN||null}))' | npx wrangler secret bulk
-49
View File
@@ -1,49 +0,0 @@
name: Deploy Web Studio
on:
push:
branches: [studio]
paths:
- "desktop/frontend-next/**"
- ".github/workflows/deploy-web-studio.yml"
permissions:
contents: read
concurrency:
group: web-studio-production
cancel-in-progress: true
jobs:
deploy:
runs-on: ubuntu-latest
defaults:
run:
working-directory: desktop/frontend-next
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
version: 10
run_install: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
cache: pnpm
cache-dependency-path: desktop/frontend-next/pnpm-lock.yaml
- name: Install
run: pnpm install --frozen-lockfile
- name: Build
env:
VITE_REMOTE_HOME: https://reasonix.io/remote/
run: pnpm build
- name: Deploy
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
run: npx --yes [email protected] deploy --config wrangler.jsonc
-191
View File
@@ -1,191 +0,0 @@
name: e2e-bot
# Comment "/e2e" (fixed suite) or "/e2e diff" (generate tests for the PR's diff)
# on a pull request to run the e2e benchmark against the real provider and post a
# report back. Gated to trusted authors: the job checks out PR-head code and runs
# it with the provider API key, so only the repo owner, members, and collaborators
# may trigger it.
on:
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
concurrency:
group: e2e-bot-${{ github.event.issue.number }}
cancel-in-progress: true
jobs:
e2e:
if: >-
github.event.issue.pull_request &&
contains(github.event.comment.body, '/e2e') &&
contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.comment.author_association)
runs-on: ubuntu-latest
# Running PR-head code with the provider secret is gated twice: the author_
# association check above, and this deployment environment. Configure the
# `e2e-bot` environment with required reviewers in repo settings to force a
# human approval per run (actions/untrusted-checkout-toctou).
environment: e2e-bot
steps:
- name: Acknowledge
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
with:
script: |
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner, repo: context.repo.repo,
comment_id: context.payload.comment.id, content: 'eyes',
});
# Default-branch checkout: this is where the harness (cmd/e2ebench), the
# suite, and a run --metrics-capable agent live.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
with:
go-version-file: go.mod
cache: true
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
with:
python-version: '3.12'
- name: Install and verify Linux sandbox backend
run: |
sudo apt-get update
sudo apt-get install -y bubblewrap
if sysctl -n kernel.unprivileged_userns_clone >/dev/null 2>&1; then
sudo sysctl -w kernel.unprivileged_userns_clone=1
fi
if sysctl -n kernel.apparmor_restrict_unprivileged_userns >/dev/null 2>&1; then
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
fi
bwrap --ro-bind / / --dev /dev --proc /proc -- true
- name: Build harness + fallback agent from the default branch
# Harness (e2ebench) and suite always come from main-v2 so a PR can't weaken
# its own grader or tests. The agent is rebuilt from the PR head below; this
# main-v2 build is only the fallback for heads that predate `run --metrics`.
run: |
go build -o "$RUNNER_TEMP/reasonix-base" ./cmd/reasonix
go build -o "$RUNNER_TEMP/e2ebench" ./cmd/e2ebench
cp -r benchmarks/e2e "$RUNNER_TEMP/suite"
- name: Check out the PR head
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Pin to the head commit resolved now and check it out detached, not the
# mutable PR ref: a force-push mid-run can't swap in different code after
# the trusted-author gate passed.
run: |
SHA=$(gh pr view ${{ github.event.issue.number }} --json headRefOid -q .headRefOid)
git fetch -q origin "$SHA"
git checkout -q --detach "$SHA"
- name: Build the agent from the PR head
# The whole point of the bot is to drive the PR's code, not main-v2's. Fall
# back to the main-v2 build only when the PR head can't yield a
# run --metrics-capable binary (build break or predates the flag).
id: agent
run: |
bin="$RUNNER_TEMP/reasonix-base"
src="main-v2 fallback (PR head lacks run --metrics)"
if go build -o "$RUNNER_TEMP/reasonix-pr" ./cmd/reasonix \
&& "$RUNNER_TEMP/reasonix-pr" run -h 2>&1 | grep -q -- '-metrics'; then
bin="$RUNNER_TEMP/reasonix-pr"
src="PR head ($(git rev-parse --short HEAD))"
fi
echo "bin=$bin" >> "$GITHUB_OUTPUT"
echo "src=$src" >> "$GITHUB_OUTPUT"
echo "agent under test: $src"
- name: Write provider config
env:
REASONIX_HOME: ${{ runner.temp }}/reasonix-e2e-home
# User config covers suite tasks (they run in temp dirs); the repo-root copy
# covers diff mode (the agent runs in the repo root, where project config wins).
run: |
mkdir -p "$REASONIX_HOME"
cat > /tmp/reasonix-e2e.toml <<EOF
default_model = "e2e"
[[providers]]
name = "e2e"
kind = "openai"
base_url = "${{ vars.REASONIX_E2E_BASE_URL || 'https://api.deepseek.com' }}"
model = "${{ vars.REASONIX_E2E_MODEL || 'deepseek-v4-flash' }}"
api_key_env = "DEEPSEEK_API_KEY"
context_window = 20000 # small so the suite actually exercises compaction + cache churn
[providers.price]
cache_hit = ${{ vars.REASONIX_E2E_PRICE_CACHE_HIT || '0.02' }}
input = ${{ vars.REASONIX_E2E_PRICE_INPUT || '1' }}
output = ${{ vars.REASONIX_E2E_PRICE_OUTPUT || '2' }}
currency = "${{ vars.REASONIX_E2E_PRICE_CURRENCY || '¥' }}"
[permissions]
mode = "allow"
[codegraph]
enabled = false
EOF
cp /tmp/reasonix-e2e.toml "$REASONIX_HOME/config.toml"
cp /tmp/reasonix-e2e.toml ./reasonix.toml
- name: Run e2e
env:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
REASONIX_HOME: ${{ runner.temp }}/reasonix-e2e-home
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
COMMENT_BODY: ${{ github.event.comment.body }}
run: |
if [ -z "$DEEPSEEK_API_KEY" ]; then
printf 'missing DEEPSEEK_API_KEY secret\n\nAdd a repository secret named DEEPSEEK_API_KEY to enable the e2e bot.\n' > report.md
exit 1
fi
# Provider credentials are deliberately loaded only from Reasonix's
# global credential file, not inherited process variables. Keep this
# ephemeral runner copy private and outside the checked-out project.
umask 077
printf 'DEEPSEEK_API_KEY=%s\n' "$DEEPSEEK_API_KEY" > "$REASONIX_HOME/.env"
if printf '%s' "$COMMENT_BODY" | grep -q '/e2e[[:space:]]\+diff'; then
ATTEMPTS=$(printf '%s' "$COMMENT_BODY" | sed -nE 's@.*/e2e[[:space:]]+diff[[:space:]]+x([0-9]+).*@\1@p' | head -1)
[ -z "$ATTEMPTS" ] && ATTEMPTS=1
[ "$ATTEMPTS" -gt 5 ] && ATTEMPTS=5
BASE_REF=$(gh pr view ${{ github.event.issue.number }} --json baseRefName -q .baseRefName)
git fetch -q origin "$BASE_REF"
BASE=$(git merge-base "origin/$BASE_REF" HEAD)
"$RUNNER_TEMP/e2ebench" -mode diff -bin "${{ steps.agent.outputs.bin }}" -repo . -base "$BASE" -model e2e -attempts "$ATTEMPTS" -out report.md
else
# The current five-task baseline can exceed 400k after only three
# successful tasks. Keep bounded headroom so every scenario is graded.
"$RUNNER_TEMP/e2ebench" -bin "${{ steps.agent.outputs.bin }}" -suite "$RUNNER_TEMP/suite" -model e2e -out report.md -json report.json -budget 800000
node -e '
const results = require("./report.json");
const unsuccessful = results.filter((result) => !result.Passed || result.Skipped);
if (results.length === 0 || unsuccessful.length > 0) {
console.error(`e2e suite incomplete: ${unsuccessful.length}/${results.length} unsuccessful`);
process.exit(1);
}
'
fi
- name: Post report
if: always() && hashFiles('report.md') != ''
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TRIGGER_USER: ${{ github.event.comment.user.login }}
run: |
printf '\n> agent: %s · triggered by @%s\n' "${{ steps.agent.outputs.src }}" "$TRIGGER_USER" >> report.md
gh pr comment ${{ github.event.issue.number }} --body-file report.md
- name: Report failure
if: failure()
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh pr comment ${{ github.event.issue.number }} --body "🤖 e2e bot failed — see the [run log](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})."
-77
View File
@@ -1,77 +0,0 @@
name: Sync in-app feedback
# Turns feedback submitted from Reasonix Studio into issues and reports issue
# state (in progress, fixed in a tag, won't fix, duplicate) back to the worker,
# and mirrors the reporter's replies onto their issue as bot comments.
# Text from the public reaches the script only through the worker's JSON and
# the GitHub API, never through a shell command line or an expression.
on:
schedule:
- cron: '*/10 * * * *'
- cron: '5 3 * * *'
workflow_dispatch:
inputs:
dry_run:
description: Print what would happen without creating issues or writing back
required: false
default: false
type: boolean
full:
description: Re-read every open entry instead of only recently changed issues
required: false
default: false
type: boolean
permissions:
contents: read
issues: write
concurrency:
group: feedback-sync
cancel-in-progress: false
jobs:
sync:
if: github.repository == 'esengine/DeepSeek-Reasonix'
runs-on: ubuntu-latest
timeout-minutes: 8
steps:
- name: Check secret
id: gate
env:
FEEDBACK_ADMIN_TOKEN: ${{ secrets.FEEDBACK_ADMIN_TOKEN }}
run: |
if [ -z "$FEEDBACK_ADMIN_TOKEN" ]; then
echo "::notice::FEEDBACK_ADMIN_TOKEN is not set; feedback sync skipped"
echo "run=false" >> "$GITHUB_OUTPUT"
else
echo "run=true" >> "$GITHUB_OUTPUT"
fi
- if: steps.gate.outputs.run == 'true'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
# git tag --contains needs full history; the tag API would cost a request per entry.
fetch-depth: 0
persist-credentials: false
- if: steps.gate.outputs.run == 'true'
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '22'
- name: Sync
if: steps.gate.outputs.run == 'true'
env:
FEEDBACK_ADMIN_TOKEN: ${{ secrets.FEEDBACK_ADMIN_TOKEN }}
# crash.reasonix.io answers runner IPs with a managed challenge; workers.dev serves only the converter's admin paths.
FEEDBACK_BASE_URL: https://reasonix-crash-report.reasonix.workers.dev
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DRY_RUN: ${{ github.event.inputs.dry_run || 'false' }}
FULL: ${{ github.event.inputs.full || 'false' }}
SCHEDULE: ${{ github.event.schedule }}
run: |
set -euo pipefail
args=()
if [ "$DRY_RUN" = "true" ]; then args+=(--dry-run); fi
# The daily schedule sweeps everything the change window could have missed.
if [ "$FULL" = "true" ] || [ "$SCHEDULE" = "5 3 * * *" ]; then args+=(--full); fi
node scripts/feedback-sync.mjs "${args[@]}"
-99
View File
@@ -1,99 +0,0 @@
name: Auto-label issues
# Classify new issues into area / platform / severity labels using the DeepSeek
# API (the project's own model). The model is constrained to a fixed label set —
# anything it returns outside the set is dropped — so it can't invent labels.
# Issues it can't place into any area get `needs-triage` for a human to look at.
# Version (v1/v2) labels are handled separately by issue-version-label.yml.
on:
issues:
types: [opened, reopened]
permissions:
issues: write
concurrency:
group: issue-autolabel-${{ github.event.issue.number }}
cancel-in-progress: true
jobs:
classify:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
env:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
with:
script: |
const AREA = ['agent','mcp','config','updater','provider','desktop','tui','skills','rendering'];
const PLATFORM = ['windows','macos','linux'];
const SEVERITY = ['crash','data-loss','security'];
const ALLOWED = new Set([...AREA, ...PLATFORM, ...SEVERITY]);
const issue = context.payload.issue;
const title = issue.title || '';
const body = (issue.body || '').slice(0, 4000);
const system = [
'You categorize GitHub issues for Reasonix, a Go-based AI coding agent with an Electron desktop app and a terminal UI.',
'Pick labels ONLY from these fixed sets. Never invent labels.',
'area (0-2, the affected subsystem):',
' agent: core agent loop / tool-calling / reasoning',
' mcp: MCP servers, plugins, codegraph',
' config: configuration, setup wizard, .toml/.env',
' updater: auto-update, installer, release packaging',
' provider: model providers, model selection/switching',
' desktop: Electron desktop GUI',
' tui: terminal UI / CLI',
' skills: skills system',
' rendering: terminal rendering / flicker / repaint',
'platform (only if clearly specific to one OS): windows, macos, linux',
'severity (only if clearly applicable):',
' crash: app crashes, hangs, or freezes',
' data-loss: loss of sessions, config, or history',
' security: credential/secret exposure or a security flaw',
'Be conservative: omit a label when unsure. The issue may be in Chinese.',
'Reply with JSON only: {"area":[],"platform":[],"severity":[]}',
].join('\n');
let labels = [];
try {
const res = await fetch('https://api.deepseek.com/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'deepseek-chat',
temperature: 0,
response_format: { type: 'json_object' },
messages: [
{ role: 'system', content: system },
{ role: 'user', content: `Title: ${title}\n\nBody:\n${body}` },
],
}),
});
if (!res.ok) {
core.warning(`DeepSeek API ${res.status}: ${await res.text()}`);
return;
}
const data = await res.json();
const parsed = JSON.parse(data.choices[0].message.content);
labels = [...(parsed.area || []), ...(parsed.platform || []), ...(parsed.severity || [])]
.filter(l => ALLOWED.has(l));
} catch (e) {
core.warning(`Classification failed: ${e.message}`);
return;
}
if (!labels.some(l => AREA.includes(l))) labels.push('needs-triage');
if (labels.length) {
await github.rest.issues.addLabels({
...context.repo,
issue_number: issue.number,
labels,
});
core.info(`Applied: ${labels.join(', ')}`);
}
-116
View File
@@ -1,116 +0,0 @@
name: Issue replies
# Posts maintainer replies as github-actions[bot], so a batch of triage answers
# spends the repository's quota instead of a person's content-creation limit.
on:
workflow_dispatch:
inputs:
replies:
description: 'JSON array of {"issue": 123, "body": "...", "close": true | "not_planned"} or {"discussion": 123, "body": "...", "close": "resolved" | "outdated" | "duplicate"}'
required: true
type: string
interval:
description: Seconds between entries
required: false
default: '20'
type: string
permissions:
issues: write
pull-requests: write
discussions: write
concurrency:
group: issue-replies
cancel-in-progress: false
jobs:
reply:
runs-on: win-gpu
timeout-minutes: 180
steps:
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
env:
REPLIES: ${{ inputs.replies }}
INTERVAL: ${{ inputs.interval }}
with:
script: |
const replies = JSON.parse(process.env.REPLIES);
if (!Array.isArray(replies)) throw new Error('replies must be a JSON array');
const { owner, repo } = context.repo;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const failed = [];
// Only a rate limit is worth waiting out; any other refusal is final.
const rateLimited = (error) => {
const headers = error.response?.headers ?? {};
return error.status === 429 ||
(error.status === 403 && (headers['retry-after'] !== undefined || headers['x-ratelimit-remaining'] === '0'));
};
// Discussions have no REST comment API; they are addressed by node id.
const replyToDiscussion = async (number, body) => {
const q = await github.graphql(
`query($owner:String!,$repo:String!,$n:Int!){repository(owner:$owner,name:$repo){discussion(number:$n){id comments(last:100){nodes{body author{login}}}}}}`,
{ owner, repo, n: number });
const d = q.repository.discussion;
if (!d) throw new Error('no such discussion');
if (d.comments.nodes.some((c) => c.author?.login === 'github-actions' && c.body === body)) return false;
await github.graphql(`mutation($id:ID!,$body:String!){addDiscussionComment(input:{discussionId:$id,body:$body}){comment{id}}}`, { id: d.id, body });
return true;
};
const closeReasons = { resolved: 'RESOLVED', outdated: 'OUTDATED', duplicate: 'DUPLICATE' };
const closeDiscussion = async (number, reason) => {
const q = await github.graphql(
`query($owner:String!,$repo:String!,$n:Int!){repository(owner:$owner,name:$repo){discussion(number:$n){id closed}}}`,
{ owner, repo, n: number });
const d = q.repository.discussion;
if (d.closed) return;
await github.graphql(`mutation($id:ID!,$r:DiscussionCloseReason!){closeDiscussion(input:{discussionId:$id,reason:$r}){discussion{id}}}`, { id: d.id, r: reason });
};
for (const { issue, discussion, body, close } of replies) {
if (Number.isInteger(discussion) && typeof body === 'string' && body.trim() !== '') {
try {
const posted = await replyToDiscussion(discussion, body);
if (close !== undefined && close !== false) {
const reason = closeReasons[close];
if (!reason) throw new Error(`unknown close reason ${close}`);
await closeDiscussion(discussion, reason);
}
core.info(`discussion #${discussion}: ${posted ? 'replied' : 'already replied'}${close ? ', closed' : ''}`);
} catch (error) {
failed.push(`discussion ${discussion}: ${error.message}`);
}
await sleep(Math.max(1, Number(process.env.INTERVAL) || 20) * 1000);
continue;
}
if (!Number.isInteger(issue) || typeof body !== 'string' || body.trim() === '') {
failed.push(`${issue}: malformed entry`);
continue;
}
try {
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number: issue, per_page: 100 });
const posted = comments.some((c) => c.user?.type === 'Bot' && c.body === body);
if (!posted) {
for (let attempt = 0; ; attempt++) {
try {
await github.rest.issues.createComment({ owner, repo, issue_number: issue, body });
break;
} catch (error) {
if (attempt >= 5 || !rateLimited(error)) throw error;
core.warning(`#${issue}: ${error.message}; retrying in 2 minutes`);
await sleep(120_000);
}
}
}
if (close === true || close === 'not_planned') {
const { data } = await github.rest.issues.get({ owner, repo, issue_number: issue });
if (data.state === 'open') {
await github.rest.issues.update({ owner, repo, issue_number: issue, state: 'closed', state_reason: close === 'not_planned' ? 'not_planned' : 'completed' });
}
}
core.info(`#${issue}: ${posted ? 'already replied' : 'replied'}${close ? ', closed' : ''}`);
} catch (error) {
failed.push(`${issue}: ${error.message}`);
}
await sleep(Math.max(1, Number(process.env.INTERVAL) || 20) * 1000);
}
if (failed.length) core.setFailed(`not done:\n${failed.join('\n')}`);
-64
View File
@@ -1,64 +0,0 @@
name: Label issue version
# Issue forms can't let a reporter set a label directly (that needs triage rights),
# so the bug/feature forms carry a "Version line" dropdown and this workflow reads
# the submitted value and applies the matching label on their behalf:
# 0.x -> v1 (TypeScript), 1.x -> v2 (main-v2), 2.x -> v3 (studio).
on:
issues:
types: [opened, edited]
permissions:
issues: write
concurrency:
group: issue-version-${{ github.event.issue.number }}
cancel-in-progress: true
jobs:
label:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
with:
script: |
const body = context.payload.issue.body || '';
const sectionOf = (name) =>
body.split(/^###\s+/m).find((s) => new RegExp(`^${name}`, 'i').test(s)) || '';
const labelOf = (major) => ({ 0: 'v1', 1: 'v2', 2: 'v3' })[major];
const m = sectionOf('Version line').match(/\b([012])\.x\b/);
if (!m) {
core.info('No version line found; nothing to label.');
return;
}
let choice = labelOf(Number(m[1]));
// The dropdown is a choice, and its first entry gets picked by
// reporters who never looked. `Exact version` is pasted from
// `reasonix --version` or Studio, so when it parses it is the better
// evidence. Anything that does not parse (a commit sha, a branch
// name) or names no known line leaves the dropdown to decide.
const exact = sectionOf('Exact version').match(/\b(\d+)\.(\d+)\.(\d+)/);
const fromVersion = exact && labelOf(Number(exact[1]));
if (fromVersion && fromVersion !== choice) {
core.info(`Version line says ${choice} but ${exact[0]} says ${fromVersion}; trusting the version.`);
choice = fromVersion;
}
await github.rest.issues.addLabels({
...context.repo,
issue_number: context.issue.number,
labels: [choice],
});
// Keep the line labels mutually exclusive in case an edit flipped the choice.
for (const other of ['v1', 'v2', 'v3'].filter((l) => l !== choice)) {
try {
await github.rest.issues.removeLabel({
...context.repo,
issue_number: context.issue.number,
name: other,
});
} catch (e) {
core.info(`No ${other} label to remove.`);
}
}
-32
View File
@@ -1,32 +0,0 @@
name: Deploy website
# GitHub requires workflow_dispatch to be registered on the default branch.
# The production implementation is the same workflow path on website.
on:
workflow_dispatch:
inputs:
release_version:
description: "Optional product release version associated with this publication"
required: false
default: ""
type: string
release_request:
description: "Optional release workflow correlation ID"
required: false
default: ""
type: string
studio_version:
description: "Studio version that must be present in the generated changelog"
required: false
default: ""
type: string
permissions: {}
jobs:
require-website:
runs-on: ubuntu-latest
steps:
- run: |
echo "::error::Deploy the website with --ref website; production is restricted to that branch."
exit 1
-27
View File
@@ -1,27 +0,0 @@
name: PR author gate
# Pull requests are limited to maintainers and the logins in .github/pr-authors.txt.
# This runs in the base repository's context, checks out the base branch only, and
# never executes pull-request code; the allowlist it reads is the base branch's.
on:
pull_request_target:
types: [opened]
permissions:
contents: read
pull-requests: write
concurrency:
group: pr-author-gate-${{ github.event.pull_request.number }}
cancel-in-progress: false
jobs:
gate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- run: node scripts/pr-author-gate.mjs
env:
GH_TOKEN: ${{ github.token }}
-28
View File
@@ -1,28 +0,0 @@
name: Auto-label PRs
# Apply area labels to PRs based on changed paths (see .github/labeler.yml).
# Complements the AI-based issue labeler (issue-auto-label.yml). Version (v1/v2)
# labels are handled separately by pr-version-label.yml.
#
# pull_request_target runs in the base repo context so it has the write token
# needed to label PRs from forks; actions/labeler only reads the diff file list
# (it never checks out or runs PR code), so this is safe.
on:
pull_request_target:
types: [opened, synchronize, reopened]
permissions:
contents: read
pull-requests: write
concurrency:
group: pr-autolabel-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
label:
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@bf12e9b00b37c5c0ca2b87b79b2daf7891dbda13 # v7
with:
sync-labels: false
-49
View File
@@ -1,49 +0,0 @@
name: Label PR version
# Contributors (especially from forks) can't set labels themselves — that needs
# triage rights. A PR's version line is fully determined by its base branch, so
# this reads base.ref and applies v1/v2 on their behalf. pull_request_target runs
# in the base repo's context so it has write access even for fork PRs; it only
# reads trusted metadata (the base ref) and never checks out or runs PR code.
on:
pull_request_target:
types: [opened, reopened, edited]
permissions:
pull-requests: write
concurrency:
group: pr-version-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
label:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
with:
script: |
const base = context.payload.pull_request.base.ref;
const label = base === 'v1' ? 'v1'
: base === 'main-v2' ? 'v2'
: null;
if (!label) {
core.info(`Base branch '${base}' isn't a release line; skipping.`);
return;
}
const other = label === 'v2' ? 'v1' : 'v2';
await github.rest.issues.addLabels({
...context.repo,
issue_number: context.payload.pull_request.number,
labels: [label],
});
// Drop the other line's label if the base was changed after opening.
try {
await github.rest.issues.removeLabel({
...context.repo,
issue_number: context.payload.pull_request.number,
name: other,
});
} catch (e) {
core.info(`No ${other} label to remove.`);
}
File diff suppressed because it is too large. Load diff
-64
View File
@@ -1,64 +0,0 @@
name: Spam comment guard
# Activity-farming bots post short emoji-padded template comments on whatever
# issue is currently active. They are cheap to spot structurally: a recently
# registered account with no history here, no followers, and a pile of forked
# repos, posting a sub-50 character comment with emoji and no code/link/log.
# Every signal must fire — on 7604 replayed comments that caught all 83 known
# spam posts with no false positive. Loosening any one of them reintroduces
# real users ("点赞", "同样的问题", a 2020 account posting "感谢各位❤").
on:
issue_comment:
types: [created]
permissions:
issues: write
pull-requests: write
concurrency:
group: spam-guard-${{ github.event.comment.id }}
jobs:
screen:
if: github.event.comment.user.type != 'Bot' && github.event.comment.author_association == 'NONE'
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
with:
script: |
const EMOJI = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{2B00}-\u{2BFF}\u{FE0F}]/gu;
const comment = context.payload.comment;
const body = comment.body || '';
const hasSubstance = /```|https?:\/\/|!\[|^>/m.test(body);
const emojiCount = (body.match(EMOJI) || []).length;
const bare = body.replace(EMOJI, '').trim();
const { data: author } = await github.rest.users.getByUsername({
username: comment.user.login,
});
const ageDays = (Date.now() - Date.parse(author.created_at)) / 86400000;
const signals = {
newAccount: ageDays < 365,
noFollowers: author.followers === 0,
forkPadded: author.public_repos >= 15,
tooShort: bare.length <= 45,
emojiPadded: emojiCount >= 1,
noSubstance: !hasSubstance,
};
const failed = Object.entries(signals).filter(([, v]) => !v).map(([k]) => k);
core.info(`${comment.user.login}: ${failed.length ? `kept (${failed.join(',')})` : 'spam'}`);
if (failed.length) return;
await github.graphql(
`mutation($id: ID!) {
minimizeComment(input: { subjectId: $id, classifier: SPAM }) {
minimizedComment { isMinimized }
}
}`,
{ id: comment.node_id },
);
core.notice(`Minimized spam comment by ${comment.user.login}`);
-68
View File
@@ -1,68 +0,0 @@
name: Sweep stale version reports
# Reports filed many minors back cannot be confirmed against a current build,
# and 65% of the open tracker has never had a reply. This asks, waits, then
# closes — never closing anything that was not asked first.
on:
workflow_dispatch:
inputs:
dry_run:
description: Print what would happen without commenting
required: false
default: true
type: boolean
limit:
description: Maximum issues to touch in this run
required: false
default: '40'
type: string
schedule:
- cron: '17 3 * * 1'
push:
branches:
- main-v2
paths:
- '.github/workflows/stale-report-sweep.yml'
- 'scripts/stale-report-sweep.mjs'
- 'scripts/stale-report-sweep.test.mjs'
permissions:
contents: read
issues: write
concurrency:
group: stale-report-sweep
cancel-in-progress: false
jobs:
sweep:
if: github.repository == 'esengine/DeepSeek-Reasonix'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '22'
- name: Test sweeper
run: node --test scripts/stale-report-sweep.test.mjs
# A push that only touched the sweeper runs its tests and stops there.
- name: Sweep
if: github.event_name != 'push'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
LIMIT: ${{ github.event.inputs.limit || '40' }}
# Posting stays off until this repository variable is set to "true", so
# merging the sweeper cannot start commenting on its own.
ENABLED: ${{ vars.STALE_SWEEP_ENABLED }}
REQUESTED_DRY_RUN: ${{ github.event.inputs.dry_run || 'true' }}
run: |
set -euo pipefail
args=(--limit "$LIMIT")
if [ "$ENABLED" != "true" ] || [ "$REQUESTED_DRY_RUN" = "true" ]; then
args+=(--dry-run)
echo "::notice::dry run (STALE_SWEEP_ENABLED=${ENABLED:-unset})"
fi
node scripts/stale-report-sweep.mjs "${args[@]}"
@@ -1,117 +0,0 @@
name: Studio Certum signing smoke test
# Signs two throwaway probes with the certificate release-studio.yml would use,
# and publishes nothing. It reports the signer's subject, which is the value
# STUDIO_SIGNING_SUBJECT must hold.
on:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: certum-signing
cancel-in-progress: false
jobs:
sign:
if: github.repository == 'esengine/DeepSeek-Reasonix' && github.ref == 'refs/heads/studio'
runs-on: windows-2022
environment: studio-release
timeout-minutes: 20
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
with:
go-version-file: go.mod
cache: false
- name: Check signing configuration
shell: pwsh
env:
CERTUM_USERNAME: ${{ secrets.CERTUM_USERNAME }}
CERTUM_OTP_URI: ${{ secrets.CERTUM_OTP_URI }}
CERTUM_KEY_ID: ${{ secrets.CERTUM_KEY_ID }}
run: |
$ErrorActionPreference = 'Stop'
if ([string]::IsNullOrWhiteSpace($env:CERTUM_USERNAME)) { throw 'Missing secret CERTUM_USERNAME' }
if ($env:CERTUM_OTP_URI -notmatch '^otpauth://totp/') { throw 'Secret CERTUM_OTP_URI must be a complete TOTP URI' }
if ($env:CERTUM_KEY_ID -notmatch '^[0-9a-fA-F]{40}$') { throw 'Secret CERTUM_KEY_ID must be the 40-character SHA-1 certificate thumbprint' }
- name: Build open-source signing probes
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
# This minimal probe is covered by the repository's MIT license.
New-Item -ItemType Directory payload | Out-Null
'package main; func main() { println("Reasonix Studio Certum signing probe") }' | Set-Content probe.go
$env:GOOS = 'windows'
$env:GOARCH = 'amd64'
$env:CGO_ENABLED = '0'
go build -trimpath -o payload/probe.exe probe.go
if ($LASTEXITCODE -ne 0) { throw 'Probe compilation failed' }
'probe.exe' | Set-Content payload/signing-files.txt
Copy-Item payload/probe.exe installer-probe.exe
- name: Connect to SimplySign cloud certificate
uses: ./.github/actions/setup-certum
with:
username: ${{ secrets.CERTUM_USERNAME }}
otp-uri: ${{ secrets.CERTUM_OTP_URI }}
thumbprint: ${{ secrets.CERTUM_KEY_ID }}
- name: Sign and verify payload and installer probes
shell: pwsh
env:
CERTUM_KEY_ID: ${{ secrets.CERTUM_KEY_ID }}
run: |
./scripts/sign-certum.ps1 -PayloadDirectory payload
./scripts/sign-certum.ps1 -FilePath installer-probe.exe
# The session signs for any process on the runner while it is up.
- name: Disconnect from Certum
if: always()
shell: pwsh
run: Get-Process -Name '*SimplySign*' -ErrorAction SilentlyContinue | Stop-Process -Force
# With the switch on, an unset subject fails here as it would in a
# release; with it off, the value is reported so it can be recorded.
- name: Report and check the signer
shell: pwsh
env:
SIGNING_ENABLED: ${{ vars.STUDIO_SIGNING_ENABLED }}
EXPECTED_SUBJECT: ${{ vars.STUDIO_SIGNING_SUBJECT }}
run: |
$ErrorActionPreference = 'Stop'
$failed = $false
foreach ($file in @('payload/probe.exe', 'installer-probe.exe')) {
$signature = Get-AuthenticodeSignature -LiteralPath $file
$certificate = $signature.SignerCertificate
$stamp = if ($signature.TimeStamperCertificate) { $signature.TimeStamperCertificate.Subject } else { '(none)' }
@("### $file", '', "- subject: ``$($certificate.Subject)``", "- issuer: ``$($certificate.Issuer)``",
"- thumbprint: ``$($certificate.Thumbprint)``", "- timestamp: ``$stamp``", '') >> $env:GITHUB_STEP_SUMMARY
if (-not $signature.TimeStamperCertificate) {
Write-Output "::error title=studio-signing.timestamp-missing::$file carries no timestamp"
$failed = $true
}
if ([string]::IsNullOrWhiteSpace($certificate.Issuer)) {
Write-Output "::error title=studio-signing.issuer-missing::$file has a signer certificate without an issuer"
$failed = $true
}
if ([string]::IsNullOrWhiteSpace($env:EXPECTED_SUBJECT)) {
if ($env:SIGNING_ENABLED -eq 'true') {
Write-Output "::error title=studio-signing.subject-unset::STUDIO_SIGNING_SUBJECT is empty while STUDIO_SIGNING_ENABLED=true"
$failed = $true
} else {
Write-Output "::warning::STUDIO_SIGNING_SUBJECT is not set; record '$($certificate.Subject)'"
}
} elseif ($certificate.Subject -cne $env:EXPECTED_SUBJECT) {
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
@@ -1,107 +0,0 @@
name: Studio Windows self-test
# An unsigned Windows installer for trying a branch on a real machine before it
# is released. It runs on the intranet runner, so it is dispatch-only: the
# repository is public, and nothing a pull request writes may run there.
on:
workflow_dispatch:
inputs:
ref:
description: Branch, tag or commit to build
required: false
default: studio
type: string
permissions:
contents: read
concurrency:
group: studio-selftest-windows
cancel-in-progress: true
jobs:
build:
runs-on: win-gpu
timeout-minutes: 90
steps:
# The machine's PATH finds WSL's bash before Git's, and a bash step run in
# WSL sees neither this checkout's toolchain nor Windows paths. cmd, since
# the machine's execution policy refuses the script a powershell step is.
- name: Put Git Bash first on PATH
shell: cmd
run: '>>"%GITHUB_PATH%" echo C:\Program Files\Git\bin'
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ inputs.ref }}
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
with:
go-version-file: go.mod
cache: true
cache-dependency-path: go.sum
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
version: 10
run_install: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
cache: pnpm
cache-dependency-path: |
desktop/frontend-next/pnpm-lock.yaml
desktop/electron/pnpm-lock.yaml
# A patch above the newest release, as a prerelease: it ranks ahead of
# what is published, so the build does not offer itself that release as
# an update, and behind the next one, which it does offer.
- name: Choose the version
id: version
shell: bash
run: |
latest="$(git ls-remote --tags origin 'refs/tags/studio-v*' | sed -n 's#.*refs/tags/studio-v\([0-9.]*\)$#\1#p' | sort -V | tail -1)"
test -n "$latest" || { echo "::error::no studio-v* release tag"; exit 1; }
IFS=. read -r major minor patch <<< "$latest"
version="$major.$minor.$((patch + 1))-selftest.${{ github.run_number }}"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "Version: \`$version\` from \`$(git rev-parse --short HEAD)\`" >> "$GITHUB_STEP_SUMMARY"
# The intranet's route to the module proxy drops connections now and then.
# What arrives stays in this machine's module cache, so a retry resumes.
- name: Fetch Go modules
shell: bash
run: for i in 1 2 3 4 5; do go mod download && exit 0; sleep 10; done; exit 1
- name: Build the SPA
working-directory: desktop/frontend-next
shell: bash
run: pnpm install --frozen-lockfile && pnpm build
- name: Build the kernel
working-directory: desktop/electron
shell: bash
env:
REASONIX_VERSION: v${{ steps.version.outputs.version }}
run: pnpm install --frozen-lockfile && pnpm run build:host
- name: Build the bundle
working-directory: desktop/electron
shell: bash
run: pnpm exec electron-builder --dir -c.extraMetadata.version="${{ steps.version.outputs.version }}"
- name: Package the installer
working-directory: desktop/electron
shell: bash
run: |
pnpm exec electron-builder --prepackaged ../../dist/win-unpacked --win nsis \
-c.extraMetadata.version="${{ steps.version.outputs.version }}"
sha256sum ../../dist/ReasonixStudio-windows-amd64-installer.exe | tee -a "$GITHUB_STEP_SUMMARY"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: studio-selftest-windows-${{ steps.version.outputs.version }}
path: dist/ReasonixStudio-windows-amd64-installer.exe
if-no-files-found: error
retention-days: 7
-688
View File
@@ -1,688 +0,0 @@
name: Studio
# Studio's own surface — desktop/frontend-next (the SPA) and the Electron shell
# that serves it — exists only on the studio branch, so it cannot live in ci.yml
# without failing on main-v2 where neither directory is present. ci.yml covers
# the kernel; this file covers the frontend build, the desktop module's Go side,
# and the packaging contract on real artifacts.
on:
push:
branches: [studio]
pull_request:
branches: [studio]
permissions:
contents: read
concurrency:
group: studio-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.ref == 'refs/heads/studio' }}
jobs:
frontend:
name: frontend-next
runs-on: ubuntu-latest
defaults:
run:
working-directory: desktop/frontend-next
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
version: 10
run_install: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
cache: pnpm
cache-dependency-path: desktop/frontend-next/pnpm-lock.yaml
- name: Install
run: pnpm install --frozen-lockfile
- name: typecheck
run: pnpm typecheck
# The reducer and the event port carry the two pieces of logic a type
# error cannot reach: what a card means when a turn is interrupted, and
# what the client does about a frame that never arrived.
- name: test
run: pnpm test
# What the UI census holds. The gate reads structure — which inputs reach
# a mutating endpoint, and which of those the product names an action for
# — so UNDECLARED_MUTATION == 0 is a fact about the tree, not a lint over
# how anything is spelled.
- name: census invariants
run: pnpm census > /dev/null
# And that the analyzer still judges the way it did. _fx is a corpus
# written to exercise the rules, so its reports move only when a judgement
# moves; the product's name every root by file and line and are stale the
# moment a button moves, which is why they are not frozen.
- name: census fixture reports have not drifted
run: pnpm census:verify
# `build` runs tsc -b before vite, so this also proves the project
# references resolve — typecheck alone uses --noEmit and does not.
- name: build
run: pnpm build
# The published bundle must not carry MockPort's scripted fixtures: a
# release that cannot reach the kernel has to say so, not act out a fake
# session. main.tsx guards the import behind import.meta.env.DEV, and this
# is what proves the guard still holds.
- name: no fixtures in the bundle
run: |
if grep -rl 网关瞬时态 dist/ 2>/dev/null; then
echo "::error::MockPort fixtures reached the production bundle - check the import.meta.env.DEV guard in main.tsx"
exit 1
fi
# Real-Chromium guards that run without a kernel. Only the ones that passed
# three consecutive local runs are wired; the rest stay manual (see
# desktop/frontend-next/perf/README.md). Skipped unless the SPA changed.
browser-guards:
name: browser guards
runs-on: ubuntu-latest
timeout-minutes: 25
defaults:
run:
working-directory: desktop/frontend-next
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
- name: SPA changed?
id: spa
working-directory: .
run: |
if [ "${{ github.event_name }}" = "pull_request" ] &&
git diff --quiet "origin/${{ github.base_ref }}...HEAD" -- desktop/frontend-next; then
echo "run=false" >> "$GITHUB_OUTPUT"
else
echo "run=true" >> "$GITHUB_OUTPUT"
fi
- if: steps.spa.outputs.run == 'true'
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
version: 10
run_install: false
- if: steps.spa.outputs.run == 'true'
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
cache: pnpm
cache-dependency-path: desktop/frontend-next/pnpm-lock.yaml
- if: steps.spa.outputs.run == 'true'
name: Install
run: pnpm install --frozen-lockfile
- if: steps.spa.outputs.run == 'true'
name: Build the perf harness and install Chromium
run: |
pnpm exec vite build --config vite.perf.config.ts
pnpm exec playwright install --with-deps chromium
- if: steps.spa.outputs.run == 'true'
name: Guards
run: |
python3 -m http.server 4399 --directory dist-perf >/dev/null 2>&1 &
for _ in $(seq 30); do curl -sf http://localhost:4399/perf.html >/dev/null && break; sleep 1; done
node perf/intrinsic.mjs
node perf/firstscreen-fonts.mjs
node perf/contrast.mjs
node perf/stickyfold.mjs
node perf/crumb.mjs
node perf/hoverradius.mjs
node perf/jump-ends.mjs
node perf/modelrows.mjs
node perf/explorersize.mjs
node perf/git-panel.mjs
node perf/session-move-to.mjs
node perf/shell-refused.mjs
node perf/external-origin.mjs
node perf/rail-search-hold.mjs
node perf/rail-toggle-panes.mjs
node perf/session-move.mjs
node perf/session-ref.mjs
node perf/browser-full.mjs
node perf/mod-ui.mjs
node perf/codeeditor-size.mjs
node perf/composer-reflow.mjs
node perf/composer-toolbar-row.mjs
node perf/action-icons.mjs
node perf/rowhit.mjs
node perf/prefs-wide-centered.mjs
node perf/tab-pip.mjs
node perf/syntax-tokens.mjs
node perf/tab-close-inside.mjs
node perf/context-card-hover.mjs
node perf/sessquick.mjs
node perf/sessionrows.mjs
node perf/session-row-marker.mjs
node perf/session-selected-row.mjs
node perf/wheel.mjs
node perf/branch-tooltip.mjs
node perf/branch-alignment.mjs
node perf/branch-menu.mjs
node perf/image-preview.mjs
node perf/user-images.mjs
node perf/toast-anchor.mjs
node perf/addfolder-rest.mjs
node perf/scroll-jump.mjs
node perf/add-project-selects.mjs
node perf/project-header.mjs
node perf/setup-defer.mjs
node perf/narrow.mjs
node perf/settings-rows.mjs
node perf/narrow-steps.mjs
node perf/job-names.mjs
node perf/mcp-actions.mjs
node perf/web-access.mjs
node perf/peers-settings.mjs
node perf/output-cap.mjs
node perf/tool-output-clip.mjs
node perf/agent-run-tab.mjs
node perf/changes-cap.mjs
node perf/session-menu-fit.mjs
node perf/rail-rows-typography.mjs
node perf/settings-nav-fit.mjs
node perf/rail-rows-align.mjs
node perf/progress-tail.mjs
node perf/trust-wait.mjs
node perf/nest-nodes.mjs
node perf/provider-ports.mjs
node perf/peer-threads.mjs
node perf/text-size.mjs
node perf/fs-scale.mjs
node perf/composer-feel.mjs
node perf/side-panel.mjs
node perf/card-shell.mjs
node perf/line-cards.mjs
node perf/detail-panel.mjs
node perf/brand-lockup.mjs
node perf/notice-line.mjs
node perf/brought-line.mjs
node perf/modal-focus.mjs
node perf/focus-ring.mjs
node perf/narrow-forms.mjs
node perf/i18n-rendered.mjs
node perf/narrow-rail.mjs
node perf/selfcheck.mjs branch-tooltip
# What a hosted page does over the relay, end to end: the production bundle,
# the real Studio host and kernel, a real Chromium; only the accounts API and
# the relay are stand-ins (tools/relayfake). Event-transport changes are
# judged here, because a unit test of one side cannot see the other.
relay-harness:
name: relay harness
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
- name: Transport changed?
id: scope
env:
BASE_REF: ${{ github.base_ref }}
run: |
paths="desktop/frontend-next internal/frontend/serve internal/platform/remotecloud internal/platform/account tools/relayfake cmd/reasonix-studio-host"
if [ "$GITHUB_EVENT_NAME" = "pull_request" ] &&
git diff --quiet "origin/$BASE_REF...HEAD" -- $paths; then
echo "run=false" >> "$GITHUB_OUTPUT"
else
echo "run=true" >> "$GITHUB_OUTPUT"
fi
- if: steps.scope.outputs.run == 'true'
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
with:
go-version-file: go.mod
cache: true
- if: steps.scope.outputs.run == 'true'
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
version: 10
run_install: false
- if: steps.scope.outputs.run == 'true'
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
cache: pnpm
cache-dependency-path: desktop/frontend-next/pnpm-lock.yaml
- if: steps.scope.outputs.run == 'true'
name: Build the host, the stand-ins and the page
run: |
go build -o desktop/frontend-next/relay/bin/studio-host ./cmd/reasonix-studio-host
go build -o desktop/frontend-next/relay/bin/relayfake ./tools/relayfake
cd desktop/frontend-next
pnpm install --frozen-lockfile
pnpm exec vite build --outDir dist-relay --emptyOutDir
pnpm exec playwright install --with-deps chromium
- if: steps.scope.outputs.run == 'true'
name: Scenarios (hosted page over the relay; local page on a flapping network)
working-directory: desktop/frontend-next
env:
RELAY_HOST_BIN: ${{ github.workspace }}/desktop/frontend-next/relay/bin/studio-host
RELAY_FAKE_BIN: ${{ github.workspace }}/desktop/frontend-next/relay/bin/relayfake
RELAY_DIST: ${{ github.workspace }}/desktop/frontend-next/dist-relay
run: |
node relay/live.mjs
node relay/storm.mjs
# A pull request with no platform-relevant change (scripts/ci-platform-scope.sh)
# moves the Windows and macOS legs onto an ubuntu runner with every step
# skipped, so the check names still report without a scarce runner. A push to
# studio, or a failed `scope`, runs all three.
desktop:
name: desktop (${{ matrix.os }})
needs: scope
if: always()
runs-on: ${{ github.event_name == 'pull_request' && needs.scope.outputs.platform == 'false' && matrix.os != 'ubuntu-22.04' && 'ubuntu-latest' || matrix.os }}
env:
RUN_STEPS: ${{ github.event_name != 'pull_request' || needs.scope.outputs.platform != 'false' || matrix.os == 'ubuntu-22.04' }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-22.04, windows-latest, macos-latest]
defaults:
run:
working-directory: desktop
steps:
- if: env.RUN_STEPS == 'true'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- if: env.RUN_STEPS == 'true'
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
with:
go-version-file: desktop/go.mod
cache: true
cache-dependency-path: desktop/go.sum
# The desktop module's Go tests: the elevated update helper, the
# release-side tools and the Windows uninstall planner. The code this
# gate covers is what replaces a running application on a user's disk.
# The module is CGO-free since the Wails shell retired, so no platform
# carries build dependencies of its own.
# Same command as `make studio-test`; this job is already in desktop/.
- name: go test
if: env.RUN_STEPS == 'true'
run: go test ./...
- if: env.RUN_STEPS == 'true'
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
- name: CUA process and packaging contracts
if: env.RUN_STEPS == 'true'
timeout-minutes: 2
run: node --test --test-name-pattern=CUA electron/test/unit.mjs
- name: Install Linux native CUA fixture dependencies
if: env.RUN_STEPS == 'true' && runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y xvfb openbox dbus-x11 libgtk-3-dev at-spi2-core
- name: Native CUA application acceptance
if: env.RUN_STEPS == 'true'
timeout-minutes: 6
shell: bash
run: |
if [ "$RUNNER_OS" = Linux ]; then
dbus-run-session -- xvfb-run -a sh -c 'openbox >/tmp/reasonix-openbox.log 2>&1 & export NO_AT_BRIDGE=0 GTK_MODULES=gail:atk-bridge; node electron/test/cua-native.mjs'
else
node electron/test/cua-native.mjs
fi
# The host sits in the main module and nothing else builds it, so its
# dependency closure is checked here: it must stay CGO-free and
# platform-neutral or the Electron bundle cannot ship it. Cross-compiling
# is host-independent, so once is enough.
- name: host stays pure Go and platform-neutral
if: env.RUN_STEPS == 'true' && runner.os == 'Linux'
working-directory: .
run: |
for os in windows linux darwin; do
for arch in amd64 arm64; do
CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build -o /dev/null ./cmd/reasonix-studio-host
done
done
# The ARM64 leg queues on a scarcer runner pool, so a pull request runs it
# only when it touches what the leg verifies; a push to studio always does.
# The macOS and Windows package legs follow `platform`, the same rule as the
# desktop matrix above.
scope:
name: package matrix
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.pick.outputs.matrix }}
arm64: ${{ steps.pick.outputs.arm64 }}
platform: ${{ steps.pick.outputs.platform }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
- id: pick
env:
EVENT: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
arm64=true
platform=true
if [ "$EVENT" = pull_request ]; then
arm64=false
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
arm64=true
fi
fi
legs='[
{"os":"macos-latest","arch":"arm64","platform":"darwin"},
{"os":"ubuntu-22.04","arch":"amd64","platform":"linux"},
{"os":"windows-latest","arch":"amd64","platform":"windows","ebarch":"x64"}
]'
if [ "$platform" = false ]; then
legs="$(jq -c 'map(select(.platform == "linux"))' <<<"$legs")"
elif [ "$arm64" = true ]; then
legs="$(jq -c '. + [{"os":"windows-11-arm","arch":"arm64","platform":"windows","ebarch":"arm64"},{"os":"ubuntu-22.04-arm","arch":"arm64","platform":"linux"}]' <<<"$legs")"
else
legs="$(jq -c . <<<"$legs")"
fi
{
echo "arm64=$arm64"
echo "platform=$platform"
echo "matrix={\"include\":$legs}"
} >> "$GITHUB_OUTPUT"
# The packaging contract, on real artifacts rather than on the config that
# describes them. Unsigned on purpose: signing and notarization are a
# distribution concern and belong to the release workflow, and treating their
# absence as "packaging unverified" is what left macOS and Linux resting on a
# cross-compile while only Windows had ever produced a package.
package:
name: package (${{ matrix.os }})
needs: scope
runs-on: ${{ matrix.os }}
timeout-minutes: 45
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.scope.outputs.matrix) }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
with:
go-version-file: desktop/go.mod
cache: true
cache-dependency-path: desktop/go.sum
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
version: 10
run_install: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: "24"
cache: pnpm
cache-dependency-path: desktop/electron/pnpm-lock.yaml
# electron-builder shells out to dpkg-deb through fakeroot for the .deb and
# to rpmbuild for the .rpm.
- name: Install Linux packaging deps
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y fakeroot rpm cpio xvfb xauth policykit-1
# The fpm electron-builder carries is an x86_64 program, so on an ARM64
# runner the .deb and .rpm are built with one installed from RubyGems.
- name: Use a native fpm on ARM64 Linux
if: runner.os == 'Linux' && runner.arch == 'ARM64'
run: |
sudo apt-get install -y ruby ruby-dev build-essential
sudo gem install --no-document fpm -v 1.16.0
echo "USE_SYSTEM_FPM=true" >> "$GITHUB_ENV"
- name: Build the SPA
working-directory: desktop/frontend-next
run: pnpm install --frozen-lockfile && pnpm build
# The Windows legs name their architecture instead of taking the
# toolchain's, so a runner whose Go or Node is the other architecture
# fails here rather than shipping a mislabelled package.
- name: Build the kernel the shell speaks to
working-directory: desktop/electron
env:
REASONIX_GOARCH: ${{ matrix.platform == 'windows' && matrix.arch || '' }}
REASONIX_VERSION: v0.0.0-ci
run: pnpm install --frozen-lockfile && pnpm test && pnpm run build:host
# The .deb's absolute-path payload. A no-op off Linux, so it is not
# guarded here: the one place it must not be forgotten is the one place
# it does anything.
- name: Stage the Linux package payload
working-directory: desktop/electron
run: pnpm run build:linux-payload
# No identity on a runner, and none wanted here: auto-discovery would make
# this job fail for the one reason it is not testing.
- name: Package
working-directory: desktop/electron
env:
CSC_IDENTITY_AUTO_DISCOVERY: "false"
ELECTRON_BUILDER_7Z_FILTER: ${{ matrix.platform == 'windows' && matrix.arch == 'arm64' && 'BCJ' || '' }}
run: pnpm run build:dist ${{ matrix.ebarch && format('--{0}', matrix.ebarch) || '' }} -c.extraMetadata.version=0.0.0-ci
# The release vocabulary is GOARCH. electron-builder's own is not, and the
# rename that reconciles them runs here rather than in the manifest.
- name: Artifacts carry the release architecture
run: |
ls -la dist
if ls dist | grep -q -- '-x64'; then
echo "::error::an artifact still names x64; studio-manifest reads names as GOARCH"
exit 1
fi
if ! ls dist | grep -q -- "-${{ matrix.platform }}-${{ matrix.arch }}"; then
echo "::error::no artifact named for ${{ matrix.platform }}-${{ matrix.arch }}"
exit 1
fi
# An emulated x64 program runs on ARM64 Windows, so a package that merely
# starts proves nothing about its architecture: every PE image in the
# bundle has to be built for the one the package is named for.
- name: Every PE image is built for the package's architecture
if: matrix.platform == 'windows'
run: |
dir=$(find dist -maxdepth 1 -type d -name 'win*-unpacked' | head -1)
test -n "$dir"
node desktop/electron/packaging/pe.js "$dir" "${{ matrix.arch }}"
# An update starts the installer with --updated, and that is what keeps the
# shortcuts (and the taskbar pin hanging off them) from being deleted and
# recreated. Installed twice over itself the way an update does it, the
# desktop shortcut has to still be the same file, pointing at a path with
# no version in it, or every update costs the user their pin.
- name: An update keeps the shortcuts and they name no version
if: matrix.platform == 'windows'
shell: pwsh
run: |
$installer = (Get-ChildItem dist -Filter 'ReasonixStudio-windows-*-installer.exe' | Select-Object -First 1).FullName
$dir = Join-Path $env:RUNNER_TEMP 'rx-update-guard'
Start-Process $installer -ArgumentList '/S', "/D=$dir" -Wait
$lnk = Join-Path ([Environment]::GetFolderPath('Desktop')) 'Reasonix Studio.lnk'
$target = (New-Object -ComObject WScript.Shell).CreateShortcut($lnk).TargetPath
if ($target -ne (Join-Path $dir 'Reasonix Studio.exe')) { throw "the desktop shortcut targets $target, not the stable executable" }
$mark = [datetime]'2020-01-01'
(Get-Item $lnk).LastWriteTime = $mark
Start-Process $installer -ArgumentList '/S', '--updated', "/D=$dir" -Wait
if ((Get-Item $lnk).LastWriteTime -ne $mark) { throw 'an update rewrote the desktop shortcut' }
Start-Process (Join-Path $dir 'Uninstall Reasonix Studio.exe') -ArgumentList '/S', '/currentuser' -Wait
# The release packages a signed copy of the bundle and then reads both
# packages back against it. The same recipe on an unsigned copy, so the
# packaging contract (the installer's one application archive, the pinned
# elevate.exe, every PE image's architecture) is exercised on pull
# requests and not first by a release.
- name: The packages read back against the bundle they were made from
if: matrix.platform == 'windows'
shell: bash
env:
ELECTRON_BUILDER_7Z_FILTER: ${{ matrix.arch == 'arm64' && 'BCJ' || '' }}
run: |
rm -rf payload nsis-src packed zip-src
cp -r "$(find dist -maxdepth 1 -type d -name 'win*-unpacked' | head -1)" payload
rm -f payload/resources/elevate.exe
# The NSIS run writes elevate.exe into the tree it packs, so each
# packager gets a copy and payload stays what was signed.
cp -r payload zip-src
cp -r payload nsis-src
cd desktop/electron
pnpm exec electron-builder --prepackaged ../../zip-src --win zip --${{ matrix.ebarch }} \
-c.extraMetadata.version=0.0.0-ci -c.directories.output=../../packed-zip
pnpm exec electron-builder --prepackaged ../../nsis-src --win nsis --${{ matrix.ebarch }} \
-c.extraMetadata.version=0.0.0-ci -c.directories.output=../../packed
mv ../../packed-zip/ReasonixStudio-windows-${{ matrix.arch }}.zip ../../packed/
ls -la ../../packed
- name: verify-windows-package.ps1 accepts them
if: matrix.platform == 'windows'
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
. ./scripts/windows-signing-lib.ps1
$digest = Get-ManifestDigest -Manifest @(Get-TreeManifest -Root payload)
./scripts/verify-windows-package.ps1 `
-PayloadDirectory payload `
-ExpectedPayloadDigest $digest `
-InstallerPath "packed/ReasonixStudio-windows-${{ matrix.arch }}-installer.exe" `
-PortableArchivePath "packed/ReasonixStudio-windows-${{ matrix.arch }}.zip" `
-OutputPath "$env:RUNNER_TEMP/verify-output.txt" `
-Architecture ${{ matrix.arch }}
Get-Content "$env:RUNNER_TEMP/verify-output.txt"
# The release's own install smoke, against the unsigned installer: the
# package is installed where it is meant to run, its tree checked, and
# removed.
- name: The package installs, runs and uninstalls
if: matrix.platform == 'windows'
shell: pwsh
run: |
./scripts/install-smoke.ps1 `
-Installer "dist/ReasonixStudio-windows-${{ matrix.arch }}-installer.exe" `
-Architecture ${{ matrix.arch }}
- name: Keep the arm64 installer for the x64 refusal check
if: matrix.platform == 'windows' && matrix.arch == 'arm64'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: studio-arm64-installer-ci
path: dist/ReasonixStudio-windows-arm64-installer.exe
if-no-files-found: error
retention-days: 1
# The update channel is the signed manifest. A second answer to which
# version is current is not a convenience. The .blockmap is the same
# channel's differential index and carries the release prefix, so it also
# inflates the count the release uses to refuse a partial publish.
- name: No electron-updater metadata
run: |
if ls dist | grep -qiE '^(latest|beta|alpha).*\.yml$'; then
echo "::error::electron-updater metadata was published beside the manifest channel"
exit 1
fi
if ls dist | grep -q '\.blockmap$'; then
echo "::error::a .blockmap ships under the release prefix; set differentialPackage: false"
exit 1
fi
# A binary inside app.asar cannot be spawned and the kernel serves the SPA
# off disk, so both have to be resources. Found rather than asserted at a
# path, because the unpacked directory is named by the builder.
- name: The kernel and the page are resources, not archive members
run: |
host=$(find dist -type f -path '*/bin/reasonix-studio-host*' ! -path '*app.asar*' | head -1)
page=$(find dist -type f -path '*/frontend-next/dist/index.html' ! -path '*app.asar*' | head -1)
echo "kernel: ${host:-<missing>}"
echo "page: ${page:-<missing>}"
test -n "$host" -a -n "$page"
- name: Linux packages carry their declared architecture and update payload
if: runner.os == 'Linux'
run: bash scripts/verify-linux-package.sh "dist/ReasonixStudio-linux-${{ matrix.arch }}.deb" "dist/ReasonixStudio-linux-${{ matrix.arch }}.rpm" "${{ matrix.arch }}"
- name: The Linux package installs, runs, reinstalls and uninstalls
if: runner.os == 'Linux'
run: bash scripts/linux-install-smoke.sh "dist/ReasonixStudio-linux-${{ matrix.arch }}.deb" "${{ matrix.arch }}" 0.0.0-ci
- name: The AppImage carries its architecture, the kernel and the page
if: runner.os == 'Linux'
run: bash scripts/verify-linux-appimage.sh "dist/ReasonixStudio-linux-${{ matrix.arch }}.AppImage" "${{ matrix.arch }}"
# Recorded, not asserted: the real bundle layout, so later work argues
# from what electron-builder produced rather than from its documentation.
- name: Record the macOS bundle layout
if: runner.os == 'macOS'
run: |
app=$(find dist -maxdepth 2 -name '*.app' | head -1)
echo "app: $app"
ls "$app/Contents"
ls "$app/Contents/Resources" | head -20
ls "$app/Contents/Frameworks" | head -20
# The end of the contract: not that the name parses, but that the manifest
# keys the artifact under the platform this runner actually is. The tool
# writes latest.json into the directory and logs to stdout, so the check
# reads the file -- captured output would match its own progress line.
- name: studio-manifest resolves the platform this runner is
working-directory: desktop
env:
GITHUB_REPOSITORY: ${{ github.repository }}
run: |
go run ./cmd/studio-manifest ../dist v0.0.0-ci v0.0.0-ci
cat ../dist/latest.json
if ! grep -q '"${{ matrix.platform }}-${{ matrix.arch }}"' ../dist/latest.json; then
echo "::error::the manifest has no entry for ${{ matrix.platform }}-${{ matrix.arch }}"
exit 1
fi
# The arm64 installer carries one application and no other. Run anywhere but
# ARM64 Windows it has to say so and stop, instead of exiting 0 with nothing
# installed.
arm64-installer-refuses-x64:
name: arm64 installer refuses an x64 machine
needs: [scope, package]
if: needs.scope.outputs.arm64 == 'true'
runs-on: windows-latest
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: studio-arm64-installer-ci
path: installer
- name: Run it silently
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$target = Join-Path $env:RUNNER_TEMP 'rx-refused'
$run = Start-Process -FilePath installer/ReasonixStudio-windows-arm64-installer.exe -ArgumentList '/S', "/D=$target" -Wait -PassThru
Write-Host "exit code $($run.ExitCode)"
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' }
@@ -1,38 +0,0 @@
name: Update acknowledgments
on:
workflow_dispatch:
schedule:
- cron: '17 3 * * 1'
permissions:
contents: write
pull-requests: write
jobs:
update:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '22'
- name: Update README contributor tables
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: node scripts/update-acknowledgments.mjs
- name: Open pull request
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8
with:
# GITHUB_TOKEN-authored pull requests never trigger CI, so required checks would never report.
token: ${{ secrets.ACKNOWLEDGMENTS_TOKEN || secrets.GITHUB_TOKEN }}
branch: chore/update-acknowledgments
delete-branch: true
title: 'Update acknowledgments contributors / 更新致谢贡献者'
commit-message: 'docs: update acknowledgments contributors'
body: |
Refreshes the README acknowledgments tables from the GitHub contributors API.
- Source: `repos/esengine/DeepSeek-Reasonix/contributors?per_page=50&anon=1`
- The repository owner, declared aliases, tool identities, bots and entries without a GitHub login are left out (`scripts/credit-identities.json`).
labels: documentation
-74
View File
@@ -1,74 +0,0 @@
name: Update Star History chart
on:
workflow_dispatch:
push:
branches:
- main-v2
paths:
- '.github/workflows/update-star-history.yml'
- 'scripts/update-star-history.mjs'
- 'scripts/update-star-history.test.mjs'
schedule:
- cron: '23 */3 * * *'
permissions:
contents: write
concurrency:
group: update-star-history
cancel-in-progress: false
jobs:
update:
if: github.repository == 'esengine/DeepSeek-Reasonix'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '22'
- name: Test chart generator
run: node --test scripts/update-star-history.test.mjs
- name: Generate chart assets
env:
STAR_HISTORY_GITHUB_TOKEN: ${{ secrets.STAR_HISTORY_GITHUB_TOKEN }}
STAR_HISTORY_OUTPUT_DIR: ${{ runner.temp }}/star-history
run: node scripts/update-star-history.mjs
- name: Publish chart assets
env:
OUTPUT_DIR: ${{ runner.temp }}/star-history
TARGET_BRANCH: star-history
run: |
set -euo pipefail
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if git fetch origin "$TARGET_BRANCH"; then
git switch --force-create "$TARGET_BRANCH" "origin/$TARGET_BRANCH"
else
git switch --create "$TARGET_BRANCH"
fi
mkdir -p assets/star-history
cp "$OUTPUT_DIR/star-history-light.svg" assets/star-history/star-history-light.svg
cp "$OUTPUT_DIR/star-history-dark.svg" assets/star-history/star-history-dark.svg
git add assets/star-history
if git diff --cached --quiet; then
echo "Star History chart is already current."
exit 0
fi
git commit \
-m "docs: update Star History chart" \
-m "Automated update:
Refresh the repository-hosted light and dark Star History SVGs from the authenticated GitHub stargazers API.
Verification:
- chart generator tests passed
- both SVG assets were rendered from timestamped stargazer data"
git push origin HEAD:"$TARGET_BRANCH"
@@ -1,29 +0,0 @@
name: 1.x nightly monitoring
# A schedule runs only from the default branch. These monitors measure the 1.x
# desktop app, which lives on main-v2 alone, so their nightly runs are started
# from here on that branch. Their push and pull_request gates run on main-v2 as
# before.
on:
schedule:
- cron: "17 3 * * *"
- cron: "43 4 * * *"
workflow_dispatch:
permissions:
actions: write
jobs:
dispatch:
runs-on: ubuntu-latest
steps:
- name: App memory screening
if: github.event_name == 'workflow_dispatch' || github.event.schedule == '17 3 * * *'
env:
GH_TOKEN: ${{ github.token }}
run: gh workflow run app-memory.yml --repo "$GITHUB_REPOSITORY" --ref main-v2
- name: Diagnostic overhead monitoring
if: github.event_name == 'workflow_dispatch' || github.event.schedule == '43 4 * * *'
env:
GH_TOKEN: ${{ github.token }}
run: gh workflow run diagnostic-overhead.yml --repo "$GITHUB_REPOSITORY" --ref main-v2
@@ -1,84 +0,0 @@
name: Withdraw a Studio version
# Pulls a published Studio release out of the update catalog (or puts it back),
# so installs stop being offered it without waiting for a new release. Only the
# catalog changes: the release's files stay where they are, and a withdrawn
# release can be restored with the same run.
on:
workflow_dispatch:
inputs:
version:
description: "Version to withdraw or restore, for example 2.36.0"
required: true
type: string
reason:
description: "Why it is withdrawn (shown to users on that version); ignored when restoring"
required: false
type: string
restore:
description: "Put a withdrawn version back instead of withdrawing it"
required: false
type: boolean
default: false
concurrency:
group: studio-catalog
cancel-in-progress: false
jobs:
withdraw:
name: ${{ inputs.restore && 'restore' || 'withdraw' }} ${{ inputs.version }}
runs-on: ubuntu-latest
timeout-minutes: 10
environment: studio-release
permissions:
contents: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: studio
persist-credentials: false
- name: Update the Studio catalog
env:
VERSION: ${{ inputs.version }}
REASON: ${{ inputs.reason }}
RESTORE: ${{ inputs.restore }}
R2_BUCKET: ${{ secrets.R2_BUCKET }}
HAS_R2: ${{ secrets.R2_ACCESS_KEY_ID != '' && secrets.R2_SECRET_ACCESS_KEY != '' && secrets.R2_ACCOUNT_ID != '' && secrets.R2_BUCKET != '' }}
run: |
if [ "$HAS_R2" != "true" ]; then
echo "::error::R2 credentials are not configured, so the catalog cannot be changed"
exit 1
fi
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then
echo "::error::version must look like 2.36.0"
exit 1
fi
aws configure set aws_access_key_id "${{ secrets.R2_ACCESS_KEY_ID }}"
aws configure set aws_secret_access_key "${{ secrets.R2_SECRET_ACCESS_KEY }}"
aws configure set default.region auto
endpoint="https://${{ secrets.R2_ACCOUNT_ID }}.r2.cloudflarestorage.com"
at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
current=/tmp/studio-versions-current.json
next=/tmp/studio-versions-next.json
aws s3 cp "s3://${R2_BUCKET}/studio/versions.json" "$current" --endpoint-url "$endpoint"
if [ "$RESTORE" = "true" ]; then
bash scripts/withdraw-version.sh "$current" --restore "$VERSION" "$at" > "$next"
jq -e --arg v "$VERSION" '.versions | map(select((.version | ltrimstr("v")) == $v)) | length == 1' "$next" >/dev/null
else
bash scripts/withdraw-version.sh "$current" "$VERSION" "$REASON" "$at" > "$next"
jq -e --arg v "$VERSION" '(.versions | map(select((.version | ltrimstr("v")) == $v)) | length == 0) and (.withdrawn | map(select((.version | ltrimstr("v")) == $v)) | length == 1)' "$next" >/dev/null
fi
aws s3 cp "$next" "s3://${R2_BUCKET}/studio/versions.json" \
--endpoint-url "$endpoint" \
--content-type "application/json; charset=utf-8" \
--cache-control "public, max-age=300, stale-if-error=86400"
echo "Studio catalog updated for $VERSION (restore=$RESTORE)"
- name: Keep the GitHub release off the latest slot
if: ${{ !inputs.restore }}
env:
GH_TOKEN: ${{ github.token }}
VERSION: ${{ inputs.version }}
run: gh release edit "studio-v${VERSION}" --prerelease --latest=false --repo "$GITHUB_REPOSITORY"
+29 -91
View File
@@ -1,98 +1,36 @@
# Build artifacts. A `go build` of one command writes its binary into the
# working directory, so every main package in the root module can drop its own
# name here; repolint's build-artifact rule holds the two lists together.
/bin/
/dist/
/stage/
/npm/.stage/
/reasonix
/reasonix.exe
/e2ebench
/e2ebench.exe
/context-retrieval
/compaction
/context-maintenance-e2e
/runtime-resume
/extension-protocol-gen
/reasonix-plugin-example
/mcp-line-counter-kit
/reasonix-studio-host
/signpath-contract
/studio-delta
/covergate
/pricecheck
/repolint
/workgroupassay
/write_heartbeat
/catalog-detector
/tool-surface-cache
# Go test/build scratch
*.test
*.out
*.coverprofile
coverage.out
cpu.prof
mem.prof
# Wails desktop artifacts
/desktop/build/*
!/desktop/build/appicon.png
!/desktop/build/appicon.svg
/desktop/desktop
/desktop/frontend/dist/*
!/desktop/frontend/dist/.gitkeep
/desktop/frontend/sourcemaps/
/desktop/frontend/wailsjs/
/desktop/frontend/package.json.md5
# Environment / local config (reasonix.example.toml is the shared template)
node_modules/
dist/
coverage/
.stryker-tmp/
.env
.env.local
*.local
/reasonix.toml
/desktop/.env
/desktop/reasonix.toml
# Node / frontend dependencies and caches
node_modules/
.pnpm-store/
.npm/
# Project-local Reasonix state; keep the checked-in review command.
/.reasonix/*
!/.reasonix/commands/
!/.reasonix/commands/review.md
# Stray Reasonix state written under a package dir by a test whose RealPath
# resolves to CWD (e.g. remote bootstrap EnsureServe). Never commit these.
internal/**/.reasonix/
desktop/**/.reasonix/
# CodeGraph per-project index (rebuilt locally; never committed)
.codegraph/
# Editor / OS
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
.DS_Store
Thumbs.db
.idea/
.vscode/
*.tsbuildinfo
transcripts/
sessions/
*.jsonl
!tests/**/*.jsonl
# Committed reference transcripts so readers can reasonix replay / diff
# the v0.1 bench results without an API key.
!benchmarks/tau-bench/transcripts/
!benchmarks/tau-bench/transcripts/*.jsonl
.turbo/
# Local-only Claude Code settings — personal overrides, never committed.
.claude/settings.local.json
# Per-user Reasonix state under .reasonix/ — committable team-level
# files (settings.json, skills/) stay tracked, but the user-private
# bits (semantic index, sessions, opt-out markers) never should.
.reasonix/semantic/
.reasonix/sessions/
.reasonix/semantic-skip
# Scratch entry regenerated each time scripts/bundle-codemirror.mjs runs.
scripts/.cm-entry.mjs
benchmarks/context-maintenance-e2e/run/
# Local scratch
temp/
# Official theme art intermediate outputs / caches
scripts/official-theme-art/out/
scripts/official-theme-art/__pycache__/
# Committed pointer at REASONIX.md; overrides a global CLAUDE.md ignore rule.
!/CLAUDE.md
# Go build output left in the tree by `go build ./tools/...`. The ~ form is
# what a linker leaves behind when it cannot replace a binary that is still
# running, which on Windows is every rebuild while Studio is open.
*.exe
*.exe~
/relayfake
-1
View File
@@ -1 +0,0 @@
v2.12.2
-64
View File
@@ -1,64 +0,0 @@
version: "2"
linters:
enable:
- copyloopvar
- errcheck
- errorlint
- govet
- ineffassign
- intrange
- modernize
- staticcheck
- unused
- usestdlibvars
settings:
modernize:
# omitempty -> omitzero changes which fields are written for nested
# structs. That is a wire-format change to session files and the
# extension protocol, not a refactor, so it lands on its own.
disable:
- omitzero
errcheck:
check-type-assertions: false
exclude-functions:
- (*os.File).Close
- (io.Closer).Close
- (*net/http.Response).Body.Close
- golang.org/x/term.Restore
# Win32: CloseHandle in a defer mirrors the Close exclusions above, and
# LazyProc.Call always returns a non-nil errno — the caller reads r1.
- golang.org/x/sys/windows.CloseHandle
- (*syscall.LazyProc).Call
- (*golang.org/x/sys/windows.LazyProc).Call
staticcheck:
checks:
- all
- -ST1005 # error strings ending with punctuation — too strict for initial adoption
- -ST1018 # Unicode format characters — intentional in TUI code
- -QF1001 # De Morgan's law — readability preference
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
rules:
# Setup/teardown in tests routinely ignores cleanup errors.
- path: _test\.go
linters:
- errcheck
# The pinned golangci-lint binary's staticcheck reports SA5011 false
# positives on `if x == nil { t.Fatal(...) }`-guarded derefs in tests (it
# doesn't treat t.Fatal as terminating); the same code is clean under a
# locally-built golangci-lint. Scope the suppression to tests so SA5011
# still guards production code.
- path: _test\.go
linters:
- staticcheck
text: SA5011
issues:
max-issues-per-linter: 0
max-same-issues: 0
-65
View File
@@ -1,65 +0,0 @@
version: 2
project_name: reasonix
before:
hooks:
- go mod download
builds:
- id: reasonix
main: ./cmd/reasonix
binary: reasonix
env:
- CGO_ENABLED=0
flags:
- -trimpath
ldflags:
# Inject version identity for `reasonix version --verbose/--json` (Integration D/E).
# buildTimeUTC is the goreleaser run time (UTC), not vcs.time.
- -s -w -X main.version={{ .Tag }} -X main.gitCommit={{ .ShortCommit }} -X main.buildTimeUTC={{ .Date }} -X reasonix/internal/tools/productdocs.linkedVersion={{ .Tag }} -X reasonix/internal/tools/productdocs.linkedRevision={{ .Commit }}
goos: [darwin, linux, windows]
goarch: [amd64, arm64]
archives:
- id: reasonix
ids: [reasonix]
name_template: "reasonix-{{ .Os }}-{{ .Arch }}"
formats: [tar.gz]
format_overrides:
- goos: windows
formats: [zip]
checksum:
name_template: SHA256SUMS
algorithm: sha256
homebrew_casks:
- name: reasonix
ids: [reasonix]
# Prereleases (including v*-preview.* and v*-rc*) must not update the stable
# tap; brew has no separate prerelease channel, so uploading either cask
# would make it the default `brew install`.
# npm is a separate line (release-npm.yml, `npm-v*`), so an npm prerelease no
# longer drags brew along — a stable `v*` cask can ship while npm stays on rc.
skip_upload: "auto"
repository:
owner: esengine
name: homebrew-reasonix
branch: main
token: "{{ .Env.HOMEBREW_TAP_TOKEN }}"
homepage: "https://github.com/esengine/DeepSeek-Reasonix"
description: "Cache-first DeepSeek coding agent for the terminal."
commit_author:
name: reasonix
email: [email protected]
hooks:
post:
install: |
if OS.mac?
system_command "/usr/bin/xattr", args: ["-dr", "com.apple.quarantine", "#{staged_path}/reasonix"]
end
release:
prerelease: auto
make_latest: false
name_template: "Reasonix CLI {{ .Tag }}"
-5
View File
@@ -1,5 +0,0 @@
---
description: Review a file for bugs
argument-hint: [path]
---
Read $1 and list any correctness bugs or risky patterns, with file:line references, most important first. Focus: $ARGUMENTS.
-20
View File
@@ -1,20 +0,0 @@
version: 1
project_slug: DeepSeek-Reasonix
signing_policy_slug: release-signing
repository_url: https://github.com/esengine/DeepSeek-Reasonix.git
allowed_branch_names:
- studio
allowed_build_definitions:
- .github/workflows/release-studio.yml
- .github/workflows/studio-certum-signing-smoke.yml
fingerprint_files:
- .github/workflows/release-studio.yml
- .github/workflows/studio-certum-signing-smoke.yml
- .github/actions/setup-certum/action.yml
- scripts/install-smoke.ps1
- scripts/sign-certum.ps1
- scripts/verify-windows-authenticode.ps1
- scripts/verify-windows-package.ps1
- scripts/windows-signing-lib.ps1
- desktop/electron/electron-builder.yml
- cmd/signpath-contract/main.go
-6
View File
@@ -1,6 +0,0 @@
# Reasonix
The project's standing instructions live in `REASONIX.md` — one file, read by
both Reasonix and Codex. Add rules there, never here.
@REASONIX.md
+4101
View File
File diff suppressed because it is too large. Load diff
-6
View File
@@ -1,6 +0,0 @@
# Reasonix
The project's standing instructions live in `REASONIX.md` — one file, read by
both Reasonix and Claude Code. Add rules there, never here.
@REASONIX.md
+83
View File
@@ -0,0 +1,83 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainer at <359807859@qq.com>. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
+111 -200
View File
@@ -1,241 +1,152 @@
# Contributing to Reasonix
Thank you for your interest in contributing to Reasonix! This guide covers
everything you need to get started.
Thanks for showing up. Reasonix is a small, opinionated codebase
maintained primarily by [@esengine](https://github.com/esengine);
PRs are welcome, but read this first so the round-trip is short.
## Prerequisites
## Setup
- **Go 1.26+** — the version `go.mod` requires
- **Git** — for version control
- **Node.js 24+ and pnpm 10** (optional) — only if you work on Studio
(`desktop/`)
## Getting started
```bash
git clone https://github.com/esengine/DeepSeek-Reasonix.git
cd DeepSeek-Reasonix
go build ./cmd/reasonix # builds the CLI binary
go test ./... # runs the full test suite
```sh
git clone https://github.com/esengine/reasonix
cd reasonix
npm install
npm run dev # tsx src/cli/index.ts — live source
```
## Project structure
Node ≥ 22. No global install needed during development.
| Directory | Purpose |
|-----------|---------|
| `cmd/reasonix` | CLI entry point |
| `internal/runtime/agent` | Agent loop, session, coordinator |
| `internal/frontend/cli` | TUI, subcommands, setup wizard |
| `internal/session/control` | Transport-agnostic controller |
| `internal/contract/config` | TOML configuration loading |
| `internal/tools/builtin` | Built-in tools (bash, read_file, …) |
| `internal/contract/provider` | Model-backend abstraction |
| `internal/model/openai` | OpenAI-compatible provider |
| `internal/ext/plugin` | MCP client (stdio + HTTP) |
| `internal/contract/event` | Typed event stream |
| `internal/ext/hook` | Shell hooks (PreToolUse, …) |
| `internal/state/memory` | REASONIX.md hierarchy + auto-memory |
| `internal/ext/skill` | Skill discovery from Markdown |
| `internal/safety/sandbox` | OS-level sandboxing |
| `internal/frontend/serve` | HTTP/SSE server frontend |
| `internal/state/checkpoint` | Snapshot-based rewind |
| `desktop/` | Studio: the Electron shell, the SPA it serves (separate Go module) |
| `docs/` | Engineering spec, migration guide |
For stack, layout, scripts, see [`REASONIX.md`](./REASONIX.md).
### Dependency direction
## Proposing changes
```
cli → {agent, plugin, config} → {tool, provider}
```
- **Bug fixes** — go ahead and open a PR. Include a reproduction.
- **New features / behavior changes** — open an issue first to align
on scope and approach. Reasonix tries to stay small; "we could add
X" PRs that arrive cold are usually rejected or scoped down.
- **External MCP servers, plugins, presets** — a thin wrapper is
fine; a sprawling integration is better hosted as a separate
package that depends on `reasonix`.
Built-in subpackages import their parent to self-register via `init()`.
Parents never import children.
## Code rules
## Development workflow
These are enforced by review and (where possible) by
`tests/comment-policy.test.ts` — which runs under `npm run verify`
and gates pre-push.
### Building
### Comments — default is none
```bash
make build # go build ./...
make test # go test ./...
make vet # go vet ./...
make fmt # gofmt -w .
make hooks # install git hooks (pre-push: go vet)
make cross # cross-compile for all 6 targets
```
Write a comment ONLY when **why** is non-obvious and removing the
comment would confuse a future reader. Justified examples:
### Isolated development environment
- a hidden constraint (`// Yoga miscounts wrap → must clamp to width-1`)
- a workaround for a specific bug
- a subtle invariant the type system can't express
A source-built binary shares no on-disk state with a stable release when launched
with `REASONIX_HOME` set. This gives each build its own self-contained directory
tree — config, credentials, sessions, cache, skills, commands, hooks, and
desktop tab state — so the two builds never interfere:
Don't write:
**CLI**
- **What the code does.** Names already say it. No `// when x is positive`
above `if (x > 0)`.
- **Module-level essays.** Multi-paragraph docstrings at the top of a
file are dead weight. Two short lines max.
- **Conversation history.** No "user reported X", "screenshot showed
Y", "v0.13.2 introduced Z". That belongs in commits / PR text.
- **Section banners.** `// ─── helpers ───` is noise; group by export.
- **Restated parameter docs.** If `function pad(f, top, right, bottom,
left)`, no `@param top - top padding`.
```bash
REASONIX_HOME=/tmp/reasonix-dev go run ./cmd/reasonix
# or after building:
# REASONIX_HOME=/tmp/reasonix-dev ./bin/reasonix
```
If a comment is justified, **one line is almost always enough**.
Comments needing 4+ lines usually mean the code itself needs to be
clearer (rename, extract, simplify) before any comment is added.
**Studio**
### TypeScript
```bash
REASONIX_HOME=/tmp/reasonix-dev-isolated make studio
```
- Strict mode. No `any` without a `// biome-ignore` and a reason.
- Prefer narrow types over option bags; if a function takes 5+
optional flags, split the responsibilities.
- Don't re-export types just so two files can share them — move the
type to the file that owns the concept.
On Windows, use `$env:REASONIX_HOME` in PowerShell or `set REASONIX_HOME=` in
Command Prompt; the binary extension is `.exe`.
### Libraries over hand-rolled
The directory is empty on first launch; the app behaves exactly like a fresh
install. Every subsequent write — config saves, credential storage, session
logs — stays under `REASONIX_HOME`. Legacy migration, OS-home convention
directory scanning, and all other fallback paths are skipped so no production
data leaks in or out.
If a problem has a well-maintained npm library, use it. Specific
landmines this project has hit:
### Cache-first review gate
- Visual width / unicode width → `string-width`
- Grapheme segmentation → `Intl.Segmenter`
- ANSI strip → use what `string-width` ships with
- Color → use `theme.ts` constants, not raw hex in component code
Reasonix treats high prompt-cache hit rate as product behavior. Changes that
touch provider-visible system prompt construction, memory prefix, output styles,
skill index behavior, default tool surfaces, tool schemas, provider request
serialization, compaction, or MCP/tool registration need explicit cache review.
If a lib is missing a case, file the issue upstream and add a thin
wrapper — don't fork a local table.
For these changes:
### Files
- Keep system prompt changes low-frequency and require explicit review.
- Say in the PR what the change does to the provider-visible prefix, and why
that cost is worth paying.
- Prefer focused guard tests near the changed surface; `scripts/cache-guard.sh`
remains the broader release-level cache-hit check.
- One responsibility per file. New code goes in new files when an
existing one is already large.
- File header comment: zero or one line.
- No `index.ts` re-exports unless they meaningfully shrink the
public surface.
- Don't create new `*.md` documentation files unless explicitly
asked.
### Running tests
### Errors / fallbacks
```bash
go test ./... # all tests
go test ./internal/runtime/agent/ -v # verbose, one package
go test ./internal/tools/builtin/ -run TestGrep # one test
```
- Don't add try/catch for "internal" errors. Trust your own code.
- Don't validate things the type system already proves.
- Boundary code (user input, network, FS) does validate; everything
else trusts.
- No "graceful fallback" silently masking bugs. Log + crash >
silent wrong output.
`testenv.IsolateUserState` installs a disposable user home and config-edit lock
scope. Default-path tests can clear `REASONIX_HOME` without losing the test
registry, while explicitly isolated Reasonix homes retain their own locks.
### Tests
`REASONIX_TEST_HOME` carries the scope to helper subprocesses. A helper that
skips the isolation guard must install the inherited home with
`testscope.InstallHome` before running tests.
- Test what's hard to verify by reading the code: invariants, edge
cases, regressions.
- Don't test type signatures or that `function returns X` (the type
system does that).
- Don't write tests just to bump coverage.
The environment variable alone cannot activate a test scope. Production
executables still use the OS account's home for shared config locks.
### Git / commits
The guard removes its scratch home on normal completion. Scratch homes are
created under the original home, so an interrupted run can still leave
`.reasonix-test-home-*` directories; this is separate from persistent
config-edit locks in the real `.reasonix/locks` directory.
- Imperative mood, scope tag, why-not-what. See recent `git log`
for the pattern (`feat(ui): …`, `fix(loop): …`, `chore(release):
…`).
- One logical change per commit; refactors land separately from
features.
- No `Co-Authored-By: Claude` trailer.
### Code style
## PR expectations
- `gofmt` is enforced by CI — format before committing
- Follow existing patterns: wrap errors with `fmt.Errorf("...: %w", err)`
- Library code never calls `os.Exit` or prints to stdout/stderr
- Only `cli/` and `main/` decide exit codes and user-facing messages
- Exported identifiers must have doc comments
- Branch off `main`. One logical change per PR.
- `npm run verify` must pass locally (lint + typecheck + tests +
comment-policy gate). Pre-push hook runs this; CI runs it on
Node 22.
- Don't touch `CHANGELOG.md` — release notes are written by the
maintainer at release time, drawn from commit history. PR
descriptions are the authoritative record while the work is in
flight.
### Commit messages
## Code review
Follow [Conventional Commits](https://www.conventionalcommits.org/):
Reasonix prefers blunt, fast review. Expect:
```
feat(glob): add ** recursive pattern support
fix: replace silent error discards with structured logging
test(event): add comprehensive unit tests for event package
docs: add CONTRIBUTING.md
ci: add golangci-lint and govulncheck
```
- Line-level pushback on comments that explain *what* instead of *why*.
- Pushback on new abstractions / flags introduced before there are
two real call sites.
- Pushback on hand-rolled implementations of problems a maintained
npm library already solves.
## Adding a new built-in tool
None of this is personal — it's how the codebase stays small.
1. Create `internal/tools/builtin/mytool.go`
2. Implement the `tool.Tool` interface: `Name()`, `Description()`, `Schema()`, `ReadOnly()`, `Execute()`
3. Register via `func init() { tool.RegisterBuiltin(myTool{}) }`
4. Add tests in `internal/tools/builtin/builtin_test.go` or a separate `mytool_test.go`
5. The tool is automatically available — `main` blank-imports `builtin`
## Releasing (maintainers)
## Adding a new model provider
1. Bump `package.json` version.
2. Add `## [X.Y.Z] — <date>` to `CHANGELOG.md` with a hand-written
summary drawn from `git log` since the prior tag.
3. `chore(release): X.Y.Z — <one-line summary>` commit.
4. `git tag -a vX.Y.Z -m "..."`, push commit + tag.
5. Wait for CI green, then `npm publish`.
(For MCP tool servers see `internal/ext/plugin` instead — that's a different layer.)
## Reporting security issues
1. Create `internal/contract/provider/myprovider/`
2. Implement `provider.Provider`: `Name()`, `Stream()`
3. Register via `func init() { provider.Register("mykind", New) }`
4. The provider is available from config with `kind = "mykind"`
## Adding i18n strings
1. Add the field to `internal/base/i18n/i18n.go` (`Messages` struct)
2. Add the value in `internal/base/i18n/messages_en.go` and `messages_zh.go`
3. The `TestCatalogsComplete` test will fail if you miss a locale
## Submitting changes
Reasonix ships on two lines (see the
[version roadmap](https://github.com/esengine/DeepSeek-Reasonix/discussions/10748)),
and each takes different changes:
| Line | Branch | Takes |
| --- | --- | --- |
| 2.x | `studio` | Features and fixes: active development |
| 1.x | `main-v2` | Bug fixes, provider/API compatibility, release/updater, security, platform stability |
A fix that matters on both lines lands on `main-v2` and is reviewed for
porting to `studio`; do not open the same PR against both.
1. Fork the repository
2. Create a feature branch from the branch your change targets
3. Make your changes with tests
4. Ensure `go test ./...` passes
5. Ensure `gofmt -l .` shows no changes
6. Submit a pull request to that same branch
## Pull request policy
**Related changes.** If you have several related changes of one pattern, a
tracking issue plus one pull request is easiest to review.
**Issue first for features.** A change that adds behaviour rather than fixing a
defect should link an issue the maintainers have agreed to before the work
starts. A fix for a reproducible defect may open directly, with the failing test
in the PR. Documentation-only and test-only PRs are reviewed at lower priority.
**Review tiers.**
- Changes under the `sensitive:` paths declared in `REASONIX.md` get a full
review plus a security review, regardless of author.
- Every PR carries the four sections of the PR template: Cause, Blast radius,
Neighbouring behaviours tested, Why this layer.
- The new test must fail without the change.
- A UI change (`desktop/frontend-next/src` or the website pages) fills the
template's UI section: screenshots before and after, light and dark, wide
and phone width.
- The same section carries the line "Entries moved, hidden or removed".
- Hiding or removing a visible control needs a linked issue and a release-notes
line naming it, and updates `docs/STUDIO_PARITY.md` for a 1.x feature.
- Review holds these; no check reads them.
**Transparency.** The PR template has an optional checkbox for disclosing AI
assistance. It is for transparency only and does not change how a change is
reviewed.
## Reporting issues
Open an issue on GitHub with:
- Which line (1.x or 2.x) and the exact version
- Steps to reproduce
- Expected vs actual behavior
- Go version and OS
- Relevant logs or error messages
## License
By contributing, you agree that your contributions will be licensed under the
same license as the project.
See [`SECURITY.md`](./SECURITY.md). Short version: don't open a public issue, email the maintainer privately.
-120
View File
@@ -1,120 +0,0 @@
VERSION := $(shell git describe --tags --always 2>/dev/null | sed 's/^studio-//' || echo dev)
BUILD_TIME_UTC := $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
GIT_COMMIT := $(shell git rev-parse --short=12 HEAD 2>/dev/null || echo unknown)
LDFLAGS := -s -w \
-X main.version=$(VERSION) \
-X main.gitCommit=$(GIT_COMMIT) \
-X main.buildTimeUTC=$(BUILD_TIME_UTC)
GOEXE := $(shell go env GOEXE)
# One pin for the Makefile and the CI lint job; see .github/workflows/ci.yml.
GOLANGCI_VERSION := $(shell cat .golangci-version)
.PHONY: build vet fmt lint lint-go lint-install lint-cross lint-update coverage-gate coverage-gate-update pricecheck acp-conformance check test studio-test sdk-test sdk-test-race hooks cross clean studio
build:
CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o bin/reasonix$(GOEXE) ./cmd/reasonix
CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o bin/reasonix-plugin-example$(GOEXE) ./cmd/reasonix-plugin-example
vet:
go vet ./...
# Build Studio and launch it. The Electron shell is the one this runs: it is a
# real GUI app on every platform without being bundled first, so there is one
# launch path rather than a macOS one and an everywhere-else one.
studio:
bash desktop/electron/run-studio.sh
fmt:
gofmt -w .
# Both gates CI runs, at the version CI pins. Skipping golangci-lint locally
# trades a second here for a ten-minute CI round trip: `modernize` findings in
# particular never surface in `go vet`.
lint: lint-go
go run ./tools/repolint
lint-go:
@command -v golangci-lint >/dev/null || { echo "golangci-lint not installed; run: make lint-install"; exit 1; }
@have=$$(golangci-lint version --short 2>/dev/null); want=$$(echo "$(GOLANGCI_VERSION)" | sed 's/^v//'); \
[ "$$have" = "$$want" ] || echo "warning: local golangci-lint $$have, CI pins $$want (make lint-install)"
golangci-lint run --timeout=5m ./...
# CGO_ENABLED=0 keeps the install working where a stray clang on PATH shadows
# the toolchain and breaks runtime/cgo.
lint-install:
CGO_ENABLED=0 go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_VERSION)
# repolint over what the working tree changed. It exists as a target rather than
# a command to paste because the host recognizes `make check` as a verification
# it can read the result of, while an arbitrary `go run ./tools/...` is an
# unknown program it must assume writes — so only this form can be cited as
# evidence that the standards gate passed.
check:
go run ./tools/repolint -changed
lint-update:
go run ./tools/repolint -update
# The paths the project declared sensitive, held to the coverage they already
# have. It runs their tests, so it is its own target rather than part of the
# fast `make lint`. -update records the current numbers; lowering one needs
# -allow-drop, the way widening a repolint budget does.
coverage-gate:
go run ./tools/covergate
coverage-gate-update:
go run ./tools/covergate -update
# The vendors publish their rates on pages this reads and compares the table
# against. It reaches the network, so it stays out of lint and out of CI: run it
# before touching a rate and when a vendor announces a change. A page it cannot
# read exits non-zero — unread never counts as agreement.
pricecheck:
go run ./tools/pricecheck
# Linting one GOOS leaves every //go:build windows and darwin file unchecked.
lint-cross:
@for t in "linux ." "darwin ." "windows ." "linux desktop" "windows desktop"; do \
set -- $$t; \
echo "== golangci-lint GOOS=$$1 ($$2)"; \
(cd $$2 && GOOS=$$1 golangci-lint run --timeout=5m ./...) || exit 1; \
done
# Every module, because a nested one is where a red test hides longest: the
# shell's route allowlist sat broken through a release, and `go test ./...` from
# the root cannot see it.
test: studio-test sdk-test
go test ./...
# Drives `reasonix acp` with the official ACP TypeScript SDK and holds every
# message it writes to the schema that SDK ships. Needs node and network for
# `npm ci`, which runs without install scripts against a lockfile.
acp-conformance: build
cd tools/acp-conformance && npm ci --ignore-scripts --no-audit --no-fund
cd tools/acp-conformance && REASONIX_BIN=$(CURDIR)/bin/reasonix$(GOEXE) npm test
# The shell is a nested module, so the root `test` target never reaches it.
studio-test:
cd desktop && go test ./...
sdk-test:
cd sdk/go && go test ./...
sdk-test-race:
cd sdk/go && go test -race ./...
hooks:
@git config core.hooksPath .githooks
@echo "installed: core.hooksPath -> .githooks (pre-push runs go vet)"
cross:
@mkdir -p dist
@for p in darwin/amd64 darwin/arm64 linux/amd64 linux/arm64 windows/amd64 windows/arm64; do \
os=$${p%/*}; arch=$${p#*/}; ext=; [ $$os = windows ] && ext=.exe; \
echo "build $$os/$$arch"; \
CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -ldflags "$(LDFLAGS)" -o dist/reasonix-$$os-$$arch$$ext ./cmd/reasonix; \
done
clean:
rm -rf bin dist
+124 -298
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="docs/logo-ghost-wave-effect.svg" alt="Reasonix" width="360"/>
<img src="docs/logo.svg" alt="Reasonix" width="640"/>
</p>
<p align="center">
@@ -7,315 +7,157 @@
&nbsp;·&nbsp;
<a href="./README.zh-CN.md">简体中文</a>
&nbsp;·&nbsp;
<a href="./docs/GUIDE.md">Guide</a>
<a href="https://esengine.github.io/reasonix/">Website</a>
&nbsp;·&nbsp;
<a href="./docs/ACP.md">ACP</a>
<a href="./docs/ARCHITECTURE.md">Architecture</a>
&nbsp;·&nbsp;
<a href="./docs/EXTENSIONS.md">Extensions</a>
&nbsp;·&nbsp;
<a href="./docs/SPEC.md">Spec</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/">Website</a>
&nbsp;·&nbsp;
<strong><a href="https://discord.gg/XF78rEME2D">Discord</a></strong>
&nbsp;·&nbsp;
<strong><a href="https://qm.qq.com/q/i59b0z2R8s">QQ</a></strong>
<a href="./benchmarks/">Benchmarks</a>
</p>
<p align="center">
<a href="https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true"><img src="https://img.shields.io/github/v/release/esengine/DeepSeek-Reasonix.svg?filter=studio-v*&include_prereleases&style=flat-square&color=8250df&labelColor=161b22&label=studio%202.x" alt="Reasonix Studio 2.x"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/v/reasonix.svg?style=flat-square&color=cb3837&labelColor=161b22&logo=npm&logoColor=white" alt="npm version"/></a>
<a href="https://github.com/esengine/DeepSeek-Reasonix/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/esengine/DeepSeek-Reasonix/ci.yml?style=flat-square&label=ci&labelColor=161b22&logo=githubactions&logoColor=white" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg?style=flat-square&color=8b949e&labelColor=161b22" alt="license"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=3fb950&labelColor=161b22&label=downloads" alt="downloads"/></a>
<a href="https://github.com/esengine/DeepSeek-Reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/DeepSeek-Reasonix.svg?style=flat-square&color=dbab09&labelColor=161b22&logo=github&logoColor=white" alt="GitHub stars"/></a>
<a href="https://atomgit.com/esengine/DeepSeek-Reasonix"><img src="https://atomgit.com/esengine/DeepSeek-Reasonix/star/badge.svg" alt="AtomGit stars"/></a>
<a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/DeepSeek-Reasonix.svg?style=flat-square&color=bc8cff&labelColor=161b22&logo=github&logoColor=white" alt="contributors"/></a>
<a href="https://github.com/esengine/DeepSeek-Reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/DeepSeek-Reasonix.svg?style=flat-square&color=58a6ff&labelColor=161b22&logo=github&logoColor=white" alt="Discussions"/></a>
<a href="https://discord.gg/XF78rEME2D"><img src="https://img.shields.io/badge/discord-join-5865F2.svg?style=flat-square&labelColor=161b22&logo=discord&logoColor=white" alt="Discord"/></a>
<a href="https://qm.qq.com/q/i59b0z2R8s"><img src="https://img.shields.io/badge/QQ%20group-1093562660-12B7F5.svg?style=flat-square&labelColor=161b22&logo=tencentqq&logoColor=white" alt="QQ group 1093562660"/></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/27020?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-27020" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/27020/monthly?language=Go" alt="esengine/DeepSeek-Reasonix | Trendshift" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/27020?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-27020" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/27020" alt="esengine/DeepSeek-Reasonix | Trendshift" width="250" height="55"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="npm version"/></a>
<a href="https://github.com/esengine/reasonix/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/esengine/reasonix/ci.yml?style=flat-square&label=ci&color=0d1117&labelColor=161b22" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="license"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="GitHub stars"/></a>
<a href="https://github.com/esengine/reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="contributors"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="Discussions"/></a>
</p>
<br/>
<p align="center"><strong>Open source · MIT · runs on your computer, model of your choice</strong></p>
<h3 align="center">An open-source coding agent for your terminal, desktop, browser and editor.</h3>
<p align="center">It reads your project, edits files and runs commands and tests. Have it ask before each step, or work on its own within limits you set. Files its edit tools changed can be rewound. New here? Start with the Studio desktop app.</p>
<p align="center">Maintained by <strong>Huahui Yu</strong>.</p>
> [!IMPORTANT]
> **Community · 加入社区** — bilingual Discord for setup help (`#help` / `#求助`), workflow showcases, and feature ideas. → **<https://discord.gg/XF78rEME2D>**
>
> QQ group **DeepSeek-Reasonix官方群** (`1093562660`) → **<https://qm.qq.com/q/i59b0z2R8s>** ([QR code](./docs/assets/qq-group.svg))
> Douyin: **做游戏的小鱼** (Douyin ID `22703872788`) · [QR code](./docs/assets/douyin.png)
<h3 align="center">A DeepSeek-native AI coding agent for your terminal.</h3>
<p align="center">Engineered around prefix-cache stability — so token costs stay low across long sessions, and you can leave it running.</p>
<br/>
## ❤️Sponsor
<p align="center">
<img src="docs/assets/hero-terminal.svg" alt="Reasonix code mode — assistant proposes a SEARCH/REPLACE edit; nothing on disk until /apply" width="860"/>
</p>
<table><tr><td width="180" align="center" valign="middle"><a href="https://www.rightapi.ai/register?aff=e083bf73" target="_blank" rel="sponsored noopener noreferrer"><img src="./.github/sponsor/rightcode.png" alt="Right Code" width="64"></a></td><td valign="middle">Thanks to Right Code for sponsoring this project! Right Code reliably provides routing services for models such as Claude Code, Codex, and Gemini, with both pay-as-you-go and monthly subscription billing options available. Invoices are available upon top-up, and enterprise and team users can receive dedicated one-on-one support. Register via <a href="https://www.rightapi.ai/register?aff=e083bf73" target="_blank" rel="sponsored noopener noreferrer">this link</a>.</td></tr><tr><td width="180" align="center" valign="middle"><a href="https://www.packyapi.ai/register?aff=rIbQ" target="_blank" rel="sponsored noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="./.github/sponsor/packycode-dark.svg"><img src="./.github/sponsor/packycode-light.svg" alt="PackyCode" width="80"></picture></a></td><td valign="middle">Thanks to PackyCode for sponsoring this project! Access leading AI models through PackyCode with one API endpoint and one API key, with automatic failover and dedicated high-speed routes for Codex and Claude Code. Register via <a href="https://www.packyapi.ai/register?aff=rIbQ" target="_blank" rel="sponsored noopener noreferrer">this link</a>.</td></tr></table>
<br/>
## What it is
> [!TIP]
> **Cache stability isn't a feature you turn on; it's an invariant the loop is designed around.** That's the whole reason Reasonix is DeepSeek-only — every layer is tuned to the byte-stable prefix-cache mechanic.
Reasonix is an open-source AI coding assistant. The program runs on your computer; the AI model is a service you configure, which receives what it reads. You describe a task in plain language; it reads code, edits files and runs commands and tests inside the project folder you choose, and shows you each step.
You pick the model: a DeepSeek preset is built in, any OpenAI-compatible service is one config entry, and you pay the model provider directly.
## What you get
- **Read, edit, run.** It reads code, edits files and runs tests and commands, all inside your project folder.
- **Permission levels.** Have it ask every time, or let everyday actions run on their own; your forbid rules always hold. To see the approach first, use plan mode: it starts work only once you approve.
- **Rewind.** A file is saved before it changes, so you can rewind by conversation turn without touching your git history. Only files its edit tools changed are covered, not what a shell command did.
## 30-second start
Download, add a model key, open a project. New here? Start with the Studio desktop app.
1. Download and install the desktop app, Reasonix Studio, from the [releases page](https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true).
2. Open it and enter your model provider and key when asked.
3. Open your project folder and write what you want, for example "add retry on failure to the http client".
4. At the level you chose, it stops and asks before anything that needs your say-so. Allow it to continue, or refuse.
Prefer a terminal? Download the `reasonix` command-line tool, run `reasonix setup` to pick a model, then run `reasonix`. See [Install](#install) and [Quick start](#quick-start).
## Four ways to use it
- **Desktop app (Studio).** A graphical app; the best place to start.
- **Terminal.** A full-screen text interface; `reasonix run "task"` also works in scripts.
- **Browser.** `reasonix web` opens a web interface on your own machine.
- **Editor.** Install the extension in VS Code; other editors that support ACP (Agent Client Protocol, a common way for an editor to connect to an AI assistant) can connect to `reasonix acp`.
All four are the same program underneath. What follows is for advanced users and contributors.
## Use it from DeepSeek Harness
DeepSeek Harness (`dsh`) can hand a task to Reasonix as a subagent over ACP. This repository publishes a plugin index for it:
1. Run `reasonix setup` on the machine that runs `dsh`. In the DSH Web UI turn on Custom plugin markets (Plugins, More) and add this index in the Discover tab: `https://raw.githubusercontent.com/esengine/DeepSeek-Reasonix/studio/integrations/dsh-plugin/market-index.json`
2. Install "Reasonix subagent" from it.
3. Open the plugin's page and turn its switch on. While it is off the model has no `reasonix` tool and may run `reasonix -p` in its own shell, which looks like a delegation and is not one.
Setup details, the permission policy and limits are in [Using Reasonix from DeepSeek Harness](./docs/DSH.md).
## Versions
Reasonix ships on two lines. See the [version roadmap announcement](https://github.com/esengine/DeepSeek-Reasonix/discussions/10748) for the reasoning behind the split.
| Line | Branch | Status | Get it |
| --- | --- | --- | --- |
| **Reasonix 2.x** | `studio` (this branch) | Active development | [Studio releases](https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true) |
| **Reasonix 1.x** | [`main-v2`](https://github.com/esengine/DeepSeek-Reasonix/tree/main-v2) | Maintenance / stable | `npm i -g reasonix` · [desktop download](https://reasonix.io/?download=desktop#start) |
- **Want something stable?** Stay on 1.x. It keeps receiving bug fixes,
provider/API compatibility, updater and security fixes; its core architecture
is no longer being extended.
- **Want the new architecture?** Use 2.x Reasonix Studio. It is still moving
quickly; reports are welcome.
Valuable fixes, tests and behaviour from 1.x are reviewed one by one and ported
or reimplemented on 2.x where they fit the new architecture.
- [Moving from 1.x to 2.x](./docs/MIGRATING.md): what the two lines share, and
how to run both on one machine without losing sessions.
- [2.x roadmap](./docs/ROADMAP.md): what 2.x still has to deliver, how it ships,
and the decisions still open.
## Features
Technical highlights for advanced users.
- **Config-driven.** Providers, the agent, enabled tools, and plugins are all
declared in `reasonix.toml`. No hardcoded models.
- **Multi-model & composable.** DeepSeek ships as a preset; any
OpenAI-compatible endpoint is a config entry, not new code. Optionally run
two models together (executor + planner) in separate, cache-stable sessions.
- **Plugin-driven.** MCP servers contribute tools, prompts, and resources;
Extension Protocol v1 sidecars can also intercept runtime events, contribute
Providers and structured UI, and ship versioned plugin packages.
- **Cache-aware context maintenance.** Startup injects a small stable environment
summary, stale tool output is snipped/pruned before summary compaction, and the
built-in tool schema contract is documented for regression review.
- **Zero-friction distribution.** `CGO_ENABLED=0` single binary; cross-compile
to six targets with one command. The result is a fully self-contained static
binary — nothing to install on the target machine beyond the binary itself.
<br/>
## Install
This branch is **Reasonix 2.x**. Its desktop app is Reasonix Studio; the CLI,
Studio, and editor integrations all run the same local Reasonix engine.
### Reasonix Studio (2.x)
Download the package for your platform from the latest
[Studio release](https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true)
(tagged `studio-v2.*`; candidates such as `-rc.N` are marked as
pre-releases):
| Platform | Package | Architecture |
| --- | --- | --- |
| macOS | `.dmg` or `.zip` | Apple Silicon (`arm64`) / Intel (`amd64`) |
| Windows | Installer `-installer.exe` or portable `.zip` | x64 |
| Linux | `.deb`, `.rpm`, or `.AppImage` (download only) | x64 (`amd64`) / ARM64 (`arm64`, aarch64) |
Every package ships with a `.minisig` signature, and the release carries
`SHA256SUMS`. Once installed, Studio updates itself in place.
The same release also carries the 2.x `reasonix` CLI as archives for
`darwin|linux|windows × amd64|arm64`.
The Android build ships on that release as `ReasonixMobile-<version>.apk`
(`arm64`, Android 8.0 or newer). The kernel and the page run on the phone, and
the agent reaches your servers over SSH; pairing with a computer is done by
scanning the code it shows.
The APK is signed with the Android release key rather than minisign, so it
carries a `.sha256` and no `.minisig`.
When that key is absent the build is named
`ReasonixMobile-<version>-unsigned.apk`. Android refuses to install an unsigned
package, so those builds stay a workflow artifact for whoever wants to sign one,
and the release carries no APK at all.
### Reasonix 1.x (stable)
The 1.x CLI installs through npm on any supported platform, or Homebrew on
macOS:
```sh
npm i -g reasonix # any OS; pulls the prebuilt native binary
brew install esengine/reasonix/reasonix # macOS
```bash
cd my-project
npx reasonix code # paste a DeepSeek API key on first run; persists after
```
The 1.x desktop app is on the
[official download page](https://reasonix.io/?download=desktop#start). Windows
installers are code-signed with a Certum code-signing certificate.
### VS Code extension
The extension does not bundle the CLI; it starts your local `reasonix acp`
backend and adds native chat, editor context, tool-call approvals, model
selection, and workspace sessions. Install the 1.x CLI first.
- **VS Code:** [install from Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=SivanLiu.reasonix-agent)
- **VSCodium / Eclipse Theia:** [install from Open VSX Registry](https://open-vsx.org/extension/SivanLiu/reasonix-agent)
- **Extension ID:** `SivanLiu.reasonix-agent` · [source and usage guide](https://github.com/SivanCola/reasonix-vscode)
### Build from source
Clone the repository; `studio` builds 2.x and `main-v2` builds 1.x:
```sh
git clone https://github.com/esengine/DeepSeek-Reasonix.git
cd DeepSeek-Reasonix
git switch studio
```
#### CLI
The CLI build requires **Go 1.25+**. The module pins a `toolchain` directive;
keep `GOTOOLCHAIN=auto` so Go downloads the pinned toolchain, or install it.
```sh
make build # -> bin/reasonix(.exe)
make cross # -> dist/ (darwin|linux|windows × amd64|arm64)
```
#### Studio
Studio additionally requires **Node 24+ and pnpm 10**
(`npm install -g pnpm@10`) for the frontend.
```sh
make studio
```
See the [Studio build guide](desktop/README.md#prerequisites) for platform
webview dependencies and Linux build tags.
## Quick start
### Reasonix Studio
Install and launch Studio, then connect a provider and model in the app. No CLI
setup is needed.
### CLI / TUI
```sh
reasonix setup # configure a provider and model
reasonix # start an interactive session
reasonix run "implement the TODOs in main.go"
```
In an interactive session, run `/init` when you want Reasonix to create project
instructions.
For advanced CLI usage and configuration, see the **[CLI reference](./docs/CLI.md)**,
**[Guide](./docs/GUIDE.md)**, and
**[configuration paths](./docs/CONFIG_PATHS.md)**.
## Documentation
- **Getting started:** [Guide](./docs/GUIDE.md) · [CLI reference](./docs/CLI.md) ·
[Configuration paths](./docs/CONFIG_PATHS.md) · [ACP editor integration](./docs/ACP.md) ·
[Use from DeepSeek Harness](./docs/DSH.md)
- **Features & troubleshooting:** [Subagent profiles](./docs/SUBAGENT_PROFILES.md) ·
[Context Engine v2](./docs/SESSION_MEMORY_RETRIEVAL.md) ·
[Capability diagnostics](./docs/CAPABILITY_DIAGNOSTICS.md) ·
[Recovery and updates](./docs/RECOVERY.md) ·
[Checkpoints & rewind](./docs/CHECKPOINTS.md)
- **Agent presets:** [Session Agent compositions](./docs/AGENT_COMPOSITIONS.md)
- **Engineering & migration:** [Spec](./docs/SPEC.md) ·
[Task contracts & pause policy](./docs/TASK_CONTRACT.md) ·
[Tool contract](./docs/TOOL_CONTRACT.md) · [Moving from 1.x to 2.x](./docs/MIGRATING.md) ·
[2.x roadmap](./docs/ROADMAP.md)
- **Extension development:** [Skills](./docs/SKILLS.md) · [Extensions](./docs/EXTENSIONS.md) ·
[Plugin packages and Manifest v1](./docs/PLUGIN_PACKAGES.md) ·
[Extension Protocol](./docs/EXTENSION_PROTOCOL.md) ·
[Go SDK and starter](./sdk/go/README.md)
## Star History
<a href="https://www.star-history.com/?repos=esengine%2FDeepSeek-Reasonix&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/esengine/DeepSeek-Reasonix/star-history/assets/star-history/star-history-dark.svg" />
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/esengine/DeepSeek-Reasonix/star-history/assets/star-history/star-history-light.svg" />
<img alt="Star History Chart" src="https://raw.githubusercontent.com/esengine/DeepSeek-Reasonix/star-history/assets/star-history/star-history-light.svg" />
</picture>
</a>
Requires Node ≥ 22. Tested on macOS · Linux · Windows (PowerShell · Git Bash · Windows Terminal). Get a [DeepSeek API key →](https://platform.deepseek.com/api_keys) · `reasonix code --help` for flags.
<br/>
## Acknowledgments
## What makes Reasonix different
A small list of folks whose work has shaped Reasonix the most — the current top
20 contributors by commit count. The full contributor graph is on
[GitHub](https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors?all=1).
<!-- reasonix-top-contributors:start -->
| Contributor | Contributor | Contributor | Contributor |
| --- | --- | --- | --- |
| [**SivanCola**](https://github.com/SivanCola) | [**KHG420**](https://github.com/KHG420) | [**ttmouse**](https://github.com/ttmouse) | [**chuiwenwei**](https://github.com/chuiwenwei) |
| [**lifu963**](https://github.com/lifu963) | [**XTLine**](https://github.com/XTLine) | [**HUQIANTAO**](https://github.com/HUQIANTAO) | [**xxoingr**](https://github.com/xxoingr) |
| [**Harbor404**](https://github.com/Harbor404) | [**GTC2080**](https://github.com/GTC2080) | [**mchenziyi**](https://github.com/mchenziyi) | [**Li-Charles-One**](https://github.com/Li-Charles-One) |
| [**light-front-theory**](https://github.com/light-front-theory) | [**imcreazy**](https://github.com/imcreazy) | [**eghrhegpe**](https://github.com/eghrhegpe) | [**noreply**](https://github.com/noreply) |
| [**par73e**](https://github.com/par73e) | [**Bernardxu123**](https://github.com/Bernardxu123) | [**lancy69**](https://github.com/lancy69) | [**Guan0923**](https://github.com/Guan0923) |
<!-- reasonix-top-contributors:end -->
Special thanks to [**Bernardxu123**](https://github.com/Bernardxu123) for designing the project logo and intro video.
The loop is organized around four pillars. Each one solves a problem generic agent frameworks don't even see — because they were designed for a different cache mechanic.
<p align="center">
<a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="Contributors to esengine/DeepSeek-Reasonix" width="860"/>
<a href="./docs/ARCHITECTURE.md"><img src="docs/assets/pillars.svg" alt="Reasonix four pillars — Cache-first loop, R1 thought harvesting, Tool-call repair, Cost control" width="880"/></a>
</p>
<sub align="center">
Click any card to read the full architecture writeup → [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2](./docs/ARCHITECTURE.md#pillar-2--r1-thought-harvesting-opt-in) · [Pillar 3](./docs/ARCHITECTURE.md#pillar-3--tool-call-repair) · [Pillar 4](./docs/ARCHITECTURE.md#pillar-4--cost-control-v06)
</sub>
<br/>
## Capabilities
<p align="center">
<img src="docs/assets/feature-grid.svg" alt="Reasonix capabilities — cell-diff renderer, MCP, plan mode, permissions, dashboard, persistent sessions, hooks/skills/memory, semantic search, auto-checkpoints, /effort knob, transcript replay, event log" width="880"/>
</p>
<br/>
## How it compares
| | Reasonix | Claude Code | Cursor | Aider |
|-----------------------------------|------------------|-------------------|---------------------|--------------------|
| Backend | DeepSeek | Anthropic | OpenAI / Anthropic | any (OpenRouter) |
| License | **MIT** | closed | closed | Apache 2 |
| Cost profile | **low per task** | premium | subscription + use | varies |
| DeepSeek prefix-cache | **engineered** | not applicable | not applicable | incidental |
| Embedded web dashboard | yes | — | n/a (IDE) | — |
| Persistent per-workspace sessions | yes | partial | n/a | — |
| Plan mode · MCP · hooks · skills | yes | yes | yes | partial |
| Open community development | yes | — | — | yes |
For live cache-hit rates, costs, and methodology, see [`benchmarks/`](./benchmarks/) — the numbers move with model pricing, so they live with the harness, not in the README.
<br/>
## Documentation
- [**Architecture**](./docs/ARCHITECTURE.md) — the four pillars, cache-first loop, harvesting, scaffolds
- [**Benchmarks**](./benchmarks/) — τ-bench-lite harness, transcripts, cost methodology
- [**Website**](https://esengine.github.io/reasonix/) — getting started, dashboard mockup, TUI mockup
- [**Contributing**](./CONTRIBUTING.md) — comment policy, error-handling rules, library-over-hand-rolled
- [**Code of Conduct**](./CODE_OF_CONDUCT.md) · [**Security policy**](./SECURITY.md)
<br/>
## Community
> [!NOTE]
> Reasonix is open source and community-developed. The contributors wall below isn't decoration — every avatar is a real PR that shipped.
Scoped starter tickets — each with background, code pointers, acceptance criteria, and hints — live under the [`good first issue`](https://github.com/esengine/reasonix/labels/good%20first%20issue) label. Pick anything open.
**Open Discussions — opinions wanted:**
- [#20 · CLI / TUI design](https://github.com/esengine/reasonix/discussions/20) — what's broken, what's missing, what would you change?
- [#21 · Dashboard design](https://github.com/esengine/reasonix/discussions/21) — react against the [proposed mockup](https://esengine.github.io/reasonix/design/agent-dashboard.html)
- [#22 · Future feature wishlist](https://github.com/esengine/reasonix/discussions/22) — what would you build into Reasonix next?
**Already using Reasonix and willing to help others discover it?** Publish blog posts, articles, screenshots, talks, or videos to [**Show and tell**](https://github.com/esengine/reasonix/discussions/categories/show-and-tell). The project has no marketing budget — community word of mouth is how new users find it. Sustained advocates earn the badge below, displayed next to the contributors wall once awarded:
<p align="center">
<a href="https://github.com/esengine/reasonix/discussions/categories/show-and-tell">
<img src="https://img.shields.io/badge/REASONIX-📣%20ADVOCATE-c4b5fd?style=for-the-badge&labelColor=0d1117" alt="Reasonix Advocate badge — earned by sustained advocates"/>
</a>
</p>
**Before your first PR**: read [`CONTRIBUTING.md`](./CONTRIBUTING.md) — short, strict rules (comments, errors, libraries-over-hand-rolled). `tests/comment-policy.test.ts` enforces the comment ones; `npm run verify` is the pre-push gate. By participating you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md). Security issues → [SECURITY.md](./SECURITY.md).
<p align="center">
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/reasonix&max=100&columns=12" alt="Contributors to esengine/reasonix" width="860"/>
</a>
</p>
<br/>
## Non-goals
> [!IMPORTANT]
> Reasonix is opinionated. Some things it deliberately *doesn't* do — listed here so you can pick the right tool for your work.
- **Multi-provider flexibility.** DeepSeek-only on purpose. Coupling to one backend is the feature, not a limitation.
- **IDE integration.** Terminal-first. The diff lives in `git diff`, the file tree in `ls`. The dashboard is a companion, not a Cursor replacement.
- **Hardest-leaderboard reasoning.** Claude Opus still wins some benchmarks. DeepSeek is competitive on coding; if your work is "solve this PhD proof" rather than "fix this auth bug," start with Claude.
- **Air-gapped / fully-free.** Reasonix needs a paid DeepSeek API key. For air-gapped or zero-cost runs see Aider + Ollama or [Continue](https://continue.dev).
<br/>
## Star History
<a href="https://www.star-history.com/?repos=esengine%2Freasonix&type=timeline&logscale=&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&theme=dark&logscale&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
</picture>
</a>
<br/>
---
@@ -323,21 +165,5 @@ Special thanks to [**Bernardxu123**](https://github.com/Bernardxu123) for design
<p align="center">
<sub>MIT — see <a href="./LICENSE">LICENSE</a></sub>
<br/>
<sub>Built by the community at <a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">esengine/DeepSeek-Reasonix</a></sub>
</p>
---
<p align="center"><sub><strong>Support this project</strong></sub></p>
If Reasonix has been useful and you'd like to say thanks, you can. It stays a
coffee, not a contract — donations don't buy feature priority or change how
issues get triaged.
- **International** — PayPal: [paypal.me/yuhuahui](https://paypal.me/yuhuahui)
- **国内** — 微信支付 / 支付宝(扫码)
<p align="center">
<img src=".github/sponsor/wechat-pay.jpg" alt="WeChat Pay QR code" width="180"/>
<img src=".github/sponsor/alipay.jpg" alt="Alipay QR code" width="180"/>
<sub>Built by the community at <a href="https://github.com/esengine/reasonix/graphs/contributors">esengine/reasonix</a></sub>
</p>
+125 -275
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="docs/logo-ghost-wave-effect.svg" alt="Reasonix" width="360"/>
<img src="docs/logo.svg" alt="Reasonix" width="640"/>
</p>
<p align="center">
@@ -7,292 +7,157 @@
&nbsp;·&nbsp;
<strong>简体中文</strong>
&nbsp;·&nbsp;
<a href="./docs/GUIDE.zh-CN.md">指南</a>
<a href="https://esengine.github.io/reasonix/">官方网站</a>
&nbsp;·&nbsp;
<a href="./docs/ACP.md">ACP</a>
<a href="./docs/ARCHITECTURE.md">架构文档</a>
&nbsp;·&nbsp;
<a href="./docs/EXTENSIONS.md">扩展开发</a>
&nbsp;·&nbsp;
<a href="./docs/SPEC.md">规格</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/">官方网站</a>
&nbsp;·&nbsp;
<strong><a href="https://discord.gg/XF78rEME2D">Discord</a></strong>
&nbsp;·&nbsp;
<strong><a href="https://qm.qq.com/q/i59b0z2R8s">QQ</a></strong>
<a href="./benchmarks/">基准测试</a>
</p>
<p align="center">
<a href="https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true"><img src="https://img.shields.io/github/v/release/esengine/DeepSeek-Reasonix.svg?filter=studio-v*&include_prereleases&style=flat-square&color=8250df&labelColor=161b22&label=studio%202.x" alt="Reasonix Studio 2.x"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/v/reasonix.svg?style=flat-square&color=cb3837&labelColor=161b22&logo=npm&logoColor=white" alt="npm version"/></a>
<a href="https://github.com/esengine/DeepSeek-Reasonix/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/esengine/DeepSeek-Reasonix/ci.yml?style=flat-square&label=ci&labelColor=161b22&logo=githubactions&logoColor=white" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg?style=flat-square&color=8b949e&labelColor=161b22" alt="license"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=3fb950&labelColor=161b22&label=downloads" alt="downloads"/></a>
<a href="https://github.com/esengine/DeepSeek-Reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/DeepSeek-Reasonix.svg?style=flat-square&color=dbab09&labelColor=161b22&logo=github&logoColor=white" alt="GitHub stars"/></a>
<a href="https://atomgit.com/esengine/DeepSeek-Reasonix"><img src="https://atomgit.com/esengine/DeepSeek-Reasonix/star/badge.svg" alt="AtomGit stars"/></a>
<a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/DeepSeek-Reasonix.svg?style=flat-square&color=bc8cff&labelColor=161b22&logo=github&logoColor=white" alt="contributors"/></a>
<a href="https://github.com/esengine/DeepSeek-Reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/DeepSeek-Reasonix.svg?style=flat-square&color=58a6ff&labelColor=161b22&logo=github&logoColor=white" alt="Discussions"/></a>
<a href="https://discord.gg/XF78rEME2D"><img src="https://img.shields.io/badge/discord-join-5865F2.svg?style=flat-square&labelColor=161b22&logo=discord&logoColor=white" alt="Discord"/></a>
<a href="https://qm.qq.com/q/i59b0z2R8s"><img src="https://img.shields.io/badge/QQ%20group-1093562660-12B7F5.svg?style=flat-square&labelColor=161b22&logo=tencentqq&logoColor=white" alt="QQ group 1093562660"/></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/27020?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-27020" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/27020/monthly?language=Go" alt="esengine/DeepSeek-Reasonix | Trendshift" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/27020?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-27020" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/27020" alt="esengine/DeepSeek-Reasonix | Trendshift" width="250" height="55"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="npm version"/></a>
<a href="https://github.com/esengine/reasonix/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/esengine/reasonix/ci.yml?style=flat-square&label=ci&color=0d1117&labelColor=161b22" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="license"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="GitHub stars"/></a>
<a href="https://github.com/esengine/reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="contributors"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="Discussions"/></a>
</p>
<br/>
<p align="center"><strong>开源 · MIT · 程序跑在你电脑上,模型自选</strong></p>
<h3 align="center">终端、桌面、浏览器、编辑器里都能用的 AI 编程助手。</h3>
<p align="center">它会读你的项目、改文件、跑命令和测试。每一步先问你,或在你划定的范围内自己做,由你选;它用编辑工具改过的文件可以退回去。第一次用,从桌面应用 Studio 开始。</p>
<p align="center">维护者:<strong>Huahui Yu</strong>。</p>
<h3 align="center">DeepSeek 原生的终端 AI 编程代理。</h3>
<p align="center">围绕前缀缓存稳定性设计 —— 长会话下 token 成本始终低位运行,可以一直开着。</p>
> [!IMPORTANT]
> **加入社区 · Community** — 双语 Discord,提供安装答疑(`#help` / `#求助`)、工作流展示与功能想法。→ **<https://discord.gg/XF78rEME2D>**
>
> QQ 群 **DeepSeek-Reasonix官方群**(群号 `1093562660`)→ **<https://qm.qq.com/q/i59b0z2R8s>**([二维码](./docs/assets/qq-group.svg))
<br/>
> 抖音:**做游戏的小鱼**(抖音号 `22703872788`)· [二维码](./docs/assets/douyin.png)
<p align="center">
<img src="docs/assets/hero-terminal.zh-CN.svg" alt="Reasonix code 模式预览 — 助手提出 SEARCH/REPLACE 编辑,未 /apply 不落盘" width="860"/>
</p>
## ❤️赞助商
<br/>
<table><tr><td width="180" align="center" valign="middle"><a href="https://www.rightapi.ai/register?aff=e083bf73" target="_blank" rel="sponsored noopener noreferrer"><img src="./.github/sponsor/rightcode.png" alt="Right Code" width="64"></a></td><td valign="middle">感谢 Right Code 赞助了本项目!Right Code 稳定提供 Claude Code、Codex、Gemini 等模型的中转服务,并可选按量、包月两种计费模式。充值即可开票,企业、团队用户一对一对接。通过<a href="https://www.rightapi.ai/register?aff=e083bf73" target="_blank" rel="sponsored noopener noreferrer">此链接</a>注册。</td></tr><tr><td width="180" align="center" valign="middle"><a href="https://www.packyapi.ai/register?aff=rIbQ" target="_blank" rel="sponsored noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="./.github/sponsor/packycode-dark.svg"><img src="./.github/sponsor/packycode-light.svg" alt="PackyCode" width="80"></picture></a></td><td valign="middle">感谢 PackyCode 赞助了本项目!PackyCode 是一家稳定、高效的 API 中转服务商,统一域名、统一密钥、智能容灾切换。通过<a href="https://www.packyapi.ai/register?aff=rIbQ" target="_blank" rel="sponsored noopener noreferrer">此链接</a>注册。</td></tr></table>
> [!TIP]
> **缓存稳定不是开关,而是循环要围绕设计的不变量。** 这就是 Reasonix 只支持 DeepSeek 的根本原因 —— 每一层都为 DeepSeek 字节稳定的前缀缓存机制调过。
## 它是什么
Reasonix 是一个开源的 AI 编程助手。程序跑在你的电脑上;AI 模型是你自己配置的服务,它读到的内容会发给这个服务。你用大白话描述任务,它在你选的项目文件夹里读代码、改文件、跑命令和测试,每一步都摆给你看。
模型你自己选:内置 DeepSeek 预设,其他兼容 OpenAI 接口的服务填一条配置就行,费用直接付给模型服务商。
## 你能得到什么
- **读、改、跑**:读你的项目、改文件、跑测试和命令,都在你选的项目文件夹里。
- **权限分档**:每次都问你,或让日常操作自动放行;你设的禁止规则始终有效。想先看方案,就开计划模式,批准后它才动手。
- **可回退**:改文件前先存快照,按对话轮次回退,不碰 git 历史。只覆盖编辑工具改的文件,命令行命令造成的改动不在内。
## 30 秒上手
下载、填模型密钥、打开项目。第一次用,从桌面应用 Studio 开始。
1. 从[发布页](https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true)下载并安装桌面应用 Reasonix Studio。
2. 打开应用,按提示填入模型服务商和密钥。
3. 打开你的项目文件夹,写下想做的事,例如“给 http 客户端加上失败重试”。
4. 按你选的档位,该问你的操作它会先停下来问;同意就继续,不同意就拒绝。
更喜欢终端的话,下载 `reasonix` 命令行后运行 `reasonix setup` 配好模型,再运行 `reasonix` 即可。详见[安装](#安装)和[快速开始](#快速开始)。
## 四种用法
- **桌面应用(Studio)**:图形界面,适合第一次使用。
- **终端**:全屏文字界面,也能用 `reasonix run "任务"` 在脚本里运行。
- **浏览器**:`reasonix web` 在本机打开网页界面。
- **编辑器**:VS Code 安装扩展即可;其他支持 ACP(Agent Client Protocol,编辑器接入某个 AI 助手的通用约定)的编辑器,可连接 `reasonix acp`。
四种用法背后是同一套程序。下面的内容写给进阶用户和贡献者。
## 在 DeepSeek Harness 里使用
DeepSeek Harness(`dsh`)可以通过 ACP 把任务交给 Reasonix 作为子智能体去做。本仓库为此发布了一个插件索引:
1. 在运行 `dsh` 的机器上先运行 `reasonix setup`。在 DSH 网页界面打开“自定义插件市场”(插件,更多),再到 Discover 页添加这个索引:`https://raw.githubusercontent.com/esengine/DeepSeek-Reasonix/studio/integrations/dsh-plugin/market-index.json`
2. 从中安装“Reasonix subagent”。
3. 打开这个插件的页面,把它的开关打开。关着的时候模型没有 `reasonix` 工具,可能改在自己的 shell 里直接运行 `reasonix -p`,看起来像委派,其实不是。
配置细节、权限策略和限制见 [在 DeepSeek Harness 中使用 Reasonix](./docs/DSH.md)。
## 版本
Reasonix 分为两条版本线,调整的原因见[版本路线公告](https://github.com/esengine/DeepSeek-Reasonix/discussions/10748)。
| 版本线 | 分支 | 状态 | 获取方式 |
| --- | --- | --- | --- |
| **Reasonix 2.x** | `studio`(当前分支) | 活跃开发 | [Studio 发布页](https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true) |
| **Reasonix 1.x** | [`main-v2`](https://github.com/esengine/DeepSeek-Reasonix/tree/main-v2) | 维护 / 稳定 | `npm i -g reasonix` · [桌面端下载](https://reasonix.io/?download=desktop#start) |
- **想要稳定**:继续使用 1.x。它会持续收到 Bug 修复、Provider / API 兼容、
更新器和安全修复,但不再扩展核心架构。
- **想体验新架构**:使用 2.x Reasonix Studio。它仍在快速迭代,欢迎反馈问题。
1.x 中有价值的修复、测试和行为会逐项 review,适合新架构的会迁移或重新实现到 2.x。
- [从 1.x 迁移到 2.x](./docs/MIGRATING.md)(英文):两条线共用哪些数据,以及如何在同一台
机器上同时使用而不丢会话。
- [2.x 路线图](./docs/ROADMAP.md)(英文):2.x 还要交付什么、如何发布、哪些决定尚未做出。
## 特性
以下是写给进阶用户的技术要点。
- **配置驱动**:provider、agent、启用的工具、插件全部在 `reasonix.toml` 中声明,
内核无硬编码模型。
- **多模型 · 可组合**:DeepSeek 作为预设内置;任何 OpenAI 兼容
端点都只是一条配置。可选让两个模型协同(执行器 + 规划器),各自独立、缓存稳定的 session。
- **插件驱动**:MCP server 提供工具、提示词和资源;Extension Protocol v1
Sidecar 还可以拦截运行时事件、提供 Provider 与结构化 UI,并通过版本化插件包分发。
- **缓存友好的上下文维护**:启动时注入稳定的环境摘要;旧工具输出会先 snip/prune,
再进入摘要 compaction;内置工具 schema 合约有文档和回归测试保护。
- **零摩擦分发**:`CGO_ENABLED=0` 单二进制;一条命令交叉编译到六个目标平台。
产物是完全自包含的静态二进制——目标机器上除二进制本身外无需安装任何东西。
<br/>
## 安装
当前分支是 **Reasonix 2.x**,桌面端是 Reasonix Studio;CLI、Studio 和编辑器集成
都运行同一套本地 Reasonix 引擎。
### Reasonix Studio(2.x)
从最新的 [Studio 发布](https://github.com/esengine/DeepSeek-Reasonix/releases?q=studio-v&expanded=true)
下载对应平台的安装包(标签为 `studio-v2.*`;`-rc.N` 等候选版本标为预发布):
| 平台 | 安装包 | 架构 |
| --- | --- | --- |
| macOS | `.dmg` 或 `.zip` | Apple Silicon(`arm64`)/ Intel(`amd64`) |
| Windows | 安装器 `-installer.exe` 或便携 `.zip` | x64 |
| Linux | `.deb`、`.rpm` 或 `.AppImage`(只提供下载) | x64(`amd64`)/ ARM64(`arm64`,aarch64) |
每个安装包都附带 `.minisig` 签名,发布页另有 `SHA256SUMS`。安装后 Studio 会在
应用内自行更新。
同一个发布页也提供 2.x 的 `reasonix` CLI 归档(`darwin|linux|windows × amd64|arm64`)。
安卓版在同一个发布页上,文件名是 `ReasonixMobile-<版本>.apk`(`arm64`,Android 8.0 及以上)。
这个 APK 用 Android 发布密钥签名,不走 minisign,因此只有一个 `.sha256`,没有 `.minisig`。
该密钥缺失时产物名为 `ReasonixMobile-<版本>-unsigned.apk`。Android 不接受未签名的包,
这类构建只留作 workflow 产物供自行签名,发布页上不会挂 APK。
内核与界面都跑在手机上,Agent 通过 SSH 连接你自己的服务器;与电脑配对时扫它显示的二维码。
### Reasonix 1.x(稳定版)
1.x CLI 在任意支持的平台上都可以通过 npm 安装,macOS 也可以使用 Homebrew:
```sh
npm i -g reasonix # 任意系统;自动拉取对应平台的原生二进制
brew install esengine/reasonix/reasonix # macOS
```bash
cd my-project
npx reasonix code # 首次运行粘贴 DeepSeek API Key,之后会记住
```
1.x 桌面端请前往[官方下载页](https://reasonix.io/?download=desktop#start)。
Windows 安装器使用 Certum 代码签名证书签名。
### VS Code 扩展
扩展不内置 CLI,而是启动本机的 `reasonix acp` 后端,并提供原生聊天、编辑器
上下文、工具调用审批、模型选择和工作区会话。请先安装 1.x CLI。
- **VS Code:** [从 Visual Studio Marketplace 安装](https://marketplace.visualstudio.com/items?itemName=SivanLiu.reasonix-agent)
- **VSCodium / Eclipse Theia:** [从 Open VSX Registry 安装](https://open-vsx.org/extension/SivanLiu/reasonix-agent)
- **扩展 ID:** `SivanLiu.reasonix-agent` · [源码与使用说明](https://github.com/SivanCola/reasonix-vscode)
### 从源码构建
克隆仓库;`studio` 构建 2.x,`main-v2` 构建 1.x:
```sh
git clone https://github.com/esengine/DeepSeek-Reasonix.git
cd DeepSeek-Reasonix
git switch studio
```
#### CLI
CLI 构建需要 **Go 1.25+**。模块固定了 `toolchain`,保持 `GOTOOLCHAIN=auto`
即可让 Go 自动下载对应工具链,也可以手动安装。
```sh
make build # -> bin/reasonix(.exe)
make cross # -> dist/(darwin|linux|windows × amd64|arm64)
```
#### Studio
Studio 的前端还需要 **Node 24+ 与 pnpm 10**(`npm install -g pnpm@10`)。
```sh
make studio
```
各平台的 webview 依赖和 Linux 构建标签见 [Studio 构建指南](desktop/README.md#prerequisites)。
## 快速开始
### Reasonix Studio
安装并启动 Studio,然后在应用内连接 provider 和模型即可使用,无需配置 CLI。
### CLI / TUI
```sh
reasonix setup # 配置 provider 和模型
reasonix # 启动交互式会话
reasonix run "把 main.go 里的 TODO 实现掉"
```
需要项目指令时,可在交互式会话中运行 `/init`。
CLI 进阶用法和详细配置见 **[CLI 命令参考](./docs/CLI.zh-CN.md)**、
**[指南](./docs/GUIDE.zh-CN.md)** 和
**[配置路径](./docs/CONFIG_PATHS.md)**。
## 文档
- **开始使用:** [指南](./docs/GUIDE.zh-CN.md) ·
[CLI 命令参考](./docs/CLI.zh-CN.md) · [配置路径](./docs/CONFIG_PATHS.md) ·
[ACP 编辑器接入](./docs/ACP.md) · [在 DeepSeek Harness 中使用](./docs/DSH.md)
- **功能与排障:** [子智能体 Profile](./docs/SUBAGENT_PROFILES.md) ·
[Context Engine v2](./docs/SESSION_MEMORY_RETRIEVAL.md) ·
[能力诊断](./docs/CAPABILITY_DIAGNOSTICS.md) ·
[恢复与安全模式](./docs/RECOVERY.md) ·
[Checkpoints 与 rewind](./docs/CHECKPOINTS.md)
- **Agent 预设:** [会话级组合](./docs/AGENT_COMPOSITIONS.zh.md)
- **工程与迁移:** [规格](./docs/SPEC.md) ·
[任务合约与暂停策略](./docs/TASK_CONTRACT.md) ·
[工具合约](./docs/TOOL_CONTRACT.md) ·
[从 1.x 迁移到 2.x](./docs/MIGRATING.md) ·
[2.x 路线图](./docs/ROADMAP.md)
- **扩展开发:** [扩展概览](./docs/EXTENSIONS.md) ·
[插件包与 Manifest v1](./docs/PLUGIN_PACKAGES.md) ·
[Extension Protocol](./docs/EXTENSION_PROTOCOL.md) ·
[Go SDK 与 starter](./sdk/go/README.md)
## Star 趋势
<a href="https://www.star-history.com/?repos=esengine%2FDeepSeek-Reasonix&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/esengine/DeepSeek-Reasonix/star-history/assets/star-history/star-history-dark.svg" />
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/esengine/DeepSeek-Reasonix/star-history/assets/star-history/star-history-light.svg" />
<img alt="Star History Chart" src="https://raw.githubusercontent.com/esengine/DeepSeek-Reasonix/star-history/assets/star-history/star-history-light.svg" />
</picture>
</a>
要求 Node ≥ 22。已在 macOS · Linux · Windows(PowerShell · Git Bash · Windows Terminal)测过。[去拿 DeepSeek API Key →](https://platform.deepseek.com/api_keys) · 完整 flag 看 `reasonix code --help`。
<br/>
## 致谢
## Reasonix 的不同之处
下面这些朋友的工作塑造了 Reasonix 今天的样子 —— 当前按 commit 数统计的前 20 名贡献者。
完整贡献者列表在
[GitHub](https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors?all=1)。
<!-- reasonix-top-contributors:start -->
| Contributor | Contributor | Contributor | Contributor |
| --- | --- | --- | --- |
| [**SivanCola**](https://github.com/SivanCola) | [**KHG420**](https://github.com/KHG420) | [**ttmouse**](https://github.com/ttmouse) | [**chuiwenwei**](https://github.com/chuiwenwei) |
| [**lifu963**](https://github.com/lifu963) | [**XTLine**](https://github.com/XTLine) | [**HUQIANTAO**](https://github.com/HUQIANTAO) | [**xxoingr**](https://github.com/xxoingr) |
| [**Harbor404**](https://github.com/Harbor404) | [**GTC2080**](https://github.com/GTC2080) | [**mchenziyi**](https://github.com/mchenziyi) | [**Li-Charles-One**](https://github.com/Li-Charles-One) |
| [**light-front-theory**](https://github.com/light-front-theory) | [**imcreazy**](https://github.com/imcreazy) | [**eghrhegpe**](https://github.com/eghrhegpe) | [**noreply**](https://github.com/noreply) |
| [**par73e**](https://github.com/par73e) | [**Bernardxu123**](https://github.com/Bernardxu123) | [**lancy69**](https://github.com/lancy69) | [**Guan0923**](https://github.com/Guan0923) |
<!-- reasonix-top-contributors:end -->
特别感谢 [**Bernardxu123**](https://github.com/Bernardxu123) 设计的项目 logo和开场视频。
整个循环围绕四根支柱组织。每一根解决的都是通用 agent 框架根本看不见的问题 —— 因为它们是为另一种缓存机制设计的。
<p align="center">
<a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/DeepSeek-Reasonix&max=100&columns=12" alt="esengine/DeepSeek-Reasonix 贡献者" width="860"/>
<a href="./docs/ARCHITECTURE.md"><img src="docs/assets/pillars.zh-CN.svg" alt="Reasonix 四大支柱 — 缓存优先循环、R1 思维提取、工具调用修复、成本控制" width="880"/></a>
</p>
<sub align="center">
各支柱完整说明 → [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2](./docs/ARCHITECTURE.md#pillar-2--r1-thought-harvesting-opt-in) · [Pillar 3](./docs/ARCHITECTURE.md#pillar-3--tool-call-repair) · [Pillar 4](./docs/ARCHITECTURE.md#pillar-4--cost-control-v06)
</sub>
<br/>
## 能力一览
<p align="center">
<img src="docs/assets/feature-grid.zh-CN.svg" alt="Reasonix 能力一览 — cell-diff 渲染器、MCP、计划模式、权限、仪表盘、持久化会话、Hooks/Skills/Memory、语义检索、自动 checkpoint、/effort 旋钮、transcript 重放、事件日志" width="880"/>
</p>
<br/>
## 横向对比
| | Reasonix | Claude Code | Cursor | Aider |
|----------------------------|-------------------|-------------------|---------------------|--------------------|
| 后端 | DeepSeek | Anthropic | OpenAI / Anthropic | 任意(OpenRouter) |
| 协议 | **MIT** | 闭源 | 闭源 | Apache 2 |
| 单任务成本 | **低** | 高 | 订阅 + 用量 | 不一 |
| DeepSeek 前缀缓存 | **专门工程化** | 不适用 | 不适用 | 偶发命中 |
| 内嵌 web 仪表盘 | 支持 | — | 不适用 (IDE) | — |
| 持久化的工作区会话 | 支持 | 部分 | 不适用 | — |
| 计划模式 · MCP · Hooks | 支持 | 支持 | 支持 | 部分 |
| 开放社区共建 | 支持 | — | — | 支持 |
实测缓存命中率、成本、方法论看 [`benchmarks/`](./benchmarks/) —— 这些数会随模型定价变化,所以归在 harness 里,不进 README。
<br/>
## 文档
- [**架构**](./docs/ARCHITECTURE.md) —— 四大支柱、缓存优先循环、思维提取、脚手架
- [**基准测试**](./benchmarks/) —— τ-bench-lite harness、transcript、成本方法论
- [**官方网站**](https://esengine.github.io/reasonix/) —— 入门、Dashboard 设计稿、TUI 设计稿
- [**贡献指南**](./CONTRIBUTING.md) —— 注释规则、错误处理、用现成库不手写
- [**行为准则**](./CODE_OF_CONDUCT.md) · [**安全策略**](./SECURITY.md)
<br/>
## 社区
> [!NOTE]
> Reasonix 是开源、社区共建的项目。下面贡献者墙不是装饰 —— 每一个头像都对应一次真实合并的 PR。
给新手准备的入门 issue —— 每个都带背景说明、代码定位、验收标准、提示 —— 全部挂在 [`good first issue`](https://github.com/esengine/reasonix/labels/good%20first%20issue) 标签下。挑任意一个还没人认领的就行。
**正在征集意见的 Discussions:**
- [#20 · CLI / TUI 设计](https://github.com/esengine/reasonix/discussions/20) —— 哪里坏了、哪里少东西、哪里你会怎么改?
- [#21 · Dashboard 设计](https://github.com/esengine/reasonix/discussions/21) —— 对着[设计稿](https://esengine.github.io/reasonix/design/agent-dashboard.html)拍砖
- [#22 · 未来功能愿望单](https://github.com/esengine/reasonix/discussions/22) —— 你希望 Reasonix 长出什么功能?
**正在使用 Reasonix,愿意让更多人了解它?** 欢迎将相关博客、文章、截图、演讲或视频发布到 [**Show and tell**](https://github.com/esengine/reasonix/discussions/categories/show-and-tell)。项目没有营销预算,新用户主要通过社区口碑找到这里。持续参与传播的用户将获得下方这枚徽章,颁发后会展示在贡献者墙旁:
<p align="center">
<a href="https://github.com/esengine/reasonix/discussions/categories/show-and-tell">
<img src="https://img.shields.io/badge/REASONIX-📣%20ADVOCATE-c4b5fd?style=for-the-badge&labelColor=0d1117" alt="Reasonix Advocate 徽章 —— 授予持续参与传播的用户"/>
</a>
</p>
**第一次提 PR 之前**:先读 [`CONTRIBUTING.md`](./CONTRIBUTING.md) —— 短小、严格的项目规则(注释、错误处理、用现成库不手写)。`tests/comment-policy.test.ts` 静态强制执行注释那部分,`npm run verify` 是 push 前的闸。参与本项目即同意 [行为准则](./CODE_OF_CONDUCT.md)。安全相关问题请走 [SECURITY.md](./SECURITY.md)。
<p align="center">
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/reasonix&max=100&columns=12" alt="esengine/reasonix 贡献者" width="860"/>
</a>
</p>
<br/>
## 不做的事
> [!IMPORTANT]
> Reasonix 是有立场的。有些事它故意 *不做* —— 列在这里方便你为自己的工作挑对工具。
- **多供应商灵活性。** 故意只做 DeepSeek。绑死一个后端是 feature,不是限制。
- **IDE 集成。** 终端优先。diff 在 `git diff`,文件树在 `ls`。仪表盘是 TUI 的伴生,不是 Cursor 的替代。
- **追最难的 reasoning 榜单。** Claude Opus 在某些榜单上还是赢家。DeepSeek 在编程任务上有竞争力;如果你的工作是"解一个 PhD 级证明"而不是"修个 auth bug",先用 Claude。
- **完全离线 / 永远免费。** Reasonix 需要付费的 DeepSeek API Key。要离线 / 零成本,看 Aider + Ollama 或 [Continue](https://continue.dev)。
<br/>
## Star 趋势
<a href="https://www.star-history.com/?repos=esengine%2Freasonix&type=timeline&logscale=&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&theme=dark&logscale&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
</picture>
</a>
<br/>
---
@@ -300,20 +165,5 @@ CLI 进阶用法和详细配置见 **[CLI 命令参考](./docs/CLI.zh-CN.md)**
<p align="center">
<sub>MIT —— 见 <a href="./LICENSE">LICENSE</a></sub>
<br/>
<sub>由 <a href="https://github.com/esengine/DeepSeek-Reasonix/graphs/contributors">esengine/DeepSeek-Reasonix</a> 社区共建</sub>
</p>
---
<p align="center"><sub><strong>支持本项目</strong></sub></p>
如果 Reasonix 帮你省了时间或 token,欢迎请杯咖啡。捐助不会换来 feature
优先级,也不会影响 issue 的处理顺序——就是「谢谢」。
- **国内** — 微信支付 / 支付宝(扫下方二维码)
- **海外** — PayPal: [paypal.me/yuhuahui](https://paypal.me/yuhuahui)
<p align="center">
<img src=".github/sponsor/wechat-pay.jpg" alt="微信支付收款码" width="180"/>
<img src=".github/sponsor/alipay.jpg" alt="支付宝收款码" width="180"/>
<sub>由 <a href="https://github.com/esengine/reasonix/graphs/contributors">esengine/reasonix</a> 社区共建</sub>
</p>
+67 -474
View File
@@ -1,480 +1,73 @@
# Reasonix project memory
# Reasonix — working knowledge
This file is loaded into every session's system prompt (the cache-stable prefix),
so keep it concise and durable — it is the project's standing instructions to the
agent. It is the Reasonix analog of Claude Code's CLAUDE.md.
TypeScript project. DeepSeek-native coding agent, cache-first loop.
MIT-licensed. Node ≥22 required.
## Stack
- **Language** — TS 5.6+, ES2022, ESM (`"type": "module"`)
- **CLI** — Commander.js + Ink 5 (React 18) TUI
- **Test** — Vitest 2.x
- **Lint / Format** — Biome 1.9 (2-space, double quotes, semicolons always, 100 width)
- **Build** — tsup (bundle), `tsx` (dev runner)
- **MCP** — stdio + SSE transports, in-process fake in tests
## Layout
| Path | What |
|---|---|
| `src/cli/` | CLI entry + commands (`chat.tsx`, `code.tsx`, `diff.ts`, etc.) + Ink TUI in `ui/` |
| `src/tools/` | Tool defs (filesystem, shell, MCP, plan, subagent, web, workspace) |
| `src/mcp/` | MCP client, transports (stdio, SSE), registry, spec |
| `src/repair/` | Tool-call repair pipeline (flatten, scavenge, storm, truncation) |
| `src/index/` | Semantic vector index |
| `src/code/` | SEARCH/REPLACE edit-block parser + apply gate |
| `src/core/` | Event-log kernel — `events.ts` (Event union), `reducers.ts` (pure projections), `eventize.ts` |
| `src/ports/` | Port interfaces — ModelClient, ToolHost, EventSink, MemoryStore, HookRunner, CheckpointStore |
| `src/adapters/` | Concrete adapters for the ports (e.g. `event-sink-jsonl.ts`, `event-source-jsonl.ts`) |
| `src/frame/` | Frame compiler (cell grid → ANSI) used by the TUI log renderer |
| `src/memory/` | Project / session / user / runtime memory stores |
| `src/transcript/` | Transcript log (write), diff, replay |
| `src/telemetry/` | Usage records + cross-session stats |
| `src/server/` | Dashboard HTTP server + REST API |
| `tests/` | Vitest tests, flat `*.test.ts` |
| `examples/` | `basic-chat.ts`, `mcp-server-demo.ts`, etc. |
| `benchmarks/` | Harvest + tau-bench harnesses |
| `dashboard/` | Compiled dashboard SPA assets |
| `data/` | Tokenizer data (`deepseek-tokenizer.json.gz`) |
| `dist/` | Build output — **do not edit** |
| `.github/` | CI + issue / PR templates |
## Commands
```sh
npm run build # tsup → dist/
npm run dev # tsx src/cli/index.ts
npm run chat # tsx src/cli/index.ts chat
npm run test # vitest run
npm run test:watch # vitest
npm run lint # biome check src tests
npm run lint:fix # biome check --write src tests
npm run format # biome format --write src tests
npm run typecheck # tsc --noEmit
```
`prepublishOnly`: lint → typecheck → test → build.
## Conventions
- Go kernel under `internal/`; each package owns one concern. A package's long
explanation belongs in its `doc.go`, not spread across implementation files.
- One transport-agnostic `control.Controller` sits behind every frontend (chat
TUI, HTTP/SSE serve, Electron desktop). Add behavior to the controller, not a
frontend, so all three inherit it.
- Layering (enforced): utility packages import nothing under `reasonix/` except
one another — that layer is closed, so a leaf reaching a leaf drags no graph
along, while refusing it leaves one judgement copied into several of them; only
the frontends `cli`, `serve`, `acp`, `boot` and the hosts `cmd/`, `desktop/`
may import `control`; nothing below a frontend may import one. The declared
sets live in `tools/repolint/layers.go`.
- Subagent delegation keeps five concepts apart: a profile says how a worker
thinks, `TaskSpec` what this call wants, `CapabilityGrant` what it may touch,
`ContextRequest` what it starts from, `SchedulerPolicy` when it runs. Put a
field in whichever member decides its value — profiles carry ceilings, never
per-call values. `internal/runtime/delegation/profile_boundary_test.go` enforces it.
- Cache-first: the system-prompt prefix (base prompt, tools, declared prefix
configuration) must stay byte-stable across turns so DeepSeek's automatic
prefix cache stays warm. Never mutate it mid-session — ride the turn tail
instead (see `control.Compose`), under the rules in *Context projection*.
- Performance features land with an effect test at their final boundary
(`internal/assembly/boot/effect_test.go` pattern): assert what actually reaches the
provider request, frontend sink, or trajectory through the real `boot.Build`
assembly. Component correctness is not system effectiveness.
- A mutex- or atomic-guarded struct is ratcheted on its **scalar** field count
(`struct-state`), not its total: independent flags multiply into states no
type records as legal. Fixing a boundary case by adding one more `bool` is
the move this blocks — group by lifetime into a named sub-state instead
(`agent.perTurnState` is the pattern), which costs one field and removes the
whole product.
- The context window (projection, compaction, estimation) owns `windowState`;
the loop reaches it via `a.window()`, it reaches the loop via `windowHost`.
`window-state` fails any other read of `sess.win`.
- Judgements read structure, never wording: shell ASTs (`shellparse`), types,
contracts, tool schemas. Phrase tables and message sniffing have been retired
in batches (task-policy prose, the planner's approval phrases, the executor
handoff tables) because each one misfires on real input, and a misfiring
judgement inside a gate is worse than no gate. Security allow-lists are the
exception and stay. Something that can only be built by matching words does
not get built — say what is missing instead of guessing at it.
- The other half of that rule: an error a caller must tell apart **carries an
identity** — a sentinel, a typed code — never a sentence. Only the producer
knows a deadline expired rather than a socket closed, and a message is where
that knowledge goes to die: the reader is left matching words, or with
nothing. Across HTTP the identity is a dotted code through `refuse`;
`refusal-path` fails a new `http.Error` in `internal/frontend/serve`, and the parity
test fails a code the frontend cannot say. Inside Go it is `errors.Is` on a
sentinel the wrapping preserves; `error-text` fails a new match against an
error message, following it one hop into a local because storing the text
first is what the direct form turns into.
- **Whoever first knows why an operation failed owns its class.** A transport
status is not a domain identity, and a display string is not a classification;
past that boundary a layer may project the class, never re-derive it. Both
directions were live: `catalog.go` answered 400 for a name nobody declared and
for a disk that would not write, so a failed store told the user their request
was wrong; `ServerRow` decided a connection was an authorisation problem by
matching `/401|403|unauthorized/` against prose an external MCP server wrote,
which the host had sanitised and truncated on the way through. Domain,
internal and dependency are three answers with three different things to do
next, and a caller that cannot tell them apart reports the last two as the
first.
- Failure attribution is host-owned state. When the host can determine why an
operation failed or stopped — truncation, timeout, unavailable context,
dependency skipping, policy refusal, output spill, argument parsing — that
cause goes to the model. Surfacing only the downstream symptom leaves it to
invent one, and the invented rule outlives the incident: a response cut at the
output limit reaches the model as "invalid arguments", and the session learns
to stop batching calls that were never the problem.
- A host-owned identity has to cross the model-visible boundary. Stable step
ids, typed error codes, boundary causes — anything the host expects the model
to cite must appear wherever that state is rendered for it. Telling the model
in a schema to prefer X while every concrete rendering shows only Y trains it
to use Y; `complete_step` said `step_id` PREFERRED while all four todo
renderers printed bare ordinals. Canonical dynamic state still stays out of
the cache-stable prefix — project the identities needed to act on it at the
turn tail.
- A metric is its definition, not its name. Before a number becomes a finding,
state what it counts, from which anchor, over which population, and what it
excludes. Three readings in one study died in that gap: a command of unknown
extent read as a proven write, the latest report's adjudication read as every
report's, and a syntactically accepted call read as a closed one. Each time a
convenient proxy had been left standing in for the state it was named after,
and each time the mechanism story built on it was wrong. A number without
those four lines is an observation, not a result.
- A constructed state is not a reachable one. Before a destructive test or a
counterfactual is reported as a defect, say who in production produces that
state, through which transitions, across which persistence boundary, under
whose authority, and whether a real run has been seen reaching it. A test that
assigns a private field proves the mechanism *given* the state and must be
reported as exactly that: `a.projectChecks` is written once at boot and never
again, so reassigning it stood in for a resume rather than demonstrating one,
and the bypass built on it was never shown to be production-reachable.
Severity is reachability times frequency times authority, not "can be
bypassed".
- A wire type the desktop re-declares by hand is held to the kernel's by
`wire-parity`, both directions: a field one side sends and the other cannot
read fails, and so does one it reads that nothing sends. The two are compiled
by different toolchains and meet only over JSON, so nothing else in the tree
notices when one of them grows a field. The pairs are declared in
`tools/repolint/wireparity.go`, never inferred — no spelling tells a mirrored
contract from a struct that merely carries json tags.
- "Add behavior to the controller so every frontend inherits it" is held by
`frontend-parity`: a capability one frontend already drives, a frontend whose
declared port carries it, and no call, is a missing edge, and the ratchet
counts edges. Which port each frontend drives is declared in
`tools/repolint/frontendparity.go`; a deliberate exception goes in the scope
table there with an issue and a reason, and costs what the edge cost, so the
table cannot become where debt disappears. The matrix is read from
`go/types` at one pinned build target, never from selector names — `Close`
and `Status` are capabilities and also stdlib methods, and a name match
records `os.File.Close` as a frontend driving `Lifecycle.Close`, a false
"wired" that hides real debt. How a verb is spelled — `/branch`,
`POST /branches` — is presentation and stays out of it.
- The desktop's presentation layer answers to canonical state and never
redefines it. Six rules, each held by a gate rather than by memory:
presentation reorders and reweights what the kernel owns but never restates
it; **mount is not a motion cause** — a fact enters once, and replay or
virtualization bringing its element back is not that fact happening again;
a search alias buys discoverability and never becomes a thing's identity;
when a setting takes effect is declared per block, from what its endpoint
does, never inferred from wording or handler names; ordering panels by
lifecycle moves them and must not remount them; and a control's identity
survives a change of where it is drawn — the settings sheet and the composer
render `chrome.preset` because that is one intent, not two.
- **Imports** — explicit `import type` for type-only imports (Biome `useImportType: warn`). Direct relative imports within project, no barrel re-exports.
- **Exports** — named exports only; no `export default`. Entry: `src/index.ts`.
- **Tests** — vitest `describe`/`it`/`expect`, no globals. Naming: `<module>.test.ts` flat in `tests/`.
- **JSX** — `.tsx` for Ink components. `jsx: "react"` in tsconfig.
- **TypeScript** — `strict`, `noUncheckedIndexedAccess`, `noImplicitOverride`. Tools accept `ToolCallContext` (abort signal).
- **MCP** — All transports implement `McpTransport` interface. Tools registered via registry at startup.
- **Changelog** — Keep a Changelog format. Semver.
## Comments
## Watch out for
Default is none — the code is the truth. Write one only when the **why** is
non-obvious: a hidden constraint, a workaround anchored to something verifiable,
an invariant the type system cannot express, or an external-protocol quirk.
A comment states the constraint that holds now. It does not narrate how the code
got here: a reader who has never seen an earlier version must lose nothing, and
past tense about this code's own behaviour is the tell — an external protocol's
history is not. "Ids alone do not answer it" is the rule; "ids alone were the
wrong question, so the list went on reading as the model wrote it" is the
incident behind the rule, and the incident belongs in the commit message. This
outranks the surrounding style: much of the tree reads as prose and none of it
is the standard. No gate reads register — telling narrative from a statement of
constraint needs a phrase table, which is the one thing this repo does not
build — so this rule is held by review.
- **Stylesheets carry none.** A rule's selector and its declarations are the
whole statement. What a `.css` comment would have said goes to whichever of
two places can act on it: a constraint a component has to honour belongs in
that component, and a decision about the medium itself — a measured colour, a
layout mechanic, why the obvious rule is the wrong one — belongs in the
stylesheet's companion document (`src/styles/TOKENS.md`, `LAYOUT.md`), which
is read end to end rather than met 600 times as an aside.
- **English, always** — every comment, in every other language the tree is
written in. A codebase whose commentary is half one language reads as two
codebases, and the half a given reader cannot read is the half that rots.
- Declaration doc: ≤5 lines. Package comment: ≤8 lines, or ≤40 in a `doc.go`.
- Every other comment: ≤3 lines. Struct-field and trailing `//`: 1 line.
- Never: restatements of the code, phase/stage narrative, incident or
conversation history, section banners, commented-out code, `@param` lists.
- `TODO(#nnn):` and `HACK(#nnn):` need the issue anchor. `FIXME` is banned.
- One responsibility per file; 800 lines is the ceiling. Test files are exempt:
their length tracks how many cases they cover, not how many concerns they
carry, so splitting one only scatters a subject's table across files.
`go run ./tools/repolint` enforces the budgets above against a ratchet baseline:
recorded debt is tolerated, anything new fails CI. Never widen the baseline to
land a change — fix the code. `-update` lowers budgets freely and refuses to
raise one without `-allow-widen`, so carrying debt through a rename or an
extraction is asked for in the command and justified in the PR. A clean run also
reports budget the tree stopped using: it is only reclaimed by an `-update`, and
until then it is room a file can grow back into.
## Context projection
Canonical dynamic state — the skill registry, the memory store — lives in its own
owner, and what the model sees is a projection of it onto each request. The
prefix was never where these belonged wrongly; freshness ownership was missing.
- **Prefix ownership.** Only declared prefix configuration may move the
cache-stable prefix; ordinary memory writes, skill writes and runtime facts
ride the turn. Pinned memory bodies are the one declared exception, because
pinning is a request to pay one cold start.
- **Projection freshness.** When canonical state changes, the next eligible turn
carries the new projection or can say why it is not owed. "Right after a fold,
or in the next session" is not an answer.
- **Projection ownership.** Whoever owns a dynamic fact owns the invalidation
that makes its projection owed again. A projection kept fresh because every
writer remembered to announce itself is one forgotten call from stale —
`skillSet.owedCatalog` asks the registry rather than waiting to be told.
- **Determinism.** The same canonical state and the same projection state
produce byte-identical model-visible bytes.
- **Detection is semantic.** Freshness may not rest on writer notification, on
mtime, or on which call path made the change. The registry answers from
canonical state, so a switch flipped and a file edited past every API are the
same question, and a change no projection renders is not a change.
`internal/assembly/boot/context_projection_test.go` holds all five at the provider
boundary, with the skills listing and the standing instructions as the two
worked examples. A block is settled only once the turn carrying it reaches the
runner: a turn blocked by a hook or refused by an extension after composing put
those bytes nowhere, and clearing the debt there would leave the model holding
state nobody sent it. A projection that has become empty is still owed once —
otherwise the block the model already has goes on reading as current.
## Memory
- Standing instructions are hierarchical: committed/shared `REASONIX.md`,
`AGENTS.md`, and `CLAUDE.md`; personal `*.local.md` variants; matching files in
ancestor directories; and user-global files under the memory state root
(`REASONIX_STATE_HOME`, otherwise `REASONIX_HOME`, otherwise `~/.reasonix` on
macOS/Linux or `%APPDATA%\reasonix` on Windows). All distinct supported files
in a directory load; `AGENTS.md` is not merely a fallback.
- `@path` on its own line imports another file's contents.
- `#<note>` in chat quick-adds an always-on instruction. The `remember` tool
instead saves a fallible background fact (frontmatter file + `MEMORY.md`
index). Fact `type` classifies content; independent `scope` controls whether it
is project-only (the default) or explicitly global.
- The saved-fact index stays out of the stable prefix and is reached through the
`memory` tool; pinned bodies and global user/feedback bodies load into it, the
latter as lower-priority compatibility guidance. The current turn receives a
tail note.
## Notes
One tool call costs one model round trip, so calls that do not depend on each
other belong in the same round: several reads, edits to different files, a check
after the edit that enables it. Several edits to the *same* file are one
`multi_edit` — it applies them against each other in memory and rewrites the
file only if all of them land, so a failure midway leaves nothing half-edited.
## Vendor rates
Official list prices live in one place: `officialRates` in
`internal/contract/pricing/rates.go`, oldest generation first, the last being what a
model charges today. A price change is an **append, never an edit** — the
superseded rate is what lets an installed config be recognised as holding one
of ours and brought forward, instead of quoting a retired rate for the rest of
its life. `config` reads these through `pricing.CurrentRate` and
`SupersededRates` and restates none of them; a table written twice is one that
drifts, which is how a vendor's USD rate ended up published on one side only.
`make pricecheck` reads each vendor's own page and compares it against that
table, and reports how long ago a person last confirmed each one. It reaches
the network, so it stays out of `make lint` and out of CI: run it before
touching a rate and when a vendor announces a change. A page it cannot read
exits non-zero — unread is its own verdict and never counts as agreement.
## Curated presets
A preset changing shape reaches the installs that already have the old one
through `shippedPresets` in `internal/contract/config/preset_upgrade.go`: one declared
shape per generation, and one upgrade that brings a matching entry forward. The
guard is the whole shape — catalog, window, default — because an entry holding
what we shipped is ours to move and anything else its user curated.
A preset is also what settles which of its models read images. Probing an
address a preset covers answers from that declaration, because reading a name
misses every Kimi, Qwen, MiniMax and Claude model they declare and `deepseek-
flash` spells nothing at all; the spelling is the last resort for an address
nothing has declared, and stays a correctable suggestion rather than a claim.
Three distinctions are load-bearing, and each was a separate migration function
before they were written down. A window the shape did not name is the user's,
so only a shape identified by its window moves one. `vision_models` **narrows**,
so an upgrade marks only the models it adds and only where the preset says they
read images. And an explicitly empty list is a choice — nothing here reads
images — which is not the same as the nil that means nobody has said.
## Pre-push CI simulation
Run these **before every commit** to catch the fastest CI failures locally:
```bash
gofmt -w . # catches gofmt (saves ~13s CI)
go vet ./... # catches vet warnings (saves ~52s CI/lint)
make lint # golangci-lint at CI's pin + repolint
go test ./internal/tools/builtin/ ./internal/assembly/boot/ # catches tool/boot test breaks
```
`make lint` runs both gates CI runs, at the version in `.golangci-version`;
`make lint-install` installs it. Do not skip it: a `modernize` finding never
shows up in `go vet`, and the CI round trip that catches it instead costs ten
minutes.
A full repolint run reports every file over budget, including debt your change
never touched. To see only what your own edits owe:
```bash
make check
```
Repo-wide ceilings still report under a narrowed run, because a file can push
the tree past one without exceeding its own budget.
`make check` owns the evidence-bearing changed-file universe — everything the
worktree altered *and* everything it added that git has not been told about.
Never substitute a direct `go run ./tools/repolint` invocation for it when
recording verification evidence: the host recognizes a `make` target as a check
whose result it can read, while an arbitrary `go run ./tools/...` is a program
it has to assume writes, and the flags behind the target are its implementation
rather than the contract. Building that universe from `git diff` alone once let
a new file reach the gate unopened and be reported clean.
## Import cycle rule
Before importing a new internal package from a non-test file, verify the target package's **test files** aren't already importing back to you:
```
# BAD: agent(_test.go) → tool/builtin(sessions.go) → agent → setup failed
```
Use `go test ./path/to/target/` to detect cycles **before** pushing. A `[setup failed]` message means a cycle exists.
## PR hygiene
- **One force-push per round of review feedback.** Multiple force-pushes destroy review history and confuse reviewers.
- **Keep the PR diff minimal.** Only the files relevant to the PR's purpose — no stray changes from other branches.
- **Amend, don't add commits, for review feedback** — keeps the commit history clean.
## Change discipline
**Assess before editing.** For every change, humans and agents list callers,
consumers of the same state, sibling features, reload/replay/restart paths,
error and edge states, TUI/CLI and desktop equivalents, and wire mirrors.
A fix that breaks a neighbouring behaviour is a failed fix.
**Test the neighbourhood.** UI changes add or extend interaction tests for
adjacent functions of the same component or flow (composer: submit, clear,
queue, withdraw, restore, steer, failure, replay after reload) and run the whole
affected suite.
Write tests first; they must fail without the change.
**Fix at the owning layer.** Use the existing unified pattern: no special-case
flags, duplicated paths, or workarounds at the symptom site.
If the design is duplicated or wrong, make the smallest unifying change:
one path instead of two, deleting what becomes dead. Use current language and
framework idioms; do not add a new pattern where one exists.
**PR evidence.** Every PR description carries: Cause, Blast radius,
Neighbouring behaviours tested, and Why this layer.
## Reasonix host checks
The paths below decide what the agent is allowed to do — a wrong change here
is not a bug in a feature, it is a hole in a boundary. Declaring them makes
every change under them demand `review` plus `security_review` before a turn
can finish. Sensitivity is declared, never inferred: the host does not read it
out of how a path is spelled, which cannot tell `internal/auth` from
`session_write_authority.go`, or a trace file from a data race.
- sensitive: internal/safety/permission/**
- sensitive: internal/safety/sandbox/**
- sensitive: internal/safety/shellsafe/**
- sensitive: internal/base/shellparse/**
- sensitive: internal/session/control/approval.go
- sensitive: internal/session/control/approval_bridge.go
- sensitive: internal/session/control/approval_orchestration.go
- sensitive: internal/model/providerbroker/**
- sensitive: internal/ext/installsource/**
- sensitive: internal/ext/plugin/**
- sensitive: internal/ext/pluginpkg/**
- sensitive: internal/base/netclient/**
- sensitive: internal/safety/redirectguard/**
- sensitive: internal/safety/endpointclient/**
- sensitive: internal/safety/egress/**
- sensitive: internal/platform/browser/**
- sensitive: internal/platform/computer/**
- sensitive: internal/platform/gitpush/**
- sensitive: internal/session/control/git_push.go
- sensitive: internal/frontend/serve/git_push.go
- sensitive: internal/frontend/serve/host_routes.go
One declaration, two effects: the same list is also the coverage gate's subject.
`make coverage-gate` holds each path to the coverage it already has, because
when this was written these paths sat *below* the tree's median rather than
above it — the code deciding what the agent may execute was its least-tested
part. Floors ratchet like repolint's budgets: raising one is free, lowering one
needs `-allow-drop` and a reason in the PR. Adding a `sensitive:` path gets both
effects; there is no second list to keep in sync.
## Trust domain
Three sets, kept apart because conflating them turns a performance number into a
security claim: **VerificationRelevant** (state that can change whether a
delivery claim holds), **Observable** (state the host can reconcile after an
action, so it can say what that action did), **HostProtected** (state a
capability/sandbox boundary makes unwritable). The invariant is
`Writable ∩ VerificationRelevant ⊆ Observable ∪ HostProtected`:
> Any state that can both be modified by an action and influence the delivery
> claim must either be observable by the host or protected from modification by
> host-enforced boundaries. An incomplete observation never establishes scope.
Effects and state answer different questions and never stand in for each other —
observation proves what an action did, verification proves what the resulting
state satisfies — which is why `unproven_mutation` is settled only by
observation, never by a check that ran afterwards.
What follows bounds Observable today. It is not a restatement of the invariant:
moving a number here must not move the promise.
- `scanWorkspace` walks the workspace and every granted extra root recursively,
skips VCS store dirs, and is `complete` only below 50k files in total. Over that, or past a walk error, it
establishes nothing and the mutation stays unproven.
- Symlinks are recorded by `Lstat`, so a write through one lands outside what
the walk compares. Confining the resolved target is the sandbox's job.
- `internal/safety/sandbox` confines writes to the workspace, configured extras, temp
and toolchain caches on macOS and Linux.
- On Windows a user-enabled write-restricted token bounds the *creation* of files
(create, append, overwrite, `mkdir`, HKCU writes, global git config, writes through links).
- There, deleting or renaming away an existing file is not bounded, and with the
setting off nothing the host enforces bounds `Writable`.
- The caches a command may write can be poisoned for the user's later unsandboxed
builds, on every platform.
- The governed host authorities are a *named* set — ssh-agent, docker, podman.
DBus, Wayland, X11, gpg-agent, keyrings and arbitrary sockets stay reachable,
so the claim is "these endpoints are governed", never "host IPC is isolated".
`stateEpoch` tracks host-observed mutations, not an exact filesystem snapshot;
unobserved external writers are a gap shared by the whole verification model. Go
baseline test criteria use the toolchain's build overlay and therefore share
ordinary verification's epoch semantics; the overlay is not a general filesystem
view.
A captured criterion may be superseded only by authority outside
execution-mutable state; the current workspace, its tests, and the agent itself
cannot authorize supersession.
Two gaps follow and are open, not decided: a build that reads `.git` makes VCS
state VerificationRelevant while the scan skips it, and on Windows a symlink out
of the workspace is neither observed nor protected. Closing either means
widening observation or narrowing writability — never widening what a check is
taken to prove.
## Sandbox dimensions
`HostProtected` above is the delivery-level abstraction. Sandbox policy refines
it into three independent protection dimensions. Their separation is empirical:
measured bypasses showed that protection on one dimension cannot be assumed to
imply protection on another.
- **Integrity** — what host state may be mutated. Expressed by write roots.
- **Confidentiality** — what host information may be observed. Expressed by
`ForbidReadRoots`.
- **Authority** — what host capabilities may be exercised *without* possessing
their secrets. Expressed by `HostAuthorities`.
`ReadOnly` is therefore an Integrity property only; it makes no Confidentiality
or Authority claim.
Network transport and host authority are independent even when a backend
primitive conflates them: on macOS, `(deny network*)` also cut ssh-agent, so one
flag could not express "no internet, still sign".
Filesystem visibility is not authority: denying `file-read*` on a socket did not
stop a connect. Possession is not authority: the key can be unreadable while an
agent still signs with it.
A protection claim exists only where a backend has a demonstrated enforcement
primitive for that dimension. Unsupported dimensions stay explicitly unsupported,
because a claim that outruns its enforcement is worse than an absent one: it is
believed.
Windows enforces Integrity on file creation only, when the user turns it on.
Deletion and rename, Confidentiality and Authority (the named pipes of ssh-agent
and docker, COM and RPC services) are not enforced there.
**Known unmeasured surface — macOS host-mediated delegation:** Apple Events and
Mach-service lookup are not denied by the current allow-default profile. Prior
`osascript` and `launchctl submit` probes were inconclusive; no delegation
effect has been demonstrated. This surface is outside the currently governed
host-authority endpoint set.
- **This IS Reasonix** — edits to `src/loop.ts`, `src/repair/`, `src/tools/`, `src/mcp/` affect every session. Test before publishing.
- **SEARCH must match byte-for-byte** — the edit-gate in `src/code/edit-blocks.ts` enforces exact match. Trailing whitespace or wrong indent = mismatch.
- **`dist/`** is generated by `tsup`. Never hand-edit.
- **`.reasonix/semantic/`** is auto-generated vector index. Never hand-edit.
- **`sessions/` and `.reasonix/sessions/`** are user-private, git-ignored (per `.gitignore`).
+24 -172
View File
@@ -1,188 +1,40 @@
# Security Policy
## Supported Versions
If you find a security issue in Reasonix, please report it privately rather than opening a public issue or discussion thread.
Reasonix security fixes are prioritized for the currently developed Go rewrite
and the current 1.x release line.
## How to report
| Version or branch | Security support |
| --- | --- |
| `main-v2` / 1.x releases | Supported |
| `v1` / 0.x legacy branch | Critical fixes only, where practical |
| Older releases, forks, or modified builds | Not covered unless the issue is reproducible upstream |
Email <359807859@qq.com> with:
If you are unsure whether a version is affected, report against the newest
released 1.x version and include the exact version or commit you tested.
- a clear description of the issue
- steps that reproduce it (a minimal repro is fine)
- the version (`reasonix --version`) and platform you observed it on
## Reporting a Vulnerability
You'll get an acknowledgement within a few days, and a fix or mitigation as soon as the maintainer can land it. If you'd like attribution in the release notes when the fix ships, say so in your report — the default is a quiet patch.
Please report security issues privately. Do not open a public issue with exploit
details, secrets, crash dumps, or proof-of-concept payloads.
## Supported versions
Preferred reporting path:
Only the latest published minor of `reasonix` on npm is actively maintained. If you're on something older, please reproduce on the latest before reporting.
1. Use GitHub private vulnerability reporting for this repository, if available.
2. If private reporting is not available to you, open a minimal public issue
asking for a private maintainer contact path. Do not include exploit details
in that issue.
## Scope
Please include:
**In scope:**
- Affected Reasonix version, commit, operating system, and installation method.
- The feature or surface involved, such as CLI, desktop app, HTTP `serve`, bot
gateway, MCP plugin, built-in tool, updater, or configuration loading.
- Clear reproduction steps using dummy credentials and non-sensitive files.
- The expected impact, such as secret disclosure, arbitrary file access,
command execution, sandbox escape, authentication bypass, or supply-chain risk.
- Any relevant logs with API keys, tokens, local paths, and personal data
redacted.
- The published `reasonix` npm package and its CLI / TUI
- The dashboard SPA shipped under `dashboard/` and the local HTTP server that serves it
- The shell sandbox, edit gate, and tool dispatcher in `src/`
Do not send real provider API keys, bot credentials, OAuth tokens, private
workspace files, or third-party user data.
**Out of scope:**
## Security Boundaries
- Third-party MCP servers attached via `--mcp` (report to those projects)
- Misconfiguration of the user's own DeepSeek API key, environment, or shell profile
- Vulnerabilities in upstream Node.js or in the DeepSeek API itself
- Denial-of-service via deliberately oversized prompts or tool inputs (Reasonix is a single-user CLI; there's no multi-tenant boundary to defend)
Reasonix is a local coding agent. Many features intentionally operate on the
user's local machine and workspace, including file reads, file writes, shell
commands, MCP plugins, language servers, bot sessions, and model-provider
requests. A finding is security-relevant when it crosses a supported boundary or
bypasses an explicit guard.
## Hardening notes
Supported boundaries include:
A few practical reminders for users running Reasonix:
- Workspace confinement for file operations that are documented or implemented
as workspace-scoped.
- Permission checks for tool calls, shell commands, file writes, and approvals.
- Sandbox behavior for built-in shell execution where the platform supports it.
- Secret handling for provider keys, bot credentials, OAuth tokens, plugin
headers, and credential-store fallback files.
- 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 |
| `permissions.mode`, `permissions.allow`, `permissions.allow_dynamic_bash` | Nothing |
| `desktop.default_tool_approval_mode` | Nothing |
| `[network]` proxy settings | Nothing |
| `[[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
timeline in your initial report.
- API keys live in `~/.reasonix/config.json`. Treat that file like any other credential store.
- `run_command` and the `!` shell shortcut respect a permission allowlist; the safe default is `ask` on anything not pre-approved. Don't set `editMode: yolo` on machines that hold secrets you'd regret leaking.
- Hooks (`PreToolUse`, etc.) execute arbitrary shell scripts the user has configured. Audit `.reasonix/settings.json` before running Reasonix in a directory you didn't author.
-22
View File
@@ -1,22 +0,0 @@
# Build output and local tooling state.
build/
.gradle/
.kotlin/
local.properties
*.iml
.idea/
# The signing key and the file that names it.
#
# A key is not part of the project: it is the identity one person ships under,
# and publishing it would let anyone else sign an APK that installs over
# everyone's. Neither the keystore nor its password belongs in version control.
# `app/build.gradle` reads both from here when present and falls back to the
# debug key when they are not, so a fresh clone builds without them.
keystore/
# Build inputs, produced by scripts/ before Gradle runs.
# jniLibs/ holds the cross-compiled kernel, assets/page/ the built
# frontend. assets/LICENSE is hand-placed and stays tracked.
app/src/main/jniLibs/
app/src/main/assets/page/
-216
View File
@@ -1,216 +0,0 @@
---
owner: @esengine
backup: @SivanCola
status: active
reviewed: 2026-10-20
---
# Reasonix Mobile — the Android shell
Runs Reasonix as an Android app: the kernel ships inside the APK and starts on the
device, the interface is the same `desktop/frontend-next` build the desktop Studio
serves, and the agent reaches servers over SSH.
This file is for people building it. What a person installing it needs — what it
does, how to pair with a computer, what it cannot do — belongs in the release
notes.
## One command
```bash
./scripts/build.sh release # or debug
```
Three steps, in this order:
1. `build-kernel.sh` → `app/src/main/jniLibs/arm64-v8a/libreasonix.so`
2. `sync-page.sh` → `app/src/main/assets/page/`
3. `./gradlew assembleRelease`
Output: `app/build/outputs/apk/release/app-release.apk`
The kernel and the page are **inputs to packaging, not Gradle build steps**.
Running `gradle assembleRelease` on its own fails on purpose and names the script
that produces whichever input is missing (`requireBuildInputs` in
`app/build.gradle`): an APK with no kernel in it should not be buildable by
accident.
## Requirements
| Component | Version |
| --- | --- |
| JDK | 21 (17 also works) |
| Android SDK | `platforms;android-35`, `build-tools;35.0.0`, `platform-tools` |
| Gradle | the committed wrapper, 8.14.3 (for AGP 8.11.1) |
| Go | 1.26+ |
| Node / pnpm | Node 24+ / pnpm 10 |
```bash
export ANDROID_HOME="$HOME/Android/Sdk"
export ANDROID_SDK_ROOT="$ANDROID_HOME"
export JAVA_HOME="/path/to/jdk-21"
export PATH="$PATH:$(go env GOPATH)/bin"
```
`ANDROID_HOME` is the one thing nothing sets for you.
## Scripts
| Script | What it does |
| --- | --- |
| `build.sh [debug\|release]` | The whole chain |
| `build-kernel.sh` | Cross-compiles the kernel only (`GOOS=android GOARCH=arm64 CGO_ENABLED=0`) |
| `sync-page.sh` | Builds the frontend, copies `dist/` into assets, copies `LICENSE` |
| `verify-page.sh` | **No phone needed**: starts the real kernel against the packaged page |
| `run.sh [debug\|release]` | `adb install`, launch, follow the log |
`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
`-Pandroid.overridePathCheck=true`.
-263
View File
@@ -1,263 +0,0 @@
// The app module.
//
// Two things ship inside the APK and neither is fetched at runtime: the kernel
// binary, and the built page it serves. Bundling the page is what makes the app
// work offline and start instantly; bundling the kernel is what lets it run
// `reasonix serve` on the phone itself, which is the whole point — the agent
// starts locally and reaches the server over SSH, so the interface, the model
// catalogue and the credentials all live on the phone.
//
// The kernel is placed as `jniLibs/arm64-v8a/libreasonix.so`, not under
// `assets/`. That is not a trick for its own sake: Android permits executing a
// file under `nativeLibraryDir` and nothing under `filesDir` has that
// guarantee, so a binary shipped the ordinary way would have to be copied out
// and made executable at runtime — which fails outright on a device mounted
// noexec, and fails confusingly on the ones that are merely unusual. `scripts/
// build-kernel.sh` writes it there; the name is fixed by the packaging rules.
plugins {
id "com.android.application"
id "org.jetbrains.kotlin.android"
}
// One version, read by the About screen and the update check.
//
// A published build takes its version from the tag it was cut for, so the About
// screen and the update check name that release rather than the number this file
// was last edited to. Without the property — a local build — the numbers below
// are the answer.
def publishedVersion = findProperty("reasonixVersion") as String
def versionMajor = 2
def versionMinor = 0
def versionPatch = 0
def versionBuild = 1
if (publishedVersion) {
def parsed = publishedVersion =~ /^(\d+)\.(\d+)\.(\d+)/
if (!parsed.find()) {
throw new GradleException("reasonixVersion must start with MAJOR.MINOR.PATCH, got: ${publishedVersion}")
}
versionMajor = parsed.group(1) as int
versionMinor = parsed.group(2) as int
versionPatch = parsed.group(3) as int
}
// Where the two build inputs are expected. Both are produced from the checkout
// beside this module, by the scripts named in each message.
def upstream = rootProject.file("..")
def pageDir = new File(projectDir, "src/main/assets/page")
def kernelSo = new File(projectDir, "src/main/jniLibs/arm64-v8a/libreasonix.so")
android {
namespace "io.reasonix.mobile.app"
compileSdk 35
defaultConfig {
applicationId "io.reasonix.mobile.app"
minSdk 26
// 35: the API level this app is actually built and tested against.
//
// It was briefly lowered to 26 while chasing an install failure that
// turned out to be a package-name collision with an unrelated app on the
// user's phone — the signature error named the wrong cause. Nothing about
// the target level ever caused it, so it goes back to the level the code
// is really written for.
//
// One consequence to keep in mind: from 35, Android 15 forces the window
// edge-to-edge and ignores a request to lay out inside the safe area. The
// window therefore *is* drawn under the status bar and the home indicator,
// and the only correct answer is for the page to pad itself — which is
// what `MainActivity` feeds real inset values for, since a WebView does
// not implement `env(safe-area-inset-*)`.
targetSdk 35
// versionCode must strictly increase, because Android refuses an update
// whose versionCode is not higher. The build digit is a single decimal
// place, so the scheme collides once a patch reaches 10: 2.55.10 and
// 2.56.0 both come out as 25601. Patch releases above 9 are not expected
// on Studio, and widening the digit now would renumber every build, so
// the constraint is recorded rather than fixed.
versionCode versionMajor * 10000 + versionMinor * 100 + versionPatch * 10 + versionBuild
versionName "${versionMajor}.${versionMinor}.${versionPatch}"
// The kernel is built for arm64 only, so every other ABI would ship an
// APK that installs and then cannot start. Naming the one real ABI keeps
// the store listing and the installer honest.
ndk {
abiFilters "arm64-v8a"
}
resourceConfigurations += ["zh", "en"]
}
// Android identifies an app by package name *and* signing key: an APK signed
// with a different key is not an update, it is an impostor, and the
// installer refuses it with "the signature does not match the installed
// app". Gradle's default release key is the debug key in the user's home
// directory, which is per-machine, so a build made on a second computer
// could never be installed over one made on the first.
//
// Whoever ships a build therefore pins a key — and that key is theirs, not
// the project's. It lives beside the checkout, in `keystore/`, which is
// ignored; so does the file naming it. A checkout without either signs with
// the debug key instead, which is what a contributor building locally wants
// and is what the README tells them to expect. Point the build at a real key
// by writing `keystore/keystore.properties` (storeFile, storePassword,
// keyAlias) or by setting REASONIX_KEYSTORE / REASONIX_KEYSTORE_PASSWORD /
// REASONIX_KEY_ALIAS.
def keyProperties = new Properties()
def keyPropertiesFile = rootProject.file("keystore/keystore.properties")
if (keyPropertiesFile.exists()) {
keyPropertiesFile.withInputStream { keyProperties.load(it) }
}
def keyStorePath = keyProperties.getProperty("storeFile") ?: System.getenv("REASONIX_KEYSTORE")
def keyStorePassword = keyProperties.getProperty("storePassword") ?: System.getenv("REASONIX_KEYSTORE_PASSWORD")
// The key's own password is a separate fact from the store's. PKCS#12 keystores
// almost always use one password for both, so falling back to the store's
// password keeps those working — but assuming they are equal is how a keystore
// that separates them gets a build failure at signing time, after the work is
// done, with an error that does not say which of the two was wrong.
def keyPasswordValue = keyProperties.getProperty("keyPassword") ?: System.getenv("REASONIX_KEY_PASSWORD") ?: keyStorePassword
def keyAliasName = keyProperties.getProperty("keyAlias") ?: System.getenv("REASONIX_KEY_ALIAS")
def haveReleaseKey = keyStorePath && keyStorePassword && keyAliasName &&
rootProject.file(keyStorePath).exists()
signingConfigs {
if (haveReleaseKey) {
releaseKey {
storeFile rootProject.file(keyStorePath)
storePassword keyStorePassword
keyAlias keyAliasName
keyPassword keyPasswordValue
// v1 is not optional here. Android 7+ reads v2 and ignores v1, so
// a v2-only APK installs on a modern phone — and then fails on the
// compatibility layers older devices and HarmonyOS' 卓易通 run,
// which know only the JAR signature and report its absence as a
// signature *mismatch*. Signing both is what makes one APK install
// everywhere.
enableV1Signing = true
enableV2Signing = true
enableV3Signing = true
}
}
}
// Nothing native is compiled here — the one .so is a prebuilt the kernel
// script writes — so the external native build is left alone entirely.
buildTypes {
debug {
applicationIdSuffix ".debug"
versionNameSuffix "-debug"
// The debug key, always. Signing a debug build with the release key
// would mean anyone who can read the release keystore can produce a
// build that installs over the shipped one under the same signature,
// and it buys nothing: the debug package is suffixed `.debug`, so the
// two already install side by side.
}
release {
// The kernel is a stripped Go binary and the page is minified, but
// the Kotlin shell still benefits and shipping the shrunk build is
// how a size regression gets noticed.
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
// A release with no key of its own comes out *unsigned*
// (`app-release-unsigned.apk`). It used to fall back to the debug key
// so the artifact would install, which produced a release that looked
// shippable and was signed by a per-machine key nobody chose: it could
// not be installed over the previous build, and every machine made a
// different one. An unsigned artifact says what it is.
if (haveReleaseKey) {
signingConfig signingConfigs.releaseKey
} else {
logger.warn(
"release build has no signing key: producing an unsigned APK. " +
"Write keystore/keystore.properties (storeFile, storePassword, keyAlias) " +
"or set REASONIX_KEYSTORE / REASONIX_KEYSTORE_PASSWORD / REASONIX_KEY_ALIAS."
)
}
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildFeatures {
// AGP 8 stops generating BuildConfig unless asked. `Kernel` reads the
// version name and code out of it to decide whether the bundled page
// needs unpacking, so it is asked for.
buildConfig = true
}
packaging {
jniLibs {
// `extractNativeLibs=true`: the kernel must exist as a real file on
// disk to be executed, and an uncompressed-and-mmap'd .so is not
// one. This is the only reason the flag is on.
useLegacyPackaging true
}
resources {
excludes += ["META-INF/*.version", "META-INF/*.kotlin_module", "kotlin/**", "DebugProbesKt.bin"]
}
}
// The page is read out of assets by `Kernel.publish`, not by the resource
// system, so it is not compressed — a page is already-compressed text and
// shrinking it again only costs startup time.
androidResources {
noCompress += ["json", "woff2", "ttf", "woff", "txt", "svg"]
}
lint {
abortOnError true
warningsAsErrors false
checkReleaseBuilds true
}
}
dependencies {
implementation "androidx.core:core-ktx:1.15.0"
implementation "androidx.appcompat:appcompat:1.7.0"
implementation "androidx.activity:activity-ktx:1.9.3"
implementation "androidx.webkit:webkit:1.12.1"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.7"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0"
// Scanning the pairing code a computer shows.
//
// CameraX for the preview and the frame stream, ZXing for the decode, and
// deliberately not ML Kit: this app installs on phones whose HarmonyOS
// compatibility layer has no Google Play Services, so a decoder that needs
// GMS would work on the developer's phone and fail on the user's. ZXing
// core is pure Java with no runtime dependency at all, which is what makes
// the scanner work on both.
implementation "androidx.camera:camera-core:1.4.1"
implementation "androidx.camera:camera-camera2:1.4.1"
implementation "androidx.camera:camera-lifecycle:1.4.1"
implementation "androidx.camera:camera-view:1.4.1"
implementation "com.google.zxing:core:3.5.3"
}
// Fail before the packaging step with something a person can act on, rather
// than shipping an APK whose kernel is missing or whose page is a directory the
// build never filled. The two messages name the script that produces each.
tasks.register("requireBuildInputs") {
doFirst {
if (!kernelSo.exists()) {
throw new GradleException(
"内核二进制缺失:${kernelSo}\n先运行 ./scripts/build-kernel.sh(在 android/ 目录下)交叉编译内核。")
}
if (!pageDir.exists() || !new File(pageDir, "index.html").exists()) {
throw new GradleException(
"前端页面缺失:${pageDir}/index.html\n先运行 ./scripts/sync-page.sh(在 android/ 目录下)构建并同步页面。")
}
}
}
tasks.configureEach { task ->
if (task.name.startsWith("merge") && (task.name.contains("Assets") || task.name.contains("JniLibFolders"))) {
task.dependsOn("requireBuildInputs")
}
}
-32
View File
@@ -1,32 +0,0 @@
# R8 rules for the shell.
#
# There is very little to keep here, and that is the point: the app's own code
# is reached from the manifest and from Android's own callbacks, both of which
# R8 already traces, and nothing in it is loaded reflectively. What follows is
# the two places where a name is looked up rather than called.
# The WebView's JavaScript bridge, if one is ever added, is resolved by name on
# the Java side and by the string the page uses. Keeping annotated members makes
# that survive shrinking rather than failing at runtime with a method-not-found
# that only shows up on a release build.
-keepclassmembers class * {
@android.webkit.JavascriptInterface <methods>;
}
# The Kernel's child process is started by absolute path, and its own log is
# read as text; neither is reflective, so nothing else needs keeping.
# Line numbers make a stack trace from a release build readable, which is the
# only way a crash report from a phone can be acted on.
-keepattributes SourceFile,LineNumberTable
-renamesourcefileattribute SourceFile
# Kotlin's `@Metadata` annotation is present on every class the compiler touched
# and nothing in this app reflects over it. It is tempting to `-assumenosideeffects`
# it away, and that was tried: any pattern broad enough to name its members also
# matches the methods every class inherits from `Object` — `equals`, `hashCode`,
# `toString` — and R8 then treats those as removable, which is a silent
# behaviour change for a few kilobytes. Left as a warning suppression instead:
# the annotation is dropped from the shrunk output anyway, because nothing reads
# it.
-dontwarn kotlin.Metadata
-112
View File
@@ -1,112 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
The shell's manifest.
There is no INTERNET-adjacent permission beyond INTERNET itself: the page and
the kernel talk over loopback, and reaching a server is the kernel's job over
a socket it owns. Reading and writing files goes through the system's document
picker (SAF), which hands back a grant for one file at a time — so no
storage permission is declared and none is needed.
`usesCleartextTraffic` is off here, and cleartext is re-enabled in the network
security config only because the kernel serves its page on `127.0.0.1` and a
paired computer serves the same page over its LAN address — both plain HTTP.
The config says what that costs and what bounds it.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Only to tell the person the kernel is still running while the screen is
off; it is a foreground service with a dismissible notification, not a
background wake-up. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- From API 34 every foreground-service *type* needs its own permission as
well as the general one: naming dataSync in the manifest without asking
for it is a SecurityException at startForeground, on the one code path
that keeps a long task alive. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Only to read the pairing code a computer shows. Requested at the
moment the person asks to scan, never at launch. -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- The kernel is a child process, and a task left running is one the person
expects to finish with the screen off. Android's own doze can freeze the
whole app group instead, which is what the shell asks to be exempt from
— once, when a turn is actually running, never at launch. It is a
request the person can refuse, and refusing it only costs battery life
during a long turn. -->
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<!-- Every-file access, for opening a folder on this phone as a workspace.
The kernel is a plain Go binary: it opens paths with `open(2)`, and a
document URI is not a path it can open. SAF would hand back exactly
that unusable URI, so the one honest permission is the broad one —
granted by the person in system settings, which is the only place
Android offers it. Nothing here reads storage for any other purpose. -->
<uses-permission
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<!-- Below API 33 the same folder walk needs the older pair; from 33 they are
superseded by the permission above and asking for them would be a lie. -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" />
<!-- A phone without a touchscreen cannot drive this interface; saying so
keeps the listing honest rather than letting it install on a TV. -->
<uses-feature android:name="android.hardware.touchscreen" android:required="true" />
<!-- The camera is optional: a phone without one is still a fine client for
a kernel it already knows, and it can still pair by opening the link the
computer shows. Requiring it would take the app off those devices. -->
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<application
android:name=".App"
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true"
android:theme="@style/Theme.Reasonix"
android:usesCleartextTraffic="false"
tools:targetApi="35">
<activity
android:name=".MainActivity"
android:exported="true"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|uiMode|density|fontScale|smallestScreenSize"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:theme="@style/Theme.Reasonix">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- The kernel outlives the screen: a turn that takes minutes would
otherwise be killed when the phone is pocketed. The service is
`stopWithTask="false"` so swiping the app away ends it deliberately
rather than silently, and `foregroundServiceType="dataSync"` is the
closest honest description of "an agent is working". -->
<service
android:name=".KernelService"
android:exported="false"
android:foregroundServiceType="dataSync"
android:stopWithTask="false" />
<!-- Reading the pairing code a computer shows. Its own activity rather
than a dialog, because the camera preview needs the whole screen to
be worth pointing at anything. Not exported: only this app starts
it, and a scanner another app could open is one that could be made
to read a code on someone else's behalf. -->
<activity
android:name=".ScanActivity"
android:exported="false"
android:screenOrientation="portrait"
android:theme="@style/Theme.Reasonix.Scan" />
</application>
</manifest>
@@ -1,59 +0,0 @@
package io.reasonix.mobile.app
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
/**
* The process-wide facts this app needs.
*
* The kernel is one child process, so there is exactly one of it no matter how
* many activities exist: it is held here, lazily, and the activity and the
* service both reach the same instance. Nothing else is stored — the theme, the
* language and every preference belong to the page and live in its localStorage.
*/
class App : Application() {
/**
* The kernel, created on first use.
*
* Lazy rather than eager so that merely launching the process to answer a
* notification does not unpack a 15MB page.
*/
val kernel: Kernel by lazy { Kernel(this) }
override fun onCreate() {
super.onCreate()
createChannel()
}
/**
* A channel the person can mute without muting the app, and one they can
* find: an agent that runs for minutes on a phone has to say so somewhere
* the system will not kill, and a notification is the only place Android
* offers. `IMPORTANCE_MIN` because the notification is a receipt, not an
* interruption — the work it reports is on another machine.
*/
private fun createChannel() {
// No SDK_INT guard: minSdk is 26, which is the release NotificationChannel
// arrived in, so every device this app installs on has it.
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (manager.getNotificationChannel(CHANNEL_KERNEL) != null) return
val channel = NotificationChannel(
CHANNEL_KERNEL,
getString(R.string.channel_kernel),
NotificationManager.IMPORTANCE_MIN,
).apply {
description = getString(R.string.channel_kernel_desc)
setShowBadge(false)
enableVibration(false)
setSound(null, null)
}
manager.createNotificationChannel(channel)
}
companion object {
const val CHANNEL_KERNEL = "reasonix-kernel"
}
}
@@ -1,699 +0,0 @@
package io.reasonix.mobile.app
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Handler
import android.os.Looper
import android.util.Base64
import android.util.Log
import android.webkit.WebView
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.OutputStream
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
/**
* The kernel's browser, as a loopback HTTP server.
*
* The Go kernel (`internal/platform/browser/shell.go`) drives a WebView by
* POSTing JSON to a handful of paths on 127.0.0.1. This class is the other end
* of that conversation: it accepts connections on a random port, parses the
* minimal HTTP the kernel sends, and translates each path into an operation on
* the overlay WebView.
*
* The server is deliberately tiny — no connection pooling, no keep-alive, no
* chunked encoding — because the kernel is its only client and sends one
* request per connection. A `ServerSocket` accept loop on a daemon thread is
* the whole transport; each request is handled synchronously on its own thread.
*
* WebView operations must run on the UI thread. Each handler posts to the main
* looper and waits on a latch, with a timeout that bounds the worst case (a
* page that hangs the JS thread) to something the kernel's own 30-second client
* timeout will not outlast.
*
* Memory note on `/screenshot`: a full-page `WebView.draw` into an ARGB_8888
* bitmap at device resolution can reach tens of MB for a long page. The bitmap
* is downsampled by a factor of 2 in each dimension before PNG encoding, which
* keeps the peak allocation under ~10 MB for a typical 1080p viewport. The
* original is recycled immediately after the downsample.
*/
/** One thing a page asked the network for, as the WebView's request
* interceptor reports it. The interceptor is handed the method and the URL
* and nothing about the response, so a caller may show exactly this much and
* must not read it as a completed exchange. */
data class BrowserRequest(val method: String, val url: String, val kind: String)
class BrowserShellServer(
/** The overlay WebView, when one already exists. The routes that act on an
* open page — back, forward, reload, close — use this: with no page there
* is nothing to act on, and creating one to do nothing to it would start a
* renderer nobody asked for. */
private val existingView: () -> WebView?,
/** The overlay WebView, created on first use. The routes that drive a page
* use this, because the kernel can open one before the panel has ever been
* shown: the page's own panel asks for the view when it is displayed, and
* an agent's `browser_open` can arrive first. Requiring the view to exist
* already answered every such call with "browser view not ready", which
* reads as a broken engine rather than as a view that was not created yet.
* Called on the UI thread. */
private val ensureView: () -> WebView,
/** Why the page in the view is the browser's own error page rather than a
* site, as `(url, chromium error)`; null when the last load succeeded.
* `/read` asks this, because extracting `innerText` from the error page
* returns the browser's own "this page could not be loaded" notice, which
* the kernel would hand to the model as though the site had said it. */
private val loadFailure: () -> Pair<String, String>? = { null },
/** Begin a navigation: forget the load failure recorded for the page being
* left, drop its request list, and start the wait a following `/read`
* joins. Called on the UI thread, before the new address is loaded, so the
* wait is in place before any callback for the new page can fire. */
private val startNavigation: () -> Unit = {},
/** What the page currently in the view has asked the network for, oldest
* first. The WebView reports a request's method and URL to its interceptor
* but nothing about the response, so that is all a caller may show. */
private val requests: () -> List<BrowserRequest> = { emptyList() },
/** Wait for the navigation last asked for to settle — the page arrived, or
* its load failed — up to the given milliseconds. Called on the request's
* own thread, never the UI thread: the settle is signalled from the UI
* thread, so waiting on it there would deadlock. `/load` starts a
* navigation and returns before the page has been visited; without this a
* `/read` right behind it still sees the URL of the page before, and a
* failure recorded for that page was handed back as the new one's answer. */
private val awaitNavigation: (Long) -> Unit = {},
) {
companion object {
private const val TAG = "BrowserShellServer"
/** How long a UI-thread operation may take before the handler gives up.
* The kernel's client timeout is 30 s; staying under it means the kernel
* sees a clean error rather than a dropped connection. */
private const val UI_TIMEOUT_MS = 25_000L
/** The maximum text `/read` returns. Matches the kernel's `maxReadText`
* (400 << 10). The shell truncates here and says so, rather than letting
* the kernel truncate silently. */
private const val MAX_READ_TEXT = 400 * 1024
/** Screenshot downsample factor. 2 means half width and half height. */
private const val SCREENSHOT_SCALE = 2
/** The address the kernel dials. Both ends must agree on the family:
* see [start] for what goes wrong when they do not. */
private const val LOOPBACK_V4 = "127.0.0.1"
/** How long `/read` waits for a navigation it follows to settle before
* reading whatever the view is on. A page that never finishes loading
* must not hold the tool call open to the kernel's own timeout. */
private const val NAV_SETTLE_MS = 10_000L
/** How long `/read` then waits for the page's own script to answer.
* `NAV_SETTLE_MS + READ_SCRIPT_MS` has to stay under [UI_TIMEOUT_MS],
* and that under the kernel's 30-second client timeout: a read that
* waited out both budgets would outlast the caller, which would see a
* dropped connection instead of this shell's answer. 10 + 15 = 25 s. */
private const val READ_SCRIPT_MS = 15_000L
}
@Volatile
private var serverSocket: ServerSocket? = null
/** The port the server is listening on. Valid after [start] returns. */
@Volatile
var port: Int = 0
private set
/**
* The bearer credential every request must carry. Minted by the activity
* and handed to the kernel through the child's environment, so the server
* answers only the process this shell started.
*
* A phone's loopback is not a boundary: any other app may connect to
* 127.0.0.1, and the routes here run script in and read text out of
* whatever page is loaded. Binding to `getLoopbackAddress()` keeps other
* machines out but not other apps, so the credential is what makes "only
* the kernel this shell started" true.
*/
@Volatile
var token: String = ""
private set
private val mainHandler = Handler(Looper.getMainLooper())
/**
* Start listening on 127.0.0.1 with an ephemeral port. The port is available
* via [port] immediately after this returns, and the credential the kernel
* must present via [token].
*/
fun start() {
token = newToken()
// The loopback address is spelled out as IPv4, not taken from
// `InetAddress.getLoopbackAddress()`. That call is allowed to answer
// either family and Android's libcore answers IPv6 (`::1`), while the
// kernel's client is hardcoded to `http://127.0.0.1:<port>`
// (`internal/assembly/boot/browser.go`). A socket bound to `::1` does
// not answer a dial to `127.0.0.1`, so every browser call failed with
// "connection refused" while the port was bound and reported — the
// failure looked like a server that never started. Both ends have to
// name the same family, and IPv4 is the one the kernel names.
val ss = ServerSocket(0, 16, java.net.InetAddress.getByName(LOOPBACK_V4))
serverSocket = ss
port = ss.localPort
Log.i(TAG, "browser shell server listening on $LOOPBACK_V4:$port")
Thread({
while (!ss.isClosed) {
try {
val client = ss.accept()
Thread({ handleClient(client, token) }, "browser-shell-conn").apply { isDaemon = true }.start()
} catch (_: SocketException) {
// Server was closed; exit the loop.
}
}
}, "browser-shell-accept").apply { isDaemon = true }.start()
}
fun stop() {
runCatching { serverSocket?.close() }
serverSocket = null
}
/** A fresh 256-bit credential, hex-encoded, for one launch of the server. */
private fun newToken(): String {
val bytes = ByteArray(32)
java.security.SecureRandom().nextBytes(bytes)
return bytes.joinToString("") { "%02x".format(it) }
}
// ---- HTTP plumbing --------------------------------------------------------
private fun handleClient(client: Socket, expected: String) {
try {
client.soTimeout = 30_000
val input = BufferedInputStream(client.getInputStream())
val output = client.getOutputStream()
// Parse the request line.
val requestLine = readLine(input) ?: return
val parts = requestLine.split(" ", limit = 3)
if (parts.size < 2) return
val method = parts[0]
val path = parts[1].substringBefore('?')
// Read headers.
var contentLength = 0
var bearer: String? = null
while (true) {
val header = readLine(input) ?: break
if (header.isEmpty()) break
val lower = header.lowercase()
if (lower.startsWith("content-length:")) {
contentLength = header.substringAfter(':').trim().toIntOrNull() ?: 0
} else if (lower.startsWith("authorization:")) {
bearer = header.substringAfter(':').trim().removePrefix("Bearer ").trim()
}
}
// Nothing behind this server is safe to hand out on the strength of
// an address: the port is on loopback, which any other app on the
// phone can dial, and the routes run script in and read text out of
// the loaded page. The credential the kernel was started with is the
// only thing that says a caller is that kernel. Every route is
// refused without it, /health included — a probe needs no exemption.
if (expected.isEmpty() || bearer != expected) {
writeResponse(output, 401, """{"error":"unauthorized"}""")
return
}
// Read body.
val body = if (contentLength > 0) {
val buf = ByteArray(contentLength)
var read = 0
while (read < contentLength) {
val n = input.read(buf, read, contentLength - read)
if (n == -1) break
read += n
}
String(buf, 0, read, Charsets.UTF_8)
} else ""
// Route.
val (status, responseBody) = route(method, path, body)
writeResponse(output, status, responseBody)
} catch (e: Exception) {
Log.w(TAG, "connection error: ${e.message}")
} finally {
runCatching { client.close() }
}
}
private fun route(method: String, path: String, body: String): Pair<Int, String> {
return when {
method == "GET" && path == "/health" -> 200 to """{"ok":true}"""
method == "POST" && path == "/load" -> handleLoad(body)
method == "POST" && path == "/close" -> handleClose()
method == "POST" && path == "/read" -> handleRead()
method == "POST" && path == "/screenshot" -> handleScreenshot()
method == "POST" && path == "/click" -> handleClick(body)
method == "POST" && path == "/eval" -> handleEval(body)
method == "POST" && path == "/back" -> handleBack()
method == "POST" && path == "/forward" -> handleForward()
method == "POST" && path == "/reload" -> handleReload()
method == "POST" && path == "/requests" -> handleRequests()
else -> 404 to """{"error":"not found"}"""
}
}
private fun writeResponse(out: OutputStream, status: Int, body: String) {
val reason = when (status) {
200 -> "OK"
404 -> "Not Found"
500 -> "Internal Server Error"
else -> "Error"
}
val bytes = body.toByteArray(Charsets.UTF_8)
val header = "HTTP/1.1 $status $reason\r\n" +
"Content-Type: application/json\r\n" +
"Content-Length: ${bytes.size}\r\n" +
"Connection: close\r\n" +
"\r\n"
out.write(header.toByteArray(Charsets.UTF_8))
out.write(bytes)
out.flush()
}
private fun readLine(input: BufferedInputStream): String? {
val sb = StringBuilder()
while (true) {
val b = input.read()
if (b == -1) return if (sb.isEmpty()) null else sb.toString()
if (b == '\r'.code) {
val next = input.read()
if (next == '\n'.code) return sb.toString()
sb.append(b.toChar())
if (next != -1) sb.append(next.toChar())
continue
}
if (b == '\n'.code) return sb.toString()
sb.append(b.toChar())
}
}
// ---- endpoint handlers ----------------------------------------------------
/** POST /load {"url":"..."} → {"url":"...","title":"..."} */
private fun handleLoad(body: String): Pair<Int, String> {
val json = runCatching { JSONObject(body) }.getOrNull()
?: return 500 to """{"error":"invalid request body"}"""
val url = json.optString("url", "")
if (url.isEmpty()) return 500 to """{"error":"missing url"}"""
val result = AtomicReference("")
val latch = CountDownLatch(1)
mainHandler.post {
val wv = ensureView()
// The failure recorded for the page being left stops being this
// tab's, and the wait a following `/read` joins is armed before the
// new address is loaded, so no callback for the new page can fire
// ahead of it. `/load` answers before the page arrives, which is
// what left the old failure to be read back as the new page's.
startNavigation()
wv.loadUrl(url)
// The title and final URL are not available synchronously after
// loadUrl; answer with what was requested. The kernel stores this
// as the tab's URL and reads the real one on the next /read.
result.set(JSONObject().apply {
put("url", url)
put("title", "")
}.toString())
latch.countDown()
}
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
return 500 to """{"error":"timeout waiting for UI thread"}"""
}
return 200 to result.get()
}
/** POST /close {} → 200 */
private fun handleClose(): Pair<Int, String> {
val latch = CountDownLatch(1)
mainHandler.post {
val wv = existingView()
if (wv != null) {
wv.loadUrl("about:blank")
wv.clearHistory()
}
latch.countDown()
}
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
return 500 to """{"error":"timeout"}"""
}
return 200 to "{}"
}
/**
* POST /read {} → {"title":"...","url":"...","text":"..."}
*
* Injects a script that extracts readable text from the page, preferring
* `<article>` or `<main>` and falling back to `body.innerText`. The result
* is truncated to 400 KB (matching the kernel's `maxReadText`); when
* truncated, a note is appended so the model knows the text was cut.
*/
private fun handleRead(): Pair<Int, String> {
// The page the caller just asked for has not necessarily been visited
// yet: `/load` returns as soon as it has started the navigation. Waiting
// here, off the UI thread, is what makes this read answer about that
// page instead of the one before it.
awaitNavigation(NAV_SETTLE_MS)
val result = AtomicReference("")
val latch = CountDownLatch(1)
mainHandler.post {
val wv = ensureView()
// A page that did not load is not content. Whether the view is on
// the browser's own error page is read from the view itself rather
// than from a remembered failure: a failure recorded for the page
// before a new navigation would otherwise be handed back as this
// page's answer, long after the page the caller asked for had
// loaded. The remembered failure is still what names the address
// that failed and why, since the error page's own URL does not.
if ((wv.url ?: "").startsWith("chrome-error:")) {
val (url, reason) = loadFailure() ?: ((wv.url ?: "") to "ERR_FAILED")
result.set(JSONObject().apply {
put("url", url)
put("title", "")
put("reason", reason)
put("text", "")
}.toString())
latch.countDown()
return@post
}
// 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.
val script = """
(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) : '';
elements.push({ref: ref, role: roleOf(el), name: nameOf(el), value: raw});
}
window.__rxRefSeq = seq;
var el2 = document.querySelector('article') || document.querySelector('main') || document.body;
var text = el2 ? (el2.innerText || '') : '';
var title = document.title || '';
var url = location.href;
return JSON.stringify({title: title, url: url, text: text, elements: elements});
})()
""".trimIndent()
wv.evaluateJavascript(script) { value ->
// evaluateJavascript returns a JSON-encoded string (the result
// is double-encoded). Strip the outer quotes.
val parsed = parseJsResult(value)
if (parsed != null) {
try {
val obj = JSONObject(parsed)
var text = obj.optString("text", "")
if (text.length > MAX_READ_TEXT) {
text = text.substring(0, MAX_READ_TEXT) +
"\n\n[text truncated at 400 KB]"
}
result.set(JSONObject().apply {
put("title", obj.optString("title", ""))
put("url", obj.optString("url", ""))
put("text", text)
put("elements", obj.optJSONArray("elements") ?: JSONArray())
}.toString())
} catch (e: Exception) {
result.set(JSONObject().apply {
put("title", "")
put("url", wv.url ?: "")
put("text", parsed.take(MAX_READ_TEXT))
}.toString())
}
} else {
result.set(JSONObject().apply {
put("title", "")
put("url", wv.url ?: "")
put("text", "")
}.toString())
}
latch.countDown()
}
}
if (!latch.await(READ_SCRIPT_MS, TimeUnit.MILLISECONDS)) {
return 500 to """{"error":"timeout waiting for page script"}"""
}
return 200 to result.get()
}
/**
* POST /screenshot {} → {"data":"<base64>","mime":"image/png"}
*
* Draws the WebView into a bitmap, downsamples by SCREENSHOT_SCALE to keep
* memory bounded, and encodes as PNG → base64. For a 1080×2400 viewport the
* full bitmap is ~10 MB; the downsampled one is ~2.5 MB. The full bitmap is
* recycled immediately after scaling.
*/
private fun handleScreenshot(): Pair<Int, String> {
val result = AtomicReference("")
val failed = AtomicBoolean(false)
val latch = CountDownLatch(1)
mainHandler.post {
val wv = ensureView()
try {
val width = wv.width.takeIf { it > 0 } ?: 1080
val height = wv.height.takeIf { it > 0 } ?: 1920
val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bmp)
wv.draw(canvas)
// Downsample to bound the PNG size and the base64 string.
val scaled = Bitmap.createScaledBitmap(
bmp,
width / SCREENSHOT_SCALE,
height / SCREENSHOT_SCALE,
true,
)
if (scaled !== bmp) bmp.recycle()
val baos = ByteArrayOutputStream()
scaled.compress(Bitmap.CompressFormat.PNG, 85, baos)
scaled.recycle()
val b64 = Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP)
result.set(JSONObject().apply {
put("data", b64)
put("mime", "image/png")
}.toString())
} catch (e: Exception) {
// A 200 with an error body would be read by the kernel as a
// screenshot whose data is empty, and it would build a `data:`
// URI out of nothing. The status is what tells it this failed.
result.set("""{"error":"screenshot failed: ${e.message}"}""")
failed.set(true)
}
latch.countDown()
}
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
return 500 to """{"error":"timeout"}"""
}
if (failed.get()) return 500 to result.get()
return 200 to result.get()
}
/** POST /click {"selector":"..."} → {"ok":true|false} */
private fun handleClick(body: String): Pair<Int, String> {
val json = runCatching { JSONObject(body) }.getOrNull()
?: return 500 to """{"error":"invalid request body"}"""
val selector = json.optString("selector", "")
if (selector.isEmpty()) return 500 to """{"error":"missing selector"}"""
val result = AtomicReference("")
val latch = CountDownLatch(1)
mainHandler.post {
val wv = ensureView()
// Escape the selector for embedding in a JS string.
val escaped = selector.replace("\\", "\\\\").replace("'", "\\'")
val script = """
(function(){
try {
var el = document.querySelector('$escaped');
if (!el) return JSON.stringify({ok: false});
el.click();
return JSON.stringify({ok: true});
} catch(e) {
return JSON.stringify({ok: false});
}
})()
""".trimIndent()
wv.evaluateJavascript(script) { value ->
val parsed = parseJsResult(value)
result.set(parsed ?: """{"ok":false}""")
latch.countDown()
}
}
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
return 500 to """{"error":"timeout"}"""
}
return 200 to result.get()
}
/** POST /eval {"script":"..."} → {"result":"..."} */
private fun handleEval(body: String): Pair<Int, String> {
val json = runCatching { JSONObject(body) }.getOrNull()
?: return 500 to """{"error":"invalid request body"}"""
val script = json.optString("script", "")
if (script.isEmpty()) return 500 to """{"error":"missing script"}"""
val result = AtomicReference("")
val latch = CountDownLatch(1)
mainHandler.post {
val wv = ensureView()
wv.evaluateJavascript(script) { value ->
// The kernel expects a plain string in "result". The value from
// evaluateJavascript is JSON-encoded; unwrap it.
val unwrapped = parseJsResult(value) ?: ""
result.set(JSONObject().apply {
put("result", unwrapped)
}.toString())
latch.countDown()
}
}
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
return 500 to """{"error":"timeout waiting for eval"}"""
}
return 200 to result.get()
}
/** POST /back → 200 */
private fun handleBack(): Pair<Int, String> {
val latch = CountDownLatch(1)
mainHandler.post {
existingView()?.let { if (it.canGoBack()) it.goBack() }
latch.countDown()
}
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
return 500 to """{"error":"timeout"}"""
}
return 200 to "{}"
}
/** POST /forward → 200 */
private fun handleForward(): Pair<Int, String> {
val latch = CountDownLatch(1)
mainHandler.post {
existingView()?.let { if (it.canGoForward()) it.goForward() }
latch.countDown()
}
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
return 500 to """{"error":"timeout"}"""
}
return 200 to "{}"
}
/** POST /reload → 200 */
private fun handleReload(): Pair<Int, String> {
val latch = CountDownLatch(1)
mainHandler.post {
val wv = existingView()
// A view sitting on the browser's own error page is not on the site,
// and reloading it would retry the error page itself. The address
// that failed is loaded again instead — which is the page a caller
// means by "reload" — read before `startNavigation` clears it.
val failed = if (wv != null && (wv.url ?: "").startsWith("chrome-error:"))
loadFailure()?.first else null
startNavigation()
if (wv != null) {
if (failed != null) wv.loadUrl(failed) else wv.reload()
}
latch.countDown()
}
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
return 500 to """{"error":"timeout"}"""
}
return 200 to "{}"
}
/** POST /requests {} → {"requests":[{"method","url","kind"},…]} */
private fun handleRequests(): Pair<Int, String> {
val arr = JSONArray()
for (r in requests()) {
arr.put(JSONObject().apply {
put("method", r.method)
put("url", r.url)
put("kind", r.kind)
})
}
return 200 to JSONObject().apply { put("requests", arr) }.toString()
}
// ---- helpers ----------------------------------------------------------------
/**
* Unwrap the result of `evaluateJavascript`. The callback receives a
* JSON-encoded string: a JS string "hello" arrives as `"\"hello\""`, a
* number 42 as `"42"`, null as `"null"`. Strip the outer JSON encoding to
* get the raw value.
*/
private fun parseJsResult(value: String?): String? {
if (value == null || value == "null") return null
// The value is a JSON literal. If it is a JSON string, decode it.
return try {
if (value.startsWith("\"") && value.endsWith("\"")) {
JSONObject().apply { }.let {
// Use JSONObject's string decoding: wrap in an object.
JSONObject("""{"v":$value}""").optString("v", "")
}
} else {
value
}
} catch (_: Exception) {
value
}
}
}
@@ -1,119 +0,0 @@
package io.reasonix.mobile.app
import android.content.Context
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.os.Build
/**
* The phone's DNS servers, as the kernel needs them.
*
* The kernel is a CGO-free Go binary, and Go's own source explains why that
* matters:
*
* ```
* // DNS requests don't work on Android, so prefer the cgo resolver.
* // Issue #10714.
* case "android":
* ```
*
* A normal Android program resolves names through `getaddrinfo`, which reaches
* the `netd` daemon and gets the servers of the network that is actually up.
* A static binary has no cgo resolver, so Go reads `/etc/resolv.conf` instead —
* and Android has no such file. Go then falls back to `127.0.0.1:53`, where
* nothing listens, and every lookup fails: the setup screen reports
* "连接失败" for every provider, including the official ones, on a phone whose
* browser reaches them fine.
*
* So they are read here and handed to the kernel through `REASONIX_DNS`. This is
* the same source the system itself uses, so a VPN, a private DNS hostname, or a
* network that changed since boot is all reflected without this code knowing
* anything about them.
*/
object Dns {
/**
* The active network's servers, comma separated, or "" when there is none.
*
* Read from the *active* network rather than from every link, because a phone
* commonly has several at once — Wi-Fi, mobile data, a VPN — and the servers
* of a network that is not carrying traffic are the wrong ones to ask.
*/
fun servers(context: Context): String {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
?: return ""
val properties: LinkProperties = runCatching { manager.activeNetwork }.getOrNull()
?.let { network -> runCatching { manager.getLinkProperties(network) }.getOrNull() }
?: return ""
return properties.dnsServers
.mapNotNull { address -> address.hostAddress }
.filter { it.isNotBlank() }
.filter { routable(it) }
.sortedBy { preference(it) }
.joinToString(",")
}
/**
* Whether an address can actually carry a query.
*
* A link-local address (fe80::/10) without its zone cannot: the packet has
* no interface to leave by, so it is dropped, nothing answers, and the
* lookup hangs until the kernel's own timeout expires — which is reported as
* a timeout rather than as a failure to resolve, and so reads like the
* network is slow instead of like the address is unusable.
*
* Android reports the zone as a `%wlan0` suffix on `hostAddress`, and the
* address is only usable with it kept. Nothing here trims it: an earlier
* version called `substringBefore('%')`, which turned a usable link-local
* server into an unroutable one.
*/
private fun routable(host: String): Boolean =
!(host.startsWith("fe80:", ignoreCase = true) && !host.contains('%'))
/**
* IPv4 first, then IPv6.
*
* A phone commonly reports both, and its IPv6 entry is often a router's
* link-local address — reachable on one network and not the next. The
* kernel tries the servers in the order it is given them, and stops at the
* first that answers; putting the address family that shares the network's
* own numbering first means its timeout is spent on a server that works.
*/
private fun preference(host: String): Int = if (host.contains(':')) 1 else 0
/**
* The private-DNS setting, for the one case the address list cannot answer.
*
* Since Android 9 a phone may use DNS-over-TLS, and then `dnsServers` holds a
* name rather than an address — a name this kernel cannot resolve *because*
* resolving it is the thing that is broken. There is no way for the shell to
* do that lookup for it, so this reports the situation instead of handing
* over an unusable value: the caller says so in the log, and the person can
* turn private DNS off or set it to automatic.
*/
fun looksLikeDot(servers: String): Boolean =
servers.isNotBlank() && servers.split(',').any { part ->
val host = part.trim()
host.isNotEmpty() && host.none { it == ':' } && !host.all { it.isDigit() || it == '.' }
}
/** Whether the system requires a VPN or private DNS, which changes nothing
* here but is worth saying in a bug report. */
fun describe(context: Context): String {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
?: return "no connectivity service"
val network = runCatching { manager.activeNetwork }.getOrNull() ?: return "no active network"
val properties = runCatching { manager.getLinkProperties(network) }.getOrNull()
?: return "no link properties"
// The DHCP server arrived in API 30, not 23: asked for below that it is a
// NoSuchMethodError on a device this app supports (minSdk 26), and the
// answer is only ever read out of this string by a person debugging.
val dhcp = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
properties.dhcpServerAddress?.hostAddress
} else {
null
}
return "iface=${properties.interfaceName} dns=${properties.dnsServers.joinToString(",") { it.hostAddress ?: "?" }}" +
(dhcp?.let { " dhcp=$it" } ?: "")
}
}
@@ -1,87 +0,0 @@
package io.reasonix.mobile.app
import android.content.Context
import android.net.Uri
import android.webkit.CookieManager
import android.widget.Toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.FileNotFoundException
import java.net.HttpURLConnection
import java.net.URL
/**
* Putting a file the page produced onto the phone's disk.
*
* A WebView has no downloads shelf and cannot write to the system's document
* picker itself, so the two halves are joined here: the page asks, the picker
* answers with a `content://` the app has been granted, and this copies the
* bytes across.
*
* The request carries the WebView's own cookie, read out of the jar the page
* authenticated in. That is the only reason this is not a plain `openStream`:
* the kernel's download route is behind the session the page established, and a
* shell that fetched without it would get a 403 and no explanation.
*/
object Downloader {
suspend fun run(
context: Context,
url: String,
userAgent: String,
mime: String,
name: String,
target: Uri,
): Result<Unit> = withContext(Dispatchers.IO) {
runCatching {
val connection = (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = 15_000
readTimeout = 60_000
requestMethod = "GET"
if (userAgent.isNotBlank()) setRequestProperty("User-Agent", userAgent)
// The download route answers with the same session cookie the
// page is using; without it the kernel refuses the request.
cookieFor(url)?.let { setRequestProperty("Cookie", it) }
}
try {
val code = connection.responseCode
if (code !in 200..299) {
throw IllegalStateException(
context.getString(R.string.download_failed_status, code),
)
}
val resolver = context.contentResolver
val output = resolver.openOutputStream(target, "w")
?: throw FileNotFoundException(target.toString())
output.use { out ->
connection.inputStream.use { input -> input.copyTo(out) }
}
// `copyTo` answers with a byte count; what the caller wants to
// know is that there were no bytes missing, not how many.
Unit
} finally {
connection.disconnect()
}
}
}
/**
* The cookie the page authenticated with, if any.
*
* `CookieManager` is the WebView's own store, so this asks the exact jar the
* request will be checked against rather than a copy this shell kept.
*/
private fun cookieFor(url: String): String? =
runCatching { CookieManager.getInstance().getCookie(url) }.getOrNull()?.takeIf { it.isNotBlank() }
/** A short receipt for a tap that otherwise does nothing visible. */
fun report(context: Context, name: String, result: Result<Unit>) {
val message = result.fold(
onSuccess = { context.getString(R.string.download_saved, name) },
onFailure = { failure ->
context.getString(R.string.download_failed, failure.message ?: "")
},
)
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
}
@@ -1,741 +0,0 @@
package io.reasonix.mobile.app
import android.content.Context
import android.content.res.AssetManager
import org.json.JSONArray
import org.json.JSONObject
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.security.SecureRandom
import java.util.Locale
/**
* The Reasonix kernel, as this app runs it: one child process serving loopback,
* plus the two things it needs on disk to start — the page it serves and a
* credential for this launch.
*
* The shape is the desktop host's (`cmd/reasonix-studio-host`), narrowed to what
* a phone does not have. That host binds a socket, mints a credential, speaks a
* handshake down a pipe and holds a lease; here the credential goes through
* `--token-file` and the bound address through `--port-file`, because a phone's
* app process has no pipe to hand a child and no reason to care which port was
* free. Everything after that — the kernel's own gate, its auth middleware, its
* CSRF check — is untouched, so the security of the surface is the one upstream
* tested, not one this shell invented.
*
* One instance lives in the app process. The activity asks it for a URL; the
* foreground service asks it to stay alive. Both see the same process, so there
* is nothing to synchronise beyond a lock on start/stop.
*/
class Kernel(private val context: Context) {
/** Where everything the kernel owns lives. Nothing here is backed up. */
private val home = File(context.filesDir, "home")
/**
* The folder the agent works in, which is not the folder the kernel lives in.
*
* These used to be the same directory, and that is what made the workbench
* unreadable: the kernel's home holds `config.toml`, `projects/`, `cache/`,
* `stats/` and the rest of its own bookkeeping, and a workspace pointed at
* it shows all of that as if the person had put it there. Reported as "why
* does the default workspace have so many files, the desktop version does
* not generate these" — the desktop does generate them, in a different
* directory, because its workspace is whatever folder it was opened on.
*
* Split apart, the workbench shows what the agent produced and nothing else.
* `write_roots` follows the workspace, so the file tools stay confined to
* the folder the person actually works in rather than to the kernel's own
* home — which is the stricter answer, and the one the desktop already has.
*/
private val workspaceDir = File(context.filesDir, "workspace")
/**
* The directory the kernel calls `REASONIX_HOME`, for the one caller that
* has to put a file where the kernel can read it — a private key the person
* picked from their Documents folder.
*/
fun homeDir(): File = home
/** The folder the agent works in. */
fun workspaceDir(): File = workspaceDir
/** The built page, unpacked once per version. */
private val pageDir = File(context.filesDir, "page")
private val tokenFile = File(home, "remote/launch.token")
private val portFile = File(home, "remote/serve.port")
private val pidFile = File(home, "remote/serve.pid")
private val lock = Any()
@Volatile
private var process: Process? = null
/** The port the shell's browser HTTP server listens on, set by the
* activity before `start()` is called. Zero means no server is up, and
* the kernel leaves its browser tools suspended (the correct degradation
* on a phone with no Chromium). */
@Volatile
var browserShellPort: Int = 0
/** The bearer credential for that server, set beside the port. Sent on
* every browser call so the server can refuse anything that did not come
* from the kernel this shell started — loopback on a phone is reachable
* by every other app. Empty when there is no server. */
@Volatile
var browserShellToken: String = ""
/** What the WebView should load, once the kernel has bound a port. */
@Volatile
var origin: String? = null
private set
/**
* The launch credential, as the URL fragment the page trades for a cookie.
* Kept in memory only: the file on disk belongs to the kernel's own
* bookkeeping, and a phone's app data is not a place to leave a second copy.
*/
@Volatile
private var token: String? = null
/**
* The URL the WebView loads first. It carries the credential in the
* fragment, which the page exchanges for an HttpOnly cookie before it makes
* any request — the same path a shared `reasonix web` link takes, so the
* token never enters a request line, a history entry or a log.
*/
fun entryUrl(): String? {
val origin = origin ?: return null
val token = token ?: return null
return "$origin/#token=$token"
}
/** The plain origin, for reloads once the cookie is set. */
fun plainUrl(): String? = origin
fun isRunning(): Boolean = process?.isAlive == true
/**
* Bring the kernel up, or answer the URL of the one already up.
*
* Starting is idempotent by intent: the activity and the service both call
* this, and whichever arrives second joins the running kernel instead of
* racing it for the port.
*/
suspend fun start(): Result<String> = withContext(Dispatchers.IO) {
synchronized(lock) {
origin?.let { return@withContext Result.success(it) }
runCatching {
val binary = kernelBinary()
publishPage()
prepareHome()
val launchToken = mintToken()
token = launchToken
val child = launch(binary, launchToken)
// The port is the kernel's answer, not this shell's guess. It
// writes the file after binding, so waiting on the file is
// waiting on the bind.
val bound = awaitPort(child)
val url = "http://$bound"
// A kernel that bound a port and then died would look healthy
// here and broken in the WebView; the two facts are checked
// together, and only a kernel that is answering is adopted.
awaitServing(child, url)
origin = url
process = child
url
}.onFailure { origin = null; process = null }
}
}
/**
* Stop the kernel.
*
* The graceful signal first: the kernel drains its listeners and closes the
* runtimes it opened, which is what lets a later launch adopt the sessions
* rather than find them locked. `destroyForcibly` is the second attempt, and
* only after a wait — a phone that is being shut down should not keep a
* half-killed agent.
*/
fun stop() {
synchronized(lock) {
val p = process ?: return
process = null
origin = null
token = null
runCatching {
p.destroy()
if (!p.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) {
p.destroyForcibly()
}
}
portFile.delete()
pidFile.delete()
}
}
// ---- the two inputs that ship inside the APK -------------------------
/**
* The kernel binary.
*
* It is packaged as a native library, so Android has already extracted it to
* a directory it allows execution from and given it the executable bit —
* which is the one thing a file under app storage does not get for free.
*/
private fun kernelBinary(): File {
val dir = File(context.applicationInfo.nativeLibraryDir)
val binary = File(dir, "libreasonix.so")
if (!binary.exists()) {
throw IllegalStateException(
"内核未随 APK 安装:${binary.path}\n这是一次构建问题,请重新安装完整 APK。",
)
}
return binary
}
/**
* Write the bundled page where the kernel can serve it.
*
* It goes to app storage rather than being served out of the APK because the
* kernel's `--page` is a directory on a real filesystem; there is no
* archive-aware variant, and adding one would be a change to the kernel for
* this shell's convenience alone.
*
* Unpacking is versioned: the marker holds the app's version name, so an
* update replaces the page and a relaunch does not. A partially written
* directory — the app killed mid-copy — is caught by the same marker never
* having been written, so the next launch rewrites it.
*/
private fun publishPage() {
val marker = File(pageDir, ".unpacked")
val stamp = "${BuildConfig.VERSION_NAME}:${BuildConfig.VERSION_CODE}"
if (marker.isFile && marker.readText().trim() == stamp) return
pageDir.deleteRecursively()
pageDir.mkdirs()
copyAssetTree(context.assets, "page", pageDir)
if (!File(pageDir, "index.html").isFile) {
throw IllegalStateException("随 APK 分发的页面不完整:缺少 index.html")
}
marker.writeText(stamp)
}
/**
* A directory tree out of assets.
*
* `AssetManager.list` on a file answers with an empty array, so a "file" is
* told from a directory by trying to open it — which is the only signal the
* API offers and the reason this is not a one-liner.
*/
private fun copyAssetTree(assets: AssetManager, from: String, to: File) {
val children = assets.list(from).orEmpty()
if (children.isEmpty()) {
// A leaf: open it as a stream. A directory that happens to be empty
// is indistinguishable and harmless to skip.
runCatching {
assets.open(from).use { input ->
FileOutputStream(to).use { output -> input.copyTo(output) }
}
}
return
}
to.mkdirs()
for (child in children) {
copyAssetTree(assets, "$from/$child", File(to, child))
}
}
/**
* Prepare the kernel's home.
*
* `REASONIX_HOME` is what every path in the kernel hangs off — config,
* sessions, the remote state directory its token file lands in — so pointing
* it at app storage is what keeps a phone's Reasonix separate from anything
* else and away from global storage entirely.
*/
private fun prepareHome() {
File(home, "remote").mkdirs()
// The workspace directory not existing yet is what marks the first run
// after this build split it from the kernel's home. That is the one
// moment a migration is due, and doing it here means it happens before
// the kernel is asked for anything.
val firstSplit = !workspaceDir.exists()
workspaceDir.mkdirs()
if (firstSplit) {
adoptSessionsFromHome()
}
// Every launch, not only the first. The rewrite is cheap and
// idempotent, and an entry that survived the first pass would otherwise
// survive forever: `firstSplit` is spent the moment the directory
// exists, so a build that cleaned the list once and missed leaves the
// home on the sidebar for good. Running it unconditionally costs one
// small read and makes the whole thing self-correcting.
forgetHomeFromWorkspaceList()
}
/**
* Drop the kernel's own home from the sidebar's remembered projects.
*
* The list is written whenever a pane opens, and until this build the pane
* opened on the home itself — so an upgraded install carries a "project"
* that is really the kernel's own directory. Leaving it there would put the
* person back where they started: one tap on it and the workbench is full
* of `config.toml`, `cache/` and `projects/` again, which is the complaint
* this whole change answers. Only that one path is removed; every folder
* someone added on purpose stays.
*
* Parsed rather than pattern-matched, because the file's two shapes — a bare
* array of paths and an object with `paths` and `launch` — both have to keep
* whatever else they hold.
*/
private fun forgetHomeFromWorkspaceList() {
val file = File(home, "serve-workspaces.json")
if (!file.isFile) return
val text = runCatching { file.readText() }.getOrNull() ?: return
val wrong = runCatching { homeNames() }.getOrNull() ?: return
val rewritten = runCatching { withoutHome(text, wrong) }.getOrNull() ?: return
if (!rewritten.dropped) return
runCatching { file.writeText(rewritten.text) }
.onSuccess { Log.i(TAG, "dropped the kernel home from the project list") }
.onFailure { Log.w(TAG, "could not rewrite the project list: ${it.message}") }
}
/**
* Every name of the kernel's home on this device — not just the one this
* process happens to write.
*
* Android shows one directory under two names: `/data/data/<pkg>` and
* `/data/user/0/<pkg>` are two mounts of the same tree, the same inode
* either way, and which name a path carries depends on how it was written
* rather than on where it points. The list is written by the kernel, whose
* working directory this shell set from a path it built itself; a lookup
* that compared against only one spelling would silently keep the entry
* this exists to remove. Both names are compared, so either spelling is
* recognised.
*/
private fun homeNames(): Set<String> {
val path = home.absolutePath
val names = mutableSetOf(path)
val user = "/data/user/0/"
val data = "/data/data/"
when {
path.startsWith(user) -> names.add(data + path.removePrefix(user))
path.startsWith(data) -> names.add(user + path.removePrefix(data))
}
return names
}
/** What a rewrite produced, and whether it actually removed anything. */
private class Rewrite(val text: String, val dropped: Boolean)
/**
* The list without the home, in whichever shape it arrived, and whether
* anything was actually dropped from it.
*
* The flag matters because `JSONObject` re-serialises: it escapes every
* `/` and does not preserve key order, so a round trip never reproduces
* the original bytes. Deciding to write on "the text differs" alone would
* therefore rewrite the kernel's file on every single launch, log a drop
* that never happened, and race the kernel for a file it also writes.
*/
private fun withoutHome(text: String, wrong: Set<String>): Rewrite {
if (text.trimStart().startsWith("[")) {
val paths = JSONArray(text)
val kept = JSONArray()
var dropped = false
for (i in 0 until paths.length()) {
val path = paths.optString(i)
if (path in wrong) {
dropped = true
continue
}
kept.put(path)
}
return if (dropped) Rewrite(kept.toString(), true) else Rewrite(text, false)
}
val list = JSONObject(text)
val kept = JSONArray()
var dropped = false
val paths = list.optJSONArray("paths")
if (paths != null) {
for (i in 0 until paths.length()) {
val path = paths.optString(i)
if (path in wrong) {
dropped = true
continue
}
kept.put(path)
}
if (dropped) list.put("paths", kept)
}
if (list.optString("launch") in wrong) {
list.remove("launch")
dropped = true
}
return if (dropped) Rewrite(list.toString(), true) else Rewrite(text, false)
}
/**
* Move the conversations that were filed under the kernel's own home.
*
* The transcript store is keyed by the workspace root — one directory per
* project, under `<state>/projects/<slug>/sessions` — and until this build
* the root was the home itself. Splitting the two therefore moves every
* existing conversation to a slug nothing looks under, which reads as "my
* history is gone" rather than as a reorganisation. So the old directory is
* renamed onto the new slug once.
*
* Renaming the project directory rather than just `sessions/` carries the
* rest of it too: `memory/` is filed the same way, and a project's memory
* lost while its transcripts were kept would be a stranger failure than
* either alone.
*
* The slug is the absolute path with its separators flattened, which is
* what `config.WorkspaceSlug` does on the kernel's side. Only the home's own
* slug is touched: a slug for some other folder is left exactly where it is,
* because those are projects someone added on purpose.
*/
private fun adoptSessionsFromHome() {
val projects = File(home, "projects")
if (!projects.isDirectory) return
val from = projects.resolve(slugOf(home.absolutePath))
if (!from.isDirectory) return
val to = projects.resolve(slugOf(workspaceDir.absolutePath))
// A target already there means a previous run half-finished, or the
// person opened this folder before. Either way its contents win:
// merging two transcript directories is not a thing this can do safely,
// and the old one is still on disk to be looked at.
if (to.exists()) {
Log.i(TAG, "${to.name} already exists; leaving ${from.name} in place")
return
}
if (!from.renameTo(to)) {
Log.w(TAG, "could not move ${from.name} to ${to.name}; history stays under the old slug")
} else {
Log.i(TAG, "moved conversations from ${from.name} to ${to.name}")
}
}
/** The kernel's `config.WorkspaceSlug`, for the two paths that matter here. */
private fun slugOf(path: String): String = path.replace('/', '-').replace('\\', '-').replace(':', '-')
/**
* The launch credential.
*
* Minted here rather than read from configuration: a credential a person can
* set is one anything that can read their files can present. 32 bytes, hex,
* the same shape the desktop host mints.
*/
private fun mintToken(): String {
val bytes = ByteArray(32)
SecureRandom().nextBytes(bytes)
val token = bytes.joinToString("") { "%02x".format(it) }
tokenFile.parentFile?.mkdirs()
tokenFile.writeText("$token\n")
// 0600 by intent, and the app's own private directory means it is
// already unreachable to every other app on the device.
runCatching {
tokenFile.setReadable(false, false)
tokenFile.setReadable(true, true)
tokenFile.setWritable(false, false)
tokenFile.setWritable(true, true)
}
return token
}
/**
* Start the child.
*
* `--addr 127.0.0.1:0` lets the kernel pick a free port; `--port-file`
* makes it announce which. `--auth token` is the mode a phone needs: the
* page authenticates, and a state-changing request without the credential
* is refused. `--no-open` is belt and braces — a serve never opens a
* browser, and a phone has no browser to open.
*/
private fun launch(binary: File, token: String): Process {
portFile.delete()
pidFile.delete()
// The folder the agent works in, resolved before the command line is
// built so it can be named on it. See the note under the environment
// block for why naming it is not the same as setting the directory.
val workspace = launchWorkspaceDir()
val command = listOf(
binary.absolutePath,
"serve",
"--addr", "127.0.0.1:0",
"--auth", "token",
"--token-file", tokenFile.absolutePath,
"--port-file", portFile.absolutePath,
"--pid-file", pidFile.absolutePath,
"--no-open",
"-page", pageDir.absolutePath,
// The project root, said outright. Without this the kernel derives
// it from its working directory, and on this phone the two did not
// agree: the sidebar named the shared folder, `write_roots` confined
// the file tools to the app's own directory, and every write into the
// folder the person was looking at came back
// `workspace.write_outside_scope`. A flag is a fact the kernel was
// told rather than one it inferred from a mount it sees differently.
"--dir", workspace.absolutePath,
)
val builder = ProcessBuilder(command)
builder.environment().apply {
put("REASONIX_HOME", home.absolutePath)
put("HOME", home.absolutePath)
// The kernel's own language, for its tool failures, approval
// prompts and error sentences. Without this it detects from the
// POSIX locale variables, and Android sets none of them for an
// app: the kernel then answers in English while the page in front
// of the person is Chinese, and every sentence added for a Chinese
// reader was dead text. The tag, not the bare language, so a
// Traditional Chinese device resolves to zh-TW rather than zh.
// An explicit `language` in the kernel's config.toml still wins:
// DetectLanguage applies the configured value over this.
val languageTag = Locale.getDefault().toLanguageTag()
if (languageTag.isNotBlank() && languageTag != "und") {
put("REASONIX_LANG", languageTag)
}
// Android has no /tmp. Everything that wants a scratch directory —
// the shell tool, tool output spooling, sqlite journals — reads this.
put("TMPDIR", context.cacheDir.absolutePath)
// The phone's own DNS servers. A CGO-free Go binary cannot read them
// for itself — Android keeps them in `netd`, and Go looks for a
// `/etc/resolv.conf` that does not exist — so without this the kernel
// resolves nothing and every provider probe reports "连接失败" on a
// device whose browser reaches the same address fine.
val dns = Dns.servers(context)
if (dns.isNotBlank()) {
put("REASONIX_DNS", dns)
Log.i(TAG, "kernel DNS: $dns (${Dns.describe(context)})")
if (Dns.looksLikeDot(dns)) {
// Private DNS (DNS-over-TLS) is on, and it hands back a
// hostname this kernel cannot resolve by definition. Saying
// so here is what turns "连不上" into something actionable.
Log.w(TAG, "kernel DNS looks like a private-DNS hostname; turn private DNS off or set it to automatic")
}
} else {
Log.w(TAG, "kernel DNS: none reported by the system")
}
// The shell's browser server, when one is listening. The kernel
// reads this to bind its browser tools to the shell's WebView
// instead of looking for a Chromium binary that does not exist on
// a phone. When absent (zero), the variable is not set and the
// kernel keeps the browser tools suspended — the correct
// degradation for a phone with no engine to drive.
val shellPort = browserShellPort
if (shellPort > 0) {
put("REASONIX_SHELL_BROWSER_PORT", shellPort.toString())
// The credential the server checks. Set only alongside the
// port: a token with nothing listening would be a variable the
// kernel carries for no reason.
val shellToken = browserShellToken
if (shellToken.isNotBlank()) {
put("REASONIX_SHELL_BROWSER_TOKEN", shellToken)
}
}
}
// The agent's folder, not the kernel's. `REASONIX_HOME` above is still
// where the config, the sessions and the transcripts live; this is what
// the workspace root resolves to, because the kernel reads the working
// directory for it.
//
// The folder the person last opened, when it is still usable — the same
// answer the desktop host gives (`launchWorkspace`), and the reason a
// phone session used to work in the app's own `files/workspace` while
// the sidebar said it was in the shared folder: the launch entry in
// `serve-workspaces.json` was written and then ignored, and `write_roots`
// is derived from the working directory, so the file tools were confined
// to the app's private folder and every write into the shared one was
// refused. `workspaceDir` is still the answer for a first run and for a
// folder since deleted, but the choice is never silent — see
// [launchWorkspaceDir]. `workspace` was resolved above so it could also
// be named on the command line.
builder.directory(workspace)
// `PWD` is what the kernel's own `os.Getwd` prefers: Go uses it whenever
// it names the same directory as `.`, which is exactly this case, and it
// is the only way to make the kernel resolve its root to the string this
// shell chose. Without it `os.Getwd` falls back to the kernel's view of
// the mount, and on Android `/storage/emulated/0/...` and the path the
// FUSE layer reports for it need not be spelled the same way. The kernel
// derives `write_roots` from that root, so the two spellings have to be
// the same one.
builder.environment().put("PWD", workspace.absolutePath)
builder.redirectErrorStream(true)
val process = builder.start()
// The kernel's own log is the only place a startup failure says why, and
// a phone has no terminal to read. It is drained on a thread and kept
// ring-buffered so the About screen can show the last of it.
Thread({ drain(process) }, "kernel-log").apply { isDaemon = true }.start()
return process
}
/**
* The folder the person last opened, or null when there is not one.
*
* `serve-workspaces.json` is the kernel's own record of the projects the
* sidebar lists, and its `launch` entry is which of them a session starts
* in. Both shapes the file has are read — a bare array of paths, and an
* object with `paths` and `launch` — because both are written in the wild
* and a reader that only knew one would silently fall back.
*
* The entry has to be one of the listed paths, which is the same rule the
* kernel applies when it reads this file (`workspacelist.Read` blanks a
* `launch` that is not in `paths`). It matters more here than there: the
* working directory decides `write_roots`, so whatever this answers is
* where the agent's file tools may write — and on a phone that permission
* reaches all of shared storage. A file with a `launch` outside its own
* list is one this shell did not write, and it gets the listed answer.
*
* Null for anything unusable: no file, unreadable JSON, a launch that is
* not among the listed folders, an entry that has since been deleted, or a
* path that is now a file. Every one of those means the same thing to the
* caller — start where this shell always started.
*/
private fun rememberedLaunchDir(): File? {
val file = File(home, "serve-workspaces.json")
if (!file.isFile) return null
val text = runCatching { file.readText() }.getOrNull() ?: return null
val launch = runCatching {
// A bare array is the file's other shape — the one older kernels
// wrote, and therefore the one a person upgrading is most likely to
// have. Without this branch `JSONObject(text)` throws on it and the
// whole function falls back, which is the same mismatch (the
// sidebar naming one folder, the session working in another) this
// exists to fix. `withoutHome` below reads both shapes the same way.
if (text.trimStart().startsWith("[")) {
val arr = JSONArray(text)
if (arr.length() == 0) return@runCatching null
arr.optString(0)
} else {
val json = JSONObject(text)
val paths = json.optJSONArray("paths")
?.let { arr -> (0 until arr.length()).mapNotNull { arr.optString(it).takeIf(String::isNotBlank) } }
.orEmpty()
if (paths.isEmpty()) return@runCatching null
json.optString("launch").takeIf { it.isNotBlank() && it in paths } ?: paths.first()
}
}.getOrNull()?.takeIf { it.isNotBlank() } ?: return null
val dir = runCatching { File(launch) }.getOrNull() ?: return null
if (!dir.isDirectory) {
// A launch entry this process cannot stat is exactly the failure the
// caller exists to avoid, and falling back silently is what made it
// take three releases to notice: the session opened in the app's own
// folder while the sidebar named the shared one. A phone has no
// terminal, so the log is the only place the reason can be said —
// and `exists`/`readable` tell apart "deleted" from "not permitted",
// which need different answers from the person.
Log.w(
TAG,
"launch entry $launch is not a usable directory " +
"(exists=${dir.exists()}, readable=${dir.canRead()})",
)
return null
}
return dir
}
/**
* The folder the kernel should start in.
*
* Either the launch entry — the folder the person last opened, which is
* also the one the sidebar shows — or the app's own folder when there is
* none. Whichever it is, it is logged, because the two disagreeing is the
* bug this exists to fix and a silent choice is what let it survive.
*/
private fun launchWorkspaceDir(): File {
val remembered = rememberedLaunchDir()
if (remembered != null) {
Log.i(TAG, "kernel workspace: ${remembered.absolutePath} (the remembered launch project)")
return remembered
}
Log.i(TAG, "kernel workspace: ${workspaceDir.absolutePath} (no remembered launch project)")
return workspaceDir
}
private val logLines = ArrayDeque<String>()
private fun drain(process: Process) {
runCatching {
process.inputStream.bufferedReader().useLines { lines ->
lines.forEach { line ->
Log.i(TAG, line)
synchronized(logLines) {
logLines.addLast(line)
while (logLines.size > LOG_KEEP) logLines.removeFirst()
}
}
}
}
}
/** The kernel's tail, newest last, for a bug report or the About screen. */
fun recentLog(): String = synchronized(logLines) { logLines.joinToString("\n") }
private fun awaitPort(process: Process): String {
val deadline = System.currentTimeMillis() + START_TIMEOUT_MS
while (System.currentTimeMillis() < deadline) {
if (!process.isAlive) {
throw IllegalStateException("内核启动即退出。\n${recentLog().takeLast(2000)}")
}
val text = if (portFile.isFile) runCatching { portFile.readText().trim() }.getOrNull() else null
// The file is written by the kernel on the way to serving, and the
// kernel rewrites it with the real port when it was given :0.
if (!text.isNullOrBlank() && text.contains(":")) return text
Thread.sleep(POLL_MS)
}
throw IllegalStateException("内核在 ${START_TIMEOUT_MS / 1000}s 内没有报告监听地址。\n${recentLog().takeLast(2000)}")
}
/**
* Wait until the bound port answers.
*
* A port that is open but not yet serving is the normal first second of a
* kernel's life; a WebView pointed at it would show a connection error and
* cache the failure, so the wait belongs here rather than in the page.
*/
private fun awaitServing(process: Process, origin: String) {
val deadline = System.currentTimeMillis() + START_TIMEOUT_MS
while (System.currentTimeMillis() < deadline) {
if (!process.isAlive) {
throw IllegalStateException("内核在开始服务前退出。\n${recentLog().takeLast(2000)}")
}
if (probe("$origin/")) return
Thread.sleep(POLL_MS)
}
throw IllegalStateException("内核已监听 $origin,但页面没有响应。\n${recentLog().takeLast(2000)}")
}
private fun probe(url: String): Boolean = runCatching {
(URL(url).openConnection() as HttpURLConnection).run {
connectTimeout = 1000
readTimeout = 1000
requestMethod = "GET"
try {
responseCode in 200..399
} finally {
disconnect()
}
}
}.getOrDefault(false)
private companion object {
const val TAG = "ReasonixKernel"
const val LOG_KEEP = 400
const val POLL_MS = 120L
const val START_TIMEOUT_MS = 30_000L
}
}
@@ -1,139 +0,0 @@
package io.reasonix.mobile.app
import android.Manifest
import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
/**
* Keeps the kernel alive while the app is not on screen.
*
* The reason this exists at all: an agent turn that takes minutes is a normal
* turn, and Android reclaims a backgrounded app's child process within seconds
* of the screen going off. Without the service, pocketing the phone would kill
* a running task — the one failure mode that makes a phone a bad client for
* something that works on its own.
*
* A foreground service needs a notification the person can see, which is also
* the honest thing to show: the kernel is running and what it is doing lives on
* another machine.
*/
class KernelService : Service() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// Promoted before `start()`: a service that starts work first and
// notifies after has a window in which the system may kill it, and the
// work it would have been protecting is exactly what is being started.
startForegroundNotification()
val kernel = (application as App).kernel
scope.launch {
kernel.start().onFailure { failure ->
// A kernel that will not start is a fact the person needs, and a
// notification that only ever said "running" would be a lie.
notify(SERVICE_NOTICE, getString(R.string.notify_failed_title), failure.message.orEmpty())
stopSelf()
}
}
// Sticky, so a kernel killed under memory pressure comes back when there
// is room — which is what a person who left a task running expects.
return START_STICKY
}
override fun onDestroy() {
scope.cancel()
super.onDestroy()
}
private fun startForegroundNotification() {
val notification = buildNotification(
getString(R.string.notify_running_title),
getString(R.string.notify_running_body),
)
// `dataSync` matches the manifest's declaration. On 34+ the type is
// mandatory and a mismatch throws, so it is named in both places.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
ServiceCompat.startForeground(
this,
SERVICE_NOTICE,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,
)
} else {
startForeground(SERVICE_NOTICE, notification)
}
}
private fun buildNotification(title: String, body: String): Notification {
val open = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
},
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
return NotificationCompat.Builder(this, App.CHANNEL_KERNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(open)
// The notification is a receipt, not an alarm; swiping it away
// leaves the kernel running, which is what the person meant by
// swiping it.
.setOngoing(false)
.setSilent(true)
.setPriority(NotificationCompat.PRIORITY_MIN)
.build()
}
private fun notify(id: Int, title: String, body: String) {
// The notification permission is granted at runtime from Android 13 and
// the person can refuse it. Without this check the call throws
// SecurityException and takes the service down with it — the opposite of
// what a notification that could not be shown should do. Below 13 the
// permission does not exist and posting always succeeds.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
return
}
runCatching {
NotificationManagerCompat.from(this).notify(id, buildNotification(title, body))
}
}
companion object {
private const val SERVICE_NOTICE = 1
/** Idempotent: called on every start of the activity, and by the boot
* path, and safe to repeat. */
fun start(context: Context) {
ContextCompat.startForegroundService(context, Intent(context, KernelService::class.java))
}
fun stop(context: Context) {
context.stopService(Intent(context, KernelService::class.java))
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,744 +0,0 @@
package io.reasonix.mobile.app
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ContentValues
import android.content.Context
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.webkit.JavascriptInterface
import android.webkit.MimeTypeMap
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* What the page can ask the phone for.
*
* This is the whole surface, and it is deliberately tiny. Android's
* `@JavascriptInterface` is a bridge into the app's process from a WebView whose
* content is a web page: every method here is reachable by anything that can run
* script in that page, so each one is written as a verb with no address
* parameter it does not need, and none of them can name a path outside the
* kernel's own home.
*
* It is deliberately *not* the Electron preload bridge. That one exposes window
* management, a filesystem walker, an editor launcher and a browser view host —
* all of which are meaningless on a phone, and the two that were not (open a URL,
* save a file) already have a way to happen here: `WebViewClient` routes external
* links to the browser, and the page's own download reaches the WebView's
* `DownloadListener`.
*
* The one thing a phone must add is `importIntoHome`: the kernel runs on this
* device and can only read paths under its own home, so a private key the person
* has in their Documents folder has to be copied across. Nothing else the page
* wants is out of its reach.
*/
class NativeBridge(
private val context: Context,
private val kernel: Kernel,
private val onOpen: (String) -> Unit,
) {
/**
* Whether the document calling may use this bridge.
*
* `addJavascriptInterface` makes the object reachable from whatever page the
* WebView holds, so a link the model produced — or a cleartext page on the
* LAN — would otherwise get `importIntoHome`, `pickFolder`, `hostCall` and
* the clipboard. The activity answers by comparing the main frame's origin
* against the kernel's and the one paired computer the person confirmed.
*
* Anything that reaches the device checks this first. The five methods that
* do not — version, systemTheme, safeArea, setLayerOpen, setRunning — report
* back what the page already knows about its own window and grant nothing.
*/
var trusted: () -> Boolean = { false }
/** The version the page reads to decide whether this bridge is the one it
* knows. Bumped when a method's contract changes, not when one is added. */
@JavascriptInterface
fun version(): String = BRIDGE_VERSION
/**
* Copy a file the person picks into the kernel's home, answering with its
* path there — or "" when they dismissed the picker.
*
* `kind` names the directory inside the home, because that is a fact about
* the kernel's layout and not about the file: an SSH private key belongs in
* `.ssh`, and a dotenv the kernel reads for passphrases belongs at the root
* of the home where `config.Load` looks for it.
*
* The path that comes back is *inside the home*, never the document
* provider's URI. That is the point: the kernel is a child process with no
* access to the provider, so a `content://` would be a path it cannot open.
*/
@JavascriptInterface
fun importIntoHome(kind: String, name: String): String {
if (!trusted()) return ""
val dir = when (kind) {
"identity" -> File(kernel.homeDir(), ".ssh")
"env" -> kernel.homeDir()
else -> return ""
}
val safeName = sanitise(name)
if (safeName.isEmpty()) return ""
val picked = pickFile() ?: return ""
return try {
dir.mkdirs()
val target = File(dir, safeName)
context.contentResolver.openInputStream(picked)?.use { input ->
target.outputStream().use { output -> input.copyTo(output) }
} ?: return ""
// A private key with group or world read is one OpenSSH refuses to
// use, and the refusal reads as "bad permissions" from a long way
// away. Setting it here is what makes the file usable at all.
if (kind == "identity") {
runCatching {
target.setReadable(false, false)
target.setReadable(true, true)
target.setWritable(false, false)
target.setWritable(true, true)
}
}
target.absolutePath
} catch (_: Exception) {
// A copy that failed leaves nothing behind; the caller sees "" and
// the person can try again.
""
}
}
/**
* Open a URL in the device's browser.
*
* The page asks for this when a link points somewhere outside the kernel —
* a provider's console, a documentation page — and loading it in place would
* strand the person in a window with no address bar and no way back.
*/
@JavascriptInterface
fun openExternal(url: String) {
if (!trusted()) return
// Only what a browser can open. A `file://` or `content://` here would
// be the page reaching into the device through a method named for
// leaving it.
if (!url.startsWith("http://") && !url.startsWith("https://")) return
onOpen(url)
}
/** Put text on the clipboard. A WebView's own `navigator.clipboard` write is
* gated behind a permission Android grants only to a focused document, so
* the one thing the page actually offers to copy — a token, a command, a
* path — has no other way out.
*
* Answers whether the write landed. A platform that refuses it raises
* rather than answering, and an exception must not cross
* `@JavascriptInterface` as a silent success — the page would say 已复制
* over an empty clipboard. Caught here, the answer is the one the caller
* can act on: false, and the button says 复制失败 instead. */
@JavascriptInterface
fun copyText(text: String): Boolean = if (!trusted()) false else runCatching {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboard.setPrimaryClip(ClipData.newPlainText("reasonix", text))
}.isSuccess
/**
* Write text where the person picks, and answer with the path it went to.
*
* The page's own route to a file — a blob URL on an `<a download>` — reaches
* nothing here: a WebView has no downloads shelf, and its `DownloadListener`
* fires only for a real navigation, not for a blob the page just built. So
* the text crosses the bridge and the shell opens the system's document
* picker, which is also the only way to reach a folder the person can find
* again afterwards.
*
* "" is a dismissal, the same answer `importIntoHome` gives, and the page
* reads the two the same way.
*/
/**
* Put a copy of a file where a phone's own file manager will show it.
*
* `saveText` asks the person where to put it, which is the right question
* on a desktop and the wrong one here: the kernel's workspace is
* app-private storage, so the file someone wants is in a place no file
* manager can open, and a picker that starts at "recent" is another place
* to lose it. This answers the actual question — "where is it" — by
* putting it in Downloads, in a folder named after the app, under a name
* that is the file's own.
*
* The answer is the path relative to shared storage, so the page can say
* where the file went rather than only that it worked. "" means the write
* failed or the platform refused it.
*
* MediaStore on Android 10 and later, a plain file before that. The two
* are not interchangeable: from 10 the app may not write another app's
* files directly, and MediaStore is the only way in; before it there is no
* MediaStore collection for downloads and the public directory is writable
* with the storage permission this app does not ask for, so that branch is
* best-effort and says so by answering "".
*/
@JavascriptInterface
fun exportToDownloads(name: String, content: String): String {
if (!trusted()) return ""
val safeName = sanitise(name).ifEmpty { "reasonix.txt" }
return exportFile(safeName, content).orEmpty()
}
@JavascriptInterface
fun saveText(name: String, content: String): String {
if (!trusted()) return ""
val safeName = sanitise(name).ifEmpty { "reasonix.txt" }
return saveFile(safeName, content) ?: ""
}
/**
* Hand text to whatever the device shares with — a chat app, the mail
* client, a note app.
*
* The share sheet rather than a second save dialog: "where is that file"
* is the question this answers, and on a phone a document someone wants to
* keep or send usually goes through one of those apps rather than a folder.
*
* Shared as text with the filename as its subject, which is what every
* target understands. A file attachment would need a `FileProvider` and a
* cache copy for the same words to arrive.
*/
@JavascriptInterface
fun shareText(name: String, content: String): Boolean {
if (!trusted()) return false
val safeName = sanitise(name).ifEmpty { "reasonix.txt" }
val posted = java.util.concurrent.CountDownLatch(1)
var ok = false
main.post {
ok = runCatching { askForShare(safeName, content) }.getOrDefault(false)
posted.countDown()
}
runCatching { posted.await(SHARE_TIMEOUT_SECONDS, TimeUnit.SECONDS) }
return ok
}
/**
* The device's own light/dark answer.
*
* The page resolves its theme from `localStorage` first and only asks the
* system when nothing is saved, so this is what makes a fresh install match
* the phone instead of defaulting to light.
*/
@JavascriptInterface
fun systemTheme(): String {
val night = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
return if (night == Configuration.UI_MODE_NIGHT_YES) "dark" else "light"
}
/**
* The window's real safe-area insets, in CSS pixels, as
* `top,right,bottom,left`.
*
* A WebView does not implement `env(safe-area-inset-*)`: those are an iOS
* Safari feature, and on Android every one of them resolves to `0`. So a
* page that pads itself with them — which `mobile.css` does — is un-padded
* on exactly the platform this shell exists for, and the first line of the
* interface sits under the status bar.
*
* The values have to come from here for a second reason too: from Android 15
* the window is edge-to-edge whether the app asks for it or not, so the bars
* really are drawn over the page and there is no window-manager switch that
* could move the content back down.
*
* Answered as a string because that is what crosses the bridge; the page
* sets it as a CSS custom property and `mobile.css` reads it.
*/
@JavascriptInterface
fun safeArea(): String {
val insets = onInsets?.invoke() ?: return "0,0,0,0"
return "${insets.left},${insets.top},${insets.right},${insets.bottom}"
}
/**
* Read the pairing code a computer is showing.
*
* A phone cannot type what a computer renders as a QR code — it is a
* one-time code inside a URL, and the whole reason it is a picture is that
* nobody reads one aloud. So the page asks for the camera and gets the text
* back, which is the same direction the computer's own dialog describes.
*
* The answer is the code's own text, not a parsed result: what a pairing
* fragment means is the page's to decide, and it already knows how — the
* `#pair=` handling ships with the interface.
*/
@JavascriptInterface
fun scanPairingCode(): String = if (!trusted()) "" else scanWithCamera()
/**
* Load a URL in this window instead of handing it to the browser.
*
* The page asks for this once, right after a scan: the code it read points at
* the computer's own Studio, and the whole point of scanning is to end up
* looking at that computer. Going out to a browser would leave the app on one
* screen and the paired machine on another, with the back gesture an exit
* rather than a return.
*
* Only http and https are accepted. The page is this repository's own build
* and is trusted, but a scanner reads whatever is held in front of it, so the
* one value that arrives here from outside is checked: a `file://` or
* `javascript:` that happened to be on a printed code must not become a
* navigation.
*/
@JavascriptInterface
fun openInApp(url: String) {
if (!trusted()) return
val trimmed = url.trim()
if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return
main.post { onOpenInApp?.invoke(trimmed) }
}
/** How the activity loads a URL in the window it owns. Set by the activity. */
var onOpenInApp: ((String) -> Unit)? = null
// ---- the native browser view host bridge ----
//
// The page's `host.ts` looks for `window.reasonixHost` with Promise-based
// methods (showBrowserView, hideBrowserView, etc.). `@JavascriptInterface`
// is synchronous, so the round trip is: JS generates an id, calls
// `hostCall(id, method, args)`, Kotlin does the work asynchronously, then
// pushes the result back via `evaluateJavascript` calling
// `window.__reasonixHostReply(id, json)`. The injected script (in
// MainActivity) wires each Promise to that reply channel.
/** How the activity handles an async host call. Set by the activity. */
var onHostCall: ((id: String, method: String, args: String) -> Unit)? = null
/**
* Entry point for the page's `window.reasonixHost` Promise methods.
*
* `id` is a unique call identifier the JS side generated; `method` is the
* method name (e.g. "showBrowserView"); `args` is the JSON-encoded argument
* array. The activity handles the call asynchronously and replies through
* `evaluateJavascript` with `window.__reasonixHostReply(id, resultJson)`.
*/
@JavascriptInterface
fun hostCall(id: String, method: String, args: String) {
if (!trusted()) return
onHostCall?.invoke(id, method, args)
}
/**
* Whether the page has a panel up that the back gesture should close first.
*
* Written by the page, read by the activity's back handler. The page owns the
* answer — it is the only thing that knows what is open, and a second
* implementation of that question in the shell would be one that drifts — so
* the page reports the fact and the shell keeps the action.
*
* Volatile because the two ends are on different threads: the page sets it
* from the WebView's JavaScript thread, the back gesture reads it on the main
* one, and a stale read here is a panel that does not close.
*/
@Volatile
var layerOpen: Boolean = false
private set
@JavascriptInterface
fun setLayerOpen(open: Boolean) {
layerOpen = open
}
// ---- the picker, which is an Activity result in a synchronous world ----
private val pending = AtomicReference<Uri?>(null)
private val latch = AtomicReference<CountDownLatch?>(null)
/** The code the camera read, held between the activity's answer and the
* wait below — the same round trip the file picker takes. */
private val scanned = AtomicReference<String?>(null)
private val scanLatch = AtomicReference<CountDownLatch?>(null)
/** The main thread, because starting an Activity result must happen there. */
private val main = Handler(Looper.getMainLooper())
/**
* How to ask for a file. Set by the activity, which owns the Activity Result
* API; it answers whether the ask was dispatched, not whether the person
* picked anything — that arrives through `deliver`.
*/
var askForFile: () -> Boolean = { false }
/**
* How the activity reports the window's insets. Set by the activity, which is
* the only thing that can see them, and asked on every call rather than
* cached — a rotation, a fold, or the keyboard opening all change them, and a
* stale answer here is a stripe of interface under the status bar.
*/
var onInsets: (() -> Insets?)? = null
/**
* How to open the camera. Set by the activity, which owns the Activity
* Result API; like `askForFile` it answers whether the ask was dispatched,
* and the code itself arrives through `deliverScan`.
*/
var askForScan: () -> Boolean = { false }
/**
* How to put a file where the person picks. Set by the activity, which owns
* the Activity Result API; it answers whether the ask was dispatched, and
* the chosen place arrives through `deliverSave`.
*/
var askForSave: (name: String, content: String) -> Boolean = { _, _ -> false }
/**
* How to open the share sheet. Set by the activity, which is the only thing
* that can start an Intent; it answers whether anything on the device took
* the text.
*/
var askForShare: (name: String, content: String) -> Boolean = { _, _ -> false }
/** The place the save dialog answered with, held between the two halves. */
private val saveTarget = AtomicReference<Uri?>(null)
private val saveLatch = AtomicReference<CountDownLatch?>(null)
/**
* Ask where to put a file and write it there.
*
* The same latch round trip as `pickFile`, and for the same reason:
* `@JavascriptInterface` cannot suspend, so the WebView's thread waits while
* the picker is open — a modal panel the person is looking at.
*/
private fun saveFile(name: String, content: String): String? {
val gate = CountDownLatch(1)
saveLatch.set(gate)
saveTarget.set(null)
val posted = CountDownLatch(1)
var dispatched = false
main.post {
dispatched = runCatching { askForSave(name, content) }.getOrDefault(false)
posted.countDown()
}
val ready = runCatching { posted.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS) }.getOrDefault(false)
if (!ready || !dispatched) {
saveLatch.set(null)
return null
}
return try {
if (!gate.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS)) null
else saveTarget.get()?.toString()
} catch (_: InterruptedException) {
null
} finally {
saveLatch.set(null)
}
}
/** Called by the activity once the bytes are written. A null uri is a dismissal. */
fun deliverSave(uri: Uri?) {
saveTarget.set(uri)
saveLatch.get()?.countDown()
}
/**
* Read the pairing code a computer is showing, and return it.
*
* The same shape as `pickFile` and for the same reason: a
* `@JavascriptInterface` method is called on the WebView's thread and must
* return a value, so the camera is opened on the main thread and this one
* waits. The block lasts as long as the person is aiming, which is why the
* timeout is generous — a scan that gave up after a few seconds would be
* one nobody could complete.
*
* An empty string is "no code", which is what a refusal, a cancellation and
* a timeout all are. The caller acts on the text, so a distinct error would
* only be a fourth way to say the same thing.
*/
private fun scanWithCamera(): String {
val gate = CountDownLatch(1)
scanLatch.set(gate)
scanned.set(null)
val posted = CountDownLatch(1)
var dispatched = false
main.post {
dispatched = runCatching { askForScan() }.getOrDefault(false)
posted.countDown()
}
val ready = runCatching { posted.await(SCAN_TIMEOUT_SECONDS, TimeUnit.SECONDS) }.getOrDefault(false)
if (!ready || !dispatched) {
scanLatch.set(null)
return ""
}
return try {
if (!gate.await(SCAN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) "" else scanned.get().orEmpty()
} catch (_: InterruptedException) {
""
} finally {
scanLatch.set(null)
}
}
/** Called by the activity when the scanner answers. Null is a dismissal. */
fun deliverScan(text: String?) {
scanned.set(text)
scanLatch.get()?.countDown()
}
/**
* Ask for one file and wait for the answer.
*
* `@JavascriptInterface` methods cannot suspend: the WebView calls them on
* its own thread and expects a value back. So the ask is posted to the main
* thread and this one waits on a latch. The cost is a blocked JS thread for
* as long as the picker is open — which is a modal panel the person is
* looking at, with nothing else in the page running.
*
* A timeout is set rather than waiting forever: a picker that never answers
* (the activity destroyed underneath it) would otherwise pin a WebView
* thread until the process died.
*/
private fun pickFile(): Uri? {
val gate = CountDownLatch(1)
latch.set(gate)
pending.set(null)
val posted = CountDownLatch(1)
var dispatched = false
main.post {
dispatched = runCatching { askForFile() }.getOrDefault(false)
posted.countDown()
}
val ready = runCatching { posted.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS) }.getOrDefault(false)
if (!ready || !dispatched) {
latch.set(null)
return null
}
return try {
if (!gate.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS)) null else pending.get()
} catch (_: InterruptedException) {
null
} finally {
latch.set(null)
}
}
/** Called by the activity when the picker answers. A null uri is a dismissal. */
fun deliver(uri: Uri?) {
pending.set(uri)
latch.get()?.countDown()
}
/** The folder under Downloads that this app's exports land in. */
private fun exportFolder(): String = "Reasonix"
/** The MIME type this name declares, or null when the platform does not know
* it.
*
* Where the type is written, the name and the type agree, and that agreement
* is the whole fix: `.md` is answered `text/markdown` here, so MediaStore
* has nothing to correct and the export stays `报告.md` instead of being
* renamed `报告.md.txt` by the `text/plain` it used to be given. Where the
* type is unknown the field is left off, which leaves MediaStore to derive
* the same `application/octet-stream` it would have been told — the name
* still stands on its own, which is all this is for. */
private fun mimeFor(name: String): String? {
val ext = name.substringAfterLast('.', "").lowercase()
if (ext.isEmpty() || ext == name.lowercase()) return null
return runCatching { MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) }.getOrNull()
}
private fun exportFile(name: String, content: String): String? = runCatching {
val bytes = content.toByteArray(Charsets.UTF_8)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val resolver = context.contentResolver
val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, name)
// The type is derived here rather than declared, and it is
// written only when the name really has an extension that maps
// to one.
//
// It used to be `text/plain` for everything, and MediaStore
// answers a name whose extension disagrees with the declared
// type by appending its own: exporting `报告.md` landed in
// Downloads as `报告.md.txt`, and any source file came out with
// the wrong second extension. Deriving the type from the name
// instead keeps the two in agreement — which is what stops the
// rename — and a name the platform has no type for is left off
// entirely rather than declared as `application/octet-stream`,
// so nothing is corrected there either.
mimeFor(name)?.let { put(MediaStore.Downloads.MIME_TYPE, it) }
put(
MediaStore.Downloads.RELATIVE_PATH,
Environment.DIRECTORY_DOWNLOADS + "/" + exportFolder(),
)
// Hidden until the bytes are all there, so a file manager that
// reads the folder mid-write cannot show half a document.
put(MediaStore.Downloads.IS_PENDING, 1)
}
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
?: return@runCatching null
resolver.openOutputStream(uri)?.use { it.write(bytes) } ?: return@runCatching null
values.clear()
values.put(MediaStore.Downloads.IS_PENDING, 0)
resolver.update(uri, values, null, null)
"${Environment.DIRECTORY_DOWNLOADS}/${exportFolder()}/$name"
} else {
val dir = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
exportFolder(),
)
if (!dir.exists() && !dir.mkdirs()) return@runCatching null
val target = File(dir, name)
target.writeBytes(bytes)
target.absolutePath
}
}.getOrNull()
private fun sanitise(name: String): String {
// A name from the page is used as a filename, so it is reduced to one:
// no separators, no traversal, and nothing a filesystem treats as
// special. The default is the name the field it came from suggests.
val trimmed = name.trim().substringAfterLast('/').substringAfterLast('\\')
if (trimmed.isEmpty() || trimmed == "." || trimmed == "..") return ""
return trimmed.filter { it.isLetterOrDigit() || it in "._-" }.take(64)
}
/**
* Whether a turn is running, so the screen can be kept awake for one.
*
* The page owns the answer — it is the only thing that knows if the kernel
* is working — and the shell owns the flag, because a window flag is not
* something a page can set. Nothing is asked at launch: a window that is
* merely open is one the person may be reading, and holding the screen on
* for that is holding it on for nothing.
*/
@JavascriptInterface
fun setRunning(running: Boolean) {
onRunning?.invoke(running)
}
/** How the activity applies that flag. Set by the activity. */
var onRunning: ((Boolean) -> Unit)? = null
/**
* Whether the app may read every file, which is what lets the kernel open a
* folder on this phone as a workspace.
*
* Asked rather than assumed: the permission is granted by hand in system
* settings, so the page has to be able to say "not yet" rather than fail on
* the first `stat`. Answered `true` below API 30, where ordinary read
* permission is enough and the concept does not exist.
*/
@JavascriptInterface
fun hasAllFilesAccess(): Boolean = filesAccess?.invoke() ?: true
var filesAccess: (() -> Boolean)? = null
/** Open the system page where that permission is granted. The only place
* Android offers it — there is no dialog for this one. */
@JavascriptInterface
fun requestAllFilesAccess() {
if (!trusted()) return
askForFilesAccess?.invoke()
}
var askForFilesAccess: (() -> Unit)? = null
/**
* Whether this app is exempt from the system's battery optimisation.
*
* A turn runs in a child process under a foreground service. Under doze the
* whole app group is frozen anyway, so the turn stops making progress while
* the screen is off — which is the state the person left it in on purpose.
* Unrestricted is the answer, and it is a question Android answers.
*/
@JavascriptInterface
fun batteryUnrestricted(): Boolean = if (!trusted()) false else (batteryFree?.invoke() ?: true)
var batteryFree: (() -> Boolean)? = null
/** Ask for that exemption. Unlike the storage one, this has a real dialog. */
@JavascriptInterface
fun requestBatteryUnrestricted() {
if (!trusted()) return
askForBattery?.invoke()
}
var askForBattery: (() -> Unit)? = null
/**
* Ask for a folder on this phone and answer with its real filesystem path.
*
* "" is a dismissal, the same answer `importIntoHome` gives — and, unlike
* that one, an empty string is a normal outcome here rather than a failure.
* The `startIn` hint is a path the kernel knows; the picker may ignore it,
* which is the picker's business.
*
* The round trip is the same latch as `pickFile`, for the same reason: a
* document-tree picker is another activity, and this call cannot suspend.
*/
@JavascriptInterface
fun pickFolder(startIn: String): String {
if (!trusted()) return ""
val gate = CountDownLatch(1)
folderLatch.set(gate)
folderPending.set(null)
val posted = CountDownLatch(1)
var dispatched = false
main.post {
dispatched = runCatching { askForFolder(startIn) }.getOrDefault(false)
posted.countDown()
}
val ready = runCatching { posted.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS) }.getOrDefault(false)
if (!ready || !dispatched) {
folderLatch.set(null)
return ""
}
return try {
if (!gate.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS)) "" else folderPending.get().orEmpty()
} catch (_: InterruptedException) {
""
} finally {
folderLatch.set(null)
}
}
var askForFolder: (String) -> Boolean = { false }
private val folderPending = AtomicReference<String?>(null)
private val folderLatch = AtomicReference<CountDownLatch?>(null)
/** Called by the activity with the folder's real path, or null on dismissal. */
fun deliverFolder(path: String?) {
folderPending.set(path ?: "")
folderLatch.get()?.countDown()
}
companion object {
const val BRIDGE_VERSION = "4"
private const val PICK_TIMEOUT_SECONDS = 5L * 60
/** Long, because this is however long someone takes to aim. A shorter
* one would turn "still lining it up" into a failed scan. */
private const val SCAN_TIMEOUT_SECONDS = 5L * 60
/** Only as long as the sheet takes to appear: the answer is "something
* took it", which is known the moment the Intent resolves. */
private const val SHARE_TIMEOUT_SECONDS = 15L
}
}
/**
* The window's insets, in CSS pixels.
*
* A named type rather than four numbers because the page reads them as one
* thing: half an inset is a layout that is wrong in one direction, and a caller
* that passed the wrong pair would be indistinguishable from a device with no
* cutout at all.
*/
data class Insets(val left: Int, val top: Int, val right: Int, val bottom: Int)
@@ -1,66 +0,0 @@
package io.reasonix.mobile.app
import androidx.camera.core.ImageProxy
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.PlanarYUVLuminanceSource
import com.google.zxing.common.HybridBinarizer
/**
* Reading a QR code out of one camera frame.
*
* ZXing core and nothing else: it is pure Java, so it runs identically on a
* phone with Google Play Services and on one whose HarmonyOS compatibility
* layer has none. A decoder that leaned on ML Kit would work on the machine it
* was written on and fail on the one that needs it.
*
* The frame arrives as YUV_420_888, whose Y plane is already the greyscale
* bitmap ZXing wants — no conversion, no colour maths, just the bytes. That is
* the whole reason a phone can decode 30 frames a second without warming up.
*/
object Qr {
private val reader = MultiFormatReader().apply {
setHints(
mapOf(
// Only the form the computer actually renders. Leaving the
// reader open to every 1D barcode makes each frame slower for
// a case that cannot occur, and a slower frame is a code that
// has already left the viewfinder.
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
DecodeHintType.TRY_HARDER to true,
),
)
}
/** The code's text, or null when this frame holds none. */
fun decode(image: ImageProxy): String? {
val plane = image.planes.firstOrNull() ?: return null
val buffer = plane.buffer
val data = ByteArray(buffer.remaining())
buffer.get(data)
// `rowStride` is padded to a hardware alignment and is usually wider
// than the picture. Passing the width as the row length is what tells
// ZXing where each row actually ends; getting it wrong shears the image
// and every code reads as garbage.
val source = PlanarYUVLuminanceSource(
data,
plane.rowStride,
image.height,
0,
0,
image.width,
image.height,
false,
)
return runCatching {
reader.decodeWithState(BinaryBitmap(HybridBinarizer(source))).text
}.getOrNull().also {
// The reader keeps per-frame state between calls; resetting is what
// stops a partial match in one frame from corrupting the next.
reader.reset()
}
}
}
@@ -1,146 +0,0 @@
package io.reasonix.mobile.app
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import java.util.concurrent.Executors
/**
* The camera, held open just long enough to read one pairing code.
*
* A phone that wants to drive a computer cannot type the code that computer
* shows: it is a base64 fragment inside a URL, and the whole point of showing it
* as a QR code is that nobody reads one aloud. So this is the way in — the same
* gesture the computer's own dialog asks for, from the other side.
*
* The decode is ZXing rather than ML Kit on purpose. ML Kit needs Google Play
* Services, and this app installs on phones whose HarmonyOS compatibility layer
* has none: a GMS-backed scanner would work on a developer's phone and fail on
* the device that needs it. ZXing core is pure Java, so the scanner behaves the
* same on both.
*
* It returns the first code it reads and finishes. A pairing code is
* single-use and short-lived, so "keep scanning after a hit" is not a feature —
* it is a way to spend a code that a later frame would have discarded.
*/
class ScanActivity : AppCompatActivity() {
private lateinit var preview: PreviewView
private lateinit var hint: TextView
private val executor = Executors.newSingleThreadExecutor()
/** Set once a code is found, so the frames in flight behind it do not each
* try to finish the activity. */
@Volatile
private var settled = false
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) start() else refuse()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val root = FrameLayout(this)
preview = PreviewView(this).apply {
layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
)
// The frames are analysed, not composed: filling the view and
// cropping is right here and would be wrong for a camera app.
scaleType = PreviewView.ScaleType.FILL_CENTER
}
hint = TextView(this).apply {
text = getString(R.string.scan_hint)
setTextColor(0xFFFFFFFF.toInt())
textSize = 14f
gravity = Gravity.CENTER
val pad = (16 * resources.displayMetrics.density).toInt()
setPadding(pad, pad, pad, pad)
// Readable over whatever the camera is pointing at, which is the
// one background a design system cannot choose.
setBackgroundColor(0x99000000.toInt())
layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM,
)
}
root.addView(preview)
root.addView(hint)
setContentView(root)
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
) {
start()
} else {
requestCamera.launch(Manifest.permission.CAMERA)
}
}
private fun refuse() {
// No dialog of our own: the permission prompt already said no, and a
// second window repeating it is one more tap to dismiss. The caller
// gets the same answer as a cancelled scan.
setResult(RESULT_CANCELED)
finish()
}
private fun start() {
val providerFuture = ProcessCameraProvider.getInstance(this)
providerFuture.addListener({
val provider = runCatching { providerFuture.get() }.getOrNull() ?: return@addListener refuse()
val previewUseCase = Preview.Builder().build().also { it.setSurfaceProvider(preview.surfaceProvider) }
val analysis = ImageAnalysis.Builder()
// Only the newest frame matters: a stale one describes where the
// camera was, and a code that has already left the viewfinder
// must not win over one that is in it now.
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
.also { it.setAnalyzer(executor, ::analyse) }
runCatching {
provider.unbindAll()
provider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, previewUseCase, analysis)
}.onFailure { refuse() }
}, ContextCompat.getMainExecutor(this))
}
private fun analyse(image: ImageProxy) {
try {
if (settled) return
val text = Qr.decode(image) ?: return
if (settled) return
settled = true
setResult(RESULT_OK, Intent().putExtra(EXTRA_TEXT, text))
// Finishing from the analysis thread is the whole reason `settled`
// exists; the activity teardown has to happen on the main one.
runOnUiThread { finish() }
} finally {
image.close()
}
}
override fun onDestroy() {
super.onDestroy()
executor.shutdown()
}
companion object {
const val EXTRA_TEXT = "text"
}
}
@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The mark, drawn rather than shipped as a bitmap: one R in the app's own ink
on the palette's ground, which scales to every launcher's mask without a
density bucket per size. The hole in the R is the glyph's own counter, cut
with evenOdd rather than painted over. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#F4F1EA"
android:fillType="evenOdd"
android:pathData="M39,30 L39,78 L47,78 L47,60 L54.5,60 L65,78 L74.5,78 L62.5,58 C68.6,55.8 72.6,50.6 72.6,43.6 C72.6,35.4 66.8,30 57.6,30 Z M47,37 L56.4,37 C61.2,37 64.4,39.4 64.4,43.8 C64.4,48.2 61.2,50.9 56.4,50.9 L47,50.9 Z" />
<path
android:fillColor="#A6680C"
android:pathData="M62,66 L74,66 L74,78 L62,78 Z" />
</vector>
@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The status-bar glyph, not the launcher icon: Android renders a notification
icon as a mask, so anything that is not a solid silhouette on transparency
comes out as a grey blob. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="#FFFFFF">
<path
android:fillColor="#FFFFFF"
android:pathData="M3,4h18v2H3zM3,9h18v2H3zM3,14h12v2H3zM3,19h12v2H3zM17.5,13.2l1.6,2.6 1.6,-2.6h2.3l-2.8,4.3V21h-2.2v-3.5L15.2,13.2z" />
</vector>
@@ -1,62 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
The screen between the tap and the page.
It exists for a reason that is not cosmetic: the kernel has to be unpacked and
started before there is a page to show, and on a cold start that is about a
second. A blank window for a second reads as a broken app; a line of text that
says what is happening does not.
The progress bar is indeterminate and driven by nothing: the WebView's own
progress is mirrored onto it while the page loads, and before that it simply
turns, which is the honest description of "we do not know how long".
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/page"
android:orientation="vertical"
android:gravity="center"
android:paddingStart="32dp"
android:paddingEnd="32dp">
<TextView
android:id="@+id/splash_wordmark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textColor="#8A857B"
android:textSize="22sp"
android:letterSpacing="0.08"
android:fontFamily="sans-serif-medium" />
<ProgressBar
android:id="@+id/splash_bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="132dp"
android:layout_height="wrap_content"
android:layout_marginTop="26dp"
android:indeterminate="true" />
<TextView
android:id="@+id/splash_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:gravity="center"
android:text="@string/splash_connecting"
android:textColor="#8A857B"
android:textSize="13sp"
android:lineSpacingMultiplier="1.5" />
<Button
android:id="@+id/splash_retry"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:minHeight="44dp"
android:text="@string/splash_retry"
android:textColor="#A6680C"
android:visibility="gone" />
</LinearLayout>
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The adaptive launcher icon.
minSdk is 26, which is the release that introduced adaptive icons, so this
is the only launcher asset the app needs: there is no device running it
that would ask for a bitmap fallback. -->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<!-- The safe zone is the middle 66dp of 108dp; the glyph is drawn inside it
so no launcher's mask can clip it. -->
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Reasonix</string>
<string name="channel_kernel">Kernel running</string>
<string name="channel_kernel_desc">Shown while the Reasonix kernel runs in the background. Can be muted on its own in system settings.</string>
<string name="notify_running_title">Reasonix is running</string>
<string name="notify_running_body">A task is still going. Switch back to see it.</string>
<string name="notify_failed_title">Reasonix could not start</string>
<string name="err_kernel_unreachable">Could not reach the kernel. Reopen the app from your home screen.</string>
<string name="download_default_name">reasonix-download</string>
<string name="download_saved">Saved: %1$s</string>
<string name="download_failed">Save failed: %1$s</string>
<string name="download_failed_status">Save failed: the server answered %1$d</string>
<string name="splash_connecting">Starting the kernel…</string>
<string name="splash_retry">Retry</string>
<string name="scan_title">Scan the code on the computer</string>
<string name="scan_hint">Point at the QR code in the computer\'s device panel to connect to it.</string>
<string name="scan_button">Scan to connect</string>
<string name="scan_denied">No camera permission, so scanning is unavailable. Allow it in system settings.</string>
</resources>
@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The dark palette's page colour. `DayNight` on the theme picks this up when
the system is dark, which is what keeps the frame before the WebView from
flashing light at someone using a dark phone at night. -->
<resources>
<color name="page">#0E1014</color>
</resources>
@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The light palette's page colour, and only what the window needs before the
WebView paints. The interface's own colours are `tokens.css`'s and are the
page's business; these two exist so the first frame is the app's ground
rather than the platform default white. -->
<resources>
<color name="page">#F4F1EA</color>
<color name="boot">#07080C</color>
</resources>
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The launcher ground: the interface's dark page colour. It is the same in
both themes because a launcher icon is not themed by the app. -->
<resources>
<color name="ic_launcher_background">#14161C</color>
</resources>
@@ -1,35 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Every string the shell itself shows. The interface's own text belongs to
the page and lives in its i18n bundle; these are only the few lines that
exist before it, or when it cannot load. -->
<resources>
<string name="app_name">Reasonix</string>
<string name="channel_kernel">内核运行中</string>
<string name="channel_kernel_desc">Reasonix 内核在后台运行时显示,可在系统设置中单独关闭。</string>
<string name="notify_running_title">Reasonix 正在运行</string>
<string name="notify_running_body">任务继续进行,切回应用即可查看。</string>
<string name="notify_failed_title">Reasonix 无法启动</string>
<string name="err_kernel_unreachable">连接内核失败。请返回桌面重新打开应用。</string>
<string name="download_default_name">reasonix-download</string>
<string name="download_saved">已保存:%1$s</string>
<string name="download_failed">保存失败:%1$s</string>
<string name="download_failed_status">保存失败:服务器返回 %1$d</string>
<string name="splash_connecting">正在启动内核…</string>
<string name="splash_retry">重试</string>
<string name="wsperm_title">需要「所有文件访问」权限</string>
<string name="wsperm_body">要打开手机上的文件夹作为工作区,需要先允许本应用访问所有文件。点「去设置」,在列表里打开 Reasonix 的开关,然后返回这里。</string>
<string name="wsperm_go">去设置</string>
<string name="wsperm_later">以后再说</string>
<string name="scan_title">扫描电脑上的二维码</string>
<string name="scan_hint">对准电脑上「设备访问」里的二维码,识别后即可连接这台电脑。</string>
<string name="scan_button">扫码连接电脑</string>
<string name="scan_denied">没有相机权限,无法扫码。请在系统设置里允许。</string>
<string name="share_title">分享文件</string>
</resources>
@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The shell's own furniture: a window background matching the page's light
palette before the WebView paints, and a transparent system bar so the
page's own safe-area padding is what the notch meets. The page themes
itself; this exists only so the first frame is not a white flash. -->
<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Theme.Reasonix" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="android:windowBackground">@color/page</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
<!-- The page draws its own edge-to-edge layout and pads itself with the
safe-area insets from mobile.css. Laying the window out edge to edge
while leaving the bars transparent is what makes those insets real
numbers instead of zero. -->
<item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="p">shortEdges</item>
<item name="android:enforceStatusBarContrast" tools:targetApi="q">false</item>
<item name="android:enforceNavigationBarContrast" tools:targetApi="q">false</item>
</style>
<!-- The camera. A black ground because the preview has not drawn yet and a
light window behind a dark viewfinder is a flash in the dark; the bars
stay transparent so the preview reaches the edges, which is what makes
a code near the top of the screen scannable. -->
<style name="Theme.Reasonix.Scan" parent="Theme.Reasonix">
<item name="android:windowBackground">@android:color/black</item>
</style>
</resources>
@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Backups are off, and this file says why rather than leaving it implicit.
A Reasonix home holds provider keys, an account token and every session
transcript. Android's auto-backup would copy all of it to the person's cloud
drive and, on a device-to-device transfer, to a new phone — which is a
credential leaving the device by a route nobody chose. `allowBackup="false"`
in the manifest turns that off; these two stanzas are the belt to its braces,
excluding everything explicitly so that a later change to `allowBackup` cannot
quietly start copying credentials.
What a person wants to move between phones, the kernel already moves: its own
export writes a file the person hands to the system's picker.
-->
<data-extraction-rules>
<cloud-backup>
<exclude domain="root" />
<exclude domain="file" />
<exclude domain="database" />
<exclude domain="sharedpref" />
<exclude domain="external" />
</cloud-backup>
<device-transfer>
<exclude domain="root" />
<exclude domain="file" />
<exclude domain="database" />
<exclude domain="sharedpref" />
<exclude domain="external" />
</device-transfer>
</data-extraction-rules>
@@ -1,27 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Cleartext HTTP is permitted, and the platform has no way to permit less.
Two kinds of page load over plain HTTP: the kernel's own page on
`127.0.0.1:<port>`, and the same page served by a paired computer on whatever
address its router handed out. The port is chosen when the kernel starts and
the LAN address when a code is scanned, so neither can be written here — and a
`domain-config` matches literals and domains, never a subnet.
So the boundary is not this file. `MainActivity` decides which cleartext origin
may become the window: `shouldOverrideUrlLoading` sends every http(s) origin
that is not the kernel's or the one just paired out to the browser, and the
native bridge answers only those two. A plaintext page on the LAN therefore
cannot become the document holding the bridge, which is what the reviewer's
"deliberate path for LAN pairing" asks for.
HTTPS is untouched: nothing here downgrades a request, and `trust-anchors`
keeps the system roots for every TLS connection that is made.
-->
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
-15
View File
@@ -1,15 +0,0 @@
// The build itself lives in app/build.gradle; this file declares the plugin
// versions once so the app module can be read on its own.
//
// AGP 8.11.1 is the pairing for the Gradle 8.14 toolchain this machine has:
// AGP 8.7 and older refuse a Gradle that new, and AGP 8.13+ wants a Gradle this
// one does not have. Both numbers are pinned rather than ranged, because a
// build that silently moved either one would be a different build.
plugins {
id "com.android.application" version "8.11.1" apply false
id "org.jetbrains.kotlin.android" version "2.1.20" apply false
}
tasks.register("clean", Delete) {
delete rootProject.layout.buildDirectory
}
-15
View File
@@ -1,15 +0,0 @@
# AndroidX is the only copy of the support libraries this project uses; the
# non-transitive R class keeps the app's own resources from aliasing library
# ones, which is what makes `R.string.*` unambiguous here.
android.useAndroidX=true
android.nonTransitiveRClass=true
# The daemon is what keeps a second `gradle assembleDebug` from re-reading the
# whole SDK, and the heap is sized for the R8 pass over the WebView and the
# packaged page rather than for this handful of Kotlin files.
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.caching=true
kotlin.code.style=official
File diff suppressed because it is too large. Load diff
Binary file not shown.
-12
View File
@@ -1,12 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
# Pinning the distribution's checksum is what makes the download verifiable: a
# mirror that served a different zip would fail here instead of being unpacked
# and run. The value is Gradle's own, from
# https://services.gradle.org/distributions/gradle-8.14.3-bin.zip.sha256
distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-251
View File
@@ -1,251 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
-94
View File
@@ -1,94 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
Loaded 100 of 11523 files, more files were not shown because too many files have changed in this diff. Show more