Compare commits

...
13 Commits
Author SHA1 Message Date
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
52 changed files with 10211 additions and 410 deletions

No files matched your search

+518
View File
@@ -3,6 +3,524 @@
All notable changes to Reasonix. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.4.24] — 2026-04-22
**Headline:** `reasonix stats` is now a cross-session cost dashboard.
Every turn `reasonix chat|code|run` executes 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:
```
Reasonix usage — /Users/you/.reasonix/usage.jsonl (2.3 KB)
turns cache hit cost (USD) vs Claude saved
----------------------------------------------------------------------
today 8 95.1% $0.004821 $0.1348 96.4%
week 34 93.8% $0.023104 $0.6081 96.2%
month 127 94.2% $0.081530 $2.1452 96.2%
all-time 342 94.0% $0.210881 $5.8934 96.4%
most used model: deepseek-reasoner (84% of turns)
top session: default (214 turns)
tracked since: 2026-04-20
```
Pillar 1's pitch (94–97% cost reduction vs Claude) turns from a
blog number into a fact users can check on their own machine. The
savings column is derived per turn (not synthesized) from the
existing `claudeEquivalentCost()` helper in `src/telemetry.ts`.
Back-compat: `reasonix stats <transcript>` still works — passing a
path falls back to the old per-file summary (assistant turns + tool
calls). No arg → dashboard.
Privacy: the log contains tokens + costs + the user-chosen session
name, nothing else. No prompts, no completions, no tool args.
### Added
- **`/stats` slash** — same dashboard, in-session. Reads
`~/.reasonix/usage.jsonl` and renders via the shared
`renderDashboard` pure function, so the shell command and the
slash stay in sync by construction.
- **`src/usage.ts`** — `appendUsage` (best-effort JSONL write,
swallows disk failures so a read-only `~/` never breaks the
turn), `readUsageLog` (malformed-line tolerant), `aggregateUsage`
(rolling windows: 24h / 7d / 30d / all, plus model + session
histograms), `bucketCacheHitRatio`, `bucketSavingsFraction`,
`formatLogSize`.
- **Wire-up** in `src/cli/ui/App.tsx` (assistant_final event) and
`src/cli/commands/run.ts` (CI / scripting turns land in the same
log as TUI turns).
- **Upgraded `reasonix stats`**. No-arg → dashboard; transcript arg
→ legacy per-file summary. `renderDashboard(agg, path)` is an
exported pure function so tests can assert the string output.
### Tests (+15, suite 708 → 723)
- `tests/usage.test.ts` covers: appendUsage round-trip, empty
log / malformed-line tolerance / parent-dir auto-creation / silent
write-failure (points path at a regular file), aggregateUsage
(empty, rolling-window bucketing, cross-record sums, byModel +
bySession sort + (ephemeral) grouping), bucket helpers with zero
denominators, renderDashboard (row labels + em-dash fallback).
---
## [0.4.23] — 2026-04-22
**Headline:** Hooks — user-defined automation that fires at four
well-known points in the loop. Same two-scope layout (project +
global) as memory and skills.
A hook is a shell command. Reasonix invokes it with stdin = a JSON
envelope describing the event. The exit code drives the decision:
`0` = pass, `2` = block (only on `PreToolUse` / `UserPromptSubmit`),
anything else = warn (rendered inline as a yellow row, the loop
keeps going). Block on a tool event swaps the dispatch for a
synthetic tool result carrying the hook's stderr — the model sees
a structured refusal instead of a silent omission, and can
reason about what to do next.
Settings file:
```json
// <project>/.reasonix/settings.json ← committable
// ~/.reasonix/settings.json ← per-user
{
"hooks": {
"PreToolUse": [{ "match": "edit_file|write_file", "command": "bun scripts/guard.ts" }],
"PostToolUse": [{ "match": "edit_file", "command": "biome format --write" }],
"UserPromptSubmit": [{ "command": "echo $(date +%s) >> ~/.reasonix/prompts.log" }],
"Stop": [{ "command": "bun test --run", "timeout": 60000 }]
}
}
```
Project hooks fire before global hooks. `match` is anchored regex
on the tool name (`*` or omitted = match every tool); ignored for
prompt / Stop events. Per-hook `timeout` overrides the defaults
(5s for blocking events, 30s for logging events). The CLI loads
both files at App mount; `/hooks` lists what's active and
`/hooks reload` re-reads disk without tearing down the running
loop (so the append-only log is preserved).
Deliberate non-goals for v1: workflow DSL, conditional chaining,
hook templates. Hooks are shell commands — the user already has
a programming language, we don't need to invent one.
### Added
- **`src/hooks.ts`** — `loadHooks` (project + global merge),
`runHooks` (event filter + stdin JSON + spawn dispatch),
`decideOutcome` (pure exit-code → decision matrix), `matchesTool`
(anchored-regex name filter), `formatHookOutcomeMessage` (single
source of truth for the warning row text). Spawner is injectable
for tests; default uses `shell: true` so `&&`, pipes, env
expansion all behave the way they do in the user's terminal.
- **`CacheFirstLoopOptions.hooks` + `hookCwd`**. Loop dispatches
`PreToolUse` (around line 866 in `src/loop.ts`) and `PostToolUse`
(immediately after dispatch). `loop.hooks` is mutable so
`/hooks reload` can swap the list without rebuilding the loop.
- **App-level `UserPromptSubmit` + `Stop`**. `App.tsx` calls
`runHooks` before pushing the user message (block = drop the
prompt) and after `loop.step` resolves (warnings only, since the
turn already ended).
- **`/hooks` slash command**. `list` (default) groups loaded hooks
by event with scope tags; `reload` re-reads settings.json from
disk via the App-provided `reloadHooks` callback.
- **`/update` slash command**. Shows current vs the last-resolved
latest (piggybacks on App.tsx's mount-time background check) and
prints the exact shell command to upgrade. Deliberately does NOT
spawn `npm install` from inside the TUI — stdio:inherit into a
running Ink renderer corrupts the display, and on Windows the
currently-running binary can be locked. Users exit the session
and run `reasonix update` in a fresh shell.
### Tests (+36, suite 672 → 708)
- `tests/hooks.test.ts` — `loadHooks` (empty / project+global / array
order / ignore malformed entries / tolerate malformed JSON / no
project root → global only / path helpers), `matchesTool` (`*` /
anchored regex / substring rejected / malformed regex falls back
to no-match / non-tool events ignore match), `decideOutcome`
(exit 0 / exit 2 / non-zero / timeout / spawn error per event),
`runHooks` (filters by event+match before running, stops at first
block, doesn't stop on warn, stdin envelope shape, cwd routing,
default timeouts, per-hook timeout override), `formatHookOutcomeMessage`
(pass → empty / non-pass includes scope+command+detail / 60-char
truncation).
- `tests/loop-hooks.test.ts` — `CacheFirstLoop` accepts a hook list,
default empty, `loop.hooks` is mutable, `hookCwd` defaults to
`process.cwd()` and honors override, no-tool turn doesn't fire
PreToolUse hooks.
- `tests/slash.test.ts` — updated `suggestSlashCommands("h")` to
include the new `hooks` command; added 4 tests for `/update`
(pending / up-to-date / upgrade-available / suggest-surfaces-it).
---
## [0.4.22] — 2026-04-22
**Headline:** Version display in the TUI header + `reasonix update`
self-upgrade command.
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 quietly surfaces a yellow
`update: X.Y.Z` nudge on the right side of the same row when a
newer version has been published. The nudge never blocks startup —
the fetch is bounded at 2s with a 24h on-disk cache, and any
failure (offline, firewall, registry hiccup) is silent by design.
`reasonix update` is the command form: detects whether you're
running a global install vs an ephemeral `npx` spawn, and either
spawns `npm install -g reasonix@latest` for the former or prints a
cache-refresh hint for the latter. `--dry-run` prints the plan
without executing.
The `VERSION` constant now sources from `package.json` at runtime
(walking up from `import.meta.url`) instead of a hand-maintained
literal, so it can never drift again — it was stale at `0.4.20`
before this release. Tests assert they stay in sync.
### Added
- **`src/version.ts`** — exports `VERSION`, `compareVersions`,
`getLatestVersion`, `isNpxInstall`, and the
`LATEST_CACHE_TTL_MS` / `LATEST_FETCH_TIMEOUT_MS` constants.
`getLatestVersion` caches to `~/.reasonix/version-cache.json`
(24h TTL) and returns `null` on any failure.
- **`reasonix update`** subcommand (`src/cli/commands/update.ts`).
`planUpdate()` is the pure decision function, `updateCommand()`
is the CLI orchestrator with test seams (`fetchLatest`, `isNpx`,
`spawnInstall`, `write`, `exit`).
- **StatsPanel header shows `v${VERSION}`** inline, plus an
`update: X` badge (yellow, bold) on the right when
`updateAvailable` is passed. App.tsx fires the registry check
in a background `useEffect` on mount; only a version strictly
newer than the running one flips the state.
### Fixed
- **Drifted `VERSION` constant.** `src/index.ts` hard-coded
`"0.4.20"` while `package.json` was on `0.4.21`. Replaced with a
re-export from `src/version.ts`, which reads the manifest on
first access. A regression test pins them together.
### Tests (+19, suite 588 → 607)
- `tests/version.test.ts` — `VERSION === package.json.version`,
`compareVersions` covers numeric + pre-release ordering,
`isNpxInstall` covers the three detection paths,
`getLatestVersion` covers cache hit / force-refresh / expired
entry / network failure / bad body / cache-write failure.
- `tests/update-command.test.ts` — `planUpdate` returns the
correct action for all four decision quadrants; `updateCommand`
respects every seam: no-spawn on up-to-date, no-spawn on npx,
spawns on global-behind-latest, honors `--dry-run`, exits
non-zero on registry failure, surfaces npm's non-zero exit.
---
## [0.4.21] — 2026-04-22
**Headline:** Skills — user-authored prompt packs, two-scope layout
matching user-memory.
Reasonix discovers skills under `<project>/.reasonix/skills/` (project
scope) and `~/.reasonix/skills/` (global scope). Project wins on name
collisions — per-repo overrides of a global skill work the way users
expect. Deliberately NOT tied to any other tool's directory
convention (`.claude/`, `.glm/`, etc.): Reasonix is model-agnostic at
the conversation layer, so coupling the skill filesystem to one
vendor would break anyone running a different backend.
The pinned index (names + one-line descriptions) lives in the
immutable system prefix; bodies stay lazy and enter the append-only
log only when invoked — either by the model calling the new
`run_skill` tool or by the user typing `/skill <name> [args]`. No
DAG engine, no workflow DSL — the model reads the skill's prose and
continues the normal tool-use loop from there. Pillar 1's cache
invariants are preserved: adding skills grows the pinned index
(under a 4k char cap, with a truncation marker) but never alters
the rest of the prefix.
### Added
- **`src/skills.ts`** — `SkillStore` with `SkillScope` of `"project"`
or `"global"`, both layouts recognized (`{name}/SKILL.md` and flat
`{name}.md`). `applySkillsIndex` composer is pinned into
`applyMemoryStack` alongside REASONIX.md + user memory, receiving
the same `rootDir` so the project scope picks up
`<rootDir>/.reasonix/skills/`.
- **`run_skill` tool** (`src/tools/skills.ts`) — read-only, returns
the full markdown body plus an optional forwarded `Arguments:` line.
Registered in `reasonix chat` (global only) and `reasonix code`
(project + global).
- **`/skill` slash command** — `list` / `show <name>` / bare
`<name> [args]` form. The bare form injects the skill body as a
user turn via the same `resubmit` hook `/apply-plan` uses. Reads
project scope from `ctx.codeRoot`, mirroring how `/memory` behaves.
### Notes
- Each skill's `allowed-tools` frontmatter is parsed but **ignored**
in v1. Reasonix's tool namespace (`filesystem`, `shell`, `web`)
doesn't one-to-one map onto other clients' names; the model reads
the prose instructions and picks our equivalents. Will revisit
once the tradeoffs are clearer.
- What we explicitly did **not** add: workflow DSL, DAG scheduler,
parallel branches, sub-agents. Skills are prose; the model does the
sequencing. This keeps single-loop + append-only + cache-first
intact — the architectural non-goal "no multi-agent orchestration"
stands.
### Fixed
- **`ShellConfirm` "always allow" did not take effect until relaunch.**
The `run_command` tool captured `extraAllowed` as a snapshot at
registration time, so a prefix the user approved mid-session was
written to `~/.reasonix/config.json` but the in-memory tool still
refused it — the next invocation re-triggered the confirmation
modal. `ShellToolsOptions.extraAllowed` now accepts a getter in
addition to a static array; `reasonix code` passes
`() => loadProjectShellAllowed(rootDir)` so the allowlist is
re-read from disk on every dispatch. Static-array callers keep
working unchanged.
- **Windows cmd.exe built-ins (`dir`, `echo`, `type`, `ver`, …)
crashed with ENOENT.** These aren't standalone executables, so
`PATH × PATHEXT` lookup misses and `spawn dir` fails. `prepareSpawn`
now routes bare unresolved Windows commands through
`cmd.exe /d /s /c "<cmd> <args…>"` with verbatim-args + manual
metacharacter quoting — same wrapping strategy we already use for
`.cmd`/`.bat` files. Built-ins resolve correctly; genuinely unknown
commands get the standard "'foo' is not recognized as an internal
or external command" message instead of a raw spawn error.
Already-extensioned names (`node.exe`) and paths-with-separators
(`C:\tool.exe`) still pass through unwrapped so an explicit "I
know where this is" invocation fails loudly when it's missing.
## [0.4.19] — 2026-04-22
**Headline:** Windows shell hotfix + StormBreaker visibility.
`reasonix code` now runs `npm`, `npx`, `tsc`, `yarn`, `pnpm`, `bun`,
`pytest`, and every other `.cmd` / `.bat` wrapper on Windows — both
under Node 18/20 (broken by missing PATHEXT resolution) and Node
21.7.3+/24 (broken by CVE-2024-27980's prohibition on direct
`.cmd`/`.bat` spawns with `shell: false`). Unix behavior unchanged.
Plus: the StormBreaker anti-loop-detector no longer silently halts
a turn — when it fires it emits a visible warning row explaining
what was suppressed and what the user should do next, and its
sliding window resets on each new user message so a new intent
doesn't inherit the previous turn's repeat patterns.
### Fixed
- **`spawn npm ENOENT` on Windows** — `child_process.spawn` with
`shell: false` uses `CreateProcess`, which ignores PATHEXT. Bare
`npm` failed because no `npm.exe` exists — only `npm.cmd`. New
`resolveExecutable(cmd)` walks `PATH × PATHEXT` manually and
returns the full resolved path (`C:\Program Files\nodejs\npm.CMD`)
before handing to spawn. Keeps `shell: false` (no shell expansion
of piped / chained commands — the whole reason we avoided
`shell: true` to begin with).
- **`spawn npm EINVAL` on Node ≥ 21.7.3 / 24** — even with the
resolved `.cmd` path, Node's post-CVE-2024-27980 patch refuses to
execute `.cmd` / `.bat` files via direct spawn. Second layer:
`prepareSpawn()` detects a `.cmd` / `.bat` target on Windows and
rewrites the invocation to `cmd.exe /d /s /c "<bin> <args…>"`
with `windowsVerbatimArguments: true`. Each arg is routed through
`quoteForCmdExe()`, which wraps in double quotes when the arg
contains whitespace or cmd.exe metacharacters
(`" & | < > ^ % ( ) , ; !`) and doubles embedded quotes per
cmd.exe's `""` escape rule. Arguments like `a&b` stay literal;
they don't become shell operators.
### Added
- **`resolveExecutable(cmd, opts?)`** — exported from `src/tools/shell.ts`.
Windows PATH × PATHEXT resolver. Opts lets tests inject `platform`,
`env`, and `isFile` so the Windows-specific path can be exercised
from a Linux CI runner without touching real fs.
- **`prepareSpawn(argv, opts?)`** — exported. Returns the
`(bin, args, spawnOverrides)` tuple that runCommand should pass to
`child_process.spawn`. On non-Windows it's a passthrough; on
Windows it applies the PATHEXT lookup and the `cmd.exe` wrapping
when needed. Unit-tested without spawning real processes.
- **`quoteForCmdExe(arg)`** — exported. The per-arg quoting
function. Round-trip tested against realistic argvs
(`npm install`, paths with spaces, args containing
`& | < > ^`, empty strings, embedded double quotes).
- **Silent storm-break**. When `StormBreaker` caught a repeated
`(tool, args)` pattern it dropped the offending call but emitted
nothing user-visible beyond a small `[repair] broke 1 storm` note
on the assistant row. If the suppressed call was the only tool
call of the turn, the turn just ended — no explanation of why
nothing happened. Now the loop yields a dedicated `warning` event
(same channel as Esc-abort and budget warnings) with an
actionable message, distinguishing "all calls suppressed (stuck
retry)" from "some calls suppressed" cases.
- **StormBreaker state bleeds across user turns**. The sliding
window of recent signatures persisted for the lifetime of the
loop, so a stuck pattern from an earlier intent could false-
positive against the user's legitimate new "try again with
different input" request. `CacheFirstLoop.step()` now calls
`repair.resetStorm()` on every new user turn — the window
repopulates naturally as the new turn's tool calls fire, and
genuine repeats still trip after the usual 3-in-a-row pattern.
### Added
- **`ToolCallRepair.resetStorm()`** — exposes StormBreaker.reset
through the repair facade. Called by the loop at each user turn;
library consumers that drive `repair.process` manually can use it
too if they wrap their own turn semantics.
### Tests (+22, suite 566 → 588)
- `tests/shell-tools.test.ts` (+21) — `resolveExecutable` on
non-Windows (passthrough), PATHEXT walk (first-hit ordering,
whitespace-tolerant PATHEXT entries), absolute-path / slash /
already-extensioned passthrough, empty input, missing PATH /
PATHEXT. `quoteForCmdExe` (simple identifiers unquoted, whitespace
+ metachars quoted, embedded quotes doubled, empty string
→ `""`). `prepareSpawn` (unix passthrough, `.cmd` wraps via
cmd.exe, `.bat` wraps too, `.exe` direct, metachar args quoted,
PATHEXT miss falls through).
- `tests/repair/pipeline.test.ts` (+1) — `resetStorm` clears the
repeat-window so post-reset calls aren't suppressed.
- `tests/loop.test.ts` — the iter-budget warning test refined to
filter by the iter-specific pattern, since identical fixture
calls now also trip the (correct) storm warning.
### Internals
- `runCommand` in `src/tools/shell.ts` now calls `prepareSpawn`
instead of spawning `argv[0]` directly. Every codepath that was
going through `spawn` still does; the `bin` / `args` /
`spawnOverrides` it receives are platform-normalized.
- Existing allowlist + `readOnlyCheck` plan-mode gate + timeout /
output-cap / AbortSignal wiring is untouched.
- `CacheFirstLoop.step()` now resets the StormBreaker at the top of
each turn AND emits a `warning` event after `repair.process()`
when `report.stormsBroken > 0`. The existing `repair` field on
`assistant_final` still carries the count for historical records
/ transcripts.
---
## [0.4.18] — 2026-04-22
**Headline:** Plan Mode — the model can propose a markdown plan
autonomously for large tasks (multi-file refactors, architecture
changes, ambiguous requests), and you can also force a read-only
exploration phase via `/plan`. Picker shows Approve / Refine / Cancel.
Approve pushes a synthetic "implement now" message; Refine keeps the
model exploring; Cancel drops the plan. Designed around Pillar 1 —
tool specs stay pinned, so the cache prefix doesn't break when plan
mode toggles.
### Added
- **`submit_plan` tool** (`src/tools/plan.ts`) — registered by default
in `reasonix code`. Throws `PlanProposedError` carrying the plan
text via the new `toToolResult()` protocol on ToolRegistry. Fires
the picker whether or not plan mode is active — the model is
expected to propose plans on its own for large tasks; `/plan` is
the *stronger* constraint that forces the model into read-only.
- **`/plan` slash** (code mode only) — toggles read-only plan mode.
`/plan on`, `/plan off`, or `/plan` to flip. While on, the registry
refuses non-read-only dispatch; while off, the model can still
propose plans autonomously via submit_plan. `/status` surfaces the
state; `StatsPanel` shows a red `PLAN` tag.
- **`/apply-plan` slash** (code mode only) — force-approve fallback.
Clears plan mode, clears the pending-plan picker state, and
resubmits the implement-now synthetic via the existing `resubmit`
mechanism. Useful when the model wrote the plan in assistant text
instead of calling submit_plan, or when you want to keyboard-only
the approval without the picker.
- **`ToolDefinition.readOnly` + `readOnlyCheck`** — declarative gate
used by `ToolRegistry.dispatch` when plan mode is on. Read tools
(`read_file`, `list_directory`, `search_files`, `directory_tree`,
`get_file_info`, `web_search`, `web_fetch`) run normally. Write
tools bounce with a refusal the model reads and learns from.
`run_command` uses a dynamic `readOnlyCheck` so allowlisted
invocations (`git status`, `cargo check`, `npm test`, `grep`, …)
still work during planning — exploration isn't gated. Non-allowlisted
commands refuse just like other writes.
- **`ToolRegistry.setPlanMode(on)` / `.planMode`** — the enforcement
switch + accessor. Mirrored onto the UI's `planMode` React state so
the StatsPanel badge stays in sync.
- **`toToolResult()` extension protocol** on Error subclasses —
`ToolRegistry.dispatch` calls it if present when an error is thrown,
serializing custom fields alongside `error`. Used by
`PlanProposedError` to ferry the plan text to the UI without
regex-scraping the error message. Falls back safely on serialization
failure.
- **`PlanConfirm.tsx`** — 3-option Ink picker (Approve / Refine /
Cancel) with the plan rendered as **live Markdown** (via the
existing `Markdown` component — headings, lists, code, bold all
formatted, not raw text) in a cyan-bordered panel above. 2 400-char
rendered cap; longer plans get a "use /tool for full" truncation
marker. Live rows hidden while the picker is up, matching
`ShellConfirm`'s behavior. When the plan contains headings like
"Open questions", "Risks", "Assumptions", "待确认", "开放问题", "风险",
"未知", "假设", "不确定", the picker auto-selects the Refine option
by default and shows a yellow "▲ the plan has open questions —
pick Refine to answer them" hint above the options.
- **`PlanRefineInput.tsx`** — inline text input that appears after
the user picks either **Approve** or **Refine**. Picking Approve
lets the user type last-minute instructions or answers to the
model's open questions (blank Enter = approve as-is). Picking
Refine requires specifics — the input collects them and includes
them verbatim in the synthetic sent to the model, so "refine"
actually means "revise with this feedback" instead of the generic
"try again" message the first cut sent. Esc returns to the picker
without resuming the loop.
- **System-prompt guidance** (`CODE_SYSTEM_PROMPT`) — teaches the
model when to call submit_plan autonomously (big / risky / ambiguous
tasks) vs. just making the change (typos, obvious one-line fixes),
and how `/plan` mode adds the stronger dispatch gate on top.
### Tests (+24, suite 542→566)
- `tests/plan.test.ts` (+17) — ToolRegistry plan-mode gate
(default-off, toggle, block non-read-only, allow read-only, honor
`readOnlyCheck` per-args, precedence over `readOnly`, off-mode
noop); `toToolResult` protocol (serializes custom fields, falls
back on serializer failure); `PlanProposedError` carries plan +
STOP directive; `registerPlanTool` registers submit_plan as
read-only, fires picker both in and out of plan mode, rejects
empty plans, trims whitespace.
- `tests/slash.test.ts` (+7) — `/plan` registry entries + required
commands check; `/plan` toggle / on / off / true / false / 0 / 1;
`/plan` info text explicit about the stronger-constraint
relationship; `/apply-plan` code-mode gating; `/apply-plan` flips
mode + clears pending + resubmits; works without optional
`clearPendingPlan` callback; `/status` plan-mode line appears
iff on.
### Internals
- `src/tools/filesystem.ts` — read_file / list_directory /
directory_tree / search_files / get_file_info tagged readOnly.
- `src/tools/shell.ts` — run_command gets `readOnlyCheck` tied to
the existing `isAllowed` check + `allowAll` escape hatch.
- `src/tools/web.ts` — web_search / web_fetch tagged readOnly.
- `src/cli/commands/code.tsx` — `registerPlanTool(tools)` added after
the filesystem and shell registrations so the tool is always in
the pinned spec list (prefix cache stays stable across
plan-mode toggles).
- `src/index.ts` — re-exports `PlanProposedError`, `registerPlanTool`,
`PlanToolOptions` for library consumers.
---
## [0.4.17] — 2026-04-22
**Headline:** Project memory — drop a `REASONIX.md` in your project
+372 -252
View File
@@ -6,8 +6,9 @@
[![downloads](https://img.shields.io/npm/dm/reasonix.svg)](https://www.npmjs.com/package/reasonix)
[![node](https://img.shields.io/node/v/reasonix.svg)](./package.json)
**A DeepSeek-native AI coding assistant in your terminal.** Ink TUI. MCP
first-class. No LangChain.
**A DeepSeek-native AI coding agent in your terminal.** Edits files as
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No
LangChain.
---
@@ -16,60 +17,27 @@ first-class. No LangChain.
**1. Get a DeepSeek API key.** Free credit on signup:
<https://platform.deepseek.com/api_keys>
**2. Run it.** No install needed.
```bash
npx reasonix
```
First run walks you through a 30-second wizard:
- paste your API key (saved to `~/.reasonix/config.json`)
- pick a preset — `fast` (cheap chat, default), `smart` (+R1 reasoning), `max` (+self-consistency branching)
- multi-select MCP servers from a catalog (filesystem, memory, github, puppeteer, …)
Every run after that drops you straight into chat.
**3. Inside the chat.** Type anything and hit Enter. Type `/help` to see
every command. The status bar at the top shows cache hit %, cost so far,
balance, and context usage. Press `Esc` to cancel whatever is running.
```
reasonix › explain what this project does
assistant
…streams R1 reasoning into a dim preview, then writes the answer…
status bar: cache hit 92% · cost $0.001 · ctx 8k/131k (6%) · balance 12.34 CNY
```
Requires Node ≥ 18. Works on macOS, Linux, Windows (Git Bash + PowerShell).
---
## Using `reasonix code` — your terminal pair programmer
Scoped to the directory you launch from. The model has native
`read_file` / `write_file` / `edit_file` / `list_directory` /
`search_files` / `directory_tree` / `get_file_info` /
`create_directory` / `move_file` tools, all sandboxed — any path that
resolves outside the launch root (including `..` and symlink escapes)
is refused.
**2. Point it at a project.** No install needed.
```bash
cd my-project
npx reasonix code
```
### Walkthrough: fix a bug
First run walks you through a 30-second wizard (paste API key → pick
preset → multi-select MCP servers). Every run after that drops you
straight in.
**3. Ask it to edit.** The model proposes edits as SEARCH/REPLACE
blocks — nothing hits disk until you `/apply`.
```
reasonix code › users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改成大小写不敏感
reasonix code › users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改
assistant
▸ R1 reasoning · 1243 chars of thought
▸ tool<search_files> → src/users.ts, src/users.test.ts
▸ tool<read_file> → (src/users.ts, 412 chars)
▸ tool<read_file> → (src/users.test.ts, 820 chars)
▸ 找到了。findByEmail 直接用 === 比对。我把查询和存储都规范化为小写,并补上一条测试。
▸ 找到了。findByEmail 直接用 === 比对。改成小写规范化并补一条测试。
src/users.ts
<<<<<<< SEARCH
@@ -79,49 +47,34 @@ src/users.ts
return users.find(u => u.email.toLowerCase() === needle);
>>>>>>> REPLACE
src/users.test.ts
<<<<<<< SEARCH
it("finds by email", () => {
expect(findByEmail("[email protected]")).toBeDefined();
});
=======
it("finds by email", () => {
expect(findByEmail("[email protected]")).toBeDefined();
});
▸ 1 pending edit across 1 file — /apply to write · /discard to drop
it("is case-insensitive", () => {
expect(findByEmail("[email protected]")).toBeDefined();
});
>>>>>>> REPLACE
▸ 2 pending edits across 2 files — /apply to write · /discard to drop
reasonix code › /apply
▸ ✓ applied src/users.ts
```
**At this point nothing has been written to disk.** You have three
options:
Requires Node ≥ 20.10. macOS, Linux, Windows (PowerShell / Git Bash /
Windows Terminal). Press `Esc` anytime to abort; `/help` for the full
command list.
- `/apply` — commit the pending blocks. You'll see `✓ applied
src/users.ts` and `✓ applied src/users.test.ts`. A snapshot of the
pre-edit file is kept so `/undo` can roll back.
- `/discard` — throw the blocks away without writing.
- Keep chatting — ask for adjustments. Say "also cover the empty
string case" and the model proposes another block set.
---
After applying:
## `reasonix code` — pair programmer in your terminal
```
reasonix code › /commit "fix: findByEmail case-insensitive"
▸ git add -A && git commit -m "fix: findByEmail case-insensitive"
[main a1b2c3d] fix: findByEmail case-insensitive
```
`/commit` runs `git add -A && git commit -m ...` from the sandbox root.
Scoped to the directory you launch from. The model has native
`read_file` / `write_file` / `edit_file` / `list_directory` /
`search_files` / `directory_tree` / `get_file_info` /
`create_directory` / `move_file` tools, all sandboxed — any path that
resolves outside the launch root (including `..` and symlink escapes)
is refused. Plus `run_command` with a read-only allowlist; anything
state-mutating (`npm install`, `git commit`, …) is gated behind a
confirmation picker.
### Walkthrough: explore before editing
For "what does this code do?" questions the model uses the read-side
tools and replies in prose — no SEARCH/REPLACE blocks, no file writes.
Ask to change something only when you mean it:
tools and replies in prose — no SEARCH/REPLACE blocks, no file
writes. Ask to change something only when you mean it:
```
reasonix code › 这个项目的路由是怎么组织的?
@@ -132,10 +85,53 @@ assistant
nested routes 写子路径,最后 …
```
If the SEARCH text doesn't match the file byte-for-byte, `edit_file`
refuses the edit loudly rather than fuzzy-matching. The model sees the
error and retries with the correct search text — silent wrong edits are
worse than visible rejections.
If an `edit_file` SEARCH block doesn't match the file byte-for-byte,
the edit is refused loudly rather than fuzzy-matched. The model sees
the error and retries — silent wrong edits are worse than visible
rejections.
### Plan mode — review before executing
For anything bigger than a typo, the model is encouraged to propose a
markdown plan first. You'll see a picker with **Approve / Refine /
Cancel**:
```
reasonix code › 把 auth 从 JWT 迁移到 session cookies
▸ plan submitted — awaiting your review
────────────────────────────────────────
## Summary
Swap JWT middleware for session cookies, keep user table intact.
## Files
- src/auth/middleware.ts — replace `verifyJwt` with `readSession`
- src/auth/session.ts — new file, in-memory store + signed cookie
- src/routes/login.ts — return Set-Cookie instead of a token
- tests/auth/*.test.ts — update fixtures
## Risks
- Existing logged-in users get logged out (no migration).
- Session store is in-memory; restart clears sessions.
────────────────────────────────────────
▸ Approve and implement
Refine — explore more
Cancel
```
**Force it** with `/plan` — enters an explicit read-only phase where
the model *must* submit a plan before any edit or non-allowlisted
shell call will execute. Use for high-stakes changes you want to
audit before the model touches disk. `/plan off` or picker
Approve/Cancel exits.
### `/commit` — stage + commit in one step
```
reasonix code › /commit "fix: findByEmail case-insensitive"
▸ git add -A && git commit -m "fix: findByEmail case-insensitive"
[main a1b2c3d] fix: findByEmail case-insensitive
```
### Things to try
@@ -143,18 +139,61 @@ worse than visible rejections.
inline clip isn't enough).
- `/think` — see the model's full R1 reasoning for the last turn
(reasoner preset only).
- `/memory` — show the project's `REASONIX.md` (see below).
- `/undo` — roll back the last applied edit batch.
- `/new` — start fresh in the same directory without losing the
session file.
- Drop `--no-session` for an ephemeral session that doesn't persist.
- `npx reasonix code --preset max` — R1 + 3-way self-consistency
branching for gnarly refactors.
- `npx reasonix code src/` — narrower sandbox (only `src/` is
writable).
- `npx reasonix code --no-session` — ephemeral; nothing saved.
### Project memory — `REASONIX.md`
### `reasonix stats` — how much did you actually save?
Every turn `reasonix chat|code|run` runs appends a compact record
(tokens + cost + what Claude Sonnet 4.6 would have charged) to
`~/.reasonix/usage.jsonl`. `reasonix stats` with no args rolls that
log into today / week / month / all-time windows:
```
Reasonix usage — /Users/you/.reasonix/usage.jsonl
turns cache hit cost (USD) vs Claude saved
----------------------------------------------------------------------
today 8 95.1% $0.004821 $0.1348 96.4%
week 34 93.8% $0.023104 $0.6081 96.2%
month 127 94.2% $0.081530 $2.1452 96.2%
all-time 342 94.0% $0.210881 $5.8934 96.4%
```
Privacy: only tokens, costs, and the session name you chose land
in the file. No prompts, no completions, no tool arguments.
`reasonix stats <transcript>` keeps the old per-file summary
(assistant turns + tool calls) for scripts that already use it.
### Staying current
The panel header shows the running version next to `Reasonix` (e.g.
`Reasonix v0.4.22 · model …`). A quiet 24-hour background check against
the npm registry surfaces a yellow `update: X.Y.Z` on the right side
of the same row when a newer version has been published. No blocking,
no nagging — the check runs once per day max and is silent on failure
(offline, firewall, etc.).
```bash
reasonix update # print current vs latest, run `npm i -g reasonix@latest`
reasonix update --dry-run # print the plan without running anything
```
Running via `npx`? The command detects that and prints a
cache-refresh hint instead — npx picks up the newest version on
its next invocation automatically.
### Project conventions — `REASONIX.md`
Drop a `REASONIX.md` in the project root and its contents are pinned
into the immutable-prefix system prompt every time you launch
`reasonix` in that directory. Good for house conventions, domain
glossary, or things the model keeps forgetting:
into the system prompt every launch. Committable team memory — house
conventions, domain glossary, things the model keeps forgetting:
```bash
cat > REASONIX.md <<'EOF'
@@ -167,18 +206,151 @@ EOF
Re-launch (or `/new`) to pick it up; the prefix is hashed once per
session to keep the DeepSeek cache warm. `/memory` prints what's
currently pinned. `REASONIX_MEMORY=off` disables the lookup for CI /
offline repro.
currently pinned. `REASONIX_MEMORY=off` disables every memory source
for CI / offline repro.
### User memory — `~/.reasonix/memory/`
A second, **private per-user** memory layer lives under your home
directory. Unlike `REASONIX.md` it's never committed, and the model
can write to it itself via the `remember` tool. Two scopes:
- `~/.reasonix/memory/global/` — cross-project (your preferences,
tooling).
- `~/.reasonix/memory/<project-hash>/` — scoped to one sandbox root
in `reasonix code` (decisions, local facts, per-repo shortcuts).
Each scope keeps an always-loaded `MEMORY.md` index of one-liners
plus zero or more `<name>.md` detail files (loaded on demand via
`recall_memory`). Writes land immediately; pinning into the system
prompt takes effect on next `/new` or launch so the cache prefix
stays stable for the current session.
```bash
npx reasonix code src/ # narrower sandbox (only src/ is writable)
npx reasonix code --no-session # ephemeral — nothing saved to disk
npx reasonix code --preset max # R1 reasoning + 3-way self-consistency
```
reasonix code › 我用 bun 而不是 npm,请以后都用 bun 跑构建
assistant
▸ tool<remember> → project/bun_build saved
"Build command on this machine is `bun run build`"
```
**Slash**: `/memory` · `/memory list` · `/memory show <name>` ·
`/memory forget <name>` · `/memory clear <scope> confirm`.
**Model tools**: `remember(type, scope, name, description, content)` ·
`forget(scope, name)` · `recall_memory(scope, name)`.
Project scope is only available inside `reasonix code` (needs a real
sandbox root to hash); plain `reasonix` gets the global scope only.
### Skills — user-authored prompt packs
Skills are prose instruction blocks you drop on disk. Reasonix pins
their names + one-line descriptions into the system prompt; the
model can call `run_skill({name: "..."})` on its own when a match
fits, or you can type `/skill <name> [args]` to run one manually.
Two scopes, same layout as user memory:
- `<project>/.reasonix/skills/` — per-project skills (commit them to
share with your team, or add to `.gitignore` for personal drafts).
- `~/.reasonix/skills/` — global skills available everywhere.
Either layout works: `<name>/SKILL.md` (preferred — can bundle
additional assets alongside) or flat `<name>.md`.
```markdown
---
name: review
description: Review uncommitted changes and flag risks
---
Run `git diff` on staged and unstaged changes. Summarize what each
hunk does, call out potential regressions, and list files that might
need additional tests. Don't propose edits unless I ask.
```
Use it:
```
reasonix code › /skill review
▸ running skill: review
assistant
▸ tool<run_command> → git diff --cached
▸ 3 改动,1 个需要回归测试 …
```
Or let the model pick autonomously — because the skill's name +
description are pinned in the prefix, asking "帮我看下未提交的改动有没
有风险" triggers `run_skill({name: "review"})` without you typing the
slash command.
**Slash**: `/skill` (list) · `/skill show <name>` · `/skill <name>
[args]` (inject body as user turn).
**Deliberately not tied** to any other client's directory convention
(`.claude/skills`, etc.) — Reasonix is model-agnostic at the
conversation layer. Any SKILL.md you author works; the body is
prose, so skills authored for other tools usually port over unchanged
(Reasonix's tool names differ — `filesystem` / `shell` / `web` — but
the model reads the instructions and picks our equivalents).
### Hooks — automate around tool calls and turns
Drop a `settings.json` under `.reasonix/` (project or `~/`) and
Reasonix will fire shell commands at four well-known points in
the loop: before a tool runs, after a tool returns, before your
prompt reaches the model, and after the turn ends.
```json
// <project>/.reasonix/settings.json ← committable
// ~/.reasonix/settings.json ← per-user
{
"hooks": {
"PreToolUse": [{ "match": "edit_file|write_file", "command": "bun scripts/guard.ts" }],
"PostToolUse": [{ "match": "edit_file", "command": "biome format --write" }],
"UserPromptSubmit": [{ "command": "echo $(date +%s) >> ~/.reasonix/prompts.log" }],
"Stop": [{ "command": "bun test --run", "timeout": 60000 }]
}
}
```
Each hook is a shell command. Reasonix invokes it with stdin = a
JSON envelope describing the event:
```json
{ "event": "PreToolUse", "cwd": "/path/to/project",
"toolName": "edit_file", "toolArgs": { "path": "src/x.ts", "..." } }
```
Exit code drives the decision:
- **0** — pass; loop continues normally
- **2** — block (only on `PreToolUse` / `UserPromptSubmit`); the
hook's stderr becomes the synthetic tool result the model sees,
or the prompt is dropped entirely
- **anything else** — warn; loop continues, stderr renders as a
yellow row inline
`match` is anchored regex on the tool name; `*` or omitted matches
every tool. Project hooks fire before global hooks. Default
timeouts: 5s for blocking events, 30s for logging events; per-hook
`timeout` overrides.
**Slash**: `/hooks` (list active hooks) · `/hooks reload` (re-read
`settings.json` from disk without losing your session).
### Staying current from inside the TUI
`/update` inside a running session shows your current version, the
last-resolved latest version (from the quiet 24h background check),
and the shell command to run. The slash does *not* spawn
`npm install` — stdio:inherit into a running Ink renderer corrupts
the display. Exit the session and run `reasonix update` in a
fresh shell when you actually want to install.
---
## Using `reasonix` — general chat
## `reasonix` — also works as general chat
Same TUI, no filesystem tools unless you opt in via MCP. Good for
drafting, Q&A, schema design, architecture discussions, or driving
@@ -187,102 +359,74 @@ your own MCP servers. Sessions persist per name under
```bash
npx reasonix # uses saved config + wizard-selected MCP
npx reasonix --preset smart # one-shot override
npx reasonix --session design # named session
npx reasonix --session design # resume it later — history intact
npx reasonix --preset smart # reasoner + R1 harvest for this run
npx reasonix --session design # named session — resume later with --session design
```
### Walkthrough: a multi-turn session with R1 reasoning
```
reasonix › /preset smart
▸ switched to smart · model deepseek-reasoner · harvest on · branch off
reasonix › 我要给一个 Flutter 应用设计限时折扣的弹窗展示规则。目标:
每天首次打开时弹一次,连续弹 3 天后休眠 7 天。怎么实现?
assistant
▸ R1 reasoning · 2410 chars of thought
‹ subgoals (3): 持久化展示计数 · 判断是否过了 24h · 休眠窗口判断
‹ hypotheses (2): SharedPreferences 存计数 · lastShownAt 时间戳
‹ uncertainties (1): 用户换设备后重置的策略
建议数据模型:
lastShownAt: DateTime
consecutiveShows: int (0..3)
sleepUntil: DateTime?
…
```
`/think` dumps the full R1 thought trace; `/status` shows the current
model / flags / context use; `/retry` re-samples the same prompt with
a fresh random seed (useful when the first answer missed something).
### Walkthrough: attach MCP tools on the fly
Bridge your own MCP servers on the fly:
```bash
# Attach the official filesystem server sandboxed to /tmp/scratch,
# plus a remote knowledge-base over SSE.
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/scratch" \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "kb=https://mcp.example.com/sse"
```
Inside the chat:
```
reasonix › /mcp
▸ fs (stdio, 11 tools) fs_read_file · fs_list_directory · fs_write_file · …
▸ kb (sse, 4 tools) kb_search · kb_get · kb_list_collections · kb_stat
reasonix › 在 /tmp/scratch 下把所有 .log 文件里含 "ERROR" 的行收集到 errors.txt
assistant
▸ tool<fs_search_files> → 4 matches
▸ tool<fs_read_file> → …
▸ tool<fs_write_file> → wrote 2.4 KB to errors.txt
▸ 已写入 errors.txt — 共 38 行,分布在 4 个源文件中。
```
MCP tools go through the same Cache-First + repair + context-safety
plumbing as native tools, including the 32k result cap and live
progress-notification rendering.
### When to use `reasonix` vs `reasonix code`
| situation | command |
|---|---|
| Editing files in the current project | `reasonix code` |
| Exploring a project without writing files | `reasonix code` (it only writes on `/apply`) |
| Design / architecture / research chat | `reasonix` |
| Driving your own MCP servers | `reasonix --mcp "..."` |
| One-shot question, no TUI | `reasonix run "..."` |
| Reproducing a prior session / benchmark | `reasonix replay path.jsonl` |
plumbing as native tools — 32k result cap, live progress-notification
rendering, retries.
---
## Commands inside the session
**Core**
| command | what it does |
|---|---|
| `/help` | full command reference with hints |
| `/help` · `/?` | full command reference with hints |
| `/status` | current model · flags · context · session |
| `/new` · `/reset` | fresh conversation in the same session |
| `/clear` | clear visible scrollback only (log kept) |
| `/retry` | truncate and resend your last message (fresh sample) |
| `/exit` · `/quit` | quit |
**Model**
| command | what it does |
|---|---|
| `/preset <fast\|smart\|max>` | one-tap bundle (model + harvest + branch) |
| `/model <id>` | switch DeepSeek model (`deepseek-chat`, `deepseek-reasoner`) |
| `/harvest [on\|off]` | toggle R1 plan-state extraction |
| `/branch <N\|off>` | run N parallel samples per turn, pick best (N ≥ 2) |
| `/think` | dump the last turn's full R1 reasoning |
**Context & tools**
| command | what it does |
|---|---|
| `/mcp` | list attached MCP servers and their tools |
| `/tool [N]` | dump the Nth tool call's full output (1 = latest) |
| `/think` | dump the last turn's full R1 reasoning |
| `/retry` | truncate and resend your last message (fresh sample) |
| `/compact [cap]` | shrink oversized tool results in the log |
**Memory & skills**
| command | what it does |
|---|---|
| `/memory` | show pinned memory (REASONIX.md + ~/.reasonix/memory) |
| `/memory list` · `show <name>` · `forget <name>` · `clear <scope> confirm` | manage the store |
| `/skill` · `/skill list` | list discovered skills (project + global) |
| `/skill show <name>` | dump one skill's body |
| `/skill <name> [args]` | run a skill (inject body as user turn) |
**Sessions**
| command | what it does |
|---|---|
| `/sessions` | list saved sessions (current marked with `▸`) |
| `/forget` | delete the current session from disk |
| `/new` (alias `/reset`) | start a fresh conversation in the same session |
| `/clear` | clear visible scrollback only (log kept) |
| `/setup` | reconfigure (exit and run `reasonix setup`) |
| `/exit` | quit |
Additional commands in `reasonix code`:
**Code mode only** (`reasonix code`)
| command | what it does |
|---|---|
@@ -290,32 +434,36 @@ Additional commands in `reasonix code`:
| `/discard` | drop the pending edit blocks without writing |
| `/undo` | roll back the last applied edit batch |
| `/commit "msg"` | `git add -A && git commit -m "msg"` |
| `/plan [on\|off]` | toggle read-only plan mode |
| `/apply-plan` | force-approve a pending plan |
**Keyboard:**
**Keyboard**
- `Enter` — submit
- `Shift+Enter` / `Ctrl+J` — newline (multi-line paste also supported; `\` + Enter as a portable fallback)
- `↑ / ↓` — walk prompt history while idle; navigate slash-autocomplete matches
- `Shift+Enter` / `Ctrl+J` — newline (multi-line paste also supported;
`\` + Enter as a portable fallback)
- `↑` / `↓` — walk prompt history while idle; navigate slash-autocomplete
- `Tab` / `Enter` on a `/foo` prefix — accept the highlighted suggestion
- `Esc` — abort the current turn (stops the API call, cancels any in-flight tool, rejects pending MCP requests)
- `Esc` — abort the current turn (stops the API call, cancels any
in-flight tool, rejects pending MCP requests)
- `y` / `n` on confirm prompts — hotkey accept / reject
---
## Sessions and safety nets
- Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl` (per
directory for `reasonix code`). Every message appended atomically; `Ctrl+C`
never loses context.
- Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl`
(per directory for `reasonix code`). Every message appended
atomically; `Ctrl+C` never loses context.
- Tool results are capped at 32k chars per call. Oversized sessions
self-heal on load (shrinks + rewrites the file).
- Malformed `assistant.tool_calls` / `tool` pairing is validated on
every outgoing API call so a corrupted session can't keep 400ing.
- Context gauge turns yellow at 50%, red at 80% with a `/compact` nudge.
Approaching the 131k window triggers an automatic compaction attempt
before falling back to a forced summary.
- The model's sandbox in `reasonix code` refuses any path that resolves
outside the launch directory, including symlink escape and `..` traversal.
- Context gauge turns yellow at 50%, red at 80% with a `/compact`
nudge. Approaching the 131k window triggers an automatic
compaction attempt before falling back to a forced summary.
- The `reasonix code` sandbox refuses any path that resolves outside
the launch directory, including symlink escape and `..` traversal.
### Troubleshooting: duplicate rows / ghost rendering
@@ -329,18 +477,12 @@ If you hit this, run with plain mode:
```bash
REASONIX_UI=plain npx reasonix code
# or
REASONIX_UI=plain npx reasonix
```
Plain mode suppresses every live/animated row and disables the
internal tick timer. You lose the streaming preview and spinners
but gain stable scrollback. Committed events (your prompts, tool
results, the model's final responses) still render normally via
Ink's `<Static>` append path.
Windows Terminal, PowerShell 7 in Windows Terminal, and WezTerm
don't need this opt-out.
Plain mode suppresses live/animated rows and disables the internal
tick timer. You lose the streaming preview and spinners but gain
stable scrollback. Windows Terminal, PowerShell 7 in Windows
Terminal, and WezTerm don't need this opt-out.
---
@@ -352,19 +494,11 @@ something the model wasn't trained on (new releases, current events,
obscure APIs), it decides to call `web_search` on its own; if a
snippet isn't enough it follows up with `web_fetch`.
```
you › Flutter 3.19 新加了什么?
assistant
▸ tool<web_search> → query: "Flutter 3.19 new features"
▸ tool<web_fetch> → https://docs.flutter.dev/release/3-19
▸ 3.19 主要新增了 …
```
Backed by **Mojeek**'s public search page — an independent web index,
no API key, no signup, bot-friendly. Coverage on niche or very recent
queries can be thinner than Google/Bing, but it's reliable from
scripts and doesn't gate on cookies or sessions. (DDG was the original
backend but it started serving anti-bot pages in 2026.)
Backed by **Mojeek**'s public search page — an independent web
index, bot-friendly, no cookies/sessions. Coverage on niche or very
recent queries can be thinner than Google/Bing, but it's reliable
from scripts. (DDG was the original backend but started serving
anti-bot pages in 2026.)
**Turn it off** (offline mode / privacy / CI):
@@ -374,37 +508,11 @@ backend but it started serving anti-bot pages in 2026.)
```
```bash
# Or one env var (wins over config):
REASONIX_SEARCH=off npx reasonix
REASONIX_SEARCH=off npx reasonix code
```
**Bring your own provider** (Kagi, SearXNG, Serper, an internal
cache) — implement the two tools however you want and register them
manually:
```ts
import { ToolRegistry } from "reasonix";
// Register your own `web_search` / `web_fetch` on a ToolRegistry,
// then pass it to CacheFirstLoop (or `reasonix chat --no-config`
// with seedTools via library API).
```
Inside the session:
```
reasonix › Flutter 3.19 引入了什么新的 Navigator API?
assistant
▸ tool<web_search> → query: "Flutter 3.19 new Navigator API"
answer: Flutter 3.19 introduces the NavigatorObserver changes …
1. Flutter 3.19 Release Notes — https://docs.flutter.dev/…
2. What's new in Flutter 3.19 — https://medium.com/…
▸ tool<web_fetch> → https://docs.flutter.dev/release/release-notes/3-19-0
(full page text, clipped at 32k)
▸ 3.19 新增了 …
```
For advanced / self-hosted search (Kagi, SearXNG, internal caches)
implement the `WebSearchProvider` interface and call
**Bring your own** (Kagi, SearXNG, internal caches): implement the
`WebSearchProvider` interface and call
`registerWebTools(registry, { provider })` yourself, or bridge an
existing MCP search server via `--mcp`.
@@ -412,14 +520,14 @@ existing MCP search server via `--mcp`.
## MCP — bring your own tools
Any [MCP](https://spec.modelcontextprotocol.io/) server works. Wizard
lets you pick from a catalog, or drive it by flag:
Any [MCP](https://spec.modelcontextprotocol.io/) server works. The
wizard lets you pick from a catalog, or drive it by flag:
```bash
# stdio (local subprocess)
npx reasonix --mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe"
# multiple servers at once
# multiple at once
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "demo=npx tsx examples/mcp-server-demo.ts"
@@ -428,21 +536,22 @@ npx reasonix \
npx reasonix --mcp "kb=https://mcp.example.com/sse"
```
`reasonix mcp list` shows the curated catalog. `reasonix mcp inspect <spec>`
connects once and dumps the server's tools / resources / prompts without
starting a chat. Progress notifications from long-running tools (2025-03-26
spec) render live as a progress bar in the spinner.
`reasonix mcp list` shows the curated catalog. `reasonix mcp inspect
<spec>` connects once and dumps the server's tools / resources /
prompts without starting a chat. Progress notifications from
long-running tools (2025-03-26 spec) render live as a progress bar
in the spinner.
Supported transports: **stdio** (local command) and **HTTP+SSE** (remote,
MCP 2024-11-05 spec).
Supported transports: **stdio** (local command) and **HTTP+SSE**
(remote, MCP 2024-11-05 spec).
---
## CLI reference
```bash
npx reasonix # chat (uses saved config)
npx reasonix code [path] # coding mode scoped to path (default: cwd)
npx reasonix # chat (uses saved config)
npx reasonix setup # reconfigure the wizard
npx reasonix chat --session work # named session
npx reasonix chat --no-session # ephemeral
@@ -474,6 +583,9 @@ Env vars (win over config):
```bash
export DEEPSEEK_API_KEY=sk-...
export DEEPSEEK_BASE_URL=https://... # optional alternate endpoint
export REASONIX_MEMORY=off # disable REASONIX.md + user memory
export REASONIX_SEARCH=off # disable web_search / web_fetch
export REASONIX_UI=plain # disable live rows (ghosting workaround)
```
---
@@ -519,13 +631,14 @@ for await (const ev of loop.step("What is 17 + 25?")) {
console.log(loop.stats.summary());
```
`ChatOptions.seedTools` accepts a pre-built `ToolRegistry` for callers
who want the `reasonix code` loop wiring without the CLI wrapper.
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for internals.
`ChatOptions.seedTools` accepts a pre-built `ToolRegistry` for
callers who want the `reasonix code` loop wiring without the CLI
wrapper. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for
internals.
---
## Why Reasonix (not LangChain)
## Benchmarks — verify the cache-hit claim yourself
Every abstraction here earns its weight against a DeepSeek-specific
property — dirt-cheap tokens, R1 reasoning traces, automatic prefix
@@ -539,11 +652,10 @@ caching, JSON mode. Generic wrappers leave these on the table.
| Scavenge tool calls leaked into `<think>` | yes | no |
| Call-storm breaker on identical-arg repeats | yes | no |
| Live cache-hit / cost / vs-Claude panel | yes | no |
| First-run config prompt + Markdown TUI | yes | no |
On the same τ-bench-lite workload — 8 multi-turn tool-use tasks × 3
repeats = 48 runs per side, live DeepSeek `deepseek-chat`, sole variable
prefix stability:
repeats = 48 runs per side, live DeepSeek `deepseek-chat`, sole
variable prefix stability:
| metric | baseline (cache-hostile) | Reasonix | delta |
|---|---:|---:|---:|
@@ -551,7 +663,7 @@ prefix stability:
| cost / task | $0.002599 | $0.001579 | **−39%** |
| pass rate | 96% (23/24) | **100% (24/24)** | — |
**Verify it yourself — no API key, zero cost:**
**Reproduce without spending an API credit:**
```bash
git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
@@ -567,8 +679,10 @@ model call; baseline's churns on every turn. The cache delta is
*mechanically* attributable to log stability, not to a different
system prompt.
Full 48-run report: [`benchmarks/tau-bench/report.md`](./benchmarks/tau-bench/report.md).
Reproduce with your own API key: `npx tsx benchmarks/tau-bench/runner.ts --repeats 3`.
Full 48-run report:
[`benchmarks/tau-bench/report.md`](./benchmarks/tau-bench/report.md).
Reproduce with your own API key: `npx tsx
benchmarks/tau-bench/runner.ts --repeats 3`.
MCP reference runs (one single prefix hash across all 5 turns even
with two concurrent MCP subprocesses):
@@ -583,10 +697,16 @@ with two concurrent MCP subprocesses):
## Non-goals
- Multi-agent orchestration (use LangGraph).
- RAG / vector stores (use LlamaIndex).
- Multi-provider abstraction (use LiteLLM).
- Web UI / SaaS.
- **Multi-agent orchestration / sub-agents** (use LangGraph).
- **Workflow DSL / DAG scheduler / parallel-branch engine** — skills
are prose; the model sequences via the normal tool-use loop.
Keeps single-loop + append-only + cache-first invariants intact.
- **Multi-provider abstraction** (use LiteLLM). Reasonix is
DeepSeek-only on purpose — every pillar (cache-first loop, R1
harvesting, tool-call repair) is tuned against DeepSeek-specific
behavior and economics. Coupling to one backend is the feature.
- **RAG / vector stores** (use LlamaIndex).
- **Web UI / SaaS.**
Reasonix does DeepSeek, deeply.
@@ -598,9 +718,9 @@ Reasonix does DeepSeek, deeply.
git clone https://github.com/esengine/reasonix.git
cd reasonix
npm install
npm run dev chat # run CLI from source via tsx
npm run dev code # run CLI from source via tsx
npm run build # tsup to dist/
npm test # vitest (444 tests)
npm test # vitest (648 tests)
npm run lint # biome
npm run typecheck # tsc --noEmit
```
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "reasonix",
"version": "0.4.17",
"version": "0.4.27",
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
"type": "module",
"bin": {
+192
View File
@@ -0,0 +1,192 @@
/**
* End-to-end smoke test for the memory layer. Runs against a temp
* homeDir so the developer's real ~/.reasonix/memory/ is never touched.
* Exercises: write → index regeneration → prefix assembly →
* recall → delete → REASONIX_MEMORY=off short-circuit.
*
* Run: npx tsx scripts/smoke-memory.mts
* Exit code 0 on success, 1 on any assertion failure.
*/
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ToolRegistry } from "../src/tools.js";
import { registerMemoryTools } from "../src/tools/memory.js";
import {
MemoryStore,
applyMemoryStack,
applyUserMemory,
projectHash,
} from "../src/user-memory.js";
let failures = 0;
function check(label: string, cond: unknown, detail?: string) {
if (cond) {
process.stdout.write(` ✓ ${label}\n`);
} else {
failures++;
process.stdout.write(` ✗ ${label}${detail ? ` — ${detail}` : ""}\n`);
}
}
async function main() {
const home = mkdtempSync(join(tmpdir(), "reasonix-smoke-home-"));
const projectRoot = mkdtempSync(join(tmpdir(), "reasonix-smoke-proj-"));
process.stdout.write(`home: ${home}\nproject: ${projectRoot}\n\n`);
try {
// ── 1. MemoryStore write + index regeneration ────────────────────
process.stdout.write("1. MemoryStore write → index regen\n");
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "bun_build",
type: "project",
scope: "project",
description: "Build command on this machine is `bun run build`",
body: "On this machine, no npm — always `bun run build` / `bun run test`.",
});
store.write({
name: "tabs_not_spaces",
type: "user",
scope: "global",
description: "Use tabs for indentation across all projects",
body: "Rule.\n\n**Why:** muscle memory, editor config across machines.\n\n**How to apply:** always tabs.",
});
const hash = projectHash(projectRoot);
const projectFile = join(home, "memory", hash, "bun_build.md");
const globalFile = join(home, "memory", "global", "tabs_not_spaces.md");
check("project-scoped file landed in <hash>/ dir", existsSync(projectFile));
check("global-scoped file landed in global/ dir", existsSync(globalFile));
check("no cross-contamination project ⇒ global", !existsSync(join(home, "memory", "global", "bun_build.md")));
const projectIndex = readFileSync(join(home, "memory", hash, "MEMORY.md"), "utf8");
check("project MEMORY.md points at bun_build.md", projectIndex.includes("[bun_build](bun_build.md)"));
const globalIndex = readFileSync(join(home, "memory", "global", "MEMORY.md"), "utf8");
check("global MEMORY.md points at tabs_not_spaces.md", globalIndex.includes("[tabs_not_spaces](tabs_not_spaces.md)"));
const raw = readFileSync(projectFile, "utf8");
check("frontmatter has name/type/scope/created", /^---\nname: bun_build\n/.test(raw) && /type: project/.test(raw) && /scope: project/.test(raw) && /created: \d{4}-\d{2}-\d{2}/.test(raw));
// ── 2. Prefix assembly via applyMemoryStack (+ REASONIX.md) ────────
process.stdout.write("\n2. Prefix assembly (REASONIX.md + user memory)\n");
writeFileSync(join(projectRoot, "REASONIX.md"), "# Project notes\nPrefer explicit types over inference.\n", "utf8");
const BASE = "You are a test assistant.";
const withProjOnly = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory contains global block", withProjOnly.includes("# User memory — global"));
check("applyUserMemory contains project block", withProjOnly.includes("# User memory — this project"));
check("bun_build description present in prefix", withProjOnly.includes("bun run build"));
check("tabs_not_spaces description present in prefix", withProjOnly.includes("Use tabs for indentation"));
// Order: base → (REASONIX.md would go first via applyMemoryStack) → global → project
const ordered = applyUserMemory(BASE, { homeDir: home, projectRoot });
const iGlobalBlock = ordered.indexOf("# User memory — global");
const iProjBlock = ordered.indexOf("# User memory — this project");
check("global block precedes project block (stable for cache)", iGlobalBlock > 0 && iGlobalBlock < iProjBlock);
// Determinism — two calls with same state produce byte-identical prompts.
const a = applyUserMemory(BASE, { homeDir: home, projectRoot });
const b = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory is deterministic (byte-stable)", a === b);
// ── 3. The `remember` / `recall_memory` / `forget` tools ───────────
process.stdout.write("\n3. Tool dispatch (remember / recall / forget)\n");
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home, projectRoot });
check("remember tool registered", reg.has("remember"));
check("forget tool registered", reg.has("forget"));
check("recall_memory tool registered", reg.has("recall_memory"));
check("recall_memory is readOnly (plan-mode safe)", reg.get("recall_memory")?.readOnly === true);
check("remember is NOT readOnly (plan-mode blocked)", reg.get("remember")?.readOnly !== true);
const remOut = await reg.dispatch("remember", {
type: "feedback",
scope: "global",
name: "prefers_short_replies",
description: "User wants terse answers, no trailing summaries",
content: "Default to terse. If the user wants detail they'll ask.",
});
check("remember returns a confirmation (not an error)", remOut.includes("REMEMBERED (global/prefers_short_replies)"), remOut);
const recallOut = await reg.dispatch("recall_memory", {
scope: "global",
name: "prefers_short_replies",
});
check("recall_memory returns the body", recallOut.includes("Default to terse"));
const forgetOut = await reg.dispatch("forget", {
scope: "global",
name: "prefers_short_replies",
});
check("forget returns a confirmation", forgetOut.includes("forgot (global/prefers_short_replies)"));
check("recall_memory after forget returns an error", (await reg.dispatch("recall_memory", { scope: "global", name: "prefers_short_replies" })).includes("error"));
// ── 4. Project scope refused when projectRoot is absent ────────────
process.stdout.write("\n4. Chat-mode (no projectRoot) refuses project scope\n");
const chatReg = new ToolRegistry();
registerMemoryTools(chatReg, { homeDir: home });
const projInChat = await chatReg.dispatch("remember", {
type: "project",
scope: "project",
name: "should_fail",
description: "d",
content: "c",
});
check("scope='project' in chat mode → error payload", projInChat.includes("error") && projInChat.includes("project"));
const globalInChat = await chatReg.dispatch("remember", {
type: "user",
scope: "global",
name: "global_from_chat",
description: "works across projects",
content: "body",
});
check("scope='global' in chat mode → writes successfully", globalInChat.includes("REMEMBERED (global/"));
// ── 5. REASONIX_MEMORY=off short-circuit ───────────────────────────
process.stdout.write("\n5. REASONIX_MEMORY=off opt-out\n");
process.env.REASONIX_MEMORY = "off";
try {
const silenced = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory returns BASE unchanged when off", silenced === BASE);
const fullStack = applyMemoryStack(BASE, projectRoot);
check("applyMemoryStack returns BASE unchanged when off (REASONIX.md also skipped)", fullStack === BASE);
} finally {
delete process.env.REASONIX_MEMORY;
}
// ── 6. Delete regeneration: MEMORY.md matches current file set ─────
process.stdout.write("\n6. Delete + index regeneration\n");
store.delete("global", "tabs_not_spaces");
store.delete("global", "global_from_chat");
const globalIdxAfter = join(home, "memory", "global", "MEMORY.md");
check("global MEMORY.md removed when last file deleted", !existsSync(globalIdxAfter));
const projectIdxStill = readFileSync(join(home, "memory", hash, "MEMORY.md"), "utf8");
check("project MEMORY.md untouched (different scope)", projectIdxStill.includes("bun_build"));
// ── 7. Name-sanitization boundary ──────────────────────────────────
process.stdout.write("\n7. Name sanitization (path-traversal refused)\n");
const badOut = await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "../../etc/passwd",
description: "d",
content: "c",
});
check("remember refuses path-traversal name", badOut.includes("invalid memory name"));
const outsideFile = join(home, "etc", "passwd.md");
check("no file written outside the memory dir", !existsSync(outsideFile));
process.stdout.write(`\n${failures === 0 ? "✅ all smoke checks passed" : `❌ ${failures} failure(s)`}\n`);
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
}
process.exit(failures === 0 ? 0 : 1);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+13
View File
@@ -15,6 +15,7 @@ import {
sessionPath as sessionPathOf,
} from "../../session.js";
import { ToolRegistry } from "../../tools.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerWebTools } from "../../tools/web.js";
import { App } from "../ui/App.js";
import { SessionPicker } from "../ui/SessionPicker.js";
@@ -243,6 +244,18 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
registerWebTools(tools);
}
// Memory tools — available in every session, not just code mode.
// Chat-mode callers get global scope only; project scope requires
// the seedTools path from `reasonix code` (which registers its own
// MemoryStore bound to rootDir before chatCommand runs).
// `run_skill` is registered later in App.tsx (where the client
// exists) so it can wire the subagent runner for runAs:subagent
// skills.
if (!opts.seedTools) {
if (!tools) tools = new ToolRegistry();
registerMemoryTools(tools, {});
}
// Decide whether to show the session picker. It's gated on: session
// persistence is on, the session file already has prior messages, and
// the caller didn't pre-commit to one of the choices via --resume /
+20 -1
View File
@@ -23,6 +23,8 @@ import { loadProjectShellAllowed } from "../../config.js";
import { sanitizeName } from "../../session.js";
import { ToolRegistry } from "../../tools.js";
import { registerFilesystemTools } from "../../tools/filesystem.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerPlanTool } from "../../tools/plan.js";
import { registerShellTools } from "../../tools/shell.js";
import { chatCommand } from "./chat.js";
@@ -59,8 +61,25 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
rootDir,
// Per-project "always allow" list persisted from prior ShellConfirm
// choices; merged on top of the built-in allowlist in shell.ts.
extraAllowed: loadProjectShellAllowed(rootDir),
// GETTER form — re-read every dispatch so a prefix the user adds
// via ShellConfirm mid-session takes effect on the next shell call
// instead of waiting for `/new` or a relaunch.
extraAllowed: () => loadProjectShellAllowed(rootDir),
});
// `submit_plan` is always in the spec list so the prefix cache stays
// stable across plan-mode toggles (Pillar 1). The tool itself is a
// no-op outside plan mode and throws `PlanProposedError` when the
// user has `/plan`-enabled the session.
registerPlanTool(tools);
// `remember` / `forget` / `recall_memory` — cross-session user memory.
// Project scope hashes off rootDir so switching projects gets a fresh
// per-project memory store; the global scope is shared across runs.
registerMemoryTools(tools, { projectRoot: rootDir });
// `run_skill` is intentionally NOT registered here — App.tsx wires it
// up with the subagent runner attached, so `runAs: subagent` skills
// can spawn isolated child loops. Doing it here would mean the App's
// re-registration would shadow the no-runner version, which works
// (last write wins) but obscures the wiring.
process.stderr.write(
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)\n`,
+7
View File
@@ -11,6 +11,7 @@ import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import { ToolRegistry } from "../../tools.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
import { appendUsage } from "../../usage.js";
export interface RunOptions {
task: string;
@@ -148,6 +149,12 @@ export async function runCommand(opts: RunOptions): Promise<void> {
if (ev.role === "tool") process.stdout.write(`\n[tool ${ev.toolName}] ${ev.content}\n`);
if (ev.role === "error") process.stderr.write(`\n[error] ${ev.error}\n`);
if (ev.role === "done") process.stdout.write("\n");
if (ev.role === "assistant_final" && ev.stats?.usage) {
// `reasonix run` is often used in CI / scripting — we want
// those turns to show up in `reasonix stats` too so the
// dashboard reflects all DeepSeek spend, not just TUI sessions.
appendUsage({ session: null, model: ev.stats.model, usage: ev.stats.usage });
}
// Persist every non-streaming event — deltas would flood the file and
// aren't useful for replay (replay renders final content, not keystrokes).
if (transcriptStream && ev.role !== "assistant_delta") {
+139 -5
View File
@@ -1,15 +1,60 @@
/**
* `reasonix stats` — two modes, decided by whether the user passed
* a transcript path.
*
* - `reasonix stats` → cross-session usage dashboard
* (reads `~/.reasonix/usage.jsonl`)
* - `reasonix stats <path>` → summary of a single JSONL transcript
* (original v0.1 behavior, kept so
* existing scripts don't break)
*
* The dashboard is the new story: for every turn `reasonix chat|code|run`
* has ever executed on this machine, we aggregate tokens + cost + the
* equivalent Claude spend, and print rolling-window totals (today /
* week / month / all-time). The savings column is the Pillar 1 pitch
* made concrete — "you paid $X; Claude would have charged $Y, a N%
* reduction."
*/
import { existsSync, readFileSync } from "node:fs";
import {
type UsageAggregate,
type UsageBucket,
aggregateUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
defaultUsageLogPath,
formatLogSize,
readUsageLog,
} from "../../usage.js";
export interface StatsOptions {
transcript: string;
/** Optional transcript path. Absent → dashboard mode. */
transcript?: string;
/** Override usage log location (tests). */
logPath?: string;
/** Inject a fixed timestamp (tests) so rolling windows are deterministic. */
now?: number;
}
export function statsCommand(opts: StatsOptions): void {
if (!existsSync(opts.transcript)) {
console.error(`no such transcript: ${opts.transcript}`);
if (opts.transcript) {
transcriptSummary(opts.transcript);
return;
}
dashboard(opts);
}
// ---------------------------------------------------------------------
// Transcript summary — legacy v0.1 behavior, preserved verbatim.
// ---------------------------------------------------------------------
function transcriptSummary(path: string): void {
if (!existsSync(path)) {
console.error(`no such transcript: ${path}`);
process.exit(1);
}
const lines = readFileSync(opts.transcript, "utf8").split(/\r?\n/).filter(Boolean);
const lines = readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean);
let assistantTurns = 0;
let toolCalls = 0;
let lastTurn = 0;
@@ -23,8 +68,97 @@ export function statsCommand(opts: StatsOptions): void {
/* skip */
}
}
console.log(`transcript: ${opts.transcript}`);
console.log(`transcript: ${path}`);
console.log(`assistant turns: ${assistantTurns}`);
console.log(`tool invocations: ${toolCalls}`);
console.log(`last turn index: ${lastTurn}`);
}
// ---------------------------------------------------------------------
// Dashboard — aggregates ~/.reasonix/usage.jsonl.
// ---------------------------------------------------------------------
function dashboard(opts: StatsOptions): void {
const path = opts.logPath ?? defaultUsageLogPath();
const records = readUsageLog(path);
if (records.length === 0) {
console.log("no usage data yet.");
console.log("");
console.log(` ${path}`);
console.log("");
console.log("run `reasonix chat`, `reasonix code`, or `reasonix run <task>` — every turn");
console.log("appends one line to the log and `reasonix stats` will roll it up.");
return;
}
const agg = aggregateUsage(records, { now: opts.now });
console.log(renderDashboard(agg, path));
}
/** Pure renderer — pulled out so tests can assert on the string directly. */
export function renderDashboard(agg: UsageAggregate, logPath: string): string {
const lines: string[] = [];
const size = formatLogSize(logPath);
lines.push(`Reasonix usage — ${logPath}${size ? ` (${size})` : ""}`);
lines.push("");
lines.push(header());
lines.push(divider());
for (const b of agg.buckets) {
lines.push(bucketRow(b));
}
lines.push("");
// Model + session breakdown — both trim to top 3 so a user with 20
// sessions doesn't drown the table.
if (agg.byModel.length > 0) {
const totalTurns = agg.buckets[agg.buckets.length - 1]?.turns ?? 0;
const top = agg.byModel[0];
if (top && totalTurns > 0) {
const pct = ((top.turns / totalTurns) * 100).toFixed(0);
lines.push(`most used model: ${top.model} (${pct}% of turns)`);
}
}
if (agg.bySession.length > 0) {
const top = agg.bySession[0];
if (top) lines.push(`top session: ${top.session} (${top.turns} turns)`);
}
if (agg.firstSeen) {
lines.push(`tracked since: ${new Date(agg.firstSeen).toISOString().slice(0, 10)}`);
}
return lines.join("\n");
}
function header(): string {
// Fixed column widths so alignment works in any TTY.
return [
pad("", 10),
pad("turns", 8, "right"),
pad("cache hit", 10, "right"),
pad("cost (USD)", 14, "right"),
pad("vs Claude", 14, "right"),
pad("saved", 10, "right"),
].join(" ");
}
function divider(): string {
return "-".repeat(70);
}
function bucketRow(b: UsageBucket): string {
const hit = bucketCacheHitRatio(b);
const savings = bucketSavingsFraction(b);
return [
pad(b.label, 10),
pad(b.turns.toString(), 8, "right"),
pad(b.turns > 0 ? `${(hit * 100).toFixed(1)}%` : "—", 10, "right"),
pad(b.turns > 0 ? `$${b.costUsd.toFixed(6)}` : "—", 14, "right"),
pad(b.turns > 0 ? `$${b.claudeEquivUsd.toFixed(4)}` : "—", 14, "right"),
pad(b.turns > 0 && savings > 0 ? `${(savings * 100).toFixed(1)}%` : "—", 10, "right"),
].join(" ");
}
function pad(s: string, width: number, align: "left" | "right" = "left"): string {
if (s.length >= width) return s;
const fill = " ".repeat(width - s.length);
return align === "right" ? `${fill}${s}` : `${s}${fill}`;
}
+143
View File
@@ -0,0 +1,143 @@
/**
* `reasonix update` — self-upgrade command.
*
* Talks to the npm registry, compares against the running version,
* and either runs `npm install -g reasonix@latest` (global install)
* or advises how to refresh the npx cache (ephemeral install).
*
* The decision logic is factored into `planUpdate()` so it can be
* unit-tested without spawning child processes or hitting the
* network. `updateCommand()` is the thin CLI wrapper that calls
* `getLatestVersion`, passes the result into `planUpdate`, and
* executes any suggested command.
*/
import { spawn } from "node:child_process";
import { VERSION, compareVersions, getLatestVersion, isNpxInstall } from "../../version.js";
export type UpdateAction = "up-to-date" | "newer-local" | "npx-hint" | "run-npm-install";
export interface UpdatePlan {
action: UpdateAction;
/** Human-readable summary; the CLI prints this verbatim. */
message: string;
/**
* Argv for the install command when `action === "run-npm-install"`.
* Absent otherwise. Kept as array so the CLI can pass it straight
* to `spawn` without re-parsing shell syntax.
*/
command?: string[];
}
export interface PlanUpdateInput {
current: string;
latest: string;
/** Overrides `isNpxInstall()` (tests). */
npx?: boolean;
}
/**
* Pure decision function: given current + latest + install kind,
* decide what the CLI should do. No I/O.
*
* newer-local — current > latest (dev build, local publish)
* up-to-date — current === latest
* npx-hint — current < latest AND running under npx
* run-npm-install — current < latest AND running as a real install
*/
export function planUpdate(input: PlanUpdateInput): UpdatePlan {
const diff = compareVersions(input.current, input.latest);
if (diff > 0) {
return {
action: "newer-local",
message: `current (${input.current}) is newer than the published ${input.latest} — nothing to do.`,
};
}
if (diff === 0) {
return { action: "up-to-date", message: `reasonix ${input.current} is up to date.` };
}
if (input.npx) {
return {
action: "npx-hint",
message: [
`reasonix ${input.latest} is available.`,
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch",
"the latest (npx caches packages for a short window). to force a refresh",
"sooner, clear the cache: `npm cache clean --force`.",
].join("\n"),
};
}
return {
action: "run-npm-install",
message: `upgrading reasonix ${input.current} → ${input.latest}`,
command: ["npm", "install", "-g", "reasonix@latest"],
};
}
export interface UpdateCommandOptions {
/** Skip spawning npm; print the decision only. */
dryRun?: boolean;
/** Test seam: override the registry lookup. Returns null = offline. */
fetchLatest?: () => Promise<string | null>;
/** Test seam: override the npx detector. */
isNpx?: () => boolean;
/** Test seam: override the spawner. Must return exit code. */
spawnInstall?: (argv: string[]) => Promise<number>;
/** Test seam: stdout writer. */
write?: (msg: string) => void;
/** Test seam: process exit — tests don't want to tear down vitest. */
exit?: (code: number) => void;
}
function defaultSpawn(argv: string[]): Promise<number> {
return new Promise((resolve, reject) => {
// `shell: true` on Windows is what lets `npm` resolve to `npm.cmd`
// without routing through our `prepareSpawn` helper. The args here
// are literal strings under our control — no user input flows in,
// so injection is not a concern. Avoiding `prepareSpawn` keeps
// this command free of a dep on the shell tools module.
const child = spawn(argv[0]!, argv.slice(1), {
stdio: "inherit",
shell: process.platform === "win32",
});
child.once("error", reject);
child.once("exit", (code) => resolve(code ?? 1));
});
}
/**
* Run the update command. Prints a banner, resolves the latest
* version, prints the plan, and (unless `--dry-run`) executes the
* install when applicable.
*/
export async function updateCommand(opts: UpdateCommandOptions = {}): Promise<void> {
const write = opts.write ?? ((m: string) => process.stdout.write(m));
const exit = opts.exit ?? ((c: number) => process.exit(c));
const fetchLatest = opts.fetchLatest ?? (() => getLatestVersion({ force: true }));
const isNpx = opts.isNpx ?? isNpxInstall;
const doSpawn = opts.spawnInstall ?? defaultSpawn;
write(`current: reasonix ${VERSION}\n`);
const latest = await fetchLatest();
if (!latest) {
write("could not reach registry.npmjs.org — check your network.\n");
exit(1);
return;
}
write(`latest: reasonix ${latest}\n`);
const plan = planUpdate({ current: VERSION, latest, npx: isNpx() });
write(`\n${plan.message}\n`);
if (plan.action !== "run-npm-install" || !plan.command) return;
if (opts.dryRun) {
write(`(dry run) would run: ${plan.command.join(" ")}\n`);
return;
}
write(`\nrunning: ${plan.command.join(" ")}\n`);
const code = await doSpawn(plan.command);
if (code !== 0) {
write(`\nnpm exited with code ${code}. upgrade did not complete.\n`);
exit(code);
}
}
+34 -9
View File
@@ -1,7 +1,7 @@
import { Command } from "commander";
import { readConfig } from "../config.js";
import { VERSION } from "../index.js";
import { applyProjectMemory } from "../project-memory.js";
import { applyMemoryStack } from "../user-memory.js";
import { chatCommand } from "./commands/chat.js";
import { codeCommand } from "./commands/code.js";
import { diffCommand } from "./commands/diff.js";
@@ -12,11 +12,23 @@ import { runCommand } from "./commands/run.js";
import { sessionsCommand } from "./commands/sessions.js";
import { setupCommand } from "./commands/setup.js";
import { statsCommand } from "./commands/stats.js";
import { updateCommand } from "./commands/update.js";
import { versionCommand } from "./commands/version.js";
import { resolveDefaults } from "./resolve.js";
const DEFAULT_SYSTEM =
"You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.";
const DEFAULT_SYSTEM = `You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.
# Cite or shut up — non-negotiable
Every factual claim about a codebase must be backed by evidence. Reasonix VALIDATES your citations — broken paths render in **red strikethrough with ❌** in front of the user.
**Positive claims** — append a markdown link:
- ✅ \`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\`
- ❌ \`The MCP client supports listResources.\` ← unverifiable, do not write.
**Negative claims** ("X is missing", "Y isn't implemented", "lacks Z") are the #1 hallucination shape. STOP before writing them. If you have a search tool, call it first; if the search returns nothing, cite the search itself as evidence (\`No matches for "foo" in src/\`). If you have no tool, qualify hard: "I haven't verified — this is a guess."
Asserting absence without checking is how evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.`;
const program = new Command();
program
@@ -38,7 +50,7 @@ program.action(async () => {
const defaults = resolveDefaults({});
await chatCommand({
model: defaults.model,
system: applyProjectMemory(DEFAULT_SYSTEM, process.cwd()),
system: applyMemoryStack(DEFAULT_SYSTEM, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
session: defaults.session,
@@ -120,7 +132,7 @@ program
});
await chatCommand({
model: defaults.model,
system: applyProjectMemory(opts.system, process.cwd()),
system: applyMemoryStack(opts.system, process.cwd()),
transcript: opts.transcript,
harvest: defaults.harvest,
branch: defaults.branch,
@@ -168,7 +180,7 @@ program
await runCommand({
task,
model: defaults.model,
system: applyProjectMemory(opts.system, process.cwd()),
system: applyMemoryStack(opts.system, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
transcript: opts.transcript,
@@ -178,9 +190,12 @@ program
});
program
.command("stats <transcript>")
.description("Summarize a JSONL transcript produced by `reasonix chat --transcript`.")
.action((transcript: string) => {
.command("stats [transcript]")
.description(
"Show usage dashboard (today / week / month / all-time · turns · cache hit · cost · savings vs Claude). " +
"Pass a transcript path to fall back to the per-file summary (assistant turns + tool calls).",
)
.action((transcript: string | undefined) => {
statsCommand({ transcript });
});
@@ -260,6 +275,16 @@ mcp
program.command("version").description("Print Reasonix version.").action(versionCommand);
program
.command("update")
.description(
"Check the npm registry for a newer Reasonix and install it. Detects npx vs global install; for npx users, prints a cache-refresh hint instead of running `npm i -g`.",
)
.option("--dry-run", "Print the plan without executing the install")
.action(async (opts: { dryRun?: boolean }) => {
await updateCommand({ dryRun: !!opts.dryRun });
});
program.parseAsync(process.argv).catch((err) => {
console.error(err);
process.exit(1);
+485 -9
View File
@@ -11,13 +11,25 @@ import {
snapshotBeforeEdits,
} from "../../code/edit-blocks.js";
import { addProjectShellAllowed } from "../../config.js";
import { type ResolvedHook, formatHookOutcomeMessage, loadHooks, runHooks } from "../../hooks.js";
import { CacheFirstLoop, DeepSeekClient, ImmutablePrefix } from "../../index.js";
import type { LoopEvent } from "../../loop.js";
import type { SessionSummary } from "../../telemetry.js";
import type { ToolRegistry } from "../../tools.js";
import { formatCommandResult, runCommand } from "../../tools/shell.js";
import { registerSkillTools } from "../../tools/skills.js";
import {
type SubagentEvent,
type SubagentSink,
formatSubagentResult,
spawnSubagent,
} from "../../tools/subagent.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
import { appendUsage } from "../../usage.js";
import { VERSION, compareVersions, getLatestVersion } from "../../version.js";
import { type DisplayEvent, EventRow } from "./EventLog.js";
import { PlanConfirm, type PlanConfirmChoice } from "./PlanConfirm.js";
import { PlanRefineInput } from "./PlanRefineInput.js";
import { PromptInput } from "./PromptInput.js";
import { ShellConfirm, type ShellConfirmChoice, derivePrefix } from "./ShellConfirm.js";
import { SlashSuggestions } from "./SlashSuggestions.js";
@@ -124,6 +136,16 @@ export function App({
total?: number;
message?: string;
} | null>(null);
// Live state for an in-flight subagent. The subagent runs inside a
// tool dispatch frame, so its events come in via a sink ref instead
// of through the parent loop's event channel. `null` when no
// subagent is currently active. A new spawn overwrites the previous
// entry — MVP is serial, never two at once.
const [subagentActivity, setSubagentActivity] = useState<{
task: string;
iter: number;
elapsedMs: number;
} | null>(null);
// Transient "what's happening" text set by the loop during silent
// phases (harvest round-trip, between-iteration R1 thinking, forced
// summary). Rendered as a dim spinner row; auto-cleared on the next
@@ -134,6 +156,27 @@ export function App({
// tracks reality. `null` means either the endpoint failed or we
// haven't fetched yet; the panel hides the cell in that case.
const [balance, setBalance] = useState<{ currency: string; total: number } | null>(null);
// Latest published version the npm registry returned, REGARDLESS
// of whether it's newer than what we're running. `null` only while
// the background check is in flight or when the network fails —
// so `/update` can distinguish "on latest" from "still fetching".
// The yellow header badge is derived: it only lights up when the
// fetched version is STRICTLY newer, but the slash surfaces the
// raw value so the user always gets a concrete number.
const [latestVersion, setLatestVersion] = useState<string | null>(null);
const updateAvailable =
latestVersion && compareVersions(VERSION, latestVersion) < 0 ? latestVersion : null;
// Loaded user hooks (project + global settings.json). Stays mutable
// so `/hooks reload` can rescan disk without reconstructing the
// loop. The loop holds a parallel reference for its tool-event
// dispatch; we keep them in sync via the effect below.
const [hookList, setHookList] = useState<ResolvedHook[]>(() =>
loadHooks({ projectRoot: codeMode?.rootDir }),
);
// Working directory reported in every hook's stdin payload. Hook
// scripts that `cd $REASONIX_CWD` (or read `cwd` from the JSON
// envelope) land in the project root, not the user's shell home.
const hookCwd = codeMode?.rootDir ?? process.cwd();
// Snapshots of every file the *last* edit batch touched, keyed by
// nothing more than "most recent". `/undo` restores from this ref
// and nulls it out — one level of undo, Aider-style. Multi-step
@@ -150,6 +193,28 @@ export function App({
// project / Deny and we feed the result back as a synthetic user
// message so the model sees what happened.
const [pendingShell, setPendingShell] = useState<string | null>(null);
// Plan text the model submitted via `submit_plan` while plan mode
// was active. Non-null renders PlanConfirm; user picks Approve /
// Refine / Cancel and we drive the loop from there. Separate from
// `planMode` because a pending plan is a one-shot decision even if
// plan mode stays on (Refine keeps mode on; Approve/Cancel flip off).
const [pendingPlan, setPendingPlan] = useState<string | null>(null);
// Stashed plan + intent while the user types free-form feedback
// (refinement or last instructions on approve). When the picker
// returns "refine" or "approve", we defer the loop-resume and show
// PlanRefineInput. User types + Enter → we ship it; Esc → restore
// pendingPlan and re-show the picker. Letting Approve also take
// input closes the "model left open questions, user had no place
// to answer them" hole.
const [stagedInput, setStagedInput] = useState<{
plan: string;
mode: "refine" | "approve";
} | null>(null);
// Plan-mode indicator — displayed in the StatsPanel, mirrored onto
// the ToolRegistry so dispatch enforces read-only. Toggled via the
// `/plan` slash and PlanConfirm picker. Ephemeral — not persisted
// across launches (you explicitly opt in per session).
const [planMode, setPlanMode] = useState<boolean>(false);
// Text waiting to be submitted AFTER the current turn finishes.
// Set by ShellConfirm's onChoose when the user approves faster than
// the model's "awaiting confirmation" response. We can't call
@@ -223,17 +288,75 @@ export function App({
}, [slashMatches]);
const loopRef = useRef<CacheFirstLoop | null>(null);
// Sink the subagent tool emits live events through (`start` →
// `progress` → `end`). App attaches its updater on first loop
// construction; the registration captures the ref by closure so even
// late spawns find the current handler.
const subagentSinkRef = useRef<SubagentSink>({ current: null });
// hookList + hookCwd intentionally NOT in deps — they seed the loop
// on first construction (loopRef guards a single instantiation), and
// later edits flow in through the mutable `loop.hooks = hookList`
// effect below. Putting them in deps would tear down the loop on
// every reload, wiping the append-only log mid-session.
// biome-ignore lint/correctness/useExhaustiveDependencies: hookList — see comment above
// biome-ignore lint/correctness/useExhaustiveDependencies: hookCwd — see comment above
const loop = useMemo(() => {
if (loopRef.current) return loopRef.current;
const client = new DeepSeekClient();
// Register run_skill HERE (not in code.tsx / chat.tsx) because
// subagent-runAs skills need the client + parent registry to
// spawn child loops. Wiring lives in App.tsx so the same code
// path covers both code mode and chat mode.
//
// The closure captures `tools` (parent registry), `client`, and
// the subagent sink ref by lexical scope — `spawnSubagent` reads
// them per invocation, so a sink handler attached after this
// registration still receives events.
if (tools && !tools.has("run_skill")) {
registerSkillTools(tools, {
projectRoot: codeMode?.rootDir,
subagentRunner: async (skill, task) => {
const result = await spawnSubagent({
client,
parentRegistry: tools,
// Skill body is the subagent's persona/playbook; the user-
// supplied task is what to actually do inside it.
system: skill.body,
task,
// Per-skill model override (frontmatter `model: ...`),
// else falls through to spawnSubagent's default.
model: skill.model,
sink: subagentSinkRef.current,
});
return formatSubagentResult(result);
},
});
}
const prefix = new ImmutablePrefix({
system,
toolSpecs: tools?.specs(),
});
const l = new CacheFirstLoop({ client, prefix, tools, model, harvest, branch, session });
const l = new CacheFirstLoop({
client,
prefix,
tools,
model,
harvest,
branch,
session,
hooks: hookList,
hookCwd,
});
loopRef.current = l;
return l;
}, [model, system, harvest, branch, session, tools]);
}, [model, system, harvest, branch, session, tools, codeMode]);
// Keep the loop's hook list in sync after a `/hooks reload`. The
// loop's field is intentionally mutable for exactly this case —
// construction happens once, hook edits are picked up live.
useEffect(() => {
loop.hooks = hookList;
}, [loop, hookList]);
// Fetch balance once the API key is known. Non-blocking — the
// session works without it; `null` hides the cell. We also refresh
@@ -252,6 +375,24 @@ export function App({
};
}, [loop]);
// Background registry check — 24h disk cache absorbs repeated
// launches, timeout bounded so a flaky network doesn't delay the
// notification. Set to `null` on failure (silent: no network, no
// problem). We store the raw version regardless of whether it's
// newer; the header badge's newer-only check happens at the
// `updateAvailable` derivation above.
useEffect(() => {
let cancelled = false;
void (async () => {
const latest = await getLatestVersion();
if (cancelled || !latest) return;
setLatestVersion(latest);
})();
return () => {
cancelled = true;
};
}, []);
// Wire the shared progressSink so the bridge's onProgress → us.
// Only updates progress when the frame belongs to the currently-
// running tool: late frames from a previous call shouldn't overwrite
@@ -270,6 +411,49 @@ export function App({
};
}, [progressSink]);
// Wire the subagent sink. `start` opens the activity row; each
// `progress` updates iter + elapsed in place; `end` clears the row
// and posts an info line summarizing the run. Only one subagent is
// active at a time in the MVP, so we treat overlapping events as a
// simple replace.
useEffect(() => {
subagentSinkRef.current.current = (ev: SubagentEvent) => {
if (ev.kind === "start") {
setSubagentActivity({
task: ev.task,
iter: ev.iter ?? 0,
elapsedMs: ev.elapsedMs ?? 0,
});
return;
}
if (ev.kind === "progress") {
setSubagentActivity({
task: ev.task,
iter: ev.iter ?? 0,
elapsedMs: ev.elapsedMs ?? 0,
});
return;
}
// end
setSubagentActivity(null);
const seconds = ((ev.elapsedMs ?? 0) / 1000).toFixed(1);
const summary = ev.error
? `🧬 subagent "${ev.task}" failed after ${seconds}s · ${ev.iter ?? 0} tool call(s) — ${ev.error}`
: `🧬 subagent "${ev.task}" done in ${seconds}s · ${ev.iter ?? 0} tool call(s) · ${ev.turns ?? 0} turn(s)`;
setHistorical((prev) => [
...prev,
{
id: `subagent-end-${Date.now()}`,
role: "info",
text: summary,
},
]);
};
return () => {
subagentSinkRef.current.current = null;
};
}, []);
// Surface a one-time banner about session state on first mount.
const sessionBannerShown = useRef(false);
useEffect(() => {
@@ -431,6 +615,25 @@ export function App({
[model, prefixHash],
);
/**
* Toggle plan mode on the local state AND on the ToolRegistry. The
* registry's copy is what actually gates dispatch; the local state
* drives the StatsPanel indicator and slash ergonomics. Kept in sync
* by funneling every toggle through this setter.
*/
const togglePlanMode = useCallback(
(on: boolean) => {
setPlanMode(on);
tools?.setPlanMode(on);
},
[tools],
);
/** Clear the pending-plan picker state; safe to call unconditionally. */
const clearPendingPlan = useCallback(() => {
setPendingPlan(null);
}, []);
const handleSubmit = useCallback(
async (raw: string) => {
let text = raw.trim();
@@ -479,6 +682,21 @@ export function App({
pendingEditCount: codeMode ? pendingEdits.current.length : undefined,
toolHistory: () => toolHistoryRef.current,
memoryRoot: codeMode?.rootDir ?? process.cwd(),
planMode,
setPlanMode: codeMode ? togglePlanMode : undefined,
clearPendingPlan: codeMode ? clearPendingPlan : undefined,
reloadHooks: () => {
const fresh = loadHooks({ projectRoot: codeMode?.rootDir });
setHookList(fresh);
return fresh.length;
},
latestVersion,
refreshLatestVersion: () => {
void (async () => {
const fresh = await getLatestVersion({ force: true });
if (fresh) setLatestVersion(fresh);
})();
},
});
if (result.exit) {
transcriptRef.current?.end();
@@ -524,6 +742,32 @@ export function App({
}
}
// UserPromptSubmit hooks. Exit code 2 from any matching hook
// drops the message entirely (the user's text never reaches
// the model). Other non-zero exits surface as warning rows but
// the prompt still goes through. We render every non-pass
// outcome's stderr inline so a "blocked" choice has a visible
// explanation.
if (hookList.some((h) => h.event === "UserPromptSubmit")) {
const promptReport = await runHooks({
hooks: hookList,
payload: { event: "UserPromptSubmit", cwd: hookCwd, prompt: text },
});
if (promptReport.outcomes.length > 0) {
setHistorical((prev) => [
...prev,
...promptReport.outcomes
.filter((o) => o.decision !== "pass")
.map((o) => ({
id: `hp-${Date.now()}-${Math.random()}`,
role: "warning" as const,
text: formatHookOutcomeMessage(o),
})),
]);
}
if (promptReport.blocked) return;
}
// User message is immutable — push to Static immediately.
promptHistory.current.push(text);
setHistorical((prev) => [...prev, { id: `u-${Date.now()}`, role: "user", text }]);
@@ -619,6 +863,17 @@ export function App({
// until the whole step resolves, which is especially
// confusing in multi-iter tool-call chains.
setSummary(loop.stats.summary());
// Persist a compact per-turn record to ~/.reasonix/usage.jsonl
// so `reasonix stats` (no arg) can aggregate across every
// session the user has ever run. Best-effort: a disk error
// inside appendUsage is swallowed and won't break the turn.
if (ev.stats?.usage) {
appendUsage({
session: session ?? null,
model: ev.stats.model,
usage: ev.stats.usage,
});
}
const finalText = ev.content || streamRef.text;
const iterReasoning = streamRef.reasoning || undefined;
const iterId = `${assistantId}-i${assistantIterCounter.current++}`;
@@ -710,6 +965,24 @@ export function App({
/* malformed args — skip the prompt */
}
}
// submit_plan fired while plan mode was on — the registry
// serialized `{ error, plan }` via PlanProposedError's
// toToolResult(). Extract the plan and mount PlanConfirm.
// Only the latest submission is tracked; a second overrides.
if (
codeMode &&
ev.toolName === "submit_plan" &&
ev.content.includes('"PlanProposedError:')
) {
try {
const parsed = JSON.parse(ev.content) as { plan?: unknown };
if (typeof parsed.plan === "string" && parsed.plan.trim()) {
setPendingPlan(parsed.plan.trim());
}
} catch {
/* malformed payload — skip the picker */
}
}
} else if (ev.role === "error") {
setHistorical((prev) => [
...prev,
@@ -723,6 +996,33 @@ export function App({
}
}
flush();
// Stop hooks — turn has ended (or aborted). Block decisions are
// meaningless past this point so we treat every non-pass as a
// warning. Natural place for "after every turn, run the
// formatter / lint / tests" automation.
if (hookList.some((h) => h.event === "Stop")) {
const stopReport = await runHooks({
hooks: hookList,
payload: {
event: "Stop",
cwd: hookCwd,
lastAssistantText: streamRef.text,
turn: loop.stats.summary().turns,
},
});
for (const o of stopReport.outcomes) {
if (o.decision === "pass") continue;
setHistorical((prev) => [
...prev,
{
id: `hs-${Date.now()}-${Math.random()}`,
role: "warning",
text: formatHookOutcomeMessage(o),
},
]);
}
}
} finally {
if (timer) clearInterval(timer);
setStreaming(null);
@@ -743,15 +1043,22 @@ export function App({
},
[
busy,
clearPendingPlan,
codeApply,
codeDiscard,
codeMode,
codeUndo,
exit,
hookCwd,
hookList,
loop,
latestVersion,
mcpSpecs,
mcpServers,
planMode,
session,
slashSelected,
togglePlanMode,
writeTranscript,
],
);
@@ -835,6 +1142,125 @@ export function App({
}
}, [busy, queuedSubmit, handleSubmit]);
/**
* PlanConfirm callback. Three outcomes, all ending with a synthetic
* user message so the model sees the verdict on its next turn:
* - approve → exit plan mode, tell the model to implement now.
* - refine → stay in plan mode, tell the model to revise.
* - cancel → exit plan mode, tell the model to drop the plan.
* Mirrors handleShellConfirm's busy-queue dance — if the turn is
* still streaming "plan submitted, waiting" chatter when the user
* picks, we abort it and queue the synthetic for the effect above.
*
* `approve` is also callable with no pending plan (via the
* `/apply-plan` slash fallback, used when the model wrote a plan in
* assistant text instead of calling submit_plan). In that case we
* just flip plan mode off and push the implement-now message.
*/
const handlePlanConfirm = useCallback(
async (choice: PlanConfirmChoice) => {
const hadPendingPlan = pendingPlan !== null;
if (!hadPendingPlan && choice !== "approve") {
// Refine / Cancel without a pending plan is a no-op; only the
// /apply-plan fallback makes sense without one.
return;
}
if (choice === "refine" || choice === "approve") {
// Two-step: stash the plan + the intent, show the input, wait
// for user feedback before pushing anything. Approve collects
// "last instructions / answers to open questions" (blank is
// fine, user can just hit Enter). Refine collects required
// feedback so the model has concrete guidance to revise.
if (pendingPlan) {
setStagedInput({ plan: pendingPlan, mode: choice });
setPendingPlan(null);
} else if (choice === "approve") {
// /apply-plan fallback path — no pending plan, just approve.
setStagedInput({ plan: "", mode: "approve" });
}
return;
}
// Cancel — no input needed, fire immediately.
setPendingPlan(null);
togglePlanMode(false);
const marker = "▸ plan cancelled";
const synthetic =
"The plan was cancelled. Drop it entirely. Ask me what I actually want before proposing another plan or making any changes.";
setHistorical((prev) => [
...prev,
{ id: `plan-${choice}-${Date.now()}`, role: "info", text: marker },
]);
if (busy) {
loop.abort();
setQueuedSubmit(synthetic);
} else {
await handleSubmit(synthetic);
}
},
[pendingPlan, togglePlanMode, busy, loop, handleSubmit],
);
/**
* Fired when the user submits feedback from the inline input. The
* staged `mode` decides whether this is a refine or approve: refine
* stays in plan mode and asks the model to revise; approve exits
* plan mode and pushes the implement synthetic, with any user
* guidance (answers to open questions, last-minute preferences)
* included verbatim.
*/
const handleStagedInputSubmit = useCallback(
async (feedback: string) => {
const staged = stagedInput;
setStagedInput(null);
if (!staged) return;
const trimmed = feedback.trim();
let synthetic: string;
let marker: string;
if (staged.mode === "approve") {
togglePlanMode(false);
if (trimmed) {
synthetic = `The plan above has been approved. Implement it now. You are out of plan mode — use edit_file / write_file / run_command as needed.\n\nUser's additional instructions / answers to your open questions:\n\n${trimmed}\n\nFactor these in before the first edit. Stick to the plan unless you discover a concrete reason to deviate; if you do, tell me and wait for a response.`;
marker = `▸ plan approved + instructions — ${trimmed.length > 50 ? `${trimmed.slice(0, 50)}…` : trimmed}`;
} else {
synthetic =
"The plan above has been approved. Implement it now. You are out of plan mode — use edit_file / write_file / run_command as needed. If the plan listed open questions and I didn't answer them, default to the safest interpretation and call them out in your first reply. Don't fabricate preferences — if a question is truly unanswerable without me, stop and ask.";
marker = "▸ plan approved — implementing";
}
} else {
// refine
if (trimmed) {
synthetic = `The plan needs refinement. User feedback / answers:\n\n${trimmed}\n\nStay in plan mode — address the feedback (explore more if needed), then submit an improved submit_plan call. Don't propose a near-identical plan unless you explain why the feedback doesn't apply.`;
marker = `▸ refining — ${trimmed.length > 50 ? `${trimmed.slice(0, 50)}…` : trimmed}`;
} else {
synthetic =
"The plan needs refinement, but the user didn't give specifics. Ask them one or two concrete questions — scope, approach, file boundaries, or the risks you flagged — then wait for their answer before submitting an updated plan.";
marker = "▸ refining — asking the model to clarify";
}
}
setHistorical((prev) => [
...prev,
{ id: `plan-${staged.mode}-${Date.now()}`, role: "info", text: marker },
]);
if (busy) {
loop.abort();
setQueuedSubmit(synthetic);
} else {
await handleSubmit(synthetic);
}
},
[stagedInput, togglePlanMode, busy, loop, handleSubmit],
);
/** Esc on the inline input — restore the picker without resuming. */
const handleStagedInputCancel = useCallback(() => {
if (stagedInput?.plan) setPendingPlan(stagedInput.plan);
setStagedInput(null);
}, [stagedInput]);
return (
<TickerProvider disabled={PLAIN_UI}>
<Box flexDirection="column">
@@ -844,9 +1270,13 @@ export function App({
prefixHash={prefixHash}
harvestOn={loop.harvestEnabled}
branchBudget={loop.branchOptions.budget}
planMode={planMode}
balance={balance}
updateAvailable={updateAvailable}
/>
<Static items={historical}>{(item) => <EventRow key={item.id} event={item} />}</Static>
<Static items={historical}>
{(item) => <EventRow key={item.id} event={item} projectRoot={hookCwd} />}
</Static>
{/*
Live rows are hidden while the ShellConfirm modal is up — the
model's concurrent "please confirm" stream is noise the user
@@ -854,15 +1284,23 @@ export function App({
attention. They come back naturally once the user chooses and
the next turn begins.
*/}
{!PLAIN_UI && !pendingShell && streaming ? (
{!PLAIN_UI && !pendingShell && !pendingPlan && !stagedInput && streaming ? (
<Box marginY={1}>
<EventRow event={streaming} />
<EventRow event={streaming} projectRoot={hookCwd} />
</Box>
) : null}
{!PLAIN_UI && !pendingShell && ongoingTool ? (
{!PLAIN_UI && !pendingShell && !pendingPlan && !stagedInput && ongoingTool ? (
<OngoingToolRow tool={ongoingTool} progress={toolProgress} />
) : null}
{!PLAIN_UI && !pendingShell && !ongoingTool && statusLine ? (
{!PLAIN_UI && !pendingShell && !pendingPlan && !stagedInput && subagentActivity ? (
<SubagentRow activity={subagentActivity} />
) : null}
{!PLAIN_UI &&
!pendingShell &&
!pendingPlan &&
!stagedInput &&
!ongoingTool &&
statusLine ? (
<StatusRow text={statusLine} />
) : null}
{/*
@@ -873,10 +1311,25 @@ export function App({
without a label. Catches micro-gaps between events that the
targeted status lines don't cover.
*/}
{!PLAIN_UI && !pendingShell && busy && !streaming && !ongoingTool && !statusLine ? (
{!PLAIN_UI &&
!pendingShell &&
!pendingPlan &&
!stagedInput &&
busy &&
!streaming &&
!ongoingTool &&
!statusLine ? (
<StatusRow text="processing…" />
) : null}
{pendingShell ? (
{stagedInput ? (
<PlanRefineInput
mode={stagedInput.mode}
onSubmit={handleStagedInputSubmit}
onCancel={handleStagedInputCancel}
/>
) : pendingPlan ? (
<PlanConfirm plan={pendingPlan} onChoose={handlePlanConfirm} projectRoot={hookCwd} />
) : pendingShell ? (
<ShellConfirm
command={pendingShell}
allowPrefix={derivePrefix(pendingShell)}
@@ -935,6 +1388,29 @@ function StatusRow({ text }: { text: string }) {
);
}
/**
* Live one-line indicator for a running subagent. Sits below the
* OngoingToolRow (the parent's tool dispatch row for `spawn_subagent`)
* so the user sees both layers at once: outer "spawn_subagent
* running…" + inner "🧬 subagent: <task> · iter N · 12.3s". Cleared
* when the subagent ends; a one-line summary lands in historical.
*/
function SubagentRow({
activity,
}: {
activity: { task: string; iter: number; elapsedMs: number };
}) {
const tick = useTick();
const seconds = (activity.elapsedMs / 1000).toFixed(1);
return (
<Box paddingLeft={2}>
<Text color="magenta">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
<Text color="magenta">{` 🧬 subagent: ${activity.task}`}</Text>
<Text dimColor>{` · iter ${activity.iter} · ${seconds}s`}</Text>
</Box>
);
}
function OngoingToolRow({
tool,
progress,
+12 -2
View File
@@ -24,7 +24,13 @@ export interface DisplayEvent {
toolCallBuild?: { name: string; chars: number };
}
export const EventRow = React.memo(function EventRow({ event }: { event: DisplayEvent }) {
export const EventRow = React.memo(function EventRow({
event,
projectRoot,
}: {
event: DisplayEvent;
projectRoot?: string;
}) {
if (event.role === "user") {
return (
<Box>
@@ -49,7 +55,11 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
{!isPlanStateEmpty(event.planState) ? (
<PlanStateBlock planState={event.planState!} />
) : null}
{event.text ? <Markdown text={event.text} /> : <Text dimColor>(no content)</Text>}
{event.text ? (
<Markdown text={event.text} projectRoot={projectRoot} />
) : (
<Text dimColor>(no content)</Text>
)}
{event.stats ? <StatsLine stats={event.stats} /> : null}
{event.repair ? <Text color="magenta">{event.repair}</Text> : null}
</Box>
+98
View File
@@ -0,0 +1,98 @@
/**
* Modal-style approval for a `submit_plan` proposal.
*
* Three choices:
* 1. Approve + implement — exits plan mode, pushes a synthetic user
* message telling the model to implement the plan now.
* 2. Refine — stays in plan mode; tells the model to explore more
* and submit an improved plan.
* 3. Cancel — exits plan mode, drops the plan, tells the model the
* user didn't want any of it.
*
* Mirrors ShellConfirm in structure (border, SingleSelect, three
* options, no y/n hotkey — mid-typing triggers would be painful).
* The plan body is rendered verbatim above the picker so the user can
* actually read what they're approving.
*/
import { Box, Text } from "ink";
import React from "react";
import { SingleSelect } from "./Select.js";
import { Markdown } from "./markdown.js";
export type PlanConfirmChoice = "approve" | "refine" | "cancel";
export interface PlanConfirmProps {
plan: string;
onChoose: (choice: PlanConfirmChoice) => void;
/**
* Cap on rendered plan length. A pathological 20-KB plan would push
* the picker off the bottom of the terminal; we show the head +
* "(…N chars truncated — /tool for full output)" instead. The picker
* itself gets the full plan (it's already been committed to the
* transcript via the tool result).
*/
maxRenderedChars?: number;
projectRoot?: string;
}
const DEFAULT_MAX_RENDERED = 2400;
export function PlanConfirm({ plan, onChoose, maxRenderedChars, projectRoot }: PlanConfirmProps) {
const cap = maxRenderedChars ?? DEFAULT_MAX_RENDERED;
const tooLong = plan.length > cap;
const visible = tooLong
? `${plan.slice(0, cap)}\n\n… (${plan.length - cap} chars truncated — use /tool to view the full proposal)`
: plan;
// Crude signal for "the model left questions or risks for me" — the
// typical section headings. Triggers an extra hint toward the Refine
// option so users know where to answer them.
const hasOpenQuestions =
/^#{1,6}\s*(open[-\s]?questions?|risks?|unknowns?|assumptions?|unclear)/im.test(plan) ||
/^#{1,6}\s*(待确认|开放问题|风险|未知|假设|不确定)/im.test(plan);
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box>
<Text bold color="cyan">
▸ plan submitted — awaiting your review
</Text>
</Box>
<Box marginTop={1} flexDirection="column">
<Markdown text={visible} projectRoot={projectRoot} />
</Box>
{hasOpenQuestions ? (
<Box marginTop={1}>
<Text color="yellow">
▲ the plan has open questions or flagged risks — pick{" "}
<Text bold>Refine / answer questions</Text> to write concrete answers before the model
moves on.
</Text>
</Box>
) : null}
<Box marginTop={1}>
<SingleSelect
initialValue={hasOpenQuestions ? "refine" : "approve"}
items={[
{
value: "approve",
label: "Approve and implement",
hint: "Exit plan mode. The model starts executing. You'll get a text input to add any last instructions (or just press Enter to skip).",
},
{
value: "refine",
label: "Refine / answer questions",
hint: "Stay in plan mode. Write answers, modifications, or critiques; the model revises and re-submits.",
},
{
value: "cancel",
label: "Cancel",
hint: "Exit plan mode. Drop the plan; the model won't implement it.",
},
]}
onSubmit={(v) => onChoose(v as PlanConfirmChoice)}
/>
</Box>
</Box>
);
}
+91
View File
@@ -0,0 +1,91 @@
/**
* Inline text input shown after the user picks Approve or Refine in
* PlanConfirm. Collects free-form feedback before the loop resumes.
*
* Why both paths: the plan may contain open questions or risks the
* model asked the user to weigh in on. If the user just picks Approve
* with no chance to answer, the model implements against its own
* guesses. This input lets the user answer questions, pass last-minute
* constraints, or (on Refine) request concrete changes. Empty input is
* fine for Approve (skip straight to implement) and triggers a
* "ask the user clarifying questions" path for Refine.
*
* Kept minimal: single-line prompt, Enter to submit, Esc to return to
* the picker without resuming.
*/
import { Box, Text, useInput } from "ink";
import React, { useState } from "react";
export interface PlanRefineInputProps {
/**
* Which path the user is on. Approve = "implement with these last
* instructions"; refine = "revise the plan with this feedback".
* Drives the header + hint text so users know what kind of message
* they're writing.
*/
mode: "approve" | "refine";
/** Called with trimmed feedback. Empty string is allowed. */
onSubmit: (feedback: string) => void;
/** Called when the user presses Esc to return to the picker. */
onCancel: () => void;
}
export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputProps) {
const [value, setValue] = useState("");
useInput((input, key) => {
if (key.escape) {
onCancel();
return;
}
if (key.return) {
onSubmit(value.trim());
return;
}
if (key.backspace || key.delete) {
setValue((v) => v.slice(0, -1));
return;
}
// Filter out non-printable chars; accept ordinary text + CJK.
if (input && !key.ctrl && !key.meta) {
setValue((v) => v + input);
}
});
const title =
mode === "approve"
? "▸ approving — any last instructions or answers to open questions?"
: "▸ refining — what should the model change?";
const hint =
mode === "approve"
? "Answer questions the plan raised, add constraints, or just press Enter to approve as-is."
: "Describe what's wrong or missing, or answer questions the plan raised.";
const blankHint =
mode === "approve"
? " (Enter with blank = approve without extra instructions.)"
: " (Enter with blank = ask the model to list concrete questions.)";
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
{title}
</Text>
</Box>
<Box marginTop={1}>
<Text dimColor>
{hint} Enter to send · Esc to return to the picker.
{value === "" ? blankHint : ""}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text color="yellow">› </Text>
<Text>{value || " "}</Text>
<Text color="yellow">▍</Text>
</Text>
</Box>
</Box>
);
}
+30 -1
View File
@@ -2,6 +2,7 @@ import { Box, Text } from "ink";
import React from "react";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
import type { SessionSummary } from "../../telemetry.js";
import { VERSION } from "../../version.js";
export interface StatsPanelProps {
summary: SessionSummary;
@@ -9,6 +10,13 @@ export interface StatsPanelProps {
prefixHash: string;
harvestOn?: boolean;
branchBudget?: number;
/**
* True when `reasonix code` is currently running in read-only Plan
* Mode. Surfaced as a red "PLAN" tag in the panel header so the user
* can tell at a glance that edits are gated behind submit_plan +
* approval.
*/
planMode?: boolean;
/**
* Account balance fetched once at launch (and optionally refreshed
* per-turn by the TUI). `null` or absent hides the balance cell
@@ -18,6 +26,13 @@ export interface StatsPanelProps {
* with USD both see "getting low."
*/
balance?: { currency: string; total: number } | null;
/**
* Published npm version newer than VERSION. Rendered as a yellow
* "· update: X" nudge in the panel header. `null` / `undefined`
* hides the nudge (offline launch, already up to date, or check
* still in flight).
*/
updateAvailable?: string | null;
}
export function StatsPanel({
@@ -26,7 +41,9 @@ export function StatsPanel({
prefixHash,
harvestOn,
branchBudget,
planMode,
balance,
updateAvailable,
}: StatsPanelProps) {
const hitPct = (summary.cacheHitRatio * 100).toFixed(1);
const hitColor =
@@ -44,14 +61,26 @@ export function StatsPanel({
<Text color="cyan" bold>
Reasonix
</Text>
<Text dimColor>{` v${VERSION}`}</Text>
<Text dimColor> · model </Text>
<Text color="yellow">{model}</Text>
<Text dimColor> · prefix </Text>
<Text dimColor>{prefixHash}</Text>
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
{planMode ? (
<Text color="red" bold>
{" "}
· PLAN
</Text>
) : null}
</Text>
<Text>
{updateAvailable ? (
<Text color="yellow" bold>{`update: ${updateAvailable} · `}</Text>
) : null}
<Text dimColor>turns {summary.turns} · type /help</Text>
</Text>
<Text dimColor>turns {summary.turns} · type /help</Text>
</Box>
<Box marginTop={1} gap={3}>
<Text>
+298 -44
View File
@@ -14,6 +14,8 @@
* show the expression verbatim; terminals don't do math fonts anyway.
*/
import { readFileSync, statSync } from "node:fs";
import { isAbsolute, join } from "node:path";
import { Box, Text } from "ink";
import React from "react";
@@ -144,9 +146,105 @@ export function stripMath(s: string): string {
);
}
/**
* Citation links: `[text](url)` where url either points outside the repo
* (rendered as a plain external link) or resolves to a file/line in the
* project (rendered as a validated citation — broken citations turn
* red so the user can spot model hallucinations at a glance). The point
* is: the model is encouraged to ground every codebase claim in a
* link, and Reasonix surfaces broken links instead of silently letting
* fabrications past.
*/
export type CitationStatus = { ok: true } | { ok: false; reason: string };
export type CitationMap = Map<string, CitationStatus>;
interface CitationParts {
path: string;
startLine?: number;
endLine?: number;
}
export function isExternalUrl(url: string): boolean {
return /^[a-z][a-z0-9+.-]*:\/\//i.test(url) || url.startsWith("mailto:") || url.startsWith("//");
}
export function parseCitationUrl(url: string): CitationParts | null {
const trimmed = url.trim();
if (!trimmed) return null;
// GitHub-style anchor: foo.ts#L42 or foo.ts#L42-L58
let m = trimmed.match(/^(.+?)#L(\d+)(?:-L?(\d+))?$/);
if (m) {
return {
path: m[1] ?? "",
startLine: Number(m[2]),
endLine: m[3] ? Number(m[3]) : undefined,
};
}
// Colon-style: foo.ts:42 or foo.ts:42-58
m = trimmed.match(/^(.+?):(\d+)(?:-(\d+))?$/);
if (m) {
return {
path: m[1] ?? "",
startLine: Number(m[2]),
endLine: m[3] ? Number(m[3]) : undefined,
};
}
return { path: trimmed };
}
export function validateCitation(url: string, projectRoot: string): CitationStatus {
const parts = parseCitationUrl(url);
if (!parts || !parts.path) return { ok: false, reason: "empty path" };
const fullPath = isAbsolute(parts.path) ? parts.path : join(projectRoot, parts.path);
let stat: ReturnType<typeof statSync>;
try {
stat = statSync(fullPath);
} catch {
return { ok: false, reason: "file not found" };
}
if (!stat.isFile()) return { ok: false, reason: "not a file" };
if (parts.startLine === undefined) return { ok: true };
let lineCount: number;
try {
lineCount = readFileSync(fullPath, "utf8").split("\n").length;
} catch {
return { ok: false, reason: "unreadable" };
}
if (parts.startLine < 1 || parts.startLine > lineCount) {
return { ok: false, reason: `line ${parts.startLine} > ${lineCount}` };
}
if (parts.endLine !== undefined) {
if (parts.endLine < parts.startLine || parts.endLine > lineCount) {
return { ok: false, reason: `range end ${parts.endLine} invalid` };
}
}
return { ok: true };
}
/**
* Pre-scan rendered text for every `[text](url)` link, validate the
* citation-shaped ones, and cache the result. Done once per Markdown
* mount so InlineMd doesn't re-stat the filesystem on every keystroke
* during streaming. External links short-circuit (no fs work).
*/
export function collectCitations(text: string, projectRoot: string): CitationMap {
const map: CitationMap = new Map();
const re = /\[([^\]\n]+)\]\(([^)\n]+)\)/g;
for (const m of text.matchAll(re)) {
const url = m[2] ?? "";
if (!url || isExternalUrl(url)) continue;
if (map.has(url)) continue;
map.set(url, validateCitation(url, projectRoot));
}
return map;
}
/**
* Split a single line into styled segments for bold / italic / inline
* code.
* code / links.
*
* Link group is FIRST so `[text](url)` with markup-looking URL chars
* doesn't get partially eaten by the bold/code branches.
*
* Triple-backtick (```…```) runs are matched BEFORE the single-backtick
* case so a one-line code span like `​``bash echo hi``​` is captured
@@ -158,9 +256,17 @@ export function stripMath(s: string): string {
* `parseBlocks`.
*/
const INLINE_RE =
/(\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|(?<![*\w])\*([^*\n]+?)\*(?!\w))/g;
/(\[([^\]\n]+)\]\(([^)\n]+)\)|\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|(?<![*\w])\*([^*\n]+?)\*(?!\w))/g;
function InlineMd({ text }: { text: string }) {
function InlineMd({
text,
padTo,
citations,
}: {
text: string;
padTo?: number;
citations?: CitationMap;
}) {
const parts: React.ReactNode[] = [];
let last = 0;
let idx = 0;
@@ -170,35 +276,61 @@ function InlineMd({ text }: { text: string }) {
parts.push(<Text key={`t${idx++}`}>{text.slice(last, start)}</Text>);
}
// Groups, in the order they appear in INLINE_RE:
// m[2] = bold content (inside ** **)
// m[3] = triple-backtick content (strip leading lang tag)
// m[4] = single-backtick inline code
// m[5] = italic content (inside * *)
if (m[2] !== undefined) {
// m[2] = link text m[3] = link url
// m[4] = bold content (inside ** **)
// m[5] = triple-backtick content (strip leading lang tag)
// m[6] = single-backtick inline code
// m[7] = italic content (inside * *)
if (m[2] !== undefined && m[3] !== undefined) {
const linkText = m[2];
const url = m[3];
if (isExternalUrl(url)) {
parts.push(
<Text key={`l${idx++}`} color="blue" underline>
{linkText}
</Text>,
);
} else {
const status = citations?.get(url);
if (status && !status.ok) {
parts.push(
<Text key={`l${idx++}`} color="red" strikethrough>
{`${linkText} ❌`}
</Text>,
);
} else {
parts.push(
<Text key={`l${idx++}`} color="cyan" underline>
{linkText}
</Text>,
);
}
}
} else if (m[4] !== undefined) {
parts.push(
<Text key={`b${idx++}`} bold>
{m[2]}
{m[4]}
</Text>,
);
} else if (m[3] !== undefined) {
} else if (m[5] !== undefined) {
// One-line fenced span: ```bash echo hi``` → drop the "bash "
// language tag so the user doesn't see it rendered in code color.
const stripped = m[3].replace(/^(\w+)\s+/, "");
const stripped = m[5].replace(/^(\w+)\s+/, "");
parts.push(
<Text key={`c${idx++}`} color="yellow">
{stripped}
</Text>,
);
} else if (m[4] !== undefined) {
} else if (m[6] !== undefined) {
parts.push(
<Text key={`c${idx++}`} color="yellow">
{m[4]}
{m[6]}
</Text>,
);
} else if (m[5] !== undefined) {
} else if (m[7] !== undefined) {
parts.push(
<Text key={`i${idx++}`} italic>
{m[5]}
{m[7]}
</Text>,
);
}
@@ -207,9 +339,42 @@ function InlineMd({ text }: { text: string }) {
if (last < text.length) {
parts.push(<Text key={`t${idx++}`}>{text.slice(last)}</Text>);
}
// Trailing pad — used by table cells so column widths line up after
// the inline markup is rendered (markup chars like `**` and `` ` ``
// are invisible in output, so naive `pad(rawText, width)` over-pads
// styled cells and the columns drift out of alignment).
if (padTo !== undefined) {
const seen = visibleWidth(text);
if (seen < padTo) {
parts.push(<Text key={`pad${idx++}`}>{" ".repeat(padTo - seen)}</Text>);
}
}
return <Text>{parts}</Text>;
}
/**
* Strip inline markdown markers (**, _, single + triple backtick) so the
* remaining text reflects what the user actually SEES on screen. Used
* to compute correct column widths for table cells where the raw cell
* length includes invisible markup chars.
*/
export function stripInlineMarkup(s: string): string {
return s
.replace(/\[([^\]\n]+)\]\(([^)\n]+)\)/g, "$1")
.replace(/\*\*([^*\n]+?)\*\*/g, "$1")
.replace(/```([^\n]+?)```/g, (_m, c: string) => c.replace(/^(\w+)\s+/, ""))
.replace(/`([^`\n]+?)`/g, "$1")
.replace(/(?<![*\w])\*([^*\n]+?)\*(?!\w)/g, "$1");
}
/**
* Display width AFTER stripping inline markup. The visible-on-screen
* column width — what padding decisions should be based on.
*/
export function visibleWidth(s: string): number {
return displayWidth(stripInlineMarkup(s));
}
interface ParagraphBlock {
kind: "paragraph";
text: string;
@@ -409,22 +574,79 @@ export function parseBlocks(raw: string): Block[] {
continue;
}
// Table detection: a line with at least one `|` where the NEXT
// line looks like a GFM separator (`| --- | --- |` or any mix of
// pipes + dashes + colons + spaces). Both the header row and the
// separator need to be present — a bare pipe in prose shouldn't
// trigger the table path.
if (line.includes("|")) {
// Box-drawing frame detection: top edge `┌────┐`, body lines that
// each begin and end with `│`, bottom edge `└────┘`. Models love to
// draw decorative frames around code snippets and flow charts using
// these characters; without this branch, every body line gets
// word-wrapped by Ink and the frame turns into garbage. Rendering
// the inner content as a code block preserves the fixed-width
// layout the model intended AND gives it a real border via the
// existing code-block renderer. Only triggers OUTSIDE code mode
// (where `inCode` is false) so a literal box-drawing character
// inside a real fenced block isn't grabbed.
if (/^\s*┌─+┐\s*$/.test(line)) {
let j = i + 1;
const bodyLines: string[] = [];
while (j < lines.length && !/^\s*└─+┘\s*$/.test(lines[j]!)) {
const inner = lines[j]!;
// Strip outer `│ ... │` so the content reads naturally.
const m = inner.match(/^\s*│\s?(.*?)\s?│\s*$/);
bodyLines.push(m ? (m[1] ?? "") : inner);
j++;
}
if (j < lines.length) {
flushPara();
flushList();
out.push({ kind: "code", lang: "", text: bodyLines.join("\n") });
i = j;
continue;
}
// No closing edge — fall through and let the line render as
// paragraph rather than eating to EOF.
}
// Table detection: a line with at least one column separator where
// the NEXT line looks like a separator row. Two flavors accepted:
//
// - Standard GFM: `|` columns + `---` / `:---:` separators.
// - Unicode box-drawing: `│` columns (U+2502) + `─` / `┼` (U+2500
// / U+253C) separators. Models trained on Chinese text routinely
// pick the box-drawing characters even when GFM was an option;
// accepting both keeps their output legible without forcing a
// re-prompt. `splitTableRow` normalizes `│` → `|` so the rest of
// the path stays uniform.
//
// Both the header row and the separator must be present — a bare
// pipe in prose shouldn't trigger the table path.
if (line.includes("|") || line.includes("│")) {
const next = (lines[i + 1] ?? "").trim();
if (/^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/.test(next)) {
const isGfmSep = /^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/.test(next);
const isBoxSep = /^[│─┼┬┴┌┐└┘├┤\s]+$/.test(next) && /─{2,}/.test(next);
if (isGfmSep || isBoxSep) {
flushPara();
flushList();
const header = splitTableRow(line);
const colCount = header.length;
const rows: string[][] = [];
let j = i + 2; // skip header + separator
while (j < lines.length) {
const r = lines[j]!.replace(/\s+$/g, "");
if (r.trim() === "" || !r.includes("|")) break;
if (r.trim() === "") break;
if (!r.includes("|") && !r.includes("│")) {
// Continuation row: model wrapped a long cell across lines
// without re-emitting the column separator. Fold this line
// back into the LAST cell of the previous row so its inline
// markup (backticks, bold) parses as one piece instead of
// bleeding into the paragraph stream below the table.
const prev = rows[rows.length - 1];
if (prev && prev.length === colCount) {
const lastIdx = prev.length - 1;
prev[lastIdx] = `${prev[lastIdx] ?? ""} ${r.trim()}`;
j++;
continue;
}
break;
}
rows.push(splitTableRow(r));
j++;
}
@@ -468,23 +690,23 @@ export function parseBlocks(raw: string): Block[] {
return out;
}
function BlockView({ block }: { block: Block }) {
function BlockView({ block, citations }: { block: Block; citations?: CitationMap }) {
switch (block.kind) {
case "heading":
return (
<Text bold color="cyan">
<InlineMd text={block.text} />
<InlineMd text={block.text} citations={citations} />
</Text>
);
case "paragraph":
return <InlineMd text={block.text} />;
return <InlineMd text={block.text} citations={citations} />;
case "bullet":
return (
<Box flexDirection="column">
{block.items.map((item, i) => (
<Box key={`${i}-${item.slice(0, 24)}`}>
<Text color="cyan">{block.ordered ? ` ${block.start + i}. ` : " • "}</Text>
<InlineMd text={item} />
<InlineMd text={item} citations={citations} />
</Box>
))}
</Box>
@@ -498,21 +720,23 @@ function BlockView({ block }: { block: Block }) {
case "edit-block":
return <EditBlockRow block={block} />;
case "table":
return <TableBlockRow block={block} />;
return <TableBlockRow block={block} citations={citations} />;
case "hr":
return <Text dimColor>{"────────────────────────"}</Text>;
}
}
/**
* Split one table row into trimmed cells. Leading/trailing pipes are
* optional (both `| a | b |` and `a | b` are accepted). Pipes escaped
* as `\|` stay in the cell content.
* Split one table row into trimmed cells. Leading/trailing column
* markers are optional (both `| a | b |` and `a | b` are accepted).
* Pipes escaped as `\|` stay in the cell content. Unicode `│`
* (U+2502 BOX DRAWINGS LIGHT VERTICAL) is normalized to `|` first so
* box-drawing tables and GFM tables share one code path.
*/
function splitTableRow(line: string): string[] {
// Temporarily replace escaped pipes so split() doesn't fire on them.
const SENTINEL = "\u0000";
const masked = line.replace(/\\\|/g, SENTINEL);
const masked = line.replace(/\\\|/g, SENTINEL).replace(/│/g, "|");
const trimmed = masked.trim().replace(/^\||\|$/g, "");
return trimmed.split("|").map((c) => c.trim().replace(new RegExp(SENTINEL, "g"), "|"));
}
@@ -523,19 +747,19 @@ function splitTableRow(line: string): string[] {
* doesn't wreck the layout. Header row is bold + cyan; body rows use
* the default text color. Separator is a dim row of dashes.
*/
function TableBlockRow({ block }: { block: TableBlock }) {
function TableBlockRow({ block, citations }: { block: TableBlock; citations?: CitationMap }) {
const colCount = Math.max(block.header.length, ...block.rows.map((r) => r.length));
const widths: number[] = [];
for (let c = 0; c < colCount; c++) {
const cellLengths = [displayWidth(block.header[c] ?? "")];
for (const r of block.rows) cellLengths.push(displayWidth(r[c] ?? ""));
// Use VISIBLE width (post-markup-strip) for column sizing —
// otherwise a cell like `**定义** \`dispatch\` 方法` would be
// measured with the ** and ` chars included, over-padding once
// the markers vanish at render time and shoving subsequent
// columns rightward.
const cellLengths = [visibleWidth(block.header[c] ?? "")];
for (const r of block.rows) cellLengths.push(visibleWidth(r[c] ?? ""));
widths.push(Math.min(40, Math.max(3, ...cellLengths)));
}
const pad = (s: string, w: number) => {
const dw = displayWidth(s);
if (dw >= w) return s;
return s + " ".repeat(w - dw);
};
const separator = widths.map((w) => "─".repeat(w)).join("─┼─");
return (
<Box flexDirection="column">
@@ -543,7 +767,7 @@ function TableBlockRow({ block }: { block: TableBlock }) {
{block.header.map((cell, ci) => (
// biome-ignore lint/suspicious/noArrayIndexKey: table columns never reorder — derived from a static header array
<Text key={`h-${ci}`} bold color="cyan">
{pad(cell, widths[ci] ?? 3)}
<InlineMd text={cell} padTo={widths[ci] ?? 3} citations={citations} />
{ci < colCount - 1 ? " │ " : ""}
</Text>
))}
@@ -555,7 +779,7 @@ function TableBlockRow({ block }: { block: TableBlock }) {
{Array.from({ length: colCount }).map((_, ci) => (
// biome-ignore lint/suspicious/noArrayIndexKey: same — column axis is fixed by the table shape
<Text key={`c-${ri}-${ci}`}>
{pad(row[ci] ?? "", widths[ci] ?? 3)}
<InlineMd text={row[ci] ?? ""} padTo={widths[ci] ?? 3} citations={citations} />
{ci < colCount - 1 ? " │ " : ""}
</Text>
))}
@@ -643,13 +867,43 @@ function EditBlockRow({ block }: { block: EditBlockView }) {
);
}
export function Markdown({ text }: { text: string }) {
export function Markdown({ text, projectRoot }: { text: string; projectRoot?: string }) {
const cleaned = stripMath(text);
const root = projectRoot ?? process.cwd();
const citations = React.useMemo(() => collectCitations(cleaned, root), [cleaned, root]);
const blocks = React.useMemo(() => parseBlocks(cleaned), [cleaned]);
// Collect broken citations into an ordered list so the user sees
// exactly which paths/lines failed and why. A bare count ("⚠ 1
// broken citation") tells the user something's wrong but leaves them
// to scan the wall of text for the red strikethrough — listing each
// one with its reason makes the failure actionable: the user can
// immediately push back on the specific claim, or decide it doesn't
// matter and move on.
const broken: Array<{ url: string; reason: string }> = [];
for (const [url, status] of citations) {
if (!status.ok) broken.push({ url, reason: status.reason });
}
return (
<Box flexDirection="column" gap={1}>
{blocks.map((b, i) => (
<BlockView key={`${i}-${b.kind}`} block={b} />
<BlockView key={`${i}-${b.kind}`} block={b} citations={citations} />
))}
{broken.length > 0 ? <BrokenCitationsBlock items={broken} /> : null}
</Box>
);
}
function BrokenCitationsBlock({ items }: { items: Array<{ url: string; reason: string }> }) {
return (
<Box flexDirection="column" borderStyle="round" borderColor="red" paddingX={1}>
<Text color="red" bold>
{`⚠ ${items.length} broken citation${items.length > 1 ? "s" : ""} — the model referenced paths or lines that don't exist`}
</Text>
{items.map((b, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: list is derived from a Map iteration order, stable per render
<Text key={`bc-${i}`} color="red">
{` ❌ ${b.url} → ${b.reason}`}
</Text>
))}
</Box>
);
+572 -41
View File
@@ -1,9 +1,21 @@
import { spawnSync } from "node:child_process";
import {
HOOK_EVENTS,
type HookEvent,
type ResolvedHook,
globalSettingsPath,
projectSettingsPath,
} from "../../hooks.js";
import type { CacheFirstLoop } from "../../loop.js";
import type { InspectionReport } from "../../mcp/inspect.js";
import { PROJECT_MEMORY_FILE, memoryEnabled, readProjectMemory } from "../../project-memory.js";
import { deleteSession, listSessions } from "../../session.js";
import { SkillStore } from "../../skills.js";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../usage.js";
import { type MemoryScope, MemoryStore } from "../../user-memory.js";
import { VERSION, compareVersions, isNpxInstall } from "../../version.js";
import { renderDashboard } from "../commands/stats.js";
export interface SlashResult {
/** Text to display back to the user as a system/info line. */
@@ -87,6 +99,49 @@ export interface SlashContext {
* replies "root unknown" instead of silently reading a different dir.
*/
memoryRoot?: string;
/**
* Current plan-mode state, surfaced in `/status` and toggled by
* `/plan`. Present iff the session is a `reasonix code` run — chat
* mode doesn't have plan mode.
*/
planMode?: boolean;
/**
* Callback the `/plan` slash uses to flip plan mode on/off. Also
* mirrors the state to the underlying ToolRegistry so dispatch
* enforcement follows. Absent → `/plan` replies "only available in
* code mode".
*/
setPlanMode?: (on: boolean) => void;
/**
* Callback that clears a pending-plan picker state. Called by
* `/apply-plan` so that when the user force-approves, the picker
* dismisses without also firing its own approval synthetic (the
* slash returns its own `resubmit` instead). Safe to call with no
* pending plan.
*/
clearPendingPlan?: () => void;
/**
* Re-load `~/.reasonix/settings.json` + `<project>/.reasonix/settings.json`
* and update both the App's hook state and the loop's mutable hook
* list. Returns the new hook count so the slash can echo a sane
* confirmation. Absent → `/hooks reload` replies "not available".
*/
reloadHooks?: () => number;
/**
* Latest published version if App's background registry check
* has completed, `null` otherwise (still in flight OR offline).
* Drives `/update` — the slash shows whatever the async check
* already resolved, so the command is fully synchronous.
*/
latestVersion?: string | null;
/**
* Fire-and-forget: kick off a fresh registry fetch. `/update`
* calls this whenever it encounters `latestVersion === null`
* so the user can rerun the slash a few seconds later and see
* a concrete answer. Absent → the slash just reports "pending"
* with no retry path.
*/
refreshLatestVersion?: () => void;
}
export interface McpServerSummary {
@@ -131,7 +186,30 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
{ cmd: "branch", argsHint: "<N|off>", summary: "run N parallel samples per turn (N>=2)" },
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
{ cmd: "tool", argsHint: "[N]", summary: "dump full output of the Nth tool call (1=latest)" },
{ cmd: "memory", summary: "show the project's REASONIX.md (pinned into the system prompt)" },
{
cmd: "memory",
argsHint: "[list|show <name>|forget <name>|clear <scope> confirm]",
summary: "show / manage pinned memory (REASONIX.md + ~/.reasonix/memory)",
},
{
cmd: "skill",
argsHint: "[list|show <name>|<name> [args]]",
summary: "list / run user skills (<project>/.reasonix/skills + ~/.reasonix/skills)",
},
{
cmd: "hooks",
argsHint: "[reload]",
summary: "list active hooks (settings.json under .reasonix/) · reload re-reads from disk",
},
{
cmd: "update",
summary: "show current vs latest version + the shell command to upgrade",
},
{
cmd: "stats",
summary:
"cross-session cost dashboard (today / week / month / all-time · cache hit · vs Claude)",
},
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
{ cmd: "compact", argsHint: "[cap]", summary: "shrink oversized tool results in the log" },
@@ -151,6 +229,17 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
summary: "git add -A && git commit -m ...",
contextual: "code",
},
{
cmd: "plan",
argsHint: "[on|off]",
summary: "toggle read-only plan mode (writes bounced until submit_plan + approval)",
contextual: "code",
},
{
cmd: "apply-plan",
summary: "force-approve a pending / in-text plan (fallback if picker was missed)",
contextual: "code",
},
];
/**
@@ -219,12 +308,17 @@ export function handleSlash(
" /compact [cap] shrink large tool results in history (default 4k/result)",
" /think dump the most recent turn's full R1 reasoning (reasoner only)",
" /tool [N] list tool calls (or dump full output of #N, 1=most recent)",
" /memory show the project's REASONIX.md (pinned into the system prompt)",
" /memory [sub] show pinned memory (REASONIX.md + ~/.reasonix/memory).",
" subs: list | show <name> | forget <name> | clear <scope> confirm",
" /skill [sub] list / run user skills (project/.reasonix/skills + ~/.reasonix/skills).",
" subs: list | show <name> | <name> [args] (injects skill body as user turn)",
" /retry truncate & resend your last message (fresh sample from the model)",
" /apply (code mode) commit the pending edit blocks to disk",
" /discard (code mode) drop pending edits without writing",
" /undo (code mode) roll back the last applied edit batch",
' /commit "msg" (code mode) git add -A && git commit -m "msg"',
" /plan [on|off] (code mode) toggle read-only plan mode; writes gated behind submit_plan + your approval",
" /apply-plan (code mode) force-approve pending/in-text plan (fallback)",
" /sessions list saved sessions (current is marked with ▸)",
" /forget delete the current session from disk",
" /new start fresh: drop all context + clear scrollback",
@@ -313,45 +407,25 @@ export function handleSlash(
}
case "memory": {
if (!memoryEnabled()) {
return {
info: "project memory is disabled (REASONIX_MEMORY=off in env). Unset the var to re-enable; no REASONIX.md will be pinned in the meantime.",
};
}
if (!ctx.memoryRoot) {
return {
info: "no project root on this session — `/memory` needs a working directory to resolve REASONIX.md from.",
};
}
const mem = readProjectMemory(ctx.memoryRoot);
if (!mem) {
return {
info: [
`no ${PROJECT_MEMORY_FILE} in ${ctx.memoryRoot}.`,
"",
"Project memory is an optional file you pin notes into — project conventions,",
"things the model keeps forgetting, domain glossary, setup gotchas. When present,",
"its contents are appended to the system prompt (the immutable-prefix region)",
"so every turn sees it without eating per-turn context, and the prefix cache stays",
"warm as long as the file is stable.",
"",
`Create it with: echo "# Project notes for Reasonix" > ${PROJECT_MEMORY_FILE}`,
"Re-launch (or `/new`) to pick up changes — the prefix is hashed at session start.",
].join("\n"),
};
}
const header = mem.truncated
? `▸ project memory: ${mem.path} (${mem.originalChars.toLocaleString()} chars, truncated for the prefix)`
: `▸ project memory: ${mem.path} (${mem.originalChars.toLocaleString()} chars)`;
return {
info: [
header,
"",
mem.content,
"",
"Changes take effect on the next launch or `/new` — the system prompt is hashed once per session to keep the prefix cache warm.",
].join("\n"),
};
return handleMemorySlash(args, ctx);
}
case "skill":
case "skills": {
return handleSkillSlash(args, ctx);
}
case "hook":
case "hooks": {
return handleHooksSlash(args, loop, ctx);
}
case "update": {
return handleUpdateSlash(ctx);
}
case "stats": {
return handleStatsSlash();
}
case "think":
@@ -431,6 +505,45 @@ export function handleSlash(
return { info: ctx.codeDiscard() };
}
case "plan": {
if (!ctx.setPlanMode) {
return {
info: "/plan is only available inside `reasonix code` — chat mode doesn't gate tool writes.",
};
}
const currentOn = Boolean(ctx.planMode);
const raw = (args[0] ?? "").toLowerCase();
let target: boolean;
if (raw === "on" || raw === "true" || raw === "1") target = true;
else if (raw === "off" || raw === "false" || raw === "0") target = false;
else target = !currentOn;
ctx.setPlanMode(target);
if (target) {
return {
info: "▸ plan mode ON — write tools are gated; the model MUST call `submit_plan` before anything executes. (The model can also call submit_plan on its own for big tasks even when plan mode is off — this toggle is the stronger, explicit constraint.) Type /plan off to leave.",
};
}
return {
info: "▸ plan mode OFF — write tools are live again. Model can still propose plans autonomously for large tasks.",
};
}
case "apply-plan":
case "applyplan": {
if (!ctx.setPlanMode) {
return {
info: "/apply-plan is only available inside `reasonix code`.",
};
}
ctx.setPlanMode(false);
ctx.clearPendingPlan?.();
return {
info: "▸ plan approved — implementing",
resubmit:
"The plan above has been approved. Implement it now. You are out of plan mode — use edit_file / write_file / run_command as needed. Stick to the plan unless you discover a concrete reason to deviate; if you do, tell me and wait for a response before making that deviation.",
};
}
case "commit": {
if (!ctx.codeRoot) {
return {
@@ -522,6 +635,7 @@ export function handleSlash(
const mcpLine = ` mcp ${mcpCount} server(s), ${toolCount} tool(s) in registry`;
const pendingLine =
pending > 0 ? ` edits ${pending} pending (/apply to commit, /discard to drop)` : "";
const planLine = ctx.planMode ? " plan ON — writes gated (submit_plan + approval)" : "";
const lines = [
` model ${loop.model}`,
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"}`,
@@ -530,6 +644,7 @@ export function handleSlash(
sessionLine,
];
if (pendingLine) lines.push(pendingLine);
if (planLine) lines.push(planLine);
return { info: lines.join("\n") };
}
@@ -588,6 +703,422 @@ export function handleSlash(
}
}
/**
* `/skill` family. Bare `/skill` (or `/skill list`) prints the
* discovered skills from `<projectRoot>/.reasonix/skills` (code mode
* only) + `~/.reasonix/skills`. `/skill show <name>` dumps one body
* inline for reading. `/skill <name> [args...]` injects the skill body
* as a user turn via `resubmit` — the same mechanism `/apply-plan`
* uses — so the next model turn runs with the skill's instructions
* fresh in the log.
*
* Project scope is only populated when the session has a `codeRoot`
* (set by `reasonix code`). In plain chat mode the store reads the
* global scope only, matching how user-memory behaves.
*/
/**
* `/update` — inside the TUI we deliberately do NOT spawn `npm install`.
* stdio:inherit into a running Ink renderer corrupts the display, and
* the process being upgraded is the same process that's still reading
* its own binaries (messy on Windows). Instead we surface what we
* already know from the App's background registry check and print the
* exact shell command the user should run after exiting.
*
* The `latestVersion` ctx field is populated by App.tsx's mount-time
* `getLatestVersion()` effect. When it's `null` we report the check
* as pending/offline — still a useful output (current version + how
* to force a fresh check from another terminal).
*/
/**
* `/stats` — dashboard view of `~/.reasonix/usage.jsonl`, the same
* roll-up `reasonix stats` (no arg) prints at the shell. Synchronous
* disk read; cheap enough that we don't bother caching between slash
* invocations.
*
* No transcript-path variant in-TUI: the per-file summary is scripty
* and rarely wanted mid-session. If someone needs it they have the
* CLI form (`reasonix stats <path>`).
*/
function handleStatsSlash(): SlashResult {
const path = defaultUsageLogPath();
const records = readUsageLog(path);
if (records.length === 0) {
return {
info: [
"no usage data yet.",
"",
` ${path}`,
"",
"every turn you run here appends one record — this session's turns",
"will show up in the dashboard once you send a message.",
].join("\n"),
};
}
const agg = aggregateUsage(records);
return { info: renderDashboard(agg, path) };
}
function handleUpdateSlash(ctx: SlashContext): SlashResult {
const latest = ctx.latestVersion ?? null;
const lines: string[] = [`current: reasonix ${VERSION}`];
if (latest === null) {
// Kick off a fresh fetch so a follow-up /update a few seconds
// later has a real answer instead of the same pending message.
ctx.refreshLatestVersion?.();
lines.push(
"latest: (not yet resolved — background check in flight or offline)",
"",
"triggered a fresh registry fetch — retry `/update` in a few seconds,",
"or run `reasonix update` in another terminal to force it synchronously.",
);
return { info: lines.join("\n") };
}
lines.push(`latest: reasonix ${latest}`);
const diff = compareVersions(VERSION, latest);
if (diff >= 0) {
lines.push("", "you're on the latest. nothing to do.");
return { info: lines.join("\n") };
}
if (isNpxInstall()) {
lines.push(
"",
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch.",
"to force a refresh sooner: `npm cache clean --force`.",
);
} else {
lines.push(
"",
"to upgrade, exit this session and run:",
" reasonix update (interactive, dry-run supported via --dry-run)",
" npm install -g reasonix@latest (direct)",
"",
"in-session install is deliberately disabled — the npm spawn would",
"corrupt this TUI's rendering and Windows can lock the running binary.",
);
}
return { info: lines.join("\n") };
}
function handleHooksSlash(args: string[], loop: CacheFirstLoop, ctx: SlashContext): SlashResult {
const sub = (args[0] ?? "").toLowerCase();
if (sub === "reload") {
if (!ctx.reloadHooks) {
return {
info: "/hooks reload is not available in this context (no reload callback wired).",
};
}
const count = ctx.reloadHooks();
return { info: `▸ reloaded hooks · ${count} active` };
}
if (sub !== "" && sub !== "list" && sub !== "ls") {
return {
info: "usage: /hooks list active hooks\n /hooks reload re-read settings.json files",
};
}
const hooks = loop.hooks;
const projPath = ctx.codeRoot ? projectSettingsPath(ctx.codeRoot) : undefined;
const globPath = globalSettingsPath();
if (hooks.length === 0) {
const lines = [
"no hooks configured.",
"",
"drop a settings.json with a `hooks` key into either of:",
ctx.codeRoot
? ` · ${projPath} (project)`
: " · <project>/.reasonix/settings.json (project)",
` · ${globPath} (global)`,
"",
"events: PreToolUse, PostToolUse, UserPromptSubmit, Stop",
"exit 0 = pass · exit 2 = block (Pre*) · other = warn",
];
return { info: lines.join("\n") };
}
const grouped = new Map<HookEvent, ResolvedHook[]>();
for (const event of HOOK_EVENTS) grouped.set(event, []);
for (const h of hooks) grouped.get(h.event)?.push(h);
const lines: string[] = [`▸ ${hooks.length} hook(s) loaded`];
for (const event of HOOK_EVENTS) {
const list = grouped.get(event) ?? [];
if (list.length === 0) continue;
lines.push("", `${event}:`);
for (const h of list) {
const match = h.match && h.match !== "*" ? ` match=${h.match}` : "";
const desc = h.description ? ` — ${h.description}` : "";
lines.push(` [${h.scope}]${match} ${h.command}${desc}`);
}
}
lines.push("", `sources: project=${projPath ?? "(none — chat mode)"} · global=${globPath}`);
return { info: lines.join("\n") };
}
function handleSkillSlash(args: string[], ctx: SlashContext): SlashResult {
const store = new SkillStore({ projectRoot: ctx.codeRoot });
const sub = (args[0] ?? "").toLowerCase();
if (sub === "" || sub === "list" || sub === "ls") {
const skills = store.list();
if (skills.length === 0) {
const lines = ["no skills found. Reasonix reads skills from:"];
if (store.hasProjectScope()) {
lines.push(
" · <project>/.reasonix/skills/<name>/SKILL.md (or <name>.md) — project scope",
);
}
lines.push(" · ~/.reasonix/skills/<name>/SKILL.md (or <name>.md) — global scope");
if (!store.hasProjectScope()) {
lines.push(" (project scope is only active in `reasonix code`)");
}
lines.push(
"",
"Each file's frontmatter needs at least `name` and `description`.",
"Invoke a skill with `/skill <name> [args]` or by asking the model to call `run_skill`.",
);
return { info: lines.join("\n") };
}
const lines = [`User skills (${skills.length}):`];
for (const s of skills) {
const scope = `(${s.scope})`.padEnd(11);
const name = s.name.padEnd(24);
const desc = s.description.length > 70 ? `${s.description.slice(0, 69)}…` : s.description;
lines.push(` ${scope} ${name} ${desc}`);
}
lines.push("");
lines.push("View body: /skill show <name> Run: /skill <name> [args]");
return { info: lines.join("\n") };
}
if (sub === "show" || sub === "cat") {
const target = args[1];
if (!target) return { info: "usage: /skill show <name>" };
const skill = store.read(target);
if (!skill) return { info: `no skill found: ${target}` };
return {
info: [
`▸ ${skill.name} (${skill.scope})`,
skill.description ? ` ${skill.description}` : "",
` ${skill.path}`,
"",
skill.body,
]
.filter((l) => l !== "")
.join("\n"),
};
}
// Bare `/skill <name> [args...]` — inject the body as a user turn.
// The first arg is the skill name; remaining args are forwarded
// verbatim as the skill's "Arguments:" line.
const name = args[0] ?? "";
const skill = store.read(name);
if (!skill) {
return {
info: `no skill found: ${name} (try /skill list)`,
};
}
const extra = args.slice(1).join(" ").trim();
const header = `# Skill: ${skill.name}${skill.description ? `\n> ${skill.description}` : ""}`;
const argsLine = extra ? `\n\nArguments: ${extra}` : "";
const payload = `${header}\n\n${skill.body}${argsLine}`;
return {
info: `▸ running skill: ${skill.name}${extra ? ` — ${extra}` : ""}`,
resubmit: payload,
};
}
/**
* `/memory` family. Bare `/memory` shows what's pinned (REASONIX.md +
* both MEMORY.md blocks). Subcommands manage the user-memory store:
* list — every memory file, both scopes
* show <name> — dump one file's body
* show <scope>/<name> — disambiguate when name exists in both scopes
* forget <name> — delete (same scope resolution as show)
* clear <scope> confirm — wipe a scope (typed literal "confirm" required)
*/
function handleMemorySlash(args: string[], ctx: SlashContext): SlashResult {
if (!memoryEnabled()) {
return {
info: "memory is disabled (REASONIX_MEMORY=off in env). Unset the var to re-enable — no REASONIX.md or ~/.reasonix/memory content will be pinned in the meantime.",
};
}
if (!ctx.memoryRoot) {
return {
info: "no working directory on this session — `/memory` needs a root to resolve REASONIX.md from. (Running in a test harness?)",
};
}
// `codeRoot` is set only when running `reasonix code`. Chat mode has
// `memoryRoot` = cwd (for REASONIX.md), but we don't treat cwd as a
// sandbox — project-scope user memory requires a real code-mode root.
const store = new MemoryStore({ projectRoot: ctx.codeRoot });
const sub = (args[0] ?? "").toLowerCase();
if (sub === "list" || sub === "ls") {
const entries = store.list();
if (entries.length === 0) {
return {
info: "no user memories yet. The model can call `remember` to save one, or you can create files by hand in ~/.reasonix/memory/global/ or the per-project subdir.",
};
}
const lines = [`User memories (${entries.length}):`];
for (const e of entries) {
const tag = `${e.scope}/${e.type}`.padEnd(18);
const name = e.name.padEnd(28);
const desc = e.description.length > 70 ? `${e.description.slice(0, 69)}…` : e.description;
lines.push(` ${tag} ${name} ${desc}`);
}
lines.push("");
lines.push("View body: /memory show <name> Delete: /memory forget <name>");
return { info: lines.join("\n") };
}
if (sub === "show" || sub === "cat") {
const target = args[1];
if (!target) return { info: "usage: /memory show <name> or /memory show <scope>/<name>" };
const resolved = resolveMemoryTarget(store, target);
if (!resolved) return { info: `no memory found: ${target}` };
try {
const entry = store.read(resolved.scope, resolved.name);
return {
info: [
`▸ ${entry.scope}/${entry.name} (${entry.type}, created ${entry.createdAt || "?"})`,
entry.description ? ` ${entry.description}` : "",
"",
entry.body,
]
.filter((l) => l !== "")
.concat("")
.join("\n"),
};
} catch (err) {
return { info: `show failed: ${(err as Error).message}` };
}
}
if (sub === "forget" || sub === "rm" || sub === "delete") {
const target = args[1];
if (!target) return { info: "usage: /memory forget <name> or /memory forget <scope>/<name>" };
const resolved = resolveMemoryTarget(store, target);
if (!resolved) return { info: `no memory found: ${target}` };
try {
const ok = store.delete(resolved.scope, resolved.name);
return {
info: ok
? `▸ forgot ${resolved.scope}/${resolved.name}. Next /new or launch won't see it.`
: `could not forget ${resolved.scope}/${resolved.name} (already gone?)`,
};
} catch (err) {
return { info: `forget failed: ${(err as Error).message}` };
}
}
if (sub === "clear") {
const rawScope = (args[1] ?? "").toLowerCase();
if (rawScope !== "global" && rawScope !== "project") {
return { info: "usage: /memory clear <global|project> confirm" };
}
if ((args[2] ?? "").toLowerCase() !== "confirm") {
return {
info: `about to delete every memory in scope=${rawScope}. Re-run with the word 'confirm' to proceed: /memory clear ${rawScope} confirm`,
};
}
const scope = rawScope as MemoryScope;
const entries = store.list().filter((e) => e.scope === scope);
let deleted = 0;
for (const e of entries) {
try {
if (store.delete(scope, e.name)) deleted++;
} catch {
/* skip */
}
}
return { info: `▸ cleared scope=${scope} — deleted ${deleted} memory file(s).` };
}
// Bare `/memory` — show REASONIX.md + both MEMORY.md blocks.
const parts: string[] = [];
const projMem = readProjectMemory(ctx.memoryRoot);
if (projMem) {
const hdr = projMem.truncated
? `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars, truncated)`
: `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars)`;
parts.push(hdr, "", projMem.content);
}
const globalIdx = store.loadIndex("global");
if (globalIdx) {
parts.push(
"",
`▸ global memory (${globalIdx.originalChars.toLocaleString()} chars${globalIdx.truncated ? ", truncated" : ""})`,
"",
globalIdx.content,
);
}
const projectIdx = store.loadIndex("project");
if (projectIdx) {
parts.push(
"",
`▸ project memory (${projectIdx.originalChars.toLocaleString()} chars${projectIdx.truncated ? ", truncated" : ""})`,
"",
projectIdx.content,
);
}
if (parts.length === 0) {
return {
info: [
`no memory pinned in ${ctx.memoryRoot}.`,
"",
"Three layers are available:",
` 1. ${PROJECT_MEMORY_FILE} — committable team memory (in the repo).`,
" 2. ~/.reasonix/memory/global/ — your cross-project private memory.",
` 3. ~/.reasonix/memory/<project-hash>/ — this project's private memory.`,
"",
"Ask the model to `remember` something, or hand-edit files directly.",
"Changes take effect on next /new or launch — the system prompt is hashed once per session to keep the prefix cache warm.",
"",
"Subcommands: /memory list | /memory show <name> | /memory forget <name> | /memory clear <scope> confirm",
].join("\n"),
};
}
parts.push(
"",
"Changes take effect on next /new or launch. Subcommands: /memory list | show | forget | clear",
);
return { info: parts.join("\n") };
}
/**
* Parse a `/memory show|forget` argument. Accepts bare `<name>` or
* `<scope>/<name>`. For bare names, tries project scope first (more
* specific, usually what the user means) then falls back to global.
*/
function resolveMemoryTarget(
store: MemoryStore,
raw: string,
): { scope: MemoryScope; name: string } | null {
const slash = raw.indexOf("/");
if (slash > 0) {
const scopeRaw = raw.slice(0, slash).toLowerCase();
const name = raw.slice(slash + 1);
if (scopeRaw !== "global" && scopeRaw !== "project") return null;
const scope = scopeRaw as MemoryScope;
if (scope === "project" && !store.hasProjectScope()) return null;
return { scope, name };
}
for (const scope of ["project", "global"] as MemoryScope[]) {
if (scope === "project" && !store.hasProjectScope()) continue;
try {
store.read(scope, raw);
return { scope, name: raw };
} catch {
/* next scope */
}
}
return null;
}
/**
* Render a section (resources / prompts) of an MCP inspection into a
* compact "name count items" form, collapsing when unsupported.
+77 -6
View File
@@ -15,10 +15,69 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { applyProjectMemory } from "../project-memory.js";
import { applyMemoryStack } from "../user-memory.js";
export const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, list_directory, search_files, etc.) rooted at the user's working directory.
# Cite or shut up — non-negotiable
Every factual claim you make about THIS codebase must be backed by evidence. Reasonix VALIDATES the citations you write — broken paths or out-of-range lines render in **red strikethrough with ❌** in front of the user.
**Positive claims** (a file exists, a function does X, a feature IS implemented) — append a markdown link to the source:
- ✅ Correct: \`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\`
- ❌ Wrong: \`The MCP client supports listResources.\` ← no citation, looks authoritative but unverifiable.
**Negative claims** (X is missing, Y is not implemented, lacks Z, doesn't have W) are the **most common hallucination shape**. They feel safe to write because no citation seems possible — but that's exactly why you must NOT write them on instinct.
If you are about to write "X is missing" or "Y is not implemented" — **STOP**. Call \`search_content\` for the relevant symbol or term FIRST. Only then:
- If the search returns matches → you were wrong; correct yourself and cite the matches.
- If the search returns nothing → state the absence with the search query as your evidence: \`No callers of \\\`foo()\\\` found (search_content "foo").\`
Asserting absence without a search is the #1 way evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.
# When to propose a plan (submit_plan)
You have a \`submit_plan\` tool that shows the user a markdown plan and lets them Approve / Refine / Cancel before you execute. Use it proactively when the task is large enough to deserve a review gate:
- Multi-file refactors or renames.
- Architecture changes (moving modules, splitting / merging files, new abstractions).
- Anything where "undo" after the fact would be expensive — migrations, destructive cleanups, API shape changes.
- When the user's request is ambiguous and multiple reasonable interpretations exist — propose your reading as a plan and let them confirm.
Skip submit_plan for small, obvious changes: one-line typo, clear bug with a clear fix, adding a missing import, renaming a local variable. Just do those.
Plan body: one-sentence summary, then a file-by-file breakdown of what you'll change and why, and any risks or open questions. If some decisions are genuinely up to the user (naming, tradeoffs, out-of-scope possibilities), list them in an "Open questions" section — the user sees the plan in a picker and has a text input to answer your questions before approving. Don't pretend certainty you don't have; flagged questions are how the user tells you what they care about. After calling submit_plan, STOP — don't call any more tools, wait for the user's verdict.
# Plan mode (/plan)
The user can ALSO enter "plan mode" via /plan, which is a stronger, explicit constraint:
- Write tools (edit_file, write_file, create_directory, move_file) and non-allowlisted run_command calls are BOUNCED at dispatch — you'll get a tool result like "unavailable in plan mode". Don't retry them.
- Read tools (read_file, list_directory, search_files, directory_tree, get_file_info) and allowlisted read-only / test shell commands still work — use them to investigate.
- You MUST call submit_plan before anything will execute. Approve exits plan mode; Refine stays in; Cancel exits without implementing.
# Delegating to subagents via Skills (🧬)
The pinned Skills index below lists playbooks you can invoke with \`run_skill\`. Skills marked with **🧬** spawn an **isolated subagent** — a fresh child loop that runs the playbook in its own context and returns only the final answer. The subagent's tool calls and reasoning never enter your context, so 🧬 skills are how you keep the main session lean.
Two built-ins ship by default:
- **🧬 explore** — read-only investigation across the codebase. Use when the user says things like "find all places that...", "how does X work across the project", "survey the code for Y". Pass \`arguments\` describing the concrete question.
- **🧬 research** — combines web search + code reading. Use for "is X supported by lib Y", "what's the canonical way to Z", "compare our impl to the spec".
When to delegate (call \`run_skill\` with a 🧬 skill):
- The task would otherwise need >5 file reads or searches.
- You only need the conclusion, not the exploration trail.
- The work is self-contained (you can describe it in one paragraph).
When NOT to delegate:
- Direct, narrow questions answerable in 1-2 tool calls — just do them.
- Anything where you need to track intermediate results yourself (planning, multi-step edits).
- Anything that requires user interaction (subagents can't submit plans or ask you for clarification).
Always pass a clear, self-contained \`arguments\` — that text is the **only** context the subagent gets.
# When to edit vs. when to explore
Only propose edits when the user explicitly asks you to change, fix, add, remove, refactor, or write something. Do NOT propose edits when the user asks you to:
@@ -53,16 +112,28 @@ Rules:
- Do NOT use write_file to change existing files — the user reviews your edits as SEARCH/REPLACE. write_file is only for files you explicitly want to overwrite wholesale (rare).
- Paths are relative to the working directory. Don't use absolute paths.
# Trust what you already know
Before exploring the filesystem to answer a factual question, check whether the answer is already in context: the user's current message, earlier turns in this conversation (including prior tool results from \`remember\`), and the pinned memory blocks at the top of this prompt. When the user has stated a fact or you have remembered one, it outranks what the files say — don't re-derive from code what the user already told you. Explore when you genuinely don't know.
# Exploration
- Avoid listing or reading inside these common dependency / build directories unless the user explicitly asks about them: node_modules, dist, build, out, .next, .nuxt, .svelte-kit, .git, .venv, venv, __pycache__, target, coverage, .turbo, .cache. They're expensive and usually irrelevant.
- Prefer search_files / grep over list_directory when you know roughly what you're looking for — it saves context and avoids enumerating huge trees.
- Skip dependency, build, and VCS directories unless the user explicitly asks. The pinned .gitignore block (if any, below) is your authoritative denylist.
- Prefer \`search_files\` over \`list_directory\` when you know roughly what you're looking for — it saves context and avoids enumerating huge trees. Note: \`search_files\` matches file NAMES; for searching file CONTENTS use \`search_content\`.
- Available exploration tools: \`read_file\`, \`list_directory\`, \`directory_tree\`, \`search_files\` (filename match), \`search_content\` (content grep — use for "where is X called", "find all references to Y"), \`get_file_info\`. Don't call \`grep\` or other tools that aren't in this list — they don't exist as functions.
# Path conventions
Two different rules depending on which tool:
- **Filesystem tools** (\`read_file\`, \`list_directory\`, \`search_files\`, \`edit_file\`, etc.): paths are sandbox-relative. \`/\` means the project root, \`/src/foo.ts\` means \`<project>/src/foo.ts\`. Both relative (\`src/foo.ts\`) and POSIX-absolute (\`/src/foo.ts\`) forms work.
- **\`run_command\`**: the command runs in a real OS shell with cwd pinned to the project root. Paths inside the shell command are interpreted by THAT shell, not by us. **Never use leading \`/\` in run_command arguments** — Windows treats \`/tests\` as drive-root \`F:\\tests\` (non-existent), POSIX shells treat it as filesystem root. Use plain relative paths (\`tests\`, \`./tests\`, \`src/loop.ts\`) instead.
# Style
- Show edits; don't narrate them in prose. "Here's the fix:" is enough.
- One short paragraph explaining *why*, then the blocks.
- If you need to explore first (list / grep / read), do it with tool calls before writing any prose — silence while exploring is fine.
- If you need to explore first (list / read / search), do it with tool calls before writing any prose — silence while exploring is fine.
`;
/**
@@ -72,10 +143,10 @@ Rules:
* don't eat context budget on huge generated ignore lists.
*
* Stacking order (stable for cache prefix):
* base prompt → project memory (REASONIX.md) → .gitignore block
* base prompt → REASONIX.md → global MEMORY.md → project MEMORY.md → .gitignore
*/
export function codeSystemPrompt(rootDir: string): string {
const withMemory = applyProjectMemory(CODE_SYSTEM_PROMPT, rootDir);
const withMemory = applyMemoryStack(CODE_SYSTEM_PROMPT, rootDir);
const gitignorePath = join(rootDir, ".gitignore");
if (!existsSync(gitignorePath)) return withMemory;
let content: string;
+404
View File
@@ -0,0 +1,404 @@
/**
* Hooks — user-defined automation that fires at well-known points in
* the agent loop. Mirrors the two-scope layout we use for memory and
* skills:
*
* - `<project>/.reasonix/settings.json` — committable per-project
* - `~/.reasonix/settings.json` — every session
*
* A hook is a shell command. We invoke it with stdin = a JSON
* payload describing the event, and interpret the exit code:
*
* - `0` — pass; loop continues normally
* - `2` — block; for `PreToolUse` / `UserPromptSubmit` the
* loop refuses to continue with that step and surfaces the
* hook's stderr as the reason. For `PostToolUse` / `Stop` block
* is meaningless (the action already happened) — treat as warn.
* - anything else — warn; loop continues but stderr is rendered
* to the user as an inline notice.
*
* stdin JSON shape (one envelope per event):
*
* {
* "event": "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop",
* "cwd": "<absolute project root or process.cwd()>",
* "toolName": "<string>", // tool events only
* "toolArgs": <unknown>, // tool events only — already JSON-decoded
* "toolResult": "<string>", // PostToolUse only — same body the model sees
* "prompt": "<string>", // UserPromptSubmit only
* "lastAssistantText": "<string>", // Stop only
* "turn": <number>, // Stop only
* }
*
* Hooks are executed in order: project scope first, then global.
* `Pre*` events stop dispatching at the first block; non-block
* outcomes accumulate into a single report so the UI can render
* each warning inline.
*/
import { spawn } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
export type HookEvent = "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop";
/** All four events as a const array — drives slash listing + validation. */
export const HOOK_EVENTS: readonly HookEvent[] = [
"PreToolUse",
"PostToolUse",
"UserPromptSubmit",
"Stop",
] as const;
/** Only the gating events can block the loop. */
const BLOCKING_EVENTS: ReadonlySet<HookEvent> = new Set(["PreToolUse", "UserPromptSubmit"]);
/** Per-event default timeout. Tool/prompt hooks gate progress, so they're tight. */
const DEFAULT_TIMEOUTS_MS: Record<HookEvent, number> = {
PreToolUse: 5_000,
UserPromptSubmit: 5_000,
PostToolUse: 30_000,
Stop: 30_000,
};
export type HookScope = "project" | "global";
export interface HookConfig {
/**
* Tool-name pattern (PreToolUse / PostToolUse only). Anchored regex.
* Omitted or `"*"` matches every tool. Ignored for prompt / Stop
* events (they have no tool name to match against).
*/
match?: string;
/** Shell command to run. Spawned through the platform shell. */
command: string;
/** Optional human description — surfaced in `/hooks`. */
description?: string;
/** Per-hook timeout override in ms. */
timeout?: number;
/**
* Working directory for the spawned process. Defaults to:
* - project scope → the project root
* - global scope → process.cwd()
*/
cwd?: string;
}
/** Shape of `<scope>/.reasonix/settings.json` — only `hooks` for now. */
export interface HookSettings {
hooks?: Partial<Record<HookEvent, HookConfig[]>>;
}
/** A loaded hook with its origin scope baked in (used for ordering and `/hooks`). */
export interface ResolvedHook extends HookConfig {
event: HookEvent;
scope: HookScope;
/** Absolute path to the settings.json the hook came from. */
source: string;
}
/** Outcome of a single hook invocation. */
export interface HookOutcome {
/** Which hook fired. */
hook: ResolvedHook;
/**
* Decision:
* - `pass` — exit 0
* - `block` — exit 2 on a blocking event (otherwise downgraded to `warn`)
* - `warn` — non-zero exit that is not a successful block
* - `timeout` — the spawn was killed past `timeout`
* - `error` — could not spawn at all (missing command, etc.)
*/
decision: "pass" | "block" | "warn" | "timeout" | "error";
exitCode: number | null;
/** Captured stdout (trimmed). May be empty. */
stdout: string;
/** Captured stderr (trimmed). The block / warn message comes from here. */
stderr: string;
durationMs: number;
}
/** Aggregate report for `runHooks`. */
export interface HookReport {
event: HookEvent;
outcomes: HookOutcome[];
/** True iff at least one outcome was a `block` — only meaningful for blocking events. */
blocked: boolean;
}
export const HOOK_SETTINGS_FILENAME = "settings.json";
export const HOOK_SETTINGS_DIRNAME = ".reasonix";
/** Where the global settings.json lives. Equivalent to `~/.reasonix/settings.json`. */
export function globalSettingsPath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
}
/** Where the project settings.json lives for a given root. */
export function projectSettingsPath(projectRoot: string): string {
return join(projectRoot, HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
}
function readSettingsFile(path: string): HookSettings | null {
if (!existsSync(path)) return null;
try {
const raw = readFileSync(path, "utf8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") return parsed as HookSettings;
} catch {
/* malformed JSON → treat as no hooks; do NOT throw, the user
* shouldn't lose the whole CLI to a typo in their settings */
}
return null;
}
/**
* Pull every configured hook out of the project + global settings
* files, in the order they should fire (project first, global second,
* within each scope: array order from the file).
*
* Returns a flat list — the dispatcher filters by event + match
* pattern at run time. Loading is cheap (one or two JSON files), so
* we don't memoize across processes; re-load is allowed via
* `/hooks reload` and on every fresh App mount.
*/
export interface LoadHookSettingsOptions {
/** Absolute project root, if any. Without it, only global hooks load. */
projectRoot?: string;
/** Override `~` for tests. */
homeDir?: string;
}
export function loadHooks(opts: LoadHookSettingsOptions = {}): ResolvedHook[] {
const out: ResolvedHook[] = [];
if (opts.projectRoot) {
const projPath = projectSettingsPath(opts.projectRoot);
const settings = readSettingsFile(projPath);
if (settings) appendResolved(out, settings, "project", projPath);
}
const globalPath = globalSettingsPath(opts.homeDir);
const settings = readSettingsFile(globalPath);
if (settings) appendResolved(out, settings, "global", globalPath);
return out;
}
function appendResolved(
out: ResolvedHook[],
settings: HookSettings,
scope: HookScope,
source: string,
): void {
if (!settings.hooks) return;
for (const event of HOOK_EVENTS) {
const list = settings.hooks[event];
if (!Array.isArray(list)) continue;
for (const cfg of list) {
if (!cfg || typeof cfg.command !== "string" || cfg.command.trim() === "") continue;
out.push({ ...cfg, event, scope, source });
}
}
}
/**
* True if `toolName` matches the hook's `match` field. `"*"` and
* undefined match everything. Otherwise we anchor the field as a
* regex — partial-name matches don't fire, so `"file"` would not
* trigger on `read_file` (use `".*file"` for that).
*/
export function matchesTool(hook: ResolvedHook, toolName: string): boolean {
if (hook.event !== "PreToolUse" && hook.event !== "PostToolUse") return true;
const m = hook.match;
if (!m || m === "*") return true;
try {
const re = new RegExp(`^(?:${m})$`);
return re.test(toolName);
} catch {
/* malformed regex → don't fire (safer than firing on every tool) */
return false;
}
}
/** Payload envelope passed to hook stdin. */
export interface HookPayload {
event: HookEvent;
cwd: string;
toolName?: string;
toolArgs?: unknown;
toolResult?: string;
prompt?: string;
lastAssistantText?: string;
turn?: number;
}
/** Test seam — same shape as Node's spawn but returns a Promise of the raw outcome bits. */
export interface HookSpawnInput {
command: string;
cwd: string;
stdin: string;
timeoutMs: number;
}
export interface HookSpawnResult {
exitCode: number | null;
stdout: string;
stderr: string;
timedOut: boolean;
/** True iff spawn() itself failed (ENOENT, EACCES, …). */
spawnError?: Error;
}
export type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;
/**
* Default spawner — runs `command` through the platform shell so
* `&&`, pipes, env-var expansion all work without a tokenizer.
* Stdin is the JSON payload, stdout / stderr are buffered.
*
* Why `shell: true`? A hook is intentionally a shell command — that's
* the contract. Treating it like an argv array would surprise users
* who write `bun run check && eslint .` and expect it to behave the
* way it does in their terminal.
*/
function defaultSpawner(input: HookSpawnInput): Promise<HookSpawnResult> {
return new Promise<HookSpawnResult>((resolve) => {
const child = spawn(input.command, {
cwd: input.cwd,
shell: true,
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
// SIGTERM may not land on Windows for shell children — followed
// by a hard kill a moment later if the process is still around.
setTimeout(() => {
try {
child.kill("SIGKILL");
} catch {
/* already gone */
}
}, 500);
}, input.timeoutMs);
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf8");
});
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString("utf8");
});
child.once("error", (err) => {
clearTimeout(timer);
resolve({
exitCode: null,
stdout,
stderr,
timedOut: false,
spawnError: err,
});
});
child.once("close", (code) => {
clearTimeout(timer);
resolve({
exitCode: code,
stdout: stdout.trim(),
stderr: stderr.trim(),
timedOut,
});
});
try {
child.stdin.write(input.stdin);
child.stdin.end();
} catch {
/* stdin write can race with spawn errors; the close handler
* still fires with exit 0/null */
}
});
}
/**
* Format a hook outcome as a single-line UI string. Used by both the
* loop (for `warning` events) and the App (for UserPromptSubmit /
* Stop outcomes). Centralizing keeps the language consistent across
* scopes.
*/
export function formatHookOutcomeMessage(outcome: HookOutcome): string {
if (outcome.decision === "pass") return "";
const detail = (outcome.stderr || outcome.stdout || "").trim();
const tag = `${outcome.hook.scope}/${outcome.hook.event}`;
const cmd =
outcome.hook.command.length > 60
? `${outcome.hook.command.slice(0, 60)}…`
: outcome.hook.command;
const head = `hook ${tag} \`${cmd}\` ${outcome.decision}`;
return detail ? `${head}: ${detail}` : head;
}
/**
* Decide the hook's outcome decision from raw spawn results.
* Pulled out as a pure function so tests can pin the matrix.
*/
export function decideOutcome(
event: HookEvent,
raw: HookSpawnResult,
): "pass" | "block" | "warn" | "timeout" | "error" {
if (raw.spawnError) return "error";
if (raw.timedOut) return BLOCKING_EVENTS.has(event) ? "block" : "warn";
if (raw.exitCode === 0) return "pass";
if (raw.exitCode === 2 && BLOCKING_EVENTS.has(event)) return "block";
return "warn";
}
export interface RunHooksOptions {
payload: HookPayload;
hooks: ResolvedHook[];
/** Test seam — defaults to a real `spawn`. */
spawner?: HookSpawner;
}
/**
* Filter hooks down to the ones that match `payload.event` (and
* `payload.toolName`, for tool events), then run them in order.
* Stops at the first `block` outcome on a blocking event so a
* gating hook can prevent later hooks from incorrectly seeing a
* success that wasn't going to happen.
*/
export async function runHooks(opts: RunHooksOptions): Promise<HookReport> {
const spawner = opts.spawner ?? defaultSpawner;
const event = opts.payload.event;
const toolName = opts.payload.toolName ?? "";
const matching = opts.hooks.filter((h) => h.event === event && matchesTool(h, toolName));
const outcomes: HookOutcome[] = [];
let blocked = false;
const stdin = `${JSON.stringify(opts.payload)}\n`;
for (const hook of matching) {
const start = Date.now();
const timeoutMs = hook.timeout ?? DEFAULT_TIMEOUTS_MS[event];
const cwd = hook.cwd ?? opts.payload.cwd;
const raw = await spawner({ command: hook.command, cwd, stdin, timeoutMs });
const decision = decideOutcome(event, raw);
outcomes.push({
hook,
decision,
exitCode: raw.exitCode,
stdout: raw.stdout,
stderr:
raw.stderr ||
(raw.spawnError ? raw.spawnError.message : "") ||
(raw.timedOut ? `hook timed out after ${timeoutMs}ms` : ""),
durationMs: Date.now() - start,
});
if (decision === "block") {
blocked = true;
break;
}
}
return { event, outcomes, blocked };
}
+86 -1
View File
@@ -38,17 +38,50 @@ export {
} from "./project-memory.js";
export type { ProjectMemory } from "./project-memory.js";
export {
MEMORY_INDEX_FILE,
MEMORY_INDEX_MAX_CHARS,
MemoryStore,
USER_MEMORY_DIR,
applyMemoryStack,
applyUserMemory,
projectHash,
sanitizeMemoryName,
} from "./user-memory.js";
export type {
MemoryEntry,
MemoryScope,
MemoryStoreOptions,
MemoryType,
WriteInput as MemoryWriteInput,
} from "./user-memory.js";
export { ToolRegistry } from "./tools.js";
export type { ToolDefinition, ToolCallContext } from "./tools.js";
export { registerFilesystemTools } from "./tools/filesystem.js";
export type { FilesystemToolsOptions } from "./tools/filesystem.js";
export { registerMemoryTools } from "./tools/memory.js";
export type { MemoryToolsOptions } from "./tools/memory.js";
export { PlanProposedError, registerPlanTool } from "./tools/plan.js";
export type { PlanToolOptions } from "./tools/plan.js";
export { forkRegistryExcluding, registerSubagentTool } from "./tools/subagent.js";
export type {
SubagentEvent,
SubagentSink,
SubagentToolOptions,
} from "./tools/subagent.js";
export {
NeedsConfirmationError,
formatCommandResult,
injectPowerShellUtf8,
isAllowed,
prepareSpawn,
quoteForCmdExe,
registerShellTools,
resolveExecutable,
runCommand,
tokenizeCommand,
withUtf8Codepage,
} from "./tools/shell.js";
export type { RunCommandResult, ShellToolsOptions } from "./tools/shell.js";
export {
@@ -219,4 +252,56 @@ export type {
JSONSchema,
} from "./types.js";
export const VERSION = "0.4.17";
export {
LATEST_CACHE_TTL_MS,
LATEST_FETCH_TIMEOUT_MS,
VERSION,
compareVersions,
getLatestVersion,
isNpxInstall,
} from "./version.js";
export type { GetLatestVersionOptions } from "./version.js";
export {
HOOK_EVENTS,
HOOK_SETTINGS_DIRNAME,
HOOK_SETTINGS_FILENAME,
decideOutcome,
formatHookOutcomeMessage,
globalSettingsPath,
loadHooks,
matchesTool,
projectSettingsPath,
runHooks,
} from "./hooks.js";
export {
aggregateUsage,
appendUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
defaultUsageLogPath,
formatLogSize,
readUsageLog,
} from "./usage.js";
export type {
AggregateOptions,
AppendUsageInput,
UsageAggregate,
UsageBucket,
UsageRecord,
} from "./usage.js";
export type {
HookConfig,
HookEvent,
HookOutcome,
HookPayload,
HookReport,
HookScope,
HookSettings,
HookSpawner,
HookSpawnInput,
HookSpawnResult,
LoadHookSettingsOptions,
ResolvedHook,
RunHooksOptions,
} from "./hooks.js";
+139 -1
View File
@@ -6,6 +6,13 @@ import {
runBranches,
} from "./consistency.js";
import { type HarvestOptions, type TypedPlanState, emptyPlanState, harvest } from "./harvest.js";
import {
type HookOutcome,
type HookPayload,
type ResolvedHook,
formatHookOutcomeMessage,
runHooks,
} from "./hooks.js";
import { DEFAULT_MAX_RESULT_CHARS, truncateForModel } from "./mcp/registry.js";
import { AppendOnlyLog, type ImmutablePrefix, VolatileScratch } from "./memory.js";
import { type RepairReport, ToolCallRepair } from "./repair/index.js";
@@ -127,6 +134,21 @@ export interface CacheFirstLoopOptions {
* `~/.reasonix/sessions/<name>.jsonl` so the next run can resume.
*/
session?: string;
/**
* Resolved hook list — loaded from `<project>/.reasonix/settings.json`
* + `~/.reasonix/settings.json` by the CLI before constructing the loop.
* The loop dispatches `PreToolUse` and `PostToolUse` events itself; the
* CLI handles `UserPromptSubmit` and `Stop` since they live at the App
* boundary. Empty / unset → no hooks fire (the runtime cost of an empty
* filter is one ms). See `src/hooks.ts` for the full contract.
*/
hooks?: ResolvedHook[];
/**
* `cwd` reported to hooks via the stdin payload. Defaults to `process.cwd()`.
* `reasonix code` overrides this to the sandbox root so a hook that does
* `cd $REASONIX_CWD` lands in the project, not in the user's shell home.
*/
hookCwd?: string;
}
/**
@@ -165,6 +187,15 @@ export class CacheFirstLoop {
branchOptions: BranchOptions;
sessionName: string | null;
/**
* Hook list, mutable so `/hooks reload` can swap it without
* reconstructing the loop. Default empty — the filter cost on a
* tool call is one array length check.
*/
hooks: ResolvedHook[];
/** `cwd` reported to hook stdin. Resolved once at construction. */
readonly hookCwd: string;
/** Number of messages that were pre-loaded from the session file. */
readonly resumedMessageCount: number;
@@ -194,6 +225,8 @@ export class CacheFirstLoop {
// the decision, keep the iter cap as a last-resort backstop for
// the case where something spins without growing the prompt.
this.maxToolIters = opts.maxToolIters ?? 64;
this.hooks = opts.hooks ?? [];
this.hookCwd = opts.hookCwd ?? process.cwd();
// Resolve branch config first (since it forces harvest on).
if (typeof opts.branch === "number") {
@@ -438,6 +471,11 @@ export class CacheFirstLoop {
async *step(userInput: string): AsyncGenerator<LoopEvent> {
this._turn++;
this.scratch.reset();
// A fresh user turn is a new intent — don't let StormBreaker's
// old sliding window of (name, args) signatures keep blocking
// calls that are now legitimately on-task. The window repopulates
// naturally as this turn's tool calls flow through.
this.repair.resetStorm();
// Fresh controller for this turn: the prior step's signal has
// already fired (or stayed clean); either way we don't want its
// state to bleed into the new turn.
@@ -674,6 +712,20 @@ export class CacheFirstLoop {
usage = resp.usage;
}
} catch (err) {
// An aborted signal here is almost always our own doing —
// either Esc, or App.tsx calling `loop.abort()` to switch to a
// queued synthetic input (ShellConfirm "always allow", PlanConfirm
// approve, etc.). The DeepSeek client's fetch path translates
// the abort into a generic `AbortError("This operation was
// aborted")`, which used to bubble up here and render as a
// scary red "error" row even though nothing actually broke.
// Treat it as a clean early-exit instead: the next turn (queued
// synthetic OR user re-prompt) starts immediately and gets to
// produce its own answer.
if (signal.aborted) {
yield { turn: this._turn, role: "done", content: "" };
return;
}
yield {
turn: this._turn,
role: "error",
@@ -731,6 +783,25 @@ export class CacheFirstLoop {
branch: branchSummary,
};
// Loud signal when the storm breaker caught a repeat pattern.
// The `repair` field on assistant_final already carries the
// count as a subtext on the assistant row, but a dedicated
// warning row is far more noticeable — and critical when ALL
// calls were suppressed, because the turn then ends with no
// visible explanation of why nothing happened.
if (report.stormsBroken > 0) {
const noteTail = report.notes.length ? ` — ${report.notes[report.notes.length - 1]}` : "";
const allSuppressed = repairedCalls.length === 0 && toolCalls.length > 0;
const phrase = allSuppressed
? `stopped the model from calling the same tool with identical args repeatedly (all ${toolCalls.length} call(s) this turn were already in the recent-repeat window). Likely a stuck retry — reword your instruction, rule out the underlying blocker, or try /retry after fixing it`
: `suppressed ${report.stormsBroken} repeat tool call(s) that had fired 3+ times with identical args in a sliding window`;
yield {
turn: this._turn,
role: "warning",
content: `${phrase}${noteTail}`,
};
}
if (repairedCalls.length === 0) {
yield { turn: this._turn, role: "done", content: assistantContent };
return;
@@ -822,7 +893,52 @@ export class CacheFirstLoop {
toolName: name,
toolArgs: args,
};
const result = await this.tools.dispatch(name, args, { signal });
// PreToolUse hooks. A `block` decision (exit 2) skips dispatch
// and surfaces the hook's stderr as the tool result so the model
// sees a structured refusal instead of a silent omission. Non-
// block non-zero outcomes are warnings: the loop continues, the
// UI gets a yellow row.
const parsedArgs = safeParseToolArgs(args);
const preReport = await runHooks({
hooks: this.hooks,
payload: {
event: "PreToolUse",
cwd: this.hookCwd,
toolName: name,
toolArgs: parsedArgs,
},
});
for (const w of hookWarnings(preReport.outcomes, this._turn)) yield w;
let result: string;
if (preReport.blocked) {
const blocking = preReport.outcomes[preReport.outcomes.length - 1];
const reason = (
blocking?.stderr ||
blocking?.stdout ||
"blocked by PreToolUse hook"
).trim();
result = `[hook block] ${blocking?.hook.command ?? "<unknown>"}\n${reason}`;
} else {
result = await this.tools.dispatch(name, args, { signal });
// PostToolUse hooks — block is meaningless after the fact, so
// every non-pass outcome is a warning. Hooks here are the
// natural place for "after every edit, run the formatter."
const postReport = await runHooks({
hooks: this.hooks,
payload: {
event: "PostToolUse",
cwd: this.hookCwd,
toolName: name,
toolArgs: parsedArgs,
toolResult: result,
},
});
for (const w of hookWarnings(postReport.outcomes, this._turn)) yield w;
}
this.appendAndPersist({
role: "tool",
tool_call_id: call.id ?? "",
@@ -948,6 +1064,28 @@ export function stripHallucinatedToolMarkup(s: string): string {
return out.trim();
}
/**
* Try to JSON-decode the model's tool-call arguments so PreToolUse /
* PostToolUse hooks get a structured object instead of a string.
* Falls back to the raw string when the model emits malformed JSON
* (the loop's own dispatch already tolerates that — keep parity).
*/
function safeParseToolArgs(raw: string): unknown {
try {
return JSON.parse(raw);
} catch {
return raw;
}
}
/** Format non-pass hook outcomes as `LoopEvent`s of role `warning`. */
function* hookWarnings(outcomes: HookOutcome[], turn: number): Generator<LoopEvent> {
for (const o of outcomes) {
if (o.decision === "pass") continue;
yield { turn, role: "warning", content: formatHookOutcomeMessage(o) };
}
}
function reasonPrefixFor(reason: "budget" | "aborted" | "context-guard", iterCap: number): string {
if (reason === "aborted") return "[aborted by user (Esc) — summarizing what I found so far]";
if (reason === "context-guard") {
+11
View File
@@ -46,6 +46,17 @@ export class ToolCallRepair {
this.storm = new StormBreaker(opts.stormWindow ?? 6, opts.stormThreshold ?? 3);
}
/**
* Drop the StormBreaker's sliding window of recent (name, args)
* signatures. Called at the start of every user turn — a fresh user
* message is a new intent, so carrying old repetition state into it
* would turn a valid "try again with different input" flow into a
* false-positive block.
*/
resetStorm(): void {
this.storm.reset();
}
process(
declaredCalls: ToolCall[],
reasoningContent: string | null,
+397
View File
@@ -0,0 +1,397 @@
/**
* Skills — user-defined prompt packs pinned (by name) into the
* immutable prefix and loaded (by body) on demand.
*
* Two scopes mirror the user-memory layout:
* - `project` → `<projectRoot>/.reasonix/skills/` (this repo only)
* - `global` → `~/.reasonix/skills/` (every session)
*
* Project scope wins on a name collision. Deliberately NOT tied to
* any specific client's directory convention (`.claude/`, `.glm/`,
* etc.) — Reasonix is model-agnostic at the conversation layer, so
* coupling the skill filesystem to one vendor would break any user
* running a different backend.
*
* Accepted file layouts (both emit the same `Skill`):
* - `{dir}/<name>/SKILL.md` (preferred — lets a skill bundle
* additional assets alongside)
* - `{dir}/<name>.md` (flat, one-file shorthand)
*
* Frontmatter keys we read:
* - `name` — optional, defaults to the file / dir name
* - `description` — one-line index description (REQUIRED for listing)
* - `allowed-tools` — parsed but UNUSED in v1 (see tools/skills.ts)
*
* Cache-First contract (Pillar 1):
* - The PREFIX sees only names + descriptions (one line each).
* - Bodies enter the APPEND-ONLY LOG lazily, via `run_skill` or
* `/skill <name>` — never the prefix. That keeps the prefix hash
* stable across skill additions to the body store.
*/
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
export const SKILLS_DIRNAME = "skills";
export const SKILL_FILE = "SKILL.md";
/** Cap on the pinned skills-index block, mirrors memory-index cap. */
export const SKILLS_INDEX_MAX_CHARS = 4000;
/** Skill identifier shape — alnum + `_` + `-` + interior `.`, 1-64 chars. */
const VALID_SKILL_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
export type SkillScope = "project" | "global" | "builtin";
/**
* Execution mode for a skill. `inline` (default) returns the body as a
* tool result so the body enters the parent's append-only log — the
* model continues the loop using the loaded instructions. `subagent`
* spawns an isolated child loop with the body as the system prompt and
* the user-supplied `arguments` as the task; only the child's final
* answer comes back. Use `subagent` for big-context exploration / research
* playbooks where the parent doesn't need to see the trail.
*/
export type SkillRunAs = "inline" | "subagent";
export interface Skill {
/** Canonical name — sanitized, matches the directory / filename stem. */
name: string;
/** One-line description shown in the pinned index. */
description: string;
/** Full markdown body (post-frontmatter). Loaded on demand. */
body: string;
/** Which scope this skill was loaded from. */
scope: SkillScope;
/** Absolute path to the SKILL.md (or {name}.md) file, or "(builtin)" for shipped defaults. */
path: string;
/** Raw `allowed-tools` field from frontmatter, if any. Unused in v1. */
allowedTools?: string;
/**
* Execution mode (frontmatter `runAs`). Defaults to `inline` for
* backwards compatibility with skills written before this field
* existed.
*/
runAs: SkillRunAs;
/**
* Frontmatter `model` — when set, overrides the default model the
* subagent runs on. Only meaningful when `runAs === "subagent"`.
* Accept any DeepSeek model id; the subagent layer falls back to its
* own default if this is missing or invalid.
*/
model?: string;
}
export interface SkillStoreOptions {
/** Override `$HOME` — tests point this at a tmpdir. */
homeDir?: string;
/**
* Absolute project root. Required to surface project-scope skills;
* omit (e.g. in `reasonix chat` without `code`) and the store only
* reads the global scope.
*/
projectRoot?: string;
/**
* Suppress the bundled built-in skills (`explore`, `research`).
* Used by unit tests that want to assert exact list contents
* without the +2 builtins distorting counts. Production callers
* leave this off so users always get the bundled defaults.
*/
disableBuiltins?: boolean;
}
/**
* Parse a `---` frontmatter block. Same minimal shape as user-memory:
* `key: value` lines, no quoting, no nesting. Returns `{}` data and the
* full input as body when no frontmatter fence is present — so hand-
* written files without frontmatter still surface (with empty desc).
*/
function parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {
const lines = raw.split(/\r?\n/);
if (lines[0] !== "---") return { data: {}, body: raw };
const end = lines.indexOf("---", 1);
if (end < 0) return { data: {}, body: raw };
const data: Record<string, string> = {};
for (let i = 1; i < end; i++) {
const line = lines[i];
if (!line) continue;
const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$/);
if (m?.[1]) data[m[1]] = (m[2] ?? "").trim();
}
return {
data,
body: lines
.slice(end + 1)
.join("\n")
.replace(/^\n+/, ""),
};
}
function isValidSkillName(name: string): boolean {
return VALID_SKILL_NAME.test(name);
}
export class SkillStore {
private readonly homeDir: string;
private readonly projectRoot: string | undefined;
private readonly disableBuiltins: boolean;
constructor(opts: SkillStoreOptions = {}) {
this.homeDir = opts.homeDir ?? homedir();
this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;
this.disableBuiltins = opts.disableBuiltins === true;
}
/** True iff this store was configured with a project root. */
hasProjectScope(): boolean {
return this.projectRoot !== undefined;
}
/**
* Root directories scanned, in priority order. Project scope first
* so a per-repo skill overrides a global one with the same name —
* users expect the local copy to win when both exist.
*/
roots(): Array<{ dir: string; scope: SkillScope }> {
const out: Array<{ dir: string; scope: SkillScope }> = [];
if (this.projectRoot) {
out.push({
dir: join(this.projectRoot, ".reasonix", SKILLS_DIRNAME),
scope: "project",
});
}
out.push({ dir: join(this.homeDir, ".reasonix", SKILLS_DIRNAME), scope: "global" });
return out;
}
/**
* List every skill visible to this store. On name collisions the
* higher-priority root (project over global over builtin) wins.
* Sorted by name for stable prefix hashing.
*/
list(): Skill[] {
const byName = new Map<string, Skill>();
for (const { dir, scope } of this.roots()) {
if (!existsSync(dir)) continue;
let entries: import("node:fs").Dirent[];
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
const skill = this.readEntry(dir, scope, entry);
if (!skill) continue;
if (!byName.has(skill.name)) byName.set(skill.name, skill);
}
}
// Builtins are appended last so user/project files take precedence
// when names collide. The same priority you'd expect: my-project's
// "explore" overrides the shipped one without forcing a different
// name.
if (!this.disableBuiltins) {
for (const skill of BUILTIN_SKILLS) {
if (!byName.has(skill.name)) byName.set(skill.name, skill);
}
}
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
}
/** Resolve one skill by name. Returns `null` if not found or malformed. */
read(name: string): Skill | null {
if (!isValidSkillName(name)) return null;
for (const { dir, scope } of this.roots()) {
if (!existsSync(dir)) continue;
const dirCandidate = join(dir, name, SKILL_FILE);
if (existsSync(dirCandidate) && statSync(dirCandidate).isFile()) {
return this.parse(dirCandidate, name, scope);
}
const flatCandidate = join(dir, `${name}.md`);
if (existsSync(flatCandidate) && statSync(flatCandidate).isFile()) {
return this.parse(flatCandidate, name, scope);
}
}
// Fall back to builtins. Same precedence as `list()` — user-authored
// wins, builtins are the floor.
if (!this.disableBuiltins) {
for (const skill of BUILTIN_SKILLS) {
if (skill.name === name) return skill;
}
}
return null;
}
private readEntry(dir: string, scope: SkillScope, entry: import("node:fs").Dirent): Skill | null {
if (entry.isDirectory()) {
if (!isValidSkillName(entry.name)) return null;
const file = join(dir, entry.name, SKILL_FILE);
if (!existsSync(file)) return null;
return this.parse(file, entry.name, scope);
}
if (entry.isFile() && entry.name.endsWith(".md")) {
const stem = entry.name.slice(0, -3);
if (!isValidSkillName(stem)) return null;
return this.parse(join(dir, entry.name), stem, scope);
}
return null;
}
private parse(path: string, stem: string, scope: SkillScope): Skill | null {
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return null;
}
const { data, body } = parseFrontmatter(raw);
const name = data.name && isValidSkillName(data.name) ? data.name : stem;
return {
name,
description: (data.description ?? "").trim(),
body: body.trim(),
scope,
path,
allowedTools: data["allowed-tools"],
runAs: parseRunAs(data.runAs),
model: data.model?.startsWith("deepseek-") ? data.model : undefined,
};
}
}
/**
* Coerce a frontmatter `runAs` string to the discriminated union. Any
* value other than the literal "subagent" is treated as inline — typos
* and unknown values default to the safe (non-spawning) mode rather
* than failing the load.
*/
function parseRunAs(raw: string | undefined): SkillRunAs {
return raw?.trim() === "subagent" ? "subagent" : "inline";
}
/**
* Build a single index line for one skill. Shape mirrors memory's
* `indexLine` — a bullet suitable for a markdown fenced block in the
* system prompt. Description is truncated to keep the full line under
* ~150 chars. Subagent-runAs skills carry a 🧬 marker so the model
* sees at a glance which skills will spawn an isolated child loop.
*/
function skillIndexLine(s: Pick<Skill, "name" | "description" | "runAs">): string {
const safeDesc = s.description.replace(/\n/g, " ").trim();
const marker = s.runAs === "subagent" ? "🧬 " : "";
const max = 130 - s.name.length - marker.length;
const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;
return clipped ? `- ${marker}${s.name} — ${clipped}` : `- ${marker}${s.name}`;
}
/**
* Append a `# Skills` block to `basePrompt` listing every discovered
* skill (name + description only). Bodies are NOT inlined — that's the
* whole point: the prefix stays short and cacheable; full content loads
* on demand via `run_skill` or `/skill <name>`.
*
* Emits nothing when no skills are discovered — keeps the prefix hash
* stable for users who don't use skills at all.
*/
export function applySkillsIndex(basePrompt: string, opts: SkillStoreOptions = {}): string {
const store = new SkillStore(opts);
const skills = store.list().filter((s) => s.description);
if (skills.length === 0) return basePrompt;
const lines = skills.map(skillIndexLine);
const joined = lines.join("\n");
const truncated =
joined.length > SKILLS_INDEX_MAX_CHARS
? `${joined.slice(0, SKILLS_INDEX_MAX_CHARS)}\n… (truncated ${
joined.length - SKILLS_INDEX_MAX_CHARS
} chars)`
: joined;
return [
basePrompt,
"",
"# Skills — playbooks you can invoke",
"",
'One-liner index. Each entry is either a built-in or a user-authored playbook. Call `run_skill({ name: "<skill-name>", arguments: "<task>" })` to invoke one. Skills marked with 🧬 spawn an **isolated subagent** — its tool calls and reasoning never enter your context, only its final answer does. Use 🧬 skills for tasks that would otherwise flood your context (deep exploration, multi-step research, anything where you only need the conclusion). Plain skills are inlined: their body becomes a tool result you read and act on directly. The user can also invoke a skill via `/skill <name>`.',
"",
"```",
truncated,
"```",
].join("\n");
}
/**
* Built-in skills shipped with Reasonix. These are always available
* (no install step) and live as constants rather than files because:
* - Zero filesystem coupling — no copy-on-first-run dance, nothing
* to migrate when we update them.
* - They participate in the same `byName` priority as user/project
* skills: write `~/.reasonix/skills/explore.md` to override.
*
* Keep this list small and high-leverage. The bar for adding one: it
* demonstrates a pattern users would otherwise have to invent
* themselves, and the body fits in a screen.
*/
const BUILTIN_EXPLORE_BODY = `You are running as an exploration subagent. Your job is to investigate the codebase the parent agent pointed you at, then return one focused, distilled answer.
How to operate:
- Use read_file, search_files, search_content, directory_tree, list_directory, get_file_info as your primary tools. Stay read-only.
- For "find all places that call / reference / use X" questions, use \`search_content\` (content grep) — NOT \`search_files\` (which only matches file names). This is the most common subagent mistake; using the wrong tool gives empty results and you waste your iter budget chasing a phantom.
- Cast a wide net first (search_content for symbol references, directory_tree for structure) to map the territory; then read the 3-10 most relevant files in full.
- Don't read every file — be selective. Aim for breadth on the first pass, depth only where the question demands it.
- Stop exploring as soon as you can answer the question. The parent doesn't see your tool calls, so over-exploration is pure waste.
Your final answer:
- One paragraph (or a few short bullets). Lead with the conclusion.
- Cite specific file paths + line ranges when they support the answer.
- If the question can't be answered from what you found, say so plainly and suggest where to look next.
- No follow-up offers, no "let me know if you need more." The parent will ask again if they need more.
Formatting (rendered in a TUI):
- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\`| col | col |\` + \`| --- | --- |\`). Never use Unicode box-drawing characters (│ ─ ┼) — they break word-wrap.
- Keep table cells short; if a cell needs a paragraph, use bullets below the table instead.
- Code, file paths with line ranges, and shell commands → fenced code blocks (\`\`\`).
- NEVER draw decorative frames around code or text with \`┌──┐ │ └──┘\` box-drawing characters. Use plain code blocks; the renderer adds its own border.
- For flow charts: use a bullet list with \`→\` or \`↓\` between steps, not ASCII boxes-and-arrows.
The 'task' the parent gave you is the question you must answer. Treat any other reading of it as scope creep.`;
const BUILTIN_RESEARCH_BODY = `You are running as a research subagent. Your job is to gather information from code AND the web, synthesize it, and return one focused conclusion.
How to operate:
- Combine code reading (read_file, search_files) with web tools (web_search, web_fetch) as appropriate to the question.
- For "how does X work" / "is Y supported" questions: web first to find the canonical reference, then verify against the local code.
- For "what's our policy on Z" / "where do we use Q": local code first, web only if you need to compare against external standards.
- Cap yourself at ~10 tool calls. If you can't converge in 10, return what you have plus a note about what's missing.
Your final answer:
- One paragraph (or short bullets). Lead with the conclusion.
- Cite both code (file:line) AND web sources (URL) when they back the answer.
- Distinguish "I verified this in code" from "I read this on a docs page" — the parent will trust the former more.
- If the answer is uncertain, say so. Don't invent confidence.
Formatting (rendered in a TUI):
- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\`| col | col |\` + \`| --- | --- |\`). Never use Unicode box-drawing characters (│ ─ ┼) — they break word-wrap.
- Keep table cells short; if a cell needs a paragraph, use bullets below the table instead.
- Code, file paths with line ranges, and shell commands → fenced code blocks (\`\`\`).
- NEVER draw decorative frames around code or text with \`┌──┐ │ └──┘\` box-drawing characters. Use plain code blocks; the renderer adds its own border.
- For flow charts: use a bullet list with \`→\` or \`↓\` between steps, not ASCII boxes-and-arrows.
The 'task' the parent gave you is the research question. Stay on it.`;
const BUILTIN_SKILLS: readonly Skill[] = Object.freeze([
Object.freeze<Skill>({
name: "explore",
description:
"Explore the codebase in an isolated subagent — wide-net read-only investigation that returns one distilled answer. Best for: 'find all places that...', 'how does X work across the project', 'survey the code for Y'.",
body: BUILTIN_EXPLORE_BODY,
scope: "builtin",
path: "(builtin)",
runAs: "subagent",
}),
Object.freeze<Skill>({
name: "research",
description:
"Research a question by combining web search + code reading in an isolated subagent. Best for: 'is X feature supported by lib Y', 'what's the canonical way to do Z', 'compare our impl against the spec'.",
body: BUILTIN_RESEARCH_BODY,
scope: "builtin",
path: "(builtin)",
runAs: "subagent",
}),
]);
+71 -1
View File
@@ -17,6 +17,25 @@ export interface ToolDefinition<A = any, R = any> {
name: string;
description?: string;
parameters?: JSONSchema;
/**
* Marks a tool as read-only: safe to invoke during plan mode. `true`
* for tools that only observe (read_file, list_directory, search, web
* fetch/search). Leave undefined / `false` for anything that can write,
* execute, or mutate state.
*
* The registry enforces this at dispatch: non-readonly tools called
* while `planMode` is on return a refusal string the model can
* learn from, instead of actually running.
*/
readOnly?: boolean;
/**
* Dynamic read-only check for tools whose safety depends on arguments
* — `run_command` with an allowlisted argv is safe, `run_command
* rm -rf` isn't. Called with the parsed arguments; `true` means "treat
* as read-only for plan mode". Takes precedence over `readOnly` when
* both are set.
*/
readOnlyCheck?: (args: A) => boolean;
fn: (args: A, ctx?: ToolCallContext) => R | Promise<R>;
}
@@ -42,11 +61,29 @@ export interface ToolRegistryOptions {
export class ToolRegistry {
private readonly _tools = new Map<string, InternalTool>();
private readonly _autoFlatten: boolean;
/**
* When true, `dispatch` refuses any tool whose `readOnly` flag isn't
* set (and whose `readOnlyCheck` doesn't pass on the specific args).
* Drives `reasonix code`'s Plan Mode — the model can still explore
* via read tools but its writes and non-allowlisted shell calls are
* bounced until the user approves a submitted plan.
*/
private _planMode = false;
constructor(opts: ToolRegistryOptions = {}) {
this._autoFlatten = opts.autoFlatten !== false;
}
/** Enable / disable plan-mode enforcement at dispatch. */
setPlanMode(on: boolean): void {
this._planMode = Boolean(on);
}
/** True when the registry is currently refusing non-readonly calls. */
get planMode(): boolean {
return this._planMode;
}
register<A, R>(def: ToolDefinition<A, R>): this {
if (!def.name) throw new Error("tool requires a name");
const internal: InternalTool = { ...(def as ToolDefinition) };
@@ -120,17 +157,50 @@ export class ToolRegistry {
args = nestArguments(args);
}
// Plan-mode enforcement — runs AFTER arg parsing so a tool with a
// runtime `readOnlyCheck` can inspect the actual args (e.g.
// `run_command` is read-only iff the command matches its allowlist).
if (this._planMode && !isReadOnlyCall(tool, args)) {
return JSON.stringify({
error: `${name}: unavailable in plan mode — this is a read-only exploration phase. Use read_file / list_directory / search_files / directory_tree / web_search / allowlisted shell commands to investigate. Call submit_plan with your proposed plan when you're ready for the user's review.`,
});
}
try {
const result = await tool.fn(args, { signal: opts.signal });
return typeof result === "string" ? result : JSON.stringify(result);
} catch (err) {
const e = err as Error & { toToolResult?: () => unknown };
// Errors may opt into a richer tool-result shape by implementing
// `toToolResult()`. Used by `PlanProposedError` to smuggle the
// submitted plan text out to the UI without stuffing it into the
// error message (which the dispatcher truncates at no fixed limit,
// but keeping payloads structured is cleaner for UI parsing).
if (typeof e.toToolResult === "function") {
try {
return JSON.stringify(e.toToolResult());
} catch {
/* fall through to the default shape */
}
}
return JSON.stringify({
error: `${(err as Error).name}: ${(err as Error).message}`,
error: `${e.name}: ${e.message}`,
});
}
}
}
function isReadOnlyCall(tool: InternalTool, args: Record<string, unknown>): boolean {
if (tool.readOnlyCheck) {
try {
return Boolean(tool.readOnlyCheck(args as never));
} catch {
return false;
}
}
return tool.readOnly === true;
}
function hasDotKey(obj: Record<string, unknown>): boolean {
for (const k of Object.keys(obj)) {
if (k.includes(".")) return true;
+237 -3
View File
@@ -48,6 +48,88 @@ export interface FilesystemToolsOptions {
const DEFAULT_MAX_READ_BYTES = 2 * 1024 * 1024;
const DEFAULT_MAX_LIST_BYTES = 256 * 1024;
/**
* Directory names skipped by `search_content` unless `include_deps:true`
* is passed. The intent is "user is asking about THEIR code, not the
* libraries they depend on" — vendored / generated trees would otherwise
* dominate every match list. Pass include_deps when you genuinely need
* to grep a dependency.
*/
const SKIP_DIR_NAMES: ReadonlySet<string> = new Set([
"node_modules",
".git",
".hg",
".svn",
"dist",
"build",
"out",
".next",
".nuxt",
"target", // Rust / Java
".venv",
"venv",
"__pycache__",
".pytest_cache",
".mypy_cache",
".cache",
"coverage",
]);
/**
* Cheap binary-by-extension check for `search_content`. We err on the
* side of skipping so a NUL-byte content sniff is the second line of
* defense (handles e.g. a `.txt` that's actually a binary dump).
*/
const BINARY_EXTENSIONS: ReadonlySet<string> = new Set([
".png",
".jpg",
".jpeg",
".gif",
".bmp",
".ico",
".webp",
".tiff",
".pdf",
".zip",
".tar",
".gz",
".bz2",
".xz",
".7z",
".rar",
".exe",
".dll",
".so",
".dylib",
".bin",
".class",
".jar",
".war",
".o",
".obj",
".lib",
".a",
".woff",
".woff2",
".ttf",
".otf",
".eot",
".mp3",
".mp4",
".mov",
".avi",
".webm",
".wasm",
".pyc",
".pyo",
]);
function isLikelyBinaryByName(name: string): boolean {
const dot = name.lastIndexOf(".");
if (dot < 0) return false;
return BINARY_EXTENSIONS.has(name.slice(dot).toLowerCase());
}
export function registerFilesystemTools(
registry: ToolRegistry,
opts: FilesystemToolsOptions,
@@ -62,8 +144,22 @@ export function registerFilesystemTools(
if (typeof raw !== "string" || raw.length === 0) {
throw new Error("path must be a non-empty string");
}
// Interpret relative paths against rootDir (the session's scope).
const resolved = pathMod.resolve(rootDir, raw);
// Sandbox-root semantics: a leading POSIX-style `/` (or `\` on
// Windows) means "from the project root", not "from the filesystem
// root". Models routinely write `path: "/"` or `path: "/src/foo.ts"`
// intending the sandbox root — without this normalization,
// path.resolve interprets `/` as the actual drive root (`F:\` on
// Windows, `/` on POSIX) and the escape check rightly rejects it,
// confusing the model. Strip leading separators so the rest of the
// resolution treats the input as relative to rootDir. Drive-letter
// absolutes (`C:\foo`) and Unix absolutes outside rootDir still
// get caught by the relative-escape check below.
let normalized = raw;
while (normalized.startsWith("/") || normalized.startsWith("\\")) {
normalized = normalized.slice(1);
}
if (normalized.length === 0) normalized = ".";
const resolved = pathMod.resolve(rootDir, normalized);
const normRoot = pathMod.resolve(rootDir);
// Use relative() to catch any `..` segments that escape.
const rel = pathMod.relative(normRoot, resolved);
@@ -77,6 +173,7 @@ export function registerFilesystemTools(
name: "read_file",
description:
"Read a file under the sandbox root. Returns the full contents (truncated with a notice if larger than the per-call cap). Paths may be relative to the root or absolute-under-root.",
readOnly: true,
parameters: {
type: "object",
properties: {
@@ -117,6 +214,7 @@ export function registerFilesystemTools(
name: "list_directory",
description:
"List entries in a directory under the sandbox root. Returns one line per entry, marking directories with a trailing slash. Not recursive — use directory_tree for that.",
readOnly: true,
parameters: {
type: "object",
properties: {
@@ -138,6 +236,7 @@ export function registerFilesystemTools(
name: "directory_tree",
description:
"Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Caps output so a huge tree doesn't drown the context.",
readOnly: true,
parameters: {
type: "object",
properties: {
@@ -186,6 +285,7 @@ export function registerFilesystemTools(
name: "search_files",
description:
"Find files whose NAME matches a substring or regex. Case-insensitive. Walks the directory recursively under the sandbox root. Returns one path per line.",
readOnly: true,
parameters: {
type: "object",
properties: {
@@ -239,10 +339,144 @@ export function registerFilesystemTools(
},
});
registry.register({
name: "search_content",
description:
"Recursively grep file CONTENTS for a substring or regex. This is the right tool for 'find all places that call X', 'where is Y referenced', 'what files contain Z'. Different from search_files (which matches FILE NAMES). Returns one match per line in 'path:line: text' format. Skips dependency / VCS / build directories (node_modules, .git, dist, build, .next, target, .venv) and binary files by default.",
readOnly: true,
parameters: {
type: "object",
properties: {
pattern: {
type: "string",
description: "Substring (or regex) to search file contents for.",
},
path: {
type: "string",
description: "Directory to start the search at (default: sandbox root).",
},
glob: {
type: "string",
description:
"Optional file-name suffix or substring filter. Examples: '.ts' (only TypeScript), 'test' (any file with 'test' in the name). Reduces noise when you know the file shape.",
},
case_sensitive: {
type: "boolean",
description: "When true, match case exactly. Default false (case-insensitive).",
},
include_deps: {
type: "boolean",
description:
"When true, also search inside node_modules / .git / dist / build / etc. Off by default — most exploration questions are about the user's own code.",
},
},
required: ["pattern"],
},
fn: async (args: {
pattern: string;
path?: string;
glob?: string;
case_sensitive?: boolean;
include_deps?: boolean;
}) => {
const startAbs = safePath(args.path ?? ".");
const caseSensitive = args.case_sensitive === true;
const includeDeps = args.include_deps === true;
const nameFilter = typeof args.glob === "string" ? args.glob.toLowerCase() : null;
// Try the pattern as a regex first (lets the model say `\bdispatch\(`
// for a word-bounded match); fall back to literal substring on
// invalid regex. No `g` flag — we test once per line, so global
// statefulness (lastIndex tracking) would just be noise.
let re: RegExp | null = null;
try {
re = new RegExp(args.pattern, caseSensitive ? "" : "i");
} catch {
re = null;
}
const needle = caseSensitive ? args.pattern : args.pattern.toLowerCase();
const matches: string[] = [];
let totalBytes = 0;
let scanned = 0;
let truncated = false;
const walk = async (dir: string): Promise<void> => {
if (truncated) return;
let entries: import("node:fs").Dirent[];
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
if (truncated) return;
if (e.isDirectory()) {
if (!includeDeps && SKIP_DIR_NAMES.has(e.name)) continue;
await walk(pathMod.join(dir, e.name));
continue;
}
if (!e.isFile()) continue;
if (nameFilter && !e.name.toLowerCase().includes(nameFilter)) continue;
if (isLikelyBinaryByName(e.name)) continue;
const full = pathMod.join(dir, e.name);
let stat: import("node:fs").Stats;
try {
stat = await fs.stat(full);
} catch {
continue;
}
// Per-file size cap so a 50MB log doesn't dominate the search.
// Anything legitimately interesting fits in 2 MB; bigger files
// are usually data dumps or generated bundles.
if (stat.size > 2 * 1024 * 1024) continue;
let raw: Buffer;
try {
raw = await fs.readFile(full);
} catch {
continue;
}
// Content-based binary sniff: a NUL byte in the first 8KB is
// a strong indicator. Catches binaries with .json or .txt
// extensions (yes, this happens).
const firstNul = raw.indexOf(0);
if (firstNul !== -1 && firstNul < 8 * 1024) continue;
const text = raw.toString("utf8");
const rel = pathMod.relative(rootDir, full);
const lines = text.split(/\r?\n/);
for (let li = 0; li < lines.length; li++) {
const line = lines[li]!;
const lineForCheck = caseSensitive ? line : line.toLowerCase();
const hit = re ? re.test(line) : lineForCheck.includes(needle);
if (!hit) continue;
// Truncate very long lines so one giant minified file
// doesn't blow the budget on a single match.
const display = line.length > 200 ? `${line.slice(0, 200)}…` : line;
const out = `${rel}:${li + 1}: ${display}`;
if (totalBytes + out.length + 1 > maxListBytes) {
matches.push(`[… truncated at ${maxListBytes} bytes — refine pattern or path …]`);
truncated = true;
return;
}
matches.push(out);
totalBytes += out.length + 1;
}
scanned++;
}
};
await walk(startAbs);
if (matches.length === 0) {
return scanned === 0
? "(no files scanned — path empty or all files filtered out)"
: `(no matches across ${scanned} file${scanned === 1 ? "" : "s"})`;
}
return matches.join("\n");
},
});
registry.register({
name: "get_file_info",
description:
"Stat a path under the sandbox root. Returns type (file|directory|symlink), size in bytes, mtime in ISO-8601.",
readOnly: true,
parameters: {
type: "object",
properties: {
@@ -287,7 +521,7 @@ export function registerFilesystemTools(
registry.register({
name: "edit_file",
description:
"Apply a SEARCH/REPLACE edit to an existing file. `search` must match exactly (whitespace sensitive) — no regex. The match must be unique in the file; otherwise the edit is refused to avoid surprise rewrites. This flat-string shape replaces the `{oldText, newText}[]` JSON array form that previously triggered R1 DSML hallucinations.",
"Apply a SEARCH/REPLACE edit to an existing file. `search` must match exactly (whitespace sensitive) — no regex. The match must be unique in the file; otherwise the edit is refused to avoid surprise rewrites.",
parameters: {
type: "object",
properties: {
+180
View File
@@ -0,0 +1,180 @@
/**
* `remember` / `forget` / `recall_memory` — tools that let the model
* read and write the user-memory store across sessions.
*
* Scope rules:
* - `global` — always available (no sandbox needed).
* - `project` — requires a `projectRoot` on MemoryStore. In chat mode
* (no sandbox), the tools still register but a `scope=project` call
* returns a structured refusal so the model can try `global` instead.
*
* Memory changes are written eagerly but NOT re-loaded into the prefix
* mid-session (cache invariant). The user notices at `/new` or the next
* launch — or they can read fresh content via `recall_memory` which
* always hits disk.
*/
import type { ToolRegistry } from "../tools.js";
import {
type MemoryScope,
MemoryStore,
type MemoryType,
sanitizeMemoryName,
} from "../user-memory.js";
export interface MemoryToolsOptions {
/** Sandbox root for the `project` scope. Omit for chat mode. */
projectRoot?: string;
/** Override `~/.reasonix` (tests). */
homeDir?: string;
}
export function registerMemoryTools(
registry: ToolRegistry,
opts: MemoryToolsOptions = {},
): ToolRegistry {
const store = new MemoryStore({ homeDir: opts.homeDir, projectRoot: opts.projectRoot });
const hasProject = store.hasProjectScope();
registry.register({
name: "remember",
description:
"Save a memory for future sessions. Use when the user states a preference, corrects your approach, shares a non-obvious fact about this project, or explicitly asks you to remember something. Don't remember transient task state — only things worth recalling next session. The memory is written now but won't re-load into the system prompt until the next `/new` or launch.",
parameters: {
type: "object",
properties: {
type: {
type: "string",
enum: ["user", "feedback", "project", "reference"],
description:
"'user' = role/skills/prefs; 'feedback' = corrections or confirmed approaches; 'project' = facts/decisions about the current work; 'reference' = pointers to external systems the user uses.",
},
scope: {
type: "string",
enum: ["global", "project"],
description:
"'global' = applies across every project (preferences, tooling); 'project' = scoped to the current sandbox (decisions, local facts). Only available in `reasonix code`.",
},
name: {
type: "string",
description:
"filename-safe identifier, 3-40 chars, alnum + _ - . (no path separators, no leading dot).",
},
description: {
type: "string",
description: "One-line summary shown in MEMORY.md (under ~150 chars).",
},
content: {
type: "string",
description:
"Full memory body in markdown. For feedback/project types, structure as: rule/fact, then **Why:** line, then **How to apply:** line.",
},
},
required: ["type", "scope", "name", "description", "content"],
},
fn: async (args: {
type: MemoryType;
scope: MemoryScope;
name: string;
description: string;
content: string;
}) => {
if (args.scope === "project" && !hasProject) {
return JSON.stringify({
error:
"scope='project' is unavailable in this session (no sandbox root). Retry with scope='global', or ask the user to switch to `reasonix code` for project-scoped memory.",
});
}
try {
const path = store.write({
name: args.name,
type: args.type,
scope: args.scope,
description: args.description,
body: args.content,
});
const key = sanitizeMemoryName(args.name);
// The return text is load-bearing: it's the ONLY thing keeping
// the fact visible within the current session, because the
// prefix isn't re-hashed mid-session (Pillar 1). R1 reads this
// on its next turn — the wording is deliberately imperative so
// it doesn't get ignored in favor of explore-first behavior.
return [
`✓ REMEMBERED (${args.scope}/${key}): ${args.description}`,
"",
"TREAT THIS AS ESTABLISHED FACT for the rest of this session.",
"The user just told you — don't re-explore the filesystem to re-derive it.",
`(Saved to ${path}; pins into the system prompt on next /new or launch.)`,
].join("\n");
} catch (err) {
return JSON.stringify({ error: `remember failed: ${(err as Error).message}` });
}
},
});
registry.register({
name: "forget",
description:
"Delete a memory file and remove it from MEMORY.md. Use when the user explicitly asks to forget something, or when a previously-remembered fact has become wrong. Irreversible — no tombstone.",
parameters: {
type: "object",
properties: {
name: { type: "string", description: "Memory name (the identifier used in `remember`)." },
scope: { type: "string", enum: ["global", "project"] },
},
required: ["name", "scope"],
},
fn: async (args: { name: string; scope: MemoryScope }) => {
if (args.scope === "project" && !hasProject) {
return JSON.stringify({
error: "scope='project' is unavailable in this session (no sandbox root).",
});
}
try {
const existed = store.delete(args.scope, args.name);
return existed
? `forgot (${args.scope}/${sanitizeMemoryName(args.name)}). Re-load on next /new or launch.`
: `no such memory: ${args.scope}/${args.name} (nothing to forget).`;
} catch (err) {
return JSON.stringify({ error: `forget failed: ${(err as Error).message}` });
}
},
});
registry.register({
name: "recall_memory",
description:
"Read the full body of a memory file when its MEMORY.md one-liner (already in the system prompt) isn't enough detail. Most of the time the index suffices — only call this when the user's question genuinely requires the full context.",
readOnly: true,
parameters: {
type: "object",
properties: {
name: { type: "string" },
scope: { type: "string", enum: ["global", "project"] },
},
required: ["name", "scope"],
},
fn: async (args: { name: string; scope: MemoryScope }) => {
if (args.scope === "project" && !hasProject) {
return JSON.stringify({
error: "scope='project' is unavailable in this session (no sandbox root).",
});
}
try {
const entry = store.read(args.scope, args.name);
return [
`# ${entry.name} (${entry.scope}/${entry.type}, created ${entry.createdAt || "?"})`,
entry.description ? `> ${entry.description}` : "",
"",
entry.body,
]
.filter(Boolean)
.join("\n");
} catch (err) {
return JSON.stringify({ error: `recall failed: ${(err as Error).message}` });
}
},
});
return registry;
}
+101
View File
@@ -0,0 +1,101 @@
/**
* Plan Mode — read-only exploration phase for `reasonix code`.
*
* Shape (mirrors claude-code's plan/act split, adapted for Reasonix):
*
* 1. User types `/plan` → registry switches to plan-mode enforcement
* (write tools refused at dispatch; reads + allowlisted shell
* still work).
* 2. Model explores, then calls `submit_plan` with a markdown plan.
* 3. `submit_plan` throws `PlanProposedError`, which the TUI renders
* as a picker: Approve / Refine / Cancel.
* 4. Approve → registry leaves plan mode, a synthetic user message
* "The plan has been approved. Implement it now." is pushed into
* the loop so the next turn executes.
*
* The read-only enforcement lives in `ToolRegistry.dispatch` via
* `readOnly` / `readOnlyCheck`; this file only ships the `submit_plan`
* escape hatch and the error type that carries the plan out of the
* registry without stuffing it into the message.
*
* We do not change `ImmutablePrefix.toolSpecs` when plan mode toggles —
* that would break Pillar 1's prefix cache. Instead the same full spec
* list stays pinned, and the registry enforces mode at dispatch time.
* The refusal string teaches the model the rule; cache hits stay
* intact.
*/
import type { ToolRegistry } from "../tools.js";
/**
* Thrown by `submit_plan` when plan mode is active, carrying the plan
* text the TUI will render for the user's approval.
*
* Implements the `toToolResult` protocol so `ToolRegistry.dispatch`
* serializes the full plan into the tool-result JSON (not just the
* error message). The TUI parses `{ error, plan }` from the tool event
* and mounts the `PlanConfirm` picker.
*/
export class PlanProposedError extends Error {
readonly plan: string;
constructor(plan: string) {
super(
"PlanProposedError: plan submitted. STOP calling tools now — the TUI has shown the plan to the user. Wait for their next message; it will either approve (you'll then implement the plan), request a refinement (you should explore more and submit an updated plan), or cancel (drop the plan and ask what they want instead). Don't call any tools in the meantime.",
);
this.name = "PlanProposedError";
this.plan = plan;
}
/**
* Structured tool-result shape. Consumed by the TUI to extract the
* plan without regex-scraping the error message.
*/
toToolResult(): { error: string; plan: string } {
return { error: `${this.name}: ${this.message}`, plan: this.plan };
}
}
export interface PlanToolOptions {
/**
* Optional side-channel callback fired when the model submits a plan.
* The TUI uses this to preview the plan in real time (the tool-result
* event is also emitted; this is just earlier and friendlier to
* test harnesses that don't want to parse JSON).
*/
onPlanSubmitted?: (plan: string) => void;
}
export function registerPlanTool(registry: ToolRegistry, opts: PlanToolOptions = {}): ToolRegistry {
registry.register({
name: "submit_plan",
description:
"Submit a concrete plan to the user for review before executing. Use this for tasks that warrant a review gate — multi-file refactors, architecture changes, anything that would be expensive or confusing to undo. Skip it for small fixes (one-line typo, obvious bug with a clear fix) — just make the change. The user will either approve (you then implement it), ask for refinement, or cancel. If the user has already enabled /plan mode, writes are blocked at dispatch and you MUST use this. Write the plan as markdown with a one-line summary, a bulleted list of files to touch and what will change, and any risks or open questions.",
readOnly: true,
parameters: {
type: "object",
properties: {
plan: {
type: "string",
description:
"Markdown-formatted plan. Lead with a one-sentence summary. Then a file-by-file breakdown of what you'll change and why. Flag any risks or open questions at the end so the user can weigh in before you start.",
},
},
required: ["plan"],
},
fn: async (args: { plan: string }) => {
const plan = (args?.plan ?? "").trim();
if (!plan) {
throw new Error("submit_plan: empty plan — write a markdown plan and try again.");
}
// Always fire the picker, not just inside plan mode. Plan mode's
// role is the *stronger* constraint — it forces you into read-only
// until you submit. Outside plan mode, submit_plan is your own
// call: use it when the task is large enough to deserve a review
// gate (multi-file refactors, architecture changes, anything
// that would be expensive to undo), skip it for small fixes.
opts.onPlanSubmitted?.(plan);
throw new PlanProposedError(plan);
},
});
return registry;
}
+264 -6
View File
@@ -27,6 +27,7 @@
*/
import { type SpawnOptions, spawn } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import * as pathMod from "node:path";
import type { ToolRegistry } from "../tools.js";
@@ -43,8 +44,14 @@ export interface ShellToolsOptions {
/**
* Extra command-name prefixes the user explicitly trusts. Added on
* top of the built-in allowlist. Examples: `["my-ci-script", "lint"]`.
*
* Accepts either a fixed array (captured once at registration) or a
* getter called on every dispatch. The getter form is load-bearing:
* when the TUI's `ShellConfirm` writes a new prefix to config mid-
* session, the running `run_command` must pick it up immediately —
* otherwise the same command gets re-prompted until the next launch.
*/
extraAllowed?: string[];
extraAllowed?: readonly string[] | (() => readonly string[]);
/**
* When true, skip the allowlist entirely and auto-run every command.
* Off by default — this is an escape hatch for non-interactive use
@@ -208,10 +215,22 @@ export async function runCommand(
env: process.env,
};
// Windows: two layered fixes on top of shell:false —
// 1. Resolve bare command names via PATH × PATHEXT (CreateProcess
// ignores PATHEXT, so `npm` alone misses `npm.cmd`).
// 2. Node 21.7.3+ (CVE-2024-27980) refuses to spawn `.cmd`/`.bat`
// directly even with shell:false and safe args — throws
// EINVAL at invocation time. Wrap those via `cmd.exe /d /s /c`
// with verbatim args + manual quoting, so shell metacharacters
// in arguments stay literal.
// Unix path is unchanged.
const { bin, args, spawnOverrides } = prepareSpawn(argv);
const effectiveSpawnOpts = { ...spawnOpts, ...spawnOverrides };
return await new Promise<RunCommandResult>((resolve, reject) => {
let child: import("node:child_process").ChildProcess;
try {
child = spawn(argv[0]!, argv.slice(1), spawnOpts);
child = spawn(bin, args, effectiveSpawnOpts);
} catch (err) {
reject(err);
return;
@@ -251,6 +270,225 @@ export async function runCommand(
});
}
/**
* Test/override hooks for {@link resolveExecutable}. Omitting any field
* falls through to the real process globals — the runtime call path
* uses defaults; tests inject `platform` + `env` + `isFile` to exercise
* Windows-specific lookup from a Linux CI runner without touching
* actual fs.
*/
export interface ResolveExecutableOptions {
platform?: NodeJS.Platform;
env?: { PATH?: string; PATHEXT?: string };
/** Predicate swapped in by tests to avoid creating real files. */
isFile?: (path: string) => boolean;
/** Path.join used for the lookup. Defaults to Windows semantics on Windows. */
pathDelimiter?: string;
}
/**
* Resolve a bare command name (e.g. `npm`) to its on-disk path via
* PATH × PATHEXT on Windows. Returns the input unchanged on non-Windows
* platforms, when the input is already a path (contains `/`, `\`, or is
* absolute), or when no match is found in PATH × PATHEXT (caller gets a
* natural ENOENT from spawn, which surfaces cleanly).
*
* Why this exists: `child_process.spawn` with `shell: false` invokes
* Windows `CreateProcess`, which does not honor `PATHEXT` and does not
* search for `.cmd` / `.bat` wrappers. Node-ecosystem tools ship as
* `npm.cmd`, `npx.cmd`, `yarn.cmd`, etc., so a bare `npm` fails with
* ENOENT under `shell: false`. Flipping to `shell: true` would work
* but reintroduces shell-expansion (pipes, redirects, chained cmds)
* that the tool was explicitly designed to forbid. This resolver
* threads the needle.
*/
export function resolveExecutable(cmd: string, opts: ResolveExecutableOptions = {}): string {
const platform = opts.platform ?? process.platform;
if (platform !== "win32") return cmd;
if (!cmd) return cmd;
// Already a path fragment — spawn handles these natively.
if (cmd.includes("/") || cmd.includes("\\") || pathMod.isAbsolute(cmd)) return cmd;
// If the model wrote `npm.cmd` explicitly, respect that verbatim.
if (pathMod.extname(cmd)) return cmd;
const env = opts.env ?? process.env;
const pathExt = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
.split(";")
.map((e) => e.trim())
.filter(Boolean);
const delimiter = opts.pathDelimiter ?? (platform === "win32" ? ";" : pathMod.delimiter);
const pathDirs = (env.PATH ?? "").split(delimiter).filter(Boolean);
const isFile = opts.isFile ?? defaultIsFile;
for (const dir of pathDirs) {
for (const ext of pathExt) {
// Force win32 join so CI tests that pass `platform: "win32"`
// from a Linux runner get backslash-joined paths; the real-
// Windows runtime path lands here too and gets the correct
// separator regardless of where pathMod defaults.
const full = pathMod.win32.join(dir, cmd + ext);
if (isFile(full)) return full;
}
}
return cmd;
}
function defaultIsFile(full: string): boolean {
try {
return existsSync(full) && statSync(full).isFile();
} catch {
return false;
}
}
/**
* Prepare `(bin, args, spawnOpts)` for the runCommand spawn call,
* applying Windows-specific workarounds for (a) PATHEXT lookup and
* (b) the CVE-2024-27980 prohibition on direct `.cmd`/`.bat` spawns.
*
* Exported so tests can assert the transformation without booting an
* actual child process.
*/
export function prepareSpawn(
argv: readonly string[],
opts: ResolveExecutableOptions = {},
): { bin: string; args: string[]; spawnOverrides: SpawnOptions } {
const head = argv[0] ?? "";
const tail = argv.slice(1);
const platform = opts.platform ?? process.platform;
const resolved = resolveExecutable(head, opts);
if (platform !== "win32") {
return { bin: resolved, args: [...tail], spawnOverrides: {} };
}
// `.cmd` / `.bat` wrappers require cmd.exe on post-CVE Node.
if (/\.(cmd|bat)$/i.test(resolved)) {
const cmdline = [resolved, ...tail].map(quoteForCmdExe).join(" ");
return {
bin: "cmd.exe",
args: ["/d", "/s", "/c", withUtf8Codepage(cmdline)],
// windowsVerbatimArguments prevents Node from re-quoting the /c
// payload — we've already composed an exact cmd.exe command
// line. Without this Node wraps our already-quoted string in
// another round of quotes and cmd.exe can't parse it.
spawnOverrides: { windowsVerbatimArguments: true },
};
}
// Bare command names that PATH × PATHEXT couldn't resolve to an
// on-disk file — these are almost always cmd.exe built-ins (`dir`,
// `echo`, `type`, `ver`, `vol`, `where`, `help`, …) which don't
// exist as standalone executables. Direct spawn crashes with ENOENT;
// routing through cmd.exe lets the built-in resolve, and if it's
// genuinely unknown the user gets the standard "'foo' is not
// recognized" message instead of a raw spawn failure.
if (isBareWindowsName(resolved) && resolved === head) {
const cmdline = [head, ...tail].map(quoteForCmdExe).join(" ");
return {
bin: "cmd.exe",
args: ["/d", "/s", "/c", withUtf8Codepage(cmdline)],
spawnOverrides: { windowsVerbatimArguments: true },
};
}
// PowerShell variants: chcp 65001 doesn't help here because PowerShell
// sets its own [Console]::OutputEncoding at startup — usually system
// codepage (CP936/CP932/CP949 on CJK Windows) or UTF-16. The result
// is mojibake when our `chunk.toString()` UTF-8-decodes its stdout.
// Inject a UTF-8 setup prelude into the `-Command` (or `-c`) arg so
// any output produced thereafter is UTF-8.
if (isPowerShellExe(resolved)) {
const patched = injectPowerShellUtf8(tail);
if (patched) {
return { bin: resolved, args: patched, spawnOverrides: {} };
}
}
return { bin: resolved, args: [...tail], spawnOverrides: {} };
}
/** Resolved bin path looks like Windows PowerShell or PowerShell Core. */
function isPowerShellExe(resolved: string): boolean {
return /(?:^|[\\/])(?:powershell|pwsh)(?:\.exe)?$/i.test(resolved);
}
/**
* Locate `-Command` / `-c` in `args` and prepend the UTF-8 setup prelude
* to its value. Returns the patched args, or `null` when no `-Command`
* arg is present (in which case we leave the invocation untouched —
* inline-expression and script-file modes have their own conventions
* we don't want to silently rewrite).
*
* Why not always wrap: PowerShell's quoting semantics are finicky enough
* that adding a prelude to a script file invocation could break it.
* `-Command` is the case the model actually uses, and where mojibake
* matters; targeting just it keeps the blast radius small.
*
* Exported for tests.
*/
export function injectPowerShellUtf8(args: readonly string[]): string[] | null {
const prelude =
"[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;$OutputEncoding=[System.Text.Encoding]::UTF8;";
for (let i = 0; i < args.length; i++) {
const a = args[i] ?? "";
if (/^-(?:Command|c)$/i.test(a) && i + 1 < args.length) {
const out = [...args];
out[i + 1] = `${prelude}${args[i + 1] ?? ""}`;
return out;
}
}
return null;
}
/**
* Prefix a cmd.exe command line with `chcp 65001 >nul &` so output
* (from cmd.exe and any child it spawns) is UTF-8-encoded. Without
* this, on Chinese / Japanese / Korean Windows, `dir`, `findstr`,
* `where`, etc. emit text in the system codepage (CP936, CP932,
* CP949, …) and `chunk.toString()` — which decodes as UTF-8 — produces
* garbled mojibake the model then sees as poisoned input on the next
* turn.
*
* Scope: chcp affects ONLY this cmd.exe instance, which exits after
* `/c`. No global console state changes. Single `&` (not `&&`) so the
* command still runs even on the rare Windows builds where chcp
* itself returns a non-zero exit (Win7 quirks; harmless on Win10+).
*
* Exported so tests can verify the wrapping shape.
*/
export function withUtf8Codepage(cmdline: string): string {
return `chcp 65001 >nul & ${cmdline}`;
}
/**
* True when `s` looks like a bare executable name — no path separator,
* no drive letter, no extension. Such names on Windows, when absent
* from PATH × PATHEXT, are almost always cmd.exe built-ins.
*/
function isBareWindowsName(s: string): boolean {
if (!s) return false;
if (s.includes("/") || s.includes("\\")) return false;
if (pathMod.isAbsolute(s)) return false;
if (pathMod.extname(s)) return false;
return true;
}
/**
* Quote an argument so cmd.exe parses it back as a single token. We
* always wrap in double quotes when the arg contains whitespace or
* any cmd.exe metacharacter, doubling embedded quotes per cmd.exe's
* `""` escape rule. Bare alphanumeric args pass through unquoted for
* readability in logs.
*
* Exported for test coverage of the quoting semantics.
*/
export function quoteForCmdExe(arg: string): string {
if (arg === "") return '""';
if (!/[\s"&|<>^%(),;!]/.test(arg)) return arg;
return `"${arg.replace(/"/g, '""')}"`;
}
/** Error thrown by `run_command` when the command isn't allowlisted. */
export class NeedsConfirmationError extends Error {
readonly command: string;
@@ -267,20 +505,40 @@ export function registerShellTools(registry: ToolRegistry, opts: ShellToolsOptio
const rootDir = pathMod.resolve(opts.rootDir);
const timeoutSec = opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC;
const maxOutputChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
const extraAllowed = opts.extraAllowed ?? [];
// Resolved on every dispatch so newly-persisted "always allow"
// prefixes take effect inside the session that added them, not just
// on the next launch. Static arrays are wrapped into a constant
// getter so the call site below is uniform.
const getExtraAllowed: () => readonly string[] =
typeof opts.extraAllowed === "function"
? opts.extraAllowed
: (() => {
const snapshot = opts.extraAllowed ?? [];
return () => snapshot;
})();
const allowAll = opts.allowAll ?? false;
registry.register({
name: "run_command",
description:
"Run a shell command in the project root and return its combined stdout+stderr. Read-only and test commands (git status, ls, npm test, pytest, cargo test, grep, etc.) run immediately. Anything that could mutate state (npm install, git commit, rm, chmod) is refused and the user has to confirm in the TUI. Prefer this over asking the user to run a command manually — after edits, run the project's tests to verify.",
"Run a shell command in the project root and return its combined stdout+stderr. Common read-only inspection and test/lint/typecheck commands run immediately; anything that could mutate state, install dependencies, or touch the network is refused until the user confirms it in the TUI. Prefer this over asking the user to run a command manually — after edits, run the project's tests to verify.",
// Plan-mode gate: allow allowlisted commands through (git status,
// cargo check, ls, grep …) so the model can actually investigate
// during planning. Anything that would otherwise trigger a
// confirmation prompt is treated as "not read-only" and bounced.
readOnlyCheck: (args: { command?: unknown }) => {
if (allowAll) return true;
const cmd = typeof args?.command === "string" ? args.command.trim() : "";
if (!cmd) return false;
return isAllowed(cmd, getExtraAllowed());
},
parameters: {
type: "object",
properties: {
command: {
type: "string",
description:
"Full command line, e.g. 'npm test' or 'git diff src/foo.ts'. Tokenized with POSIX-ish quoting; no shell expansion, no pipes, no redirects.",
"Full command line. Tokenized with POSIX-ish quoting; no shell expansion, no pipes, no redirects.",
},
timeoutSec: {
type: "integer",
@@ -292,7 +550,7 @@ export function registerShellTools(registry: ToolRegistry, opts: ShellToolsOptio
fn: async (args: { command: string; timeoutSec?: number }, ctx) => {
const cmd = args.command.trim();
if (!cmd) throw new Error("run_command: empty command");
if (!allowAll && !isAllowed(cmd, extraAllowed)) {
if (!allowAll && !isAllowed(cmd, getExtraAllowed())) {
throw new NeedsConfirmationError(cmd);
}
const effectiveTimeout = Math.max(1, Math.min(600, args.timeoutSec ?? timeoutSec));
+147
View File
@@ -0,0 +1,147 @@
/**
* `run_skill` — invoke a user-authored playbook from the Skills index.
*
* Two execution modes, picked at registration time per skill via
* frontmatter `runAs`:
*
* - `inline` (default) — the skill body becomes the tool result and
* enters the parent's append-only log. The model reads the
* instructions and continues the normal loop, calling whatever
* tools the skill prescribes. Cheap, no isolation. Best for
* "load a checklist" / "load a coding style" / "load review
* criteria" patterns.
*
* - `subagent` — the skill body becomes the *system prompt* of an
* isolated child loop; the user-supplied `arguments` becomes the
* `task`. Only the child's final answer comes back as the tool
* result. Best for big-context exploration or research playbooks
* where the parent doesn't need to see the trail.
*
* Subagent dispatch is opt-in: callers must supply a `subagentRunner`
* at registration. When omitted (chat mode without a configured
* client), invoking a subagent skill returns a structured error
* instead of silently downgrading to inline — that would surprise the
* skill author.
*
* v1 deliberately ignores each skill's `allowed-tools` frontmatter:
* Reasonix's tool namespace doesn't align with Claude Code's so a
* literal pass would give wrong answers.
*/
import { type Skill, SkillStore } from "../skills.js";
import type { ToolRegistry } from "../tools.js";
/**
* Caller-supplied closure that knows how to spawn a subagent for the
* given resolved skill + task. Decoupled from `registerSkillTools` so
* the skills tool doesn't need to know about DeepSeekClient or the
* parent ToolRegistry — the App / library wiring assembles those once
* and hands in this function.
*
* Returns the JSON tool-result string verbatim (already serialized via
* `formatSubagentResult`), so the dispatch path is pure pass-through.
*/
export type SubagentRunner = (skill: Skill, task: string) => Promise<string>;
export interface SkillToolsOptions {
/** Override `$HOME` — tests set this to a tmpdir. */
homeDir?: string;
/**
* Absolute project root — enables discovery of project-scope skills
* under `<projectRoot>/.reasonix/skills/`. Omit for chat mode (global
* scope only).
*/
projectRoot?: string;
/**
* Closure that spawns a subagent for `runAs: subagent` skills. When
* omitted, invoking a subagent skill returns an error directing the
* user to wire up the runner — silent fallback to inline would be
* worse, since the skill author wrote the body assuming isolation.
*/
subagentRunner?: SubagentRunner;
/** Hide built-in skills (test-only knob; production callers leave off). */
disableBuiltins?: boolean;
}
export function registerSkillTools(
registry: ToolRegistry,
opts: SkillToolsOptions = {},
): ToolRegistry {
const store = new SkillStore({
homeDir: opts.homeDir,
projectRoot: opts.projectRoot,
disableBuiltins: opts.disableBuiltins,
});
const subagentRunner = opts.subagentRunner;
registry.register({
name: "run_skill",
description:
"Invoke a playbook from the Skills index pinned in the system prompt. Each entry is a self-contained instruction block. Skills marked with 🧬 in the index spawn an isolated subagent — only the final distilled answer comes back, the model's tool calls + reasoning during the run never enter your context. Plain skills are inlined: the body becomes a tool result you read and follow. For 🧬 subagent skills, supply 'arguments' describing the concrete task — they'll be the only context the subagent has.",
readOnly: true,
parameters: {
type: "object",
properties: {
name: {
type: "string",
description:
"Skill identifier as it appears in the pinned Skills index (e.g. 'explore', 'review', 'security-review'). Case-sensitive.",
},
arguments: {
type: "string",
description:
"Free-form arguments the skill should act on. For inline skills: appended to the body as an 'Arguments:' line; the skill's own instructions decide how to consume them. For 🧬 subagent skills: REQUIRED — becomes the entire task description the subagent receives, since it has no other context.",
},
},
required: ["name"],
},
fn: async (args: { name?: unknown; arguments?: unknown }) => {
const name = typeof args.name === "string" ? args.name.trim() : "";
if (!name) {
return JSON.stringify({ error: "run_skill requires a 'name' argument" });
}
const skill = store.read(name);
if (!skill) {
const available = store
.list()
.map((s) => s.name)
.join(", ");
return JSON.stringify({
error: `unknown skill: ${JSON.stringify(name)}`,
available: available || "(none — user has not defined any skills)",
});
}
const rawArgs = typeof args.arguments === "string" ? args.arguments.trim() : "";
if (skill.runAs === "subagent") {
if (!subagentRunner) {
return JSON.stringify({
error: `run_skill: skill ${JSON.stringify(name)} is marked runAs=subagent but no subagent runner is configured for this session. Skill authors who need isolation should run inside reasonix code (or a library setup that passes subagentRunner to registerSkillTools).`,
});
}
if (!rawArgs) {
return JSON.stringify({
error: `run_skill: skill ${JSON.stringify(name)} is a subagent and requires 'arguments' — the subagent has no other context, so describe the concrete task in the arguments field.`,
});
}
return subagentRunner(skill, rawArgs);
}
// inline path — body becomes the tool result.
const header = [
`# Skill: ${skill.name}`,
skill.description ? `> ${skill.description}` : "",
`(scope: ${skill.scope} · ${skill.path})`,
]
.filter(Boolean)
.join("\n");
const argsBlock = rawArgs ? `\n\nArguments: ${rawArgs}` : "";
// The body is handed to the model verbatim. No truncation — the
// user authored it, we trust their length choice. The append-only
// log pays the token cost exactly once per invocation.
return `${header}\n\n${skill.body}${argsBlock}`;
},
});
return registry;
}
+441
View File
@@ -0,0 +1,441 @@
/**
* Subagent runtime — isolated child loops for offloading exploration or
* self-contained subtasks.
*
* Two surfaces sit on top of the same `spawnSubagent` core:
*
* 1. `registerSubagentTool` — exposes a low-level `spawn_subagent`
* function-call tool. Library API. NOT registered into the model
* tool list by `reasonix code` since 0.4.26 — Skills (with
* `runAs: subagent` frontmatter) became the user-facing surface.
* Kept exported because library callers and tests still want
* direct access to the primitive.
*
* 2. `run_skill` (in src/tools/skills.ts) — when the resolved skill
* has `runAs: subagent`, it calls `spawnSubagent` with the skill
* body as the system prompt and the user's `arguments` as the
* task. Subagent skills are listed in the pinned Skills index
* with a 🧬 marker, which gives the model a clear pattern-match
* trigger without forcing it to reason about "is this task big
* enough to delegate."
*
* Why R1 specifically benefits:
* - R1 reasoning tokens are expensive AND inflate the parent context.
* A subagent runs its own private loop, then surfaces only the
* distilled final answer back to the parent — the main session
* never sees the reasoning trail.
*
* Invariants common to both surfaces:
* - Serial only — no parallel spawn (MVP).
* - Inherits parent's tool registry MINUS `spawn_subagent` itself
* (no recursion via the tool API) and MINUS `submit_plan`
* (subagents don't propose plans to the user).
* - No hooks, no session — runs are ephemeral.
* - Lower default `maxToolIters` than the parent (16 vs 64).
* - Independent prefix cache (subagent's prefix has its own
* fingerprint).
* - Parent registry's plan-mode state propagates: subagents can't
* escape `/plan`.
* - Non-streaming child loop — the parent isn't watching deltas, so
* streaming would only add an SSE parser to the critical path.
* Cancellation still works via the AbortSignal.
*/
import type { DeepSeekClient } from "../client.js";
import { CacheFirstLoop } from "../loop.js";
import { ImmutablePrefix } from "../memory.js";
import { applyProjectMemory } from "../project-memory.js";
import { ToolRegistry } from "../tools.js";
/**
* Live event emitted by a running subagent. Surfaced via the optional
* `sink` ref the TUI attaches its handler to. Side-channel only — these
* events do NOT pass through the parent loop's `LoopEvent` stream
* because subagents run inside a tool-dispatch frame, after the parent's
* `step()` has already yielded `tool_start` and is awaiting the result.
*/
export interface SubagentEvent {
kind: "start" | "progress" | "end";
/** First ~30 chars of the task prompt — used for the TUI status row. */
task: string;
/** Iteration count inside the child loop (number of tool results so far). */
iter?: number;
/** Wall-clock ms since the subagent started. */
elapsedMs?: number;
/** First ~120 chars of the final assistant message. Set on `end`. */
summary?: string;
/** Error message if the subagent failed. Set on `end`. */
error?: string;
/** Total turns the subagent took. Set on `end`. */
turns?: number;
}
/**
* Mutable ref the registration writes through. The TUI sets `.current`
* to its own handler on mount; nothing receives events before that
* happens (and headless callers leave `.current = null`, which is the
* library-mode default — they read the final result from the helper's
* return value instead).
*/
export interface SubagentSink {
current: ((ev: SubagentEvent) => void) | null;
}
/**
* Per-spawn options for {@link spawnSubagent}. All but `parentRegistry`
* + `client` + `system` + `task` are tunables with sensible defaults.
*/
export interface SpawnSubagentOptions {
/** Shared DeepSeek client. The subagent reuses it (same auth, same retries). */
client: DeepSeekClient;
/**
* Parent registry — the subagent inherits a copy of its tools (minus
* the never-inherited set: `spawn_subagent`, `submit_plan`).
*/
parentRegistry: ToolRegistry;
/**
* System prompt for the child loop. Skills' subagent path passes
* the skill body here; the spawn_subagent tool passes its default
* (or the model's `system` argument override).
*/
system: string;
/** The task / question / instruction the subagent must address. */
task: string;
/** Model id for the child loop. Defaults to `deepseek-chat`. */
model?: string;
/** Iteration ceiling for the child loop. Defaults to 16. */
maxToolIters?: number;
/**
* Maximum chars of the final assistant message returned. Long answers
* are truncated with a notice — the parent's prompt budget shouldn't
* be blown out by an over-eager subagent.
*/
maxResultChars?: number;
/** Optional sink for TUI live updates. */
sink?: SubagentSink;
/**
* Parent's per-tool-dispatch AbortSignal. When the parent aborts (Esc),
* we forward the cancel into the child loop. Omit for headless callers
* that don't care about cancellation.
*/
parentSignal?: AbortSignal;
}
/**
* Structured result of a subagent run. The two convenience JSON wrappers
* (`spawn_subagent` tool, `run_skill` subagent path) serialize this for
* the model; library callers can read the typed object directly.
*/
export interface SubagentResult {
success: boolean;
/** Final assistant message (possibly truncated). Empty on error. */
output: string;
/** Set when the run failed (network, child-loop error, etc.). */
error?: string;
/** Turns the child loop took. */
turns: number;
/** Tool calls dispatched inside the child loop. */
toolIters: number;
/** Wall-clock ms. */
elapsedMs: number;
/** USD spent in the child loop, summed across its turns. */
costUsd: number;
}
export interface SubagentToolOptions {
/** Shared DeepSeek client. */
client: DeepSeekClient;
/**
* Default system prompt used when the model doesn't pass one. Project
* memory (REASONIX.md) is appended automatically when `projectRoot` is
* set.
*/
defaultSystem?: string;
/** Project root for `applyProjectMemory` lookup. Omit in chat mode. */
projectRoot?: string;
/** Default model. `deepseek-chat` (V3) by default. */
defaultModel?: string;
/** Iteration ceiling. Lower than the parent (16 by default). */
maxToolIters?: number;
/** Maximum chars returned in the tool result. */
maxResultChars?: number;
/** Optional sink the TUI attaches its handler to for live updates. */
sink?: SubagentSink;
}
const DEFAULT_SUBAGENT_SYSTEM = `You are a Reasonix subagent. The parent agent spawned you to handle one focused subtask, then return.
Rules:
- Stay on the task you were given. Do not expand scope.
- Use tools as needed. You share the parent's sandbox + safety rules.
- When you're done, your final assistant message is the only thing the parent will see — make it complete and self-contained. No follow-up offers, no questions, no "let me know if you need more."
- Prefer one clear, distilled answer over a long log of what you tried.
Formatting rules (the parent renders your reply in a TUI with a real markdown renderer):
- For tabular data use GitHub-Flavored Markdown tables with ASCII pipes: \`| col | col |\` headers, \`| --- | --- |\` separator. NEVER draw tables with Unicode box-drawing characters (│ ─ ┼ ┌ ┐ └ ┘ ├ ┤). They look intentional but break terminal word-wrap and produce garbled output.
- Keep table cells short — one short phrase per cell, not multi-line paragraphs. If a description doesn't fit in ~40 chars, use bullets below the table instead.
- Use fenced code blocks (\`\`\`) for any code, file paths with line ranges, or shell commands.
- NEVER draw decorative frames around content with \`┌──┐ │ └──┘\` box-drawing characters. The renderer handles code blocks and headings on its own — extra ASCII art adds noise without value and breaks at narrow terminal widths.
- For flow charts and diagrams: use a markdown bullet list with \`→\` or \`↓\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;
const DEFAULT_MAX_RESULT_CHARS = 8000;
const DEFAULT_MAX_ITERS = 16;
const DEFAULT_SUBAGENT_MODEL = "deepseek-chat";
const SUBAGENT_TOOL_NAME = "spawn_subagent";
/**
* Tools the subagent never inherits from the parent registry:
* - spawn_subagent itself: would allow unbounded recursion via the
* tool API. Depth=1 hard cap by construction.
* - submit_plan: only the parent talks to the user about plan
* approval; a subagent submitting a plan would surface a picker
* midway through the parent's turn, which the user did not ask for.
*/
const NEVER_INHERITED_TOOLS = new Set<string>([SUBAGENT_TOOL_NAME, "submit_plan"]);
/**
* Run one subagent to completion. The unified primitive both
* `spawn_subagent` (function-call tool) and `run_skill` (subagent
* skills) call into.
*
* Headless: returns a `SubagentResult` regardless of success/failure.
* Errors are captured in the structured shape, never thrown — the
* caller decides how to surface them (tool result JSON, log line, etc.).
*/
export async function spawnSubagent(opts: SpawnSubagentOptions): Promise<SubagentResult> {
const model = opts.model ?? DEFAULT_SUBAGENT_MODEL;
const maxToolIters = opts.maxToolIters ?? DEFAULT_MAX_ITERS;
const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;
const sink = opts.sink;
const startedAt = Date.now();
const taskPreview = opts.task.length > 30 ? `${opts.task.slice(0, 30)}…` : opts.task;
sink?.current?.({
kind: "start",
task: taskPreview,
iter: 0,
elapsedMs: 0,
});
const childTools = forkRegistryExcluding(opts.parentRegistry, NEVER_INHERITED_TOOLS);
const childPrefix = new ImmutablePrefix({
system: opts.system,
toolSpecs: childTools.specs(),
});
const childLoop = new CacheFirstLoop({
client: opts.client,
prefix: childPrefix,
tools: childTools,
model,
maxToolIters,
hooks: [],
stream: false,
});
const onParentAbort = () => childLoop.abort();
opts.parentSignal?.addEventListener("abort", onParentAbort, { once: true });
let final = "";
let errorMessage: string | undefined;
let toolIter = 0;
try {
for await (const ev of childLoop.step(opts.task)) {
if (ev.role === "tool") {
toolIter++;
sink?.current?.({
kind: "progress",
task: taskPreview,
iter: toolIter,
elapsedMs: Date.now() - startedAt,
});
}
if (ev.role === "assistant_final") {
final = ev.content ?? "";
}
if (ev.role === "error") {
errorMessage = ev.error ?? "subagent error";
}
}
} catch (err) {
errorMessage = (err as Error).message;
} finally {
opts.parentSignal?.removeEventListener("abort", onParentAbort);
}
// The loop yields `done` without an `error` event when its API call
// is aborted mid-flight (intentional UX — see the matching catch in
// CacheFirstLoop.step). From a SUBAGENT consumer's perspective that
// still counts as a failure: no answer came back, the parent has
// nothing to render. Synthesize an error so `success: false` and the
// UI surfaces the abort instead of returning empty output.
if (!errorMessage && !final) {
errorMessage = opts.parentSignal?.aborted
? "subagent aborted before producing an answer"
: "subagent ended without producing an answer";
}
const elapsedMs = Date.now() - startedAt;
const turns = childLoop.stats.turns.length;
const costUsd = childLoop.stats.totalCost;
const truncated =
final.length > maxResultChars
? `${final.slice(0, maxResultChars)}\n\n[…truncated ${final.length - maxResultChars} chars; ask the subagent for a tighter summary if you need more.]`
: final;
sink?.current?.({
kind: "end",
task: taskPreview,
iter: toolIter,
elapsedMs,
summary: errorMessage ? undefined : truncated.slice(0, 120),
error: errorMessage,
turns,
});
return {
success: !errorMessage,
output: errorMessage ? "" : truncated,
error: errorMessage,
turns,
toolIters: toolIter,
elapsedMs,
costUsd,
};
}
/**
* Serialize a {@link SubagentResult} into the JSON tool-result shape
* the model consumes. Both the spawn_subagent tool and the run_skill
* subagent path return this string verbatim, so the schema stays
* stable across both surfaces.
*/
export function formatSubagentResult(r: SubagentResult): string {
if (!r.success) {
return JSON.stringify({
success: false,
error: r.error ?? "unknown subagent error",
turns: r.turns,
tool_iters: r.toolIters,
elapsed_ms: r.elapsedMs,
});
}
return JSON.stringify({
success: true,
output: r.output,
turns: r.turns,
tool_iters: r.toolIters,
elapsed_ms: r.elapsedMs,
cost_usd: r.costUsd,
});
}
/**
* Register the spawn_subagent tool into the parent registry. Library
* surface — `reasonix code` does NOT call this since 0.4.26 (Skills
* with `runAs: subagent` are the user-facing surface), but library
* consumers who want the low-level tool can opt in.
*/
export function registerSubagentTool(
parentRegistry: ToolRegistry,
opts: SubagentToolOptions,
): ToolRegistry {
const baseSystem = opts.defaultSystem ?? DEFAULT_SUBAGENT_SYSTEM;
// Bake project memory into the default once — re-reading on every
// spawn would (a) make the child prefix unstable when REASONIX.md
// changes mid-session, defeating cache reuse across multiple
// subagent calls, and (b) cost a stat() per call. The parent itself
// also reads memory once at startup; matching that semantics keeps
// subagent and parent on the same page.
const defaultSystem = opts.projectRoot
? applyProjectMemory(baseSystem, opts.projectRoot)
: baseSystem;
const defaultModel = opts.defaultModel ?? DEFAULT_SUBAGENT_MODEL;
const maxToolIters = opts.maxToolIters ?? DEFAULT_MAX_ITERS;
const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;
const sink = opts.sink;
parentRegistry.register({
name: SUBAGENT_TOOL_NAME,
description:
"Spawn an isolated subagent to handle a self-contained subtask in a fresh context, returning only its final answer. Use for: deep codebase exploration that would flood the main context, multi-step research where you only need the conclusion, or any focused subtask whose intermediate reasoning the user does not need to see. The subagent inherits all your tools (filesystem, shell, web, MCP, etc.) but runs in its own isolated message log — its tool calls and reasoning never enter your context. Only the final assistant message comes back as this tool's result. Keep tasks focused; the subagent has a stricter iter budget than you do.",
parameters: {
type: "object",
properties: {
task: {
type: "string",
description:
"The subtask the subagent should perform. Be specific and self-contained — the subagent has none of your conversation context, only what you write here.",
},
system: {
type: "string",
description:
"Optional override for the subagent's system prompt. The default tells it to stay focused and return a concise answer; override only when the subtask needs a specialized persona.",
},
model: {
type: "string",
enum: ["deepseek-chat", "deepseek-reasoner"],
description:
"Which DeepSeek model the subagent runs on. 'deepseek-chat' (V3) is the default — fast and cheap. Use 'deepseek-reasoner' (R1) only when the subtask genuinely needs planning or multi-step reasoning; it is roughly 5-10x more expensive.",
},
},
required: ["task"],
},
fn: async (args: { task?: unknown; system?: unknown; model?: unknown }, ctx) => {
const task = typeof args.task === "string" ? args.task.trim() : "";
if (!task) {
return JSON.stringify({
error: "spawn_subagent requires a non-empty 'task' argument.",
});
}
const system =
typeof args.system === "string" && args.system.trim().length > 0
? args.system.trim()
: defaultSystem;
const model =
typeof args.model === "string" && args.model.startsWith("deepseek-")
? args.model
: defaultModel;
const result = await spawnSubagent({
client: opts.client,
parentRegistry,
system,
task,
model,
maxToolIters,
maxResultChars,
sink,
parentSignal: ctx?.signal,
});
return formatSubagentResult(result);
},
});
return parentRegistry;
}
/**
* Build a child ToolRegistry that copies every tool from `parent` except
* those whose names are in `exclude`. Plan-mode state propagates so a
* subagent spawned while the parent is under `/plan` cannot escape it.
*
* Exported for tests + library callers who want the same fork behavior
* for their own nested-loop patterns.
*/
export function forkRegistryExcluding(
parent: ToolRegistry,
exclude: ReadonlySet<string>,
): ToolRegistry {
const child = new ToolRegistry();
for (const spec of parent.specs()) {
const name = spec.function.name;
if (exclude.has(name)) continue;
const def = parent.get(name);
if (!def) continue;
// Re-register copies the public ToolDefinition fields. The child
// re-runs auto-flatten analysis on its own, which produces an
// identical flatSchema for the same input — no surprise.
child.register(def);
}
if (parent.planMode) child.setPlanMode(true);
return child;
}
+2
View File
@@ -244,6 +244,7 @@ export function registerWebTools(registry: ToolRegistry, opts: WebToolsOptions =
name: "web_search",
description:
"Search the public web. Returns ranked results with title, url, and snippet. Use this when the question needs information more current than your training data, when you're unsure of a factual detail, or when the user asks about a specific webpage/library/release you haven't seen.",
readOnly: true,
parameters: {
type: "object",
properties: {
@@ -268,6 +269,7 @@ export function registerWebTools(registry: ToolRegistry, opts: WebToolsOptions =
name: "web_fetch",
description:
"Download a URL and return its visible text content (HTML pages get scripts/styles/nav stripped). Truncated at the tool-result cap. Use after web_search when a snippet isn't enough.",
readOnly: true,
parameters: {
type: "object",
properties: {
+281
View File
@@ -0,0 +1,281 @@
/**
* Persistent per-turn usage log at `~/.reasonix/usage.jsonl`.
*
* Each line is a single `UsageRecord` — one turn's tokens + cost
* snapshot — appended after every `assistant_final` event. This is
* what drives `reasonix stats` (the dashboard, no-arg form), so the
* user can see how much they've spent vs what the equivalent Claude
* spend would have been. The Pillar 1 pitch (94–97% cost reduction
* vs Claude, from the v0.3 hard-number table) becomes a fact users
* can verify on their own machine.
*
* Format choices:
* - **append-only JSONL** — one line per turn, durable, survives
* abrupt exits. A corrupted tail line loses at most one record.
* - **flat keys, no nesting** — readable with `jq` / `cut` / `awk`;
* the model doesn't need to parse this, humans do.
* - **best-effort writes** — disk errors never propagate into the
* turn. We log nothing (no `console.error`) because the TUI is
* rendering Ink; a silent skip is the least-worst failure mode.
* - **no PII, no prompts, no completions** — the log contains
* tokens and costs, that's it. Sessions are identified by the
* user-chosen name (never a prompt).
*
* This file is deliberately NOT wired through project memory or
* skills — those are content pins. Usage is pure telemetry.
*/
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import type { Usage } from "./client.js";
import {
CLAUDE_SONNET_PRICING,
DEEPSEEK_PRICING,
claudeEquivalentCost,
costUsd,
} from "./telemetry.js";
/** One turn's snapshot — serialized verbatim as a JSONL line. */
export interface UsageRecord {
/** Epoch millis when the record was written. */
ts: number;
/** Session name if the turn ran inside a persisted session, `null` for ephemeral. */
session: string | null;
/** Model id the turn ran against (drives the pricing lookup). */
model: string;
promptTokens: number;
completionTokens: number;
cacheHitTokens: number;
cacheMissTokens: number;
/** Total cost of the turn in USD. */
costUsd: number;
/** What the same turn would have cost at Claude Sonnet 4.6 rates. */
claudeEquivUsd: number;
}
/** Where the log lives. Tests override via `opts.path`. */
export function defaultUsageLogPath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), ".reasonix", "usage.jsonl");
}
export interface AppendUsageInput {
session: string | null;
model: string;
usage: Usage;
/** Override the timestamp (tests). */
now?: number;
/** Override the log path (tests). */
path?: string;
}
/**
* Append one record and return it. Swallows disk errors — the TUI
* should keep working even if `~/.reasonix/` is read-only.
*
* Returns the record that was written (or would have been written
* if the disk had cooperated) so tests / callers can assert on the
* computed cost fields without a round trip through the log file.
*/
export function appendUsage(input: AppendUsageInput): UsageRecord {
const record: UsageRecord = {
ts: input.now ?? Date.now(),
session: input.session,
model: input.model,
promptTokens: input.usage.promptTokens,
completionTokens: input.usage.completionTokens,
cacheHitTokens: input.usage.promptCacheHitTokens,
cacheMissTokens: input.usage.promptCacheMissTokens,
costUsd: costUsd(input.model, input.usage),
claudeEquivUsd: claudeEquivalentCost(input.usage),
};
const path = input.path ?? defaultUsageLogPath();
try {
mkdirSync(dirname(path), { recursive: true });
appendFileSync(path, `${JSON.stringify(record)}\n`, "utf8");
} catch {
/* best-effort — disk failure shouldn't break the chat */
}
return record;
}
/**
* Read + parse the log. Malformed lines are silently skipped so a
* single corrupted write (half-flushed on power loss, user hand-edit)
* doesn't throw away the rest of the history.
*/
export function readUsageLog(path: string = defaultUsageLogPath()): UsageRecord[] {
if (!existsSync(path)) return [];
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return [];
}
const out: UsageRecord[] = [];
for (const line of raw.split(/\r?\n/)) {
if (!line.trim()) continue;
try {
const rec = JSON.parse(line);
if (isValidRecord(rec)) out.push(rec);
} catch {
/* skip malformed */
}
}
return out;
}
function isValidRecord(rec: unknown): rec is UsageRecord {
if (!rec || typeof rec !== "object") return false;
const r = rec as Partial<UsageRecord>;
return (
typeof r.ts === "number" &&
typeof r.model === "string" &&
typeof r.promptTokens === "number" &&
typeof r.completionTokens === "number" &&
typeof r.cacheHitTokens === "number" &&
typeof r.cacheMissTokens === "number" &&
typeof r.costUsd === "number" &&
typeof r.claudeEquivUsd === "number"
);
}
/** One row of the `reasonix stats` dashboard — a rolled-up window. */
export interface UsageBucket {
label: string;
/** Start of the window as epoch millis. `0` = unbounded (all-time). */
since: number;
turns: number;
promptTokens: number;
completionTokens: number;
cacheHitTokens: number;
cacheMissTokens: number;
costUsd: number;
claudeEquivUsd: number;
}
/** Cache hit ratio for a bucket — zero denominator returns 0. */
export function bucketCacheHitRatio(b: UsageBucket): number {
const denom = b.cacheHitTokens + b.cacheMissTokens;
return denom > 0 ? b.cacheHitTokens / denom : 0;
}
/** Savings vs Claude as a fraction (0.94 = 94% savings). 0 if Claude cost is 0. */
export function bucketSavingsFraction(b: UsageBucket): number {
return b.claudeEquivUsd > 0 ? 1 - b.costUsd / b.claudeEquivUsd : 0;
}
function emptyBucket(label: string, since: number): UsageBucket {
return {
label,
since,
turns: 0,
promptTokens: 0,
completionTokens: 0,
cacheHitTokens: 0,
cacheMissTokens: 0,
costUsd: 0,
claudeEquivUsd: 0,
};
}
function addToBucket(b: UsageBucket, r: UsageRecord): void {
b.turns += 1;
b.promptTokens += r.promptTokens;
b.completionTokens += r.completionTokens;
b.cacheHitTokens += r.cacheHitTokens;
b.cacheMissTokens += r.cacheMissTokens;
b.costUsd += r.costUsd;
b.claudeEquivUsd += r.claudeEquivUsd;
}
export interface AggregateOptions {
/** Override `Date.now()` for deterministic tests. */
now?: number;
}
export interface UsageAggregate {
/** Fixed-order rolling windows: today, week, month, all-time. */
buckets: UsageBucket[];
/** Model id → turn count. Sorted descending; top entry is the "most used." */
byModel: Array<{ model: string; turns: number }>;
/** Session name → turn count. Sorted descending. Null sessions are grouped under `"(ephemeral)"`. */
bySession: Array<{ session: string; turns: number }>;
/** Earliest record's ts, or `null` when the log is empty. Drives "saved $X since <date>". */
firstSeen: number | null;
/** Latest record's ts, or `null` when the log is empty. */
lastSeen: number | null;
}
/**
* Fold a flat record list into the dashboard shape — rolling windows
* plus model / session histograms. Windows are INCLUSIVE of boundary:
* - today = last 24h (rolling, not calendar-day)
* - week = last 7d
* - month = last 30d
* - all = every record
* Rolling windows avoid "it's 00:03, 'today' is empty" surprises.
*/
export function aggregateUsage(
records: UsageRecord[],
opts: AggregateOptions = {},
): UsageAggregate {
const now = opts.now ?? Date.now();
const day = 24 * 60 * 60 * 1000;
const today = emptyBucket("today", now - day);
const week = emptyBucket("week", now - 7 * day);
const month = emptyBucket("month", now - 30 * day);
const all = emptyBucket("all-time", 0);
const modelCounts = new Map<string, number>();
const sessionCounts = new Map<string, number>();
let firstSeen: number | null = null;
let lastSeen: number | null = null;
for (const r of records) {
addToBucket(all, r);
if (r.ts >= today.since) addToBucket(today, r);
if (r.ts >= week.since) addToBucket(week, r);
if (r.ts >= month.since) addToBucket(month, r);
modelCounts.set(r.model, (modelCounts.get(r.model) ?? 0) + 1);
const sessKey = r.session ?? "(ephemeral)";
sessionCounts.set(sessKey, (sessionCounts.get(sessKey) ?? 0) + 1);
if (firstSeen === null || r.ts < firstSeen) firstSeen = r.ts;
if (lastSeen === null || r.ts > lastSeen) lastSeen = r.ts;
}
const byModel = Array.from(modelCounts.entries())
.map(([model, turns]) => ({ model, turns }))
.sort((a, b) => b.turns - a.turns);
const bySession = Array.from(sessionCounts.entries())
.map(([session, turns]) => ({ session, turns }))
.sort((a, b) => b.turns - a.turns);
return {
buckets: [today, week, month, all],
byModel,
bySession,
firstSeen,
lastSeen,
};
}
/** File-size helper for the stats header — "1.2 MB" etc. Returns "" if missing. */
export function formatLogSize(path: string = defaultUsageLogPath()): string {
if (!existsSync(path)) return "";
try {
const s = statSync(path);
const bytes = s.size;
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
} catch {
return "";
}
}
/** Re-exports for downstream consumers that also want the pricing constants. */
export { CLAUDE_SONNET_PRICING, DEEPSEEK_PRICING };
+395
View File
@@ -0,0 +1,395 @@
/**
* User memory — `~/.reasonix/memory/` markdown notes pinned into the
* immutable-prefix system prompt across sessions.
*
* Two scopes:
* - `global` → `~/.reasonix/memory/global/` (cross-project)
* - `project` → `~/.reasonix/memory/<hash>/` (per sandbox root)
*
* Each scope has an always-loaded `MEMORY.md` index plus zero-or-more
* `<name>.md` detail files loaded on demand via `recall_memory`.
*
* Distinct from `src/project-memory.ts` (REASONIX.md) in purpose:
* REASONIX.md is committable, team-shared project memory.
* ~/.reasonix/memory is user-private memory, never committed.
*/
import { createHash } from "node:crypto";
import {
existsSync,
mkdirSync,
readFileSync,
readdirSync,
unlinkSync,
writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { applyProjectMemory, memoryEnabled } from "./project-memory.js";
import { applySkillsIndex } from "./skills.js";
export const USER_MEMORY_DIR = "memory";
export const MEMORY_INDEX_FILE = "MEMORY.md";
/** Cap on the index file content loaded into the prefix, per scope. */
export const MEMORY_INDEX_MAX_CHARS = 4000;
export type MemoryType = "user" | "feedback" | "project" | "reference";
export type MemoryScope = "global" | "project";
export interface MemoryEntry {
name: string;
type: MemoryType;
scope: MemoryScope;
description: string;
body: string;
/** ISO date string (YYYY-MM-DD). */
createdAt: string;
}
export interface MemoryStoreOptions {
/** Override `~/.reasonix` — tests set this to a tmpdir. */
homeDir?: string;
/** Absolute sandbox root. Required to use `scope: "project"`. */
projectRoot?: string;
}
export interface WriteInput {
name: string;
type: MemoryType;
scope: MemoryScope;
description: string;
body: string;
}
const VALID_NAME = /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{1,38}[a-zA-Z0-9]$/;
/**
* Throws on filename injection attempts (`../foo`, `foo/bar`, leading
* dots, etc.). Allowed: 3-40 chars, alnum + `_` + `-` + interior `.`.
*/
export function sanitizeMemoryName(raw: string): string {
const trimmed = String(raw ?? "").trim();
if (!VALID_NAME.test(trimmed)) {
throw new Error(
`invalid memory name: ${JSON.stringify(raw)} — must be 3-40 chars, alnum/_/-, no path separators`,
);
}
return trimmed;
}
/** Stable 16-hex-char hash of an absolute sandbox root path. */
export function projectHash(rootDir: string): string {
const abs = resolve(rootDir);
return createHash("sha1").update(abs).digest("hex").slice(0, 16);
}
function scopeDir(opts: { homeDir: string; scope: MemoryScope; projectRoot?: string }): string {
if (opts.scope === "global") {
return join(opts.homeDir, USER_MEMORY_DIR, "global");
}
if (!opts.projectRoot) {
throw new Error("scope=project requires a projectRoot on MemoryStore");
}
return join(opts.homeDir, USER_MEMORY_DIR, projectHash(opts.projectRoot));
}
function ensureDir(p: string): void {
if (!existsSync(p)) mkdirSync(p, { recursive: true });
}
/**
* Parse a `---` frontmatter block off the top of a markdown string.
* Tolerates missing frontmatter, returning `{}` for data and the full
* string as body. Only recognizes the simple `key: value` shape — no
* quoting, no multi-line, no YAML features. Matches what we emit.
*/
function parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {
const lines = raw.split(/\r?\n/);
if (lines[0] !== "---") return { data: {}, body: raw };
const end = lines.indexOf("---", 1);
if (end < 0) return { data: {}, body: raw };
const data: Record<string, string> = {};
for (let i = 1; i < end; i++) {
const line = lines[i];
if (!line) continue;
const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$/);
if (m?.[1]) data[m[1]] = (m[2] ?? "").trim();
}
return {
data,
body: lines
.slice(end + 1)
.join("\n")
.replace(/^\n+/, ""),
};
}
function formatFrontmatter(e: WriteInput & { createdAt: string }): string {
return [
"---",
`name: ${e.name}`,
`description: ${e.description.replace(/\n/g, " ")}`,
`type: ${e.type}`,
`scope: ${e.scope}`,
`created: ${e.createdAt}`,
"---",
"",
].join("\n");
}
function todayIso(): string {
const d = new Date();
return d.toISOString().slice(0, 10);
}
/**
* A `MEMORY.md` index line for one entry. One-liner, under ~150 chars.
* `description` is truncated if it would push past the soft limit.
*/
function indexLine(e: Pick<MemoryEntry, "name" | "description">): string {
const safeDesc = e.description.replace(/\n/g, " ").trim();
const max = 130 - e.name.length;
const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;
return `- [${e.name}](${e.name}.md) — ${clipped}`;
}
export class MemoryStore {
private readonly homeDir: string;
private readonly projectRoot: string | undefined;
constructor(opts: MemoryStoreOptions = {}) {
this.homeDir = opts.homeDir ?? join(homedir(), ".reasonix");
this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;
}
/** Directory this store writes `scope` files into, creating it if needed. */
dir(scope: MemoryScope): string {
const d = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });
ensureDir(d);
return d;
}
/** Absolute path to a memory file (no existence check). */
pathFor(scope: MemoryScope, name: string): string {
return join(this.dir(scope), `${sanitizeMemoryName(name)}.md`);
}
/** True iff this store is configured with a project scope available. */
hasProjectScope(): boolean {
return this.projectRoot !== undefined;
}
/**
* Read the `MEMORY.md` index for a scope. Returns post-cap content
* (with a truncation marker if clipped), or `null` when absent / empty.
*/
loadIndex(
scope: MemoryScope,
): { content: string; originalChars: number; truncated: boolean } | null {
if (scope === "project" && !this.projectRoot) return null;
const file = join(
scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot }),
MEMORY_INDEX_FILE,
);
if (!existsSync(file)) return null;
let raw: string;
try {
raw = readFileSync(file, "utf8");
} catch {
return null;
}
const trimmed = raw.trim();
if (!trimmed) return null;
const originalChars = trimmed.length;
const truncated = originalChars > MEMORY_INDEX_MAX_CHARS;
const content = truncated
? `${trimmed.slice(0, MEMORY_INDEX_MAX_CHARS)}\n… (truncated ${originalChars - MEMORY_INDEX_MAX_CHARS} chars)`
: trimmed;
return { content, originalChars, truncated };
}
/** Read one memory file's body (frontmatter stripped). Throws if missing. */
read(scope: MemoryScope, name: string): MemoryEntry {
const file = this.pathFor(scope, name);
if (!existsSync(file)) {
throw new Error(`memory not found: scope=${scope} name=${name}`);
}
const raw = readFileSync(file, "utf8");
const { data, body } = parseFrontmatter(raw);
return {
name: data.name ?? name,
type: (data.type as MemoryType) ?? "project",
scope: (data.scope as MemoryScope) ?? scope,
description: data.description ?? "",
body: body.trim(),
createdAt: data.created ?? "",
};
}
/**
* List every memory in this store. Scans both scopes (skips project
* scope if unconfigured). Silently skips malformed files; the index
* must stay queryable even if one file is hand-edited into nonsense.
*/
list(): MemoryEntry[] {
const out: MemoryEntry[] = [];
const scopes: MemoryScope[] = this.projectRoot ? ["global", "project"] : ["global"];
for (const scope of scopes) {
const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });
if (!existsSync(dir)) continue;
let entries: string[];
try {
entries = readdirSync(dir);
} catch {
continue;
}
for (const entry of entries) {
if (entry === MEMORY_INDEX_FILE) continue;
if (!entry.endsWith(".md")) continue;
const name = entry.slice(0, -3);
try {
out.push(this.read(scope, name));
} catch {
// malformed file — skip rather than fail the whole list
}
}
}
return out;
}
/**
* Write a new memory (or overwrite existing). Creates the scope dir,
* writes the `.md` file, and regenerates `MEMORY.md`. Returns the
* absolute path written to.
*/
write(input: WriteInput): string {
if (input.scope === "project" && !this.projectRoot) {
throw new Error("cannot write project-scoped memory: no projectRoot configured");
}
const name = sanitizeMemoryName(input.name);
const desc = String(input.description ?? "").trim();
if (!desc) throw new Error("memory description cannot be empty");
const body = String(input.body ?? "").trim();
if (!body) throw new Error("memory body cannot be empty");
const entry: WriteInput & { createdAt: string } = {
...input,
name,
description: desc,
body,
createdAt: todayIso(),
};
const dir = this.dir(input.scope);
const file = join(dir, `${name}.md`);
const content = `${formatFrontmatter(entry)}${body}\n`;
writeFileSync(file, content, "utf8");
this.regenerateIndex(input.scope);
return file;
}
/** Delete one memory + its index line. No-op if the file is already gone. */
delete(scope: MemoryScope, rawName: string): boolean {
if (scope === "project" && !this.projectRoot) {
throw new Error("cannot delete project-scoped memory: no projectRoot configured");
}
const file = this.pathFor(scope, rawName);
if (!existsSync(file)) return false;
unlinkSync(file);
this.regenerateIndex(scope);
return true;
}
/**
* Rebuild `MEMORY.md` from the `.md` files currently in the scope dir.
* Called after every write/delete. Sorted by name for stable prefix
* hashing — two stores with the same set of files produce byte-identical
* MEMORY.md content, keeping the cache prefix reproducible.
*/
private regenerateIndex(scope: MemoryScope): void {
const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });
if (!existsSync(dir)) return;
let files: string[];
try {
files = readdirSync(dir);
} catch {
return;
}
const mdFiles = files
.filter((f) => f !== MEMORY_INDEX_FILE && f.endsWith(".md"))
.sort((a, b) => a.localeCompare(b));
const indexPath = join(dir, MEMORY_INDEX_FILE);
if (mdFiles.length === 0) {
if (existsSync(indexPath)) unlinkSync(indexPath);
return;
}
const lines: string[] = [];
for (const f of mdFiles) {
const name = f.slice(0, -3);
try {
const entry = this.read(scope, name);
lines.push(indexLine({ name: entry.name || name, description: entry.description }));
} catch {
// Malformed: still surface it in the index so the user notices.
lines.push(`- [${name}](${name}.md) — (malformed, check frontmatter)`);
}
}
writeFileSync(indexPath, `${lines.join("\n")}\n`, "utf8");
}
}
/**
* Append `MEMORY_GLOBAL` and (optionally) `MEMORY_PROJECT` blocks to
* `basePrompt`. Omits a block entirely when its index is absent — an
* empty tag would add bytes to the prefix hash without content.
* Respects `REASONIX_MEMORY=off` via `memoryEnabled()` from
* `project-memory.ts`.
*/
export function applyUserMemory(
basePrompt: string,
opts: { homeDir?: string; projectRoot?: string } = {},
): string {
if (!memoryEnabled()) return basePrompt;
const store = new MemoryStore(opts);
const global = store.loadIndex("global");
const project = store.hasProjectScope() ? store.loadIndex("project") : null;
if (!global && !project) return basePrompt;
const parts: string[] = [basePrompt];
if (global) {
parts.push(
"",
"# User memory — global (~/.reasonix/memory/global/MEMORY.md)",
"",
"Cross-project facts and preferences the user has told you in prior sessions. TREAT AS AUTHORITATIVE — don't re-verify via filesystem or web. One-liners index detail files; call `recall_memory` for full bodies only when the one-liner isn't enough.",
"",
"```",
global.content,
"```",
);
}
if (project) {
parts.push(
"",
"# User memory — this project",
"",
"Per-project facts the user established in prior sessions (not committed to the repo). TREAT AS AUTHORITATIVE. Same recall pattern as global memory.",
"",
"```",
project.content,
"```",
);
}
return parts.join("\n");
}
/**
* Compose every lazy-loaded prefix block in one call: REASONIX.md,
* user memory (global + project), and the skills index. Drop-in
* replacement for `applyProjectMemory` at CLI entry points. Stacking
* order is stable — the prefix hash only changes when block *content*
* changes, not when this helper is called a second time with the same
* filesystem state.
*/
export function applyMemoryStack(basePrompt: string, rootDir: string): string {
const withProject = applyProjectMemory(basePrompt, rootDir);
const withMemory = applyUserMemory(withProject, { projectRoot: rootDir });
return applySkillsIndex(withMemory, { projectRoot: rootDir });
}
+209
View File
@@ -0,0 +1,209 @@
/**
* Version module.
*
* Two jobs:
*
* 1. Expose `VERSION` sourced from the real `package.json` so the
* constant never drifts from what npm publishes. Works in dev
* (`tsx src/...`) AND after `tsup` bundles to `dist/` — both
* layouts sit two levels below the manifest, so a short
* walk-up finds it.
*
* 2. Offer an opt-in `getLatestVersion()` that hits the npm
* registry with a bounded timeout and a 24-hour on-disk
* cache at `~/.reasonix/version-cache.json`. Returns `null`
* on any failure — offline / restricted-network launches
* should stay silent rather than nag the user.
*
* The CLI wires `getLatestVersion` asynchronously at App mount
* (never in a hot path) and renders the outcome in the stats
* panel when there's a newer published version.
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
/** npm registry endpoint for the `latest` dist-tag of this package. */
const REGISTRY_URL = "https://registry.npmjs.org/reasonix/latest";
/** TTL for the on-disk cache entry. 24h keeps noise low; users who
* want a fresh check can run `reasonix update` which passes
* `force: true`. */
export const LATEST_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
/** Network timeout. Short — we never block the UI waiting on this. */
export const LATEST_FETCH_TIMEOUT_MS = 2_000;
/**
* Walk up from the current source file looking for the `reasonix`
* package.json. Works for:
* - dev: `src/version.ts` → `F:/Reasonix/package.json` (2 levels up)
* - built: `dist/index.js` → `F:/Reasonix/package.json` (2 levels up)
* - global install: `.../node_modules/reasonix/dist/index.js` → `.../reasonix/package.json`
*
* The `name === "reasonix"` guard is a cheap safety net against
* picking up the nearest *other* package.json if we're ever loaded
* as a dependency and the layout is unusual.
*/
function readPackageVersion(): string {
try {
let dir = dirname(fileURLToPath(import.meta.url));
for (let i = 0; i < 6; i++) {
const p = join(dir, "package.json");
if (existsSync(p)) {
const pkg = JSON.parse(readFileSync(p, "utf8"));
if (pkg?.name === "reasonix" && typeof pkg.version === "string") {
return pkg.version;
}
}
const parent = dirname(dir);
if (parent === dir) break;
dir = parent;
}
} catch {
/* fall through to fallback */
}
return "0.0.0-dev";
}
export const VERSION: string = readPackageVersion();
interface VersionCacheEntry {
version: string;
/** Epoch millis the entry was written. Drives TTL comparisons. */
checkedAt: number;
}
function cachePath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), ".reasonix", "version-cache.json");
}
function readCache(homeDirOverride?: string): VersionCacheEntry | null {
try {
const raw = readFileSync(cachePath(homeDirOverride), "utf8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed.version === "string" && typeof parsed.checkedAt === "number") {
return parsed;
}
} catch {
/* missing or malformed → no cached entry */
}
return null;
}
function writeCache(entry: VersionCacheEntry, homeDirOverride?: string): void {
try {
const p = cachePath(homeDirOverride);
mkdirSync(dirname(p), { recursive: true });
writeFileSync(p, JSON.stringify(entry), "utf8");
} catch {
/* cache is best-effort — a failed write just means we'll re-fetch
* next launch. No reason to surface this to the user. */
}
}
export interface GetLatestVersionOptions {
/** Ignore the cached entry and always fetch fresh. Used by `reasonix update`. */
force?: boolean;
/** Registry URL override (tests). */
registryUrl?: string;
/** Home-directory override (tests). */
homeDir?: string;
/** Fetch implementation override (tests). Defaults to `globalThis.fetch`. */
fetchImpl?: typeof fetch;
/** TTL override (tests). */
ttlMs?: number;
/** Network timeout override (tests). */
timeoutMs?: number;
}
/**
* Resolve the latest published `reasonix` version from the npm registry.
*
* Returns `null` on any network / parse failure. Callers treat `null`
* as "don't know, don't nag the user." The cache entry is only
* written on a successful fetch — a bad registry response won't
* poison the cache.
*/
export async function getLatestVersion(opts: GetLatestVersionOptions = {}): Promise<string | null> {
const ttl = opts.ttlMs ?? LATEST_CACHE_TTL_MS;
if (!opts.force) {
const cached = readCache(opts.homeDir);
if (cached && Date.now() - cached.checkedAt < ttl) return cached.version;
}
const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
if (!fetchImpl) return null;
const url = opts.registryUrl ?? REGISTRY_URL;
const timeout = opts.timeoutMs ?? LATEST_FETCH_TIMEOUT_MS;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const res = await fetchImpl(url, {
signal: controller.signal,
headers: { accept: "application/json" },
});
if (!res.ok) return null;
const body = (await res.json()) as { version?: unknown };
if (typeof body.version !== "string") return null;
writeCache({ version: body.version, checkedAt: Date.now() }, opts.homeDir);
return body.version;
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
/**
* Semver compare. Returns a negative number when `a < b`, positive
* when `a > b`, zero when equal.
*
* Minimal pre-release handling: when the CORE (`x.y.z`) parts match,
* any version WITH a suffix (`-rc.1`, `-alpha.4`) compares LOWER
* than the bare version. That matches npm's dist-tag semantics —
* `reasonix@latest` resolves to a real release, not a pre-release.
*
* We're deliberately not pulling in `semver` (~50KB). The three
* cases we care about are: current > latest (future build, no
* prompt), current < latest (prompt), current === latest (no prompt).
*/
export function compareVersions(a: string, b: string): number {
const [aCore = "0", aPre = ""] = a.split("-", 2);
const [bCore = "0", bPre = ""] = b.split("-", 2);
const aParts = aCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
const bParts = bCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
for (let i = 0; i < 3; i++) {
const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);
if (diff !== 0) return diff;
}
if (!aPre && !bPre) return 0;
if (!aPre) return 1;
if (!bPre) return -1;
return aPre < bPre ? -1 : aPre > bPre ? 1 : 0;
}
/**
* Heuristic: did this process launch via `npx` / `pnpm dlx` instead
* of a global install? The update command takes different advice in
* each case — a global install can `npm i -g reasonix@latest`, while
* npx just needs its cache to roll over on next launch.
*
* Signals checked, in order:
* - `process.argv[1]` contains `_npx` (npm's ephemeral dir name)
* - `process.argv[1]` contains `.pnpm` + `dlx`
* - `npm_config_user_agent` contains `npx/`
*
* Any one hit → npx. False negatives are safe (worst case we suggest
* `npm i -g` to an npx user, which is a valid way to upgrade too).
*/
export function isNpxInstall(): boolean {
const bin = process.argv[1] ?? "";
if (/[/\\]_npx[/\\]/.test(bin)) return true;
if (/[/\\]\.pnpm[/\\]/.test(bin) && /dlx/i.test(bin)) return true;
const ua = process.env.npm_config_user_agent ?? "";
if (ua.includes("npx/")) return true;
return false;
}
+17 -10
View File
@@ -18,8 +18,14 @@ describe("codeSystemPrompt", () => {
rmSync(root, { recursive: true, force: true });
});
it("returns the base prompt unchanged when no .gitignore exists", () => {
expect(codeSystemPrompt(root)).toBe(CODE_SYSTEM_PROMPT);
it("does not append a .gitignore section when none exists", () => {
// We can no longer assert raw equality with CODE_SYSTEM_PROMPT —
// the bundled builtin skills (`explore`, `research`) always inject
// a `# Skills` block via applySkillsIndex. Assert the absence of
// the .gitignore-specific section instead.
const out = codeSystemPrompt(root);
expect(out).not.toMatch(/# Project \.gitignore/);
expect(out).toContain(CODE_SYSTEM_PROMPT);
});
it("appends the .gitignore content as a fenced block", () => {
@@ -36,15 +42,16 @@ describe("codeSystemPrompt", () => {
writeFileSync(join(root, ".gitignore"), huge, "utf8");
const out = codeSystemPrompt(root);
expect(out).toMatch(/truncated \d+ chars/);
// The prompt (base + truncated + fences) is bounded, not 5000+.
expect(out.length).toBeLessThan(CODE_SYSTEM_PROMPT.length + 2300);
// The .gitignore block (base + truncated + fences) is bounded.
// Allow extra slack for the builtin Skills index that applyMemoryStack
// also injects — that's a fixed-size addition, not unbounded.
expect(out.length).toBeLessThan(CODE_SYSTEM_PROMPT.length + 4500);
});
it("still reminds the model about built-in ignores even without a .gitignore", () => {
// Base prompt mentions node_modules / dist / .git as "avoid listing"
// so new-repo users without .gitignore still get the hint.
expect(CODE_SYSTEM_PROMPT).toMatch(/node_modules/);
expect(CODE_SYSTEM_PROMPT).toMatch(/dist/);
expect(CODE_SYSTEM_PROMPT).toMatch(/\.git/);
it("reminds the model to skip dependency / build / VCS dirs", () => {
// We don't enumerate specific names in the prompt anymore (too
// ecosystem-biased); the principle is stated generically and the
// pinned .gitignore block is the authoritative denylist.
expect(CODE_SYSTEM_PROMPT).toMatch(/dependency.*build.*VCS|skip/i);
});
});
+128 -2
View File
@@ -51,9 +51,13 @@ describe("filesystem tools (built-in, sandbox-enforced)", () => {
expect(out).toMatch(/escapes sandbox/);
});
it("rejects absolute paths outside root", async () => {
it("reinterprets POSIX-absolute paths as sandbox-relative (model can't escape via /)", async () => {
// Sandbox-root semantics: `/etc/passwd` becomes `etc/passwd`
// under rootDir. Real /etc/passwd stays unreachable; the lookup
// just fails because <root>/etc/passwd doesn't exist.
const out = await tools.dispatch("read_file", JSON.stringify({ path: "/etc/passwd" }));
expect(out).toMatch(/escapes sandbox/);
expect(out).not.toMatch(/escapes sandbox/);
expect(out).toMatch(/ENOENT|no such file/i);
});
it("returns a truncation notice when file exceeds maxReadBytes", async () => {
@@ -110,6 +114,128 @@ describe("filesystem tools (built-in, sandbox-enforced)", () => {
const out = await tools.dispatch("search_files", JSON.stringify({ pattern: "nothing123" }));
expect(out).toBe("(no matches)");
});
it("treats path: '/' as the sandbox root (model's POSIX intuition)", async () => {
// Common model failure mode: the LLM passes path: "/" intending
// "search the whole project". Without sandbox-root semantics
// path.resolve treats "/" as the actual filesystem root, the
// escape check rejects it, and the model sees a confusing error.
const out = await tools.dispatch(
"search_files",
JSON.stringify({ path: "/", pattern: "index" }),
);
expect(out).not.toMatch(/escapes sandbox/);
expect(out).toContain("index.ts");
});
it("treats path: '/src' as <root>/src", async () => {
const out = await tools.dispatch(
"search_files",
JSON.stringify({ path: "/src", pattern: "util" }),
);
expect(out).not.toMatch(/escapes sandbox/);
expect(out).toContain("util.ts");
});
});
describe("search_content", () => {
it("finds a literal substring inside a file's content", async () => {
// src/index.ts has `export const x = 1;`
const out = await tools.dispatch(
"search_content",
JSON.stringify({ pattern: "export const x" }),
);
// Format: path:line: text
expect(out).toMatch(/src[\\/]index\.ts:1: export const x = 1;/);
});
it("matches across multiple files and reports each line", async () => {
// Both src/index.ts and src/util.ts have `export const`.
const out = await tools.dispatch(
"search_content",
JSON.stringify({ pattern: "export const" }),
);
expect(out).toContain("index.ts");
expect(out).toContain("util.ts");
});
it("supports regex patterns (word-bounded match)", async () => {
const out = await tools.dispatch(
"search_content",
JSON.stringify({ pattern: "\\bexport\\s+const\\s+y\\b" }),
);
expect(out).toContain("util.ts");
expect(out).not.toContain("index.ts");
});
it("is case-insensitive by default", async () => {
const out = await tools.dispatch("search_content", JSON.stringify({ pattern: "EXPORT" }));
expect(out).toContain("export");
});
it("respects case_sensitive when set", async () => {
const out = await tools.dispatch(
"search_content",
JSON.stringify({ pattern: "EXPORT", case_sensitive: true }),
);
expect(out).toMatch(/no matches/);
});
it("filters by glob substring on the file name", async () => {
const out = await tools.dispatch(
"search_content",
JSON.stringify({ pattern: "export const", glob: "util" }),
);
expect(out).toContain("util.ts");
expect(out).not.toContain("index.ts");
});
it("skips dependency dirs by default", async () => {
// Drop a node_modules-style file matching the pattern.
await fs.mkdir(join(root, "node_modules", "junk"), { recursive: true });
await fs.writeFile(
join(root, "node_modules", "junk", "vendor.ts"),
"export const NEEDLE = 1;\n",
);
const out = await tools.dispatch("search_content", JSON.stringify({ pattern: "NEEDLE" }));
expect(out).toMatch(/no matches/);
});
it("includes dependency dirs when include_deps:true", async () => {
await fs.mkdir(join(root, "node_modules", "junk"), { recursive: true });
await fs.writeFile(
join(root, "node_modules", "junk", "vendor.ts"),
"export const NEEDLE = 1;\n",
);
const out = await tools.dispatch(
"search_content",
JSON.stringify({ pattern: "NEEDLE", include_deps: true }),
);
expect(out).toContain("vendor.ts");
});
it("skips binary files by extension", async () => {
// A .png with searchable text inside — extension wins.
await fs.writeFile(join(root, "logo.png"), "this is a PNG with NEEDLE inside\n");
const out = await tools.dispatch("search_content", JSON.stringify({ pattern: "NEEDLE" }));
expect(out).not.toContain("logo.png");
});
it("skips binary files by content (NUL byte sniff)", async () => {
// A .txt that's actually binary — content sniff catches it.
const buf = Buffer.concat([Buffer.from("NEEDLE\0"), Buffer.from([0, 1, 2, 3])]);
await fs.writeFile(join(root, "data.txt"), buf);
const out = await tools.dispatch("search_content", JSON.stringify({ pattern: "NEEDLE" }));
expect(out).not.toContain("data.txt");
});
it("returns a clean (no matches) message when nothing matches", async () => {
const out = await tools.dispatch(
"search_content",
JSON.stringify({ pattern: "definitely_not_present_anywhere_zxq" }),
);
expect(out).toMatch(/no matches/);
});
});
describe("get_file_info", () => {
+354
View File
@@ -0,0 +1,354 @@
/**
* Tests for the hooks module — settings loading, match patterns,
* outcome decisions, and the runHooks dispatcher with a stubbed
* spawner. No real subprocesses, no real filesystem outside tmp dirs.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
type HookSpawnInput,
type HookSpawnResult,
type ResolvedHook,
decideOutcome,
formatHookOutcomeMessage,
globalSettingsPath,
loadHooks,
matchesTool,
projectSettingsPath,
runHooks,
} from "../src/hooks.js";
function writeSettings(dir: string, json: unknown): string {
const path = join(dir, ".reasonix", "settings.json");
mkdirSync(join(dir, ".reasonix"), { recursive: true });
writeFileSync(path, JSON.stringify(json), "utf8");
return path;
}
function makeSpawner(
responses: HookSpawnResult[],
log?: HookSpawnInput[],
): (input: HookSpawnInput) => Promise<HookSpawnResult> {
let i = 0;
return async (input) => {
log?.push(input);
const r = responses[i++];
if (!r) throw new Error("spawner exhausted — test set up too few responses");
return r;
};
}
const ok = (overrides: Partial<HookSpawnResult> = {}): HookSpawnResult => ({
exitCode: 0,
stdout: "",
stderr: "",
timedOut: false,
...overrides,
});
describe("loadHooks", () => {
let home: string;
let project: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-hooks-home-"));
project = mkdtempSync(join(tmpdir(), "reasonix-hooks-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(project, { recursive: true, force: true });
});
it("returns [] when no settings file exists in either scope", () => {
expect(loadHooks({ homeDir: home, projectRoot: project })).toEqual([]);
});
it("loads project then global, in array order, with scope tags", () => {
writeSettings(home, {
hooks: { Stop: [{ command: "echo global1" }, { command: "echo global2" }] },
});
writeSettings(project, {
hooks: { Stop: [{ command: "echo proj" }] },
});
const hooks = loadHooks({ homeDir: home, projectRoot: project });
expect(hooks.map((h) => `${h.scope}:${h.command}`)).toEqual([
"project:echo proj",
"global:echo global1",
"global:echo global2",
]);
});
it("ignores entries without a string command", () => {
writeSettings(home, {
hooks: {
Stop: [
{ command: "echo good" },
{ command: "" },
{ description: "no command" },
{ command: 42 } as unknown as { command: string },
],
},
});
const hooks = loadHooks({ homeDir: home });
expect(hooks).toHaveLength(1);
expect(hooks[0]?.command).toBe("echo good");
});
it("tolerates malformed JSON without throwing", () => {
mkdirSync(join(home, ".reasonix"), { recursive: true });
writeFileSync(join(home, ".reasonix", "settings.json"), "{ not valid json", "utf8");
expect(() => loadHooks({ homeDir: home })).not.toThrow();
expect(loadHooks({ homeDir: home })).toEqual([]);
});
it("project scope is skipped when projectRoot omitted", () => {
writeSettings(project, { hooks: { Stop: [{ command: "echo proj" }] } });
const hooks = loadHooks({ homeDir: home }); // no projectRoot
expect(hooks).toEqual([]);
});
it("paths reported by *SettingsPath helpers are absolute", () => {
expect(globalSettingsPath(home)).toBe(join(home, ".reasonix", "settings.json"));
expect(projectSettingsPath(project)).toBe(join(project, ".reasonix", "settings.json"));
});
});
describe("matchesTool", () => {
const baseHook: ResolvedHook = {
event: "PreToolUse",
scope: "global",
source: "/tmp/x",
command: "true",
};
it("returns true when match is undefined or '*'", () => {
expect(matchesTool(baseHook, "edit_file")).toBe(true);
expect(matchesTool({ ...baseHook, match: "*" }, "edit_file")).toBe(true);
});
it("anchored regex matches only the full tool name", () => {
const hook: ResolvedHook = { ...baseHook, match: "edit_file|write_file" };
expect(matchesTool(hook, "edit_file")).toBe(true);
expect(matchesTool(hook, "write_file")).toBe(true);
expect(matchesTool(hook, "read_file")).toBe(false);
// Substring should NOT match (anchored)
expect(matchesTool({ ...baseHook, match: "file" }, "edit_file")).toBe(false);
});
it("malformed regex falls back to no-match (safer than fire-on-everything)", () => {
const hook: ResolvedHook = { ...baseHook, match: "[unclosed" };
expect(matchesTool(hook, "edit_file")).toBe(false);
});
it("non-tool events ignore the match field", () => {
const hook: ResolvedHook = {
...baseHook,
event: "UserPromptSubmit",
match: "never",
};
expect(matchesTool(hook, "anything")).toBe(true);
});
});
describe("decideOutcome", () => {
it("exit 0 → pass", () => {
expect(decideOutcome("PreToolUse", ok())).toBe("pass");
});
it("exit 2 on PreToolUse → block", () => {
expect(decideOutcome("PreToolUse", ok({ exitCode: 2 }))).toBe("block");
});
it("exit 2 on PostToolUse → warn (block is meaningless after the fact)", () => {
expect(decideOutcome("PostToolUse", ok({ exitCode: 2 }))).toBe("warn");
});
it("any other non-zero → warn", () => {
expect(decideOutcome("PreToolUse", ok({ exitCode: 1 }))).toBe("warn");
expect(decideOutcome("Stop", ok({ exitCode: 127 }))).toBe("warn");
});
it("timeout on a blocking event → block, on a logging event → warn", () => {
expect(decideOutcome("PreToolUse", ok({ timedOut: true, exitCode: null }))).toBe("block");
expect(decideOutcome("Stop", ok({ timedOut: true, exitCode: null }))).toBe("warn");
});
it("spawn error → error, regardless of event", () => {
const err = ok({ exitCode: null, spawnError: new Error("ENOENT") });
expect(decideOutcome("PreToolUse", err)).toBe("error");
expect(decideOutcome("Stop", err)).toBe("error");
});
});
describe("runHooks", () => {
const hook = (overrides: Partial<ResolvedHook> = {}): ResolvedHook => ({
event: "PreToolUse",
scope: "project",
source: "/tmp/x",
command: "true",
...overrides,
});
it("filters by event AND tool match before running", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok()], log);
const hooks: ResolvedHook[] = [
hook({ event: "Stop", command: "wrong-event" }),
hook({ event: "PreToolUse", match: "write_file", command: "wrong-tool" }),
hook({ event: "PreToolUse", match: "edit_file", command: "right" }),
];
const report = await runHooks({
hooks,
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "edit_file" },
});
expect(log).toHaveLength(1);
expect(log[0]?.command).toBe("right");
expect(report.outcomes[0]?.decision).toBe("pass");
expect(report.blocked).toBe(false);
});
it("stops at the first block on a blocking event", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok(), ok({ exitCode: 2, stderr: "denied" }), ok()], log);
const hooks: ResolvedHook[] = [
hook({ command: "first" }),
hook({ command: "blocker" }),
hook({ command: "third — should not run" }),
];
const report = await runHooks({
hooks,
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "x" },
});
expect(log.map((l) => l.command)).toEqual(["first", "blocker"]);
expect(report.blocked).toBe(true);
expect(report.outcomes[1]?.decision).toBe("block");
});
it("does not stop on warn — collects every outcome", async () => {
const spawner = makeSpawner([ok({ exitCode: 1, stderr: "noisy" }), ok()]);
const hooks: ResolvedHook[] = [hook({ command: "warner" }), hook({ command: "ok" })];
const report = await runHooks({
hooks,
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "x" },
});
expect(report.outcomes.map((o) => o.decision)).toEqual(["warn", "pass"]);
expect(report.blocked).toBe(false);
});
it("stdin contains a single-line JSON envelope of the payload", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok()], log);
await runHooks({
hooks: [hook({ command: "echo" })],
spawner,
payload: {
event: "PreToolUse",
cwd: "/tmp",
toolName: "edit_file",
toolArgs: { path: "a.ts" },
},
});
const stdin = log[0]?.stdin ?? "";
const decoded = JSON.parse(stdin);
expect(decoded.event).toBe("PreToolUse");
expect(decoded.toolName).toBe("edit_file");
expect(decoded.toolArgs).toEqual({ path: "a.ts" });
expect(stdin.endsWith("\n")).toBe(true);
});
it("uses payload.cwd by default and per-hook cwd override when set", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok(), ok()], log);
await runHooks({
hooks: [hook({ command: "a" }), hook({ command: "b", cwd: "/special" })],
spawner,
payload: { event: "PreToolUse", cwd: "/payload-cwd", toolName: "x" },
});
expect(log[0]?.cwd).toBe("/payload-cwd");
expect(log[1]?.cwd).toBe("/special");
});
it("default timeout is 5s for blocking events and 30s for logging events", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok(), ok()], log);
const h: ResolvedHook[] = [
hook({ event: "PreToolUse", command: "pre" }),
hook({ event: "Stop", command: "stop" }),
];
await runHooks({
hooks: h,
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "x" },
});
await runHooks({
hooks: h,
spawner,
payload: { event: "Stop", cwd: "/tmp" },
});
expect(log[0]?.timeoutMs).toBe(5_000);
expect(log[1]?.timeoutMs).toBe(30_000);
});
it("per-hook timeout overrides the default", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok()], log);
await runHooks({
hooks: [hook({ command: "x", timeout: 999 })],
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "x" },
});
expect(log[0]?.timeoutMs).toBe(999);
});
});
describe("formatHookOutcomeMessage", () => {
const baseHook: ResolvedHook = {
event: "PostToolUse",
scope: "global",
source: "/tmp/x",
command: "echo hi",
};
it("returns empty string for pass", () => {
expect(
formatHookOutcomeMessage({
hook: baseHook,
decision: "pass",
exitCode: 0,
stdout: "",
stderr: "",
durationMs: 1,
}),
).toBe("");
});
it("includes scope/event tag, command, decision, and stderr detail", () => {
const msg = formatHookOutcomeMessage({
hook: baseHook,
decision: "warn",
exitCode: 1,
stdout: "",
stderr: "something went sideways",
durationMs: 5,
});
expect(msg).toContain("global/PostToolUse");
expect(msg).toContain("echo hi");
expect(msg).toContain("warn");
expect(msg).toContain("something went sideways");
});
it("truncates very long commands at 60 chars + ellipsis", () => {
const long = "x".repeat(200);
const msg = formatHookOutcomeMessage({
hook: { ...baseHook, command: long },
decision: "warn",
exitCode: 1,
stdout: "",
stderr: "",
durationMs: 5,
});
expect(msg).toContain(`${"x".repeat(60)}…`);
expect(msg).not.toContain("x".repeat(61));
});
});
+124
View File
@@ -0,0 +1,124 @@
/**
* Smoke tests for hook wiring inside CacheFirstLoop. The full
* pass / block / warn matrix is covered in tests/hooks.test.ts with
* a stubbed spawner — here we just confirm the loop honors the
* `hooks` option and exposes a mutable list that `/hooks reload`
* can swap into without reconstructing the loop.
*/
import { describe, expect, it, vi } from "vitest";
import { DeepSeekClient } from "../src/client.js";
import type { ResolvedHook } from "../src/hooks.js";
import { CacheFirstLoop, type LoopEvent } from "../src/loop.js";
import { ImmutablePrefix } from "../src/memory.js";
import { ToolRegistry } from "../src/tools.js";
import type { ChatMessage } from "../src/types.js";
interface FakeResponseShape {
content?: string;
tool_calls?: unknown[];
}
function fakeFetch(responses: FakeResponseShape[]): typeof fetch {
let i = 0;
return vi.fn(async (_url: unknown, init: { body?: string } | undefined) => {
const body = init?.body ? JSON.parse(init.body) : {};
const resp = responses[i++] ?? responses[responses.length - 1]!;
return new Response(
JSON.stringify({
_echo_messages: body.messages as ChatMessage[],
choices: [
{
index: 0,
message: {
role: "assistant",
content: resp.content ?? "",
tool_calls: resp.tool_calls ?? undefined,
},
finish_reason: resp.tool_calls ? "tool_calls" : "stop",
},
],
usage: {
prompt_tokens: 100,
completion_tokens: 20,
total_tokens: 120,
prompt_cache_hit_tokens: 0,
prompt_cache_miss_tokens: 100,
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}) as unknown as typeof fetch;
}
function makeClient(responses: FakeResponseShape[]) {
return new DeepSeekClient({ apiKey: "sk-test", fetch: fakeFetch(responses) });
}
describe("CacheFirstLoop hook wiring", () => {
it("default hooks list is empty (zero overhead when no settings.json)", () => {
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
});
expect(loop.hooks).toEqual([]);
});
it("accepts a hooks list via options", () => {
const hooks: ResolvedHook[] = [
{ event: "Stop", scope: "global", source: "/x", command: "echo done" },
];
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
hooks,
});
expect(loop.hooks).toEqual(hooks);
});
it("hooks field is mutable so /hooks reload can swap without rebuild", () => {
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
});
const fresh: ResolvedHook[] = [
{ event: "PreToolUse", scope: "project", source: "/x", command: "true" },
];
loop.hooks = fresh;
expect(loop.hooks).toEqual(fresh);
});
it("hookCwd defaults to process.cwd() when not provided", () => {
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
});
expect(loop.hookCwd).toBe(process.cwd());
});
it("hookCwd takes the explicit override when set", () => {
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
hookCwd: "/some/sandbox/root",
});
expect(loop.hookCwd).toBe("/some/sandbox/root");
});
it("a no-tool-call turn never dispatches hooks (PreToolUse only fires around tools)", async () => {
// Sanity check: a plain text response means no PreToolUse hook
// would be invoked even if one were configured. We assert only
// through observable events here — no hook = no warning rows.
const client = makeClient([{ content: "just chatting" }]);
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s" }),
stream: false,
hooks: [{ event: "PreToolUse", scope: "global", source: "/x", command: "noop" }],
});
const events: LoopEvent[] = [];
for await (const ev of loop.step("hi")) events.push(ev);
expect(events.find((e) => e.role === "warning")).toBeUndefined();
expect(events.find((e) => e.role === "assistant_final")?.content).toBe("just chatting");
});
});
+49 -5
View File
@@ -255,11 +255,13 @@ describe("CacheFirstLoop (non-streaming)", () => {
for await (const ev of loop.step("go")) {
if (ev.role === "warning") warnings.push(ev.content);
}
// Exactly one warning should fire (guard against the once-per-turn flag
// regressing). Content must mention the X/N count and "Esc".
expect(warnings).toHaveLength(1);
expect(warnings[0]).toMatch(/\d+\/4 tool calls used/);
expect(warnings[0]).toMatch(/Esc/);
// Identical fixture calls also trip the storm breaker in 0.4.19+,
// which emits its own warning. Filter for the iter-budget warning
// specifically — that's what this test guards (once-per-turn flag).
const iterBudgetWarnings = warnings.filter((w) => /tool calls used/.test(w));
expect(iterBudgetWarnings).toHaveLength(1);
expect(iterBudgetWarnings[0]).toMatch(/\d+\/4 tool calls used/);
expect(iterBudgetWarnings[0]).toMatch(/Esc/);
});
it("abort() mid-step stops immediately without a follow-up API call", async () => {
@@ -595,4 +597,46 @@ describe("CacheFirstLoop (streaming) — tool_call_delta emission", () => {
expect(deltas[0]!.name).toBe("edit_file");
expect(deltas[deltas.length - 1]!.chars).toBeGreaterThan(deltas[0]!.chars!);
});
it("does not emit a red error event when the API call is aborted mid-flight", async () => {
// Reproduces the reported "error This operation was aborted" UX
// bug: when App.tsx calls loop.abort() to switch to a queued
// synthetic input (e.g. ShellConfirm "always allow"), the in-flight
// fetch throws AbortError. We treat that as a clean early-exit
// (yield `done`) instead of bubbling it up as a red error row.
const client = new DeepSeekClient({
apiKey: "sk-test",
// Slow fake fetch — never resolves on its own; only the abort
// signal terminates it.
fetch: vi.fn(async (_url: any, init: any) => {
const signal: AbortSignal | undefined = init?.signal;
return new Promise<Response>((_resolve, reject) => {
signal?.addEventListener("abort", () =>
reject(new DOMException("This operation was aborted", "AbortError")),
);
});
}) as any,
retry: { maxAttempts: 1 },
});
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s" }),
stream: false,
});
const events: Array<{ role: string; error?: string }> = [];
const stepPromise = (async () => {
for await (const ev of loop.step("hi")) {
events.push({ role: ev.role, error: ev.error });
}
})();
// Race: fire abort before the fake fetch can resolve.
setTimeout(() => loop.abort(), 10);
await stepPromise;
// No "error" event leaked through.
expect(events.find((e) => e.role === "error")).toBeUndefined();
// Loop terminated cleanly so the TUI's busy state unsticks.
expect(events[events.length - 1]?.role).toBe("done");
});
});
+274 -2
View File
@@ -1,5 +1,17 @@
import { describe, expect, it } from "vitest";
import { parseBlocks, stripMath } from "../src/cli/ui/markdown.js";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
collectCitations,
isExternalUrl,
parseBlocks,
parseCitationUrl,
stripInlineMarkup,
stripMath,
validateCitation,
visibleWidth,
} from "../src/cli/ui/markdown.js";
describe("stripMath", () => {
it("converts \\frac, \\dfrac, \\tfrac uniformly", () => {
@@ -222,6 +234,141 @@ describe("parseBlocks — GFM tables", () => {
expect(t.rows[0]).toEqual(["x | y", "z"]);
}
});
it("recognizes Unicode box-drawing tables (│ ─ ┼) as tables too", () => {
// R1/V3 frequently emit this shape when asked for tabular data in
// Chinese — the GFM-only path treated them as plain paragraphs and
// Ink word-wrapped them into a tangle.
const md = [
"步骤 │ 说明",
"─────────────────┼─────────────────────────────────────────",
"**工具查找** │ 按 `name` 查找已注册的工具",
"**参数解析** │ 支持 string (JSON) 或 object 格式",
"",
"Trailing prose.",
].join("\n");
const blocks = parseBlocks(md);
const table = blocks.find((b) => b.kind === "table");
expect(table).toBeDefined();
if (table && table.kind === "table") {
expect(table.header).toEqual(["步骤", "说明"]);
expect(table.rows).toHaveLength(2);
expect(table.rows[0]).toEqual(["**工具查找**", "按 `name` 查找已注册的工具"]);
expect(table.rows[1]).toEqual(["**参数解析**", "支持 string (JSON) 或 object 格式"]);
}
expect(
blocks.find((b) => b.kind === "paragraph" && b.text === "Trailing prose."),
).toBeDefined();
});
it("does NOT trigger on a bare '│' in prose without a separator below", () => {
const md = ["The character │ is a vertical bar.", "Nothing tabular here."].join("\n");
expect(parseBlocks(md).find((b) => b.kind === "table")).toBeUndefined();
});
it("folds a continuation row (no column separator) into the last cell of the previous row", () => {
// Real-world LLM output: cell content too long, model wraps onto a
// second line without re-emitting the separator. Used to leak as
// a paragraph after the table; now stitched back into the cell so
// inline backticks / bold parse correctly.
const md = [
"文件 │ 角色",
"─────────────┼─────────────────────────────────────────",
"`src/tools.ts` │ `dispatch()` 方法定义(约第 106 行起)。签名:",
" async dispatch(name: string, ...)。处理 plan-mode 拦截。",
].join("\n");
const [t] = parseBlocks(md).filter((b) => b.kind === "table");
expect(t).toBeDefined();
if (t && t.kind === "table") {
expect(t.rows).toHaveLength(1);
expect(t.rows[0]?.[1]).toContain("dispatch()");
expect(t.rows[0]?.[1]).toContain("async dispatch(name");
}
});
});
describe("parseBlocks — box-drawing frames as code blocks", () => {
it("recognizes a single-line ┌─┐ │ └─┘ frame", () => {
// Models routinely wrap one line of code in a Unicode frame for
// emphasis. The renderer treats the frame as a code block so the
// inner content stays readable instead of being word-wrapped.
const md = [
"Here is the call site:",
"",
"┌──────────────────────────────────────────┐",
"│ result = await this.tools.dispatch(...); │",
"└──────────────────────────────────────────┘",
"",
"Trailing.",
].join("\n");
const blocks = parseBlocks(md);
const code = blocks.find((b) => b.kind === "code");
expect(code).toBeDefined();
if (code && code.kind === "code") {
expect(code.text).toBe("result = await this.tools.dispatch(...);");
}
expect(blocks.find((b) => b.kind === "paragraph" && b.text === "Trailing.")).toBeDefined();
});
it("recognizes a multi-line ┌─┐ │…│ └─┘ frame (flow charts and diagrams)", () => {
const md = [
"┌──────────────┐",
"│ step 1 │",
"│ ↓ │",
"│ step 2 │",
"└──────────────┘",
].join("\n");
const blocks = parseBlocks(md);
expect(blocks).toHaveLength(1);
expect(blocks[0]).toMatchObject({ kind: "code" });
if (blocks[0]?.kind === "code") {
expect(blocks[0].text).toContain("step 1");
expect(blocks[0].text).toContain("step 2");
expect(blocks[0].text).toContain("↓");
// Outer │ characters got stripped — content reads cleanly.
expect(blocks[0].text).not.toContain("│");
}
});
it("falls back to paragraph when the closing └─┘ is missing", () => {
const md = ["┌────┐", "│ a │", "no closing edge here"].join("\n");
const blocks = parseBlocks(md);
// No code block emitted — the open-edge line stays as paragraph.
expect(blocks.find((b) => b.kind === "code")).toBeUndefined();
});
});
describe("stripInlineMarkup + visibleWidth", () => {
it("strips bold markers", () => {
expect(stripInlineMarkup("**hello**")).toBe("hello");
});
it("strips inline code backticks", () => {
expect(stripInlineMarkup("call `dispatch()` now")).toBe("call dispatch() now");
});
it("strips italic markers but leaves single * inside words", () => {
expect(stripInlineMarkup("*emphasis*")).toBe("emphasis");
expect(stripInlineMarkup("a*b*c")).toBe("a*b*c");
});
it("strips triple-backtick spans + their language tag", () => {
expect(stripInlineMarkup("```bash echo hi```")).toBe("echo hi");
});
it("visibleWidth excludes markup chars", () => {
// raw is 19 chars, visible is "定义 dispatch" = 4 (CJK ×2) + 1 (space) + 8 = 13
expect(visibleWidth("**定义** `dispatch`")).toBe(13);
});
it("table cells with inline markup get sized by visible width, not raw", () => {
// Header is plain, rows have inline code. The column sized by raw
// length would be too wide; visibleWidth keeps things aligned to
// what the user actually sees.
const md = ["| 位置 | 角色 |", "|------|------|", "| `src/tools.ts` | 定义 dispatch |"].join(
"\n",
);
const [t] = parseBlocks(md).filter((b) => b.kind === "table");
expect(t).toBeDefined();
if (t && t.kind === "table") {
expect(t.rows[0]).toEqual(["`src/tools.ts`", "定义 dispatch"]);
}
});
});
describe("parseBlocks — fenced code blocks", () => {
@@ -266,3 +413,128 @@ describe("parseBlocks — fenced code blocks", () => {
expect(code && code.kind === "code" && code.text).toBe("print('hi')");
});
});
describe("citation links — parseCitationUrl", () => {
it("parses bare path", () => {
expect(parseCitationUrl("src/foo.ts")).toEqual({ path: "src/foo.ts" });
});
it("parses path:line", () => {
expect(parseCitationUrl("src/foo.ts:42")).toEqual({ path: "src/foo.ts", startLine: 42 });
});
it("parses path:start-end range", () => {
expect(parseCitationUrl("src/foo.ts:42-58")).toEqual({
path: "src/foo.ts",
startLine: 42,
endLine: 58,
});
});
it("parses GitHub-style #L42 anchor", () => {
expect(parseCitationUrl("src/foo.ts#L42")).toEqual({ path: "src/foo.ts", startLine: 42 });
});
it("parses GitHub-style #L42-L58 range", () => {
expect(parseCitationUrl("src/foo.ts#L42-L58")).toEqual({
path: "src/foo.ts",
startLine: 42,
endLine: 58,
});
});
it("returns null on empty input", () => {
expect(parseCitationUrl("")).toBeNull();
expect(parseCitationUrl(" ")).toBeNull();
});
});
describe("citation links — isExternalUrl", () => {
it("recognizes http/https/ftp", () => {
expect(isExternalUrl("https://example.com")).toBe(true);
expect(isExternalUrl("http://example.com")).toBe(true);
expect(isExternalUrl("ftp://example.com")).toBe(true);
});
it("recognizes mailto and protocol-relative", () => {
expect(isExternalUrl("mailto:[email protected]")).toBe(true);
expect(isExternalUrl("//cdn.example.com/x")).toBe(true);
});
it("rejects local paths and bare names", () => {
expect(isExternalUrl("src/foo.ts")).toBe(false);
expect(isExternalUrl("src/foo.ts:42")).toBe(false);
expect(isExternalUrl("README.md")).toBe(false);
expect(isExternalUrl("./foo")).toBe(false);
});
});
describe("citation links — validateCitation + collectCitations", () => {
let tmp: string;
beforeAll(() => {
tmp = mkdtempSync(join(tmpdir(), "reasonix-citation-"));
writeFileSync(join(tmp, "real.ts"), "line1\nline2\nline3\nline4\nline5\n");
});
afterAll(() => {
rmSync(tmp, { recursive: true, force: true });
});
it("file exists, no line → ok", () => {
expect(validateCitation("real.ts", tmp)).toEqual({ ok: true });
});
it("file exists, line in range → ok", () => {
expect(validateCitation("real.ts:3", tmp)).toEqual({ ok: true });
});
it("file exists, line out of range → broken with reason", () => {
const result = validateCitation("real.ts:99", tmp);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toContain("99");
});
it("range end out of file → broken", () => {
const result = validateCitation("real.ts:1-99", tmp);
expect(result.ok).toBe(false);
});
it("missing file → broken with 'file not found'", () => {
const result = validateCitation("ghost.ts:1", tmp);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("file not found");
});
it("collectCitations validates every unique citation, skips externals", () => {
const text = [
"See [foo](real.ts:2) for details.",
"Compare with [bar](https://example.com).",
"Bogus claim [baz](ghost.ts:1).",
"Another [foo again](real.ts:2).",
].join("\n");
const map = collectCitations(text, tmp);
expect(map.size).toBe(2);
expect(map.get("real.ts:2")).toEqual({ ok: true });
expect(map.get("ghost.ts:1")?.ok).toBe(false);
expect(map.has("https://example.com")).toBe(false);
});
});
describe("citation links — parseBlocks regression", () => {
it("plain markdown link inside paragraph still parses as paragraph", () => {
const blocks = parseBlocks("See [the docs](src/foo.ts:42) for context.");
expect(blocks).toHaveLength(1);
expect(blocks[0]?.kind).toBe("paragraph");
if (blocks[0]?.kind === "paragraph") {
expect(blocks[0].text).toContain("[the docs](src/foo.ts:42)");
}
});
it("stripInlineMarkup extracts link text only", () => {
expect(stripInlineMarkup("see [foo](path.ts:10) here")).toBe("see foo here");
});
it("visibleWidth ignores link URL", () => {
// "see " + "foo" + " here" = 12 visible chars
expect(visibleWidth("see [foo](path.ts:10) here")).toBe(12);
});
});
+195
View File
@@ -0,0 +1,195 @@
/**
* Plan Mode — the dispatch-level enforcement (ToolRegistry read-only
* gate) and the submit_plan tool (PlanProposedError + toToolResult
* protocol).
*/
import { describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import { PlanProposedError, registerPlanTool } from "../src/tools/plan.js";
describe("ToolRegistry plan mode", () => {
it("starts with plan mode off by default", () => {
const reg = new ToolRegistry();
expect(reg.planMode).toBe(false);
});
it("setPlanMode toggles the flag", () => {
const reg = new ToolRegistry();
reg.setPlanMode(true);
expect(reg.planMode).toBe(true);
reg.setPlanMode(false);
expect(reg.planMode).toBe(false);
});
it("blocks non-readOnly tools when plan mode is on", async () => {
const reg = new ToolRegistry();
let ran = false;
reg.register({
name: "mutate",
// readOnly: undefined → treated as write
fn: () => {
ran = true;
return "ok";
},
});
reg.setPlanMode(true);
const out = await reg.dispatch("mutate", "{}");
expect(ran).toBe(false);
const payload = JSON.parse(out);
expect(payload.error).toMatch(/unavailable in plan mode/);
expect(payload.error).toMatch(/submit_plan/);
});
it("allows readOnly tools when plan mode is on", async () => {
const reg = new ToolRegistry();
reg.register({
name: "read_thing",
readOnly: true,
fn: () => "the-thing",
});
reg.setPlanMode(true);
const out = await reg.dispatch("read_thing", "{}");
expect(out).toBe("the-thing");
});
it("honors readOnlyCheck taking the actual arguments into account", async () => {
const reg = new ToolRegistry();
reg.register({
name: "maybe_read",
readOnlyCheck: (args: { kind?: string }) => args.kind === "read",
fn: (args: { kind?: string }) => `did-${args.kind}`,
});
reg.setPlanMode(true);
// Read call: allowed.
const readOut = await reg.dispatch("maybe_read", '{"kind":"read"}');
expect(readOut).toBe("did-read");
// Write call: refused.
const writeOut = await reg.dispatch("maybe_read", '{"kind":"write"}');
expect(JSON.parse(writeOut).error).toMatch(/unavailable in plan mode/);
});
it("readOnlyCheck takes precedence over readOnly when both are set", async () => {
const reg = new ToolRegistry();
reg.register({
name: "mixed",
readOnly: false,
readOnlyCheck: () => true,
fn: () => "ran",
});
reg.setPlanMode(true);
const out = await reg.dispatch("mixed", "{}");
expect(out).toBe("ran");
});
it("with plan mode off, readOnly flags don't interfere", async () => {
const reg = new ToolRegistry();
reg.register({
name: "normal",
fn: () => "ran",
});
expect(reg.planMode).toBe(false);
const out = await reg.dispatch("normal", "{}");
expect(out).toBe("ran");
});
it("serializes errors via toToolResult when the thrown error implements it", async () => {
const reg = new ToolRegistry();
reg.register({
name: "structured_err",
fn: () => {
const err = new Error("oops") as Error & { toToolResult?: () => unknown };
err.name = "StructuredError";
err.toToolResult = () => ({ error: "StructuredError: oops", extra: "pinned-out-of-band" });
throw err;
},
});
const out = await reg.dispatch("structured_err", "{}");
const parsed = JSON.parse(out);
expect(parsed.error).toBe("StructuredError: oops");
expect(parsed.extra).toBe("pinned-out-of-band");
});
it("falls back to the default error shape when toToolResult throws", async () => {
const reg = new ToolRegistry();
reg.register({
name: "broken_serializer",
fn: () => {
const err = new Error("base-message") as Error & { toToolResult?: () => unknown };
err.name = "Broken";
err.toToolResult = () => {
throw new Error("serialization failed");
};
throw err;
},
});
const out = await reg.dispatch("broken_serializer", "{}");
expect(JSON.parse(out).error).toBe("Broken: base-message");
});
});
describe("PlanProposedError", () => {
it("carries the plan on the instance and in toToolResult()", () => {
const err = new PlanProposedError("# Plan\n- step 1\n- step 2");
expect(err.name).toBe("PlanProposedError");
expect(err.plan).toBe("# Plan\n- step 1\n- step 2");
const payload = err.toToolResult();
expect(payload.plan).toBe("# Plan\n- step 1\n- step 2");
expect(payload.error).toMatch(/^PlanProposedError:/);
// Message tells the model to STOP so it doesn't keep calling tools.
expect(payload.error).toMatch(/STOP/);
});
});
describe("registerPlanTool + submit_plan", () => {
it("registers submit_plan as readOnly so it passes the plan-mode gate", () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
expect(reg.has("submit_plan")).toBe(true);
expect(reg.get("submit_plan")?.readOnly).toBe(true);
});
it("throws PlanProposedError when called with a plan (plan mode ON)", async () => {
const reg = new ToolRegistry();
const submitted: string[] = [];
registerPlanTool(reg, { onPlanSubmitted: (p) => submitted.push(p) });
reg.setPlanMode(true);
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: "# Plan\n- A" }));
const parsed = JSON.parse(out);
expect(parsed.plan).toBe("# Plan\n- A");
expect(parsed.error).toMatch(/PlanProposedError/);
expect(submitted).toEqual(["# Plan\n- A"]);
});
it("also fires the picker when plan mode is OFF — autonomous proposals", async () => {
const reg = new ToolRegistry();
const submitted: string[] = [];
registerPlanTool(reg, { onPlanSubmitted: (p) => submitted.push(p) });
// Plan mode intentionally NOT enabled.
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: "big refactor plan" }));
const parsed = JSON.parse(out);
expect(parsed.plan).toBe("big refactor plan");
expect(parsed.error).toMatch(/PlanProposedError/);
expect(submitted).toEqual(["big refactor plan"]);
});
it("rejects an empty plan with a helpful message", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: " \n\n " }));
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/empty plan/);
// Empty-plan is a regular Error, not PlanProposedError — so there's
// no `plan` field.
expect(parsed.plan).toBeUndefined();
});
it("trims surrounding whitespace from the plan", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: "\n\n trimmed \n" }));
expect(JSON.parse(out).plan).toBe("trimmed");
});
});
+18
View File
@@ -76,4 +76,22 @@ describe("ToolCallRepair pipeline", () => {
expect(calls.length).toBe(1);
expect(report.scavenged).toBe(1);
});
it("resetStorm clears the repeat-window so post-reset calls aren't suppressed", () => {
const repair = new ToolCallRepair({
allowedToolNames: new Set(["x"]),
stormWindow: 6,
stormThreshold: 3,
});
// Build up to the storm threshold — third identical call would be suppressed.
for (let i = 0; i < 2; i++) {
repair.process([call(`c${i}`, "x", "{}")], null);
}
// Mid-turn reset (what step() does on each new user message).
repair.resetStorm();
// With a fresh window the next call passes through — no suppression.
const { calls, report } = repair.process([call("c-after", "x", "{}")], null);
expect(calls.length).toBe(1);
expect(report.stormsBroken).toBe(0);
});
});
+326
View File
@@ -6,8 +6,12 @@ import { ToolRegistry } from "../src/tools.js";
import {
NeedsConfirmationError,
formatCommandResult,
injectPowerShellUtf8,
isAllowed,
prepareSpawn,
quoteForCmdExe,
registerShellTools,
resolveExecutable,
runCommand,
tokenizeCommand,
} from "../src/tools/shell.js";
@@ -181,6 +185,34 @@ describe("registerShellTools — dispatch integration", () => {
expect(out).toMatch(/\[exit 0\]/);
expect(out).toContain("ok");
});
it("extraAllowed as a getter is re-read on every dispatch", async () => {
// Regression: picking "always allow" in ShellConfirm wrote to disk
// but the running run_command captured a stale snapshot, so the
// same command got re-prompted until the next launch. Getter form
// fixes this by re-resolving the allowlist on each call.
//
// `node -e` is deliberately NOT in BUILTIN_ALLOWLIST — only
// `node --version` / `node -v` are — so the "before" call must go
// through the extraAllowed path to succeed.
const cmd = "node -e \"process.stdout.write('ok')\"";
const registry = new ToolRegistry();
const list: string[] = [];
registerShellTools(registry, { rootDir: tmp, extraAllowed: () => list });
const before = await registry.dispatch("run_command", JSON.stringify({ command: cmd }));
expect(before).toMatch(/NeedsConfirmationError/);
// Simulate the TUI's "always allow" click — mutate the source the
// getter reads. No re-registration; the live tool instance picks
// it up.
list.push("node -e");
const after = await registry.dispatch("run_command", JSON.stringify({ command: cmd }));
expect(after).not.toMatch(/NeedsConfirmationError/);
expect(after).toMatch(/\[exit 0\]/);
expect(after).toContain("ok");
});
});
describe("formatCommandResult", () => {
@@ -203,6 +235,300 @@ describe("formatCommandResult", () => {
});
});
describe("resolveExecutable", () => {
it("returns the input unchanged on non-Windows platforms", () => {
expect(resolveExecutable("npm", { platform: "linux" })).toBe("npm");
expect(resolveExecutable("pytest", { platform: "darwin" })).toBe("pytest");
});
it("returns empty input unchanged", () => {
expect(resolveExecutable("", { platform: "win32" })).toBe("");
});
it("walks PATH × PATHEXT on Windows and returns the first hit", () => {
// PATHEXT case is preserved into the joined path, so the mock
// "filesystem" keys must match that case verbatim.
const hits = new Set(["C:\\tools\\npm.CMD"]);
const out = resolveExecutable("npm", {
platform: "win32",
env: { PATH: "C:\\nope;C:\\tools", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out).toBe("C:\\tools\\npm.CMD");
});
it("honors PATHEXT ordering (.EXE beats .CMD when both exist)", () => {
const hits = new Set(["C:\\bin\\foo.EXE", "C:\\bin\\foo.CMD"]);
const out = resolveExecutable("foo", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".EXE;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out).toBe("C:\\bin\\foo.EXE");
});
it("falls back to the raw cmd when PATH × PATHEXT yields nothing", () => {
const out = resolveExecutable("doesnotexist", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out).toBe("doesnotexist");
});
it("skips lookup for absolute paths (\\ or /)", () => {
const called: string[] = [];
const out1 = resolveExecutable("C:\\tools\\npm.cmd", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".CMD" },
isFile: (p) => {
called.push(p);
return true;
},
});
expect(out1).toBe("C:\\tools\\npm.cmd");
const out2 = resolveExecutable("src/tool.js", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".CMD" },
isFile: () => true,
});
expect(out2).toBe("src/tool.js");
expect(called).toEqual([]);
});
it("skips lookup when the cmd already has an extension", () => {
const called: string[] = [];
const out = resolveExecutable("npm.cmd", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".CMD" },
isFile: (p) => {
called.push(p);
return true;
},
});
expect(out).toBe("npm.cmd");
expect(called).toEqual([]);
});
it("tolerates missing PATH / PATHEXT — returns cmd unchanged", () => {
const out = resolveExecutable("npm", {
platform: "win32",
env: {},
pathDelimiter: ";",
isFile: () => false,
});
expect(out).toBe("npm");
});
it("handles whitespace inside PATHEXT entries (' .CMD ' → '.CMD')", () => {
const hits = new Set(["C:\\bin\\npm.CMD"]);
const out = resolveExecutable("npm", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: " .CMD ; .EXE " },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out).toBe("C:\\bin\\npm.CMD");
});
});
describe("quoteForCmdExe", () => {
it("leaves simple identifiers alone", () => {
expect(quoteForCmdExe("install")).toBe("install");
expect(quoteForCmdExe("foo-bar_123")).toBe("foo-bar_123");
});
it("double-quotes whitespace and cmd metacharacters", () => {
expect(quoteForCmdExe("hello world")).toBe('"hello world"');
expect(quoteForCmdExe("a&b")).toBe('"a&b"');
expect(quoteForCmdExe("a|b")).toBe('"a|b"');
expect(quoteForCmdExe("a>b")).toBe('"a>b"');
expect(quoteForCmdExe("a<b")).toBe('"a<b"');
expect(quoteForCmdExe("a^b")).toBe('"a^b"');
expect(quoteForCmdExe("a;b")).toBe('"a;b"');
});
it("doubles embedded quotes (cmd.exe escape rule)", () => {
expect(quoteForCmdExe('say "hi"')).toBe('"say ""hi"""');
});
it("empty string becomes an explicit empty-pair", () => {
expect(quoteForCmdExe("")).toBe('""');
});
it("round-trips `npm install foo` safely", () => {
const argv = ["C:\\Program Files\\nodejs\\npm.cmd", "install", "foo"];
const cmdline = argv.map(quoteForCmdExe).join(" ");
expect(cmdline).toBe('"C:\\Program Files\\nodejs\\npm.cmd" install foo');
});
});
describe("prepareSpawn", () => {
it("passes through unchanged on non-Windows", () => {
const out = prepareSpawn(["npm", "install"], { platform: "linux" });
expect(out.bin).toBe("npm");
expect(out.args).toEqual(["install"]);
expect(out.spawnOverrides).toEqual({});
});
it("wraps .cmd files through cmd.exe on Windows (post-CVE-2024-27980)", () => {
// Real-world install path with a space → quoting required.
const hits = new Set(["C:\\Program Files\\nodejs\\npm.CMD"]);
const out = prepareSpawn(["npm", "install", "foo"], {
platform: "win32",
env: { PATH: "C:\\Program Files\\nodejs", PATHEXT: ".EXE;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out.bin).toBe("cmd.exe");
expect(out.args).toEqual([
"/d",
"/s",
"/c",
'chcp 65001 >nul & "C:\\Program Files\\nodejs\\npm.CMD" install foo',
]);
expect(out.spawnOverrides.windowsVerbatimArguments).toBe(true);
});
it("wraps .cmd files without quoting when the resolved path has no metacharacters", () => {
const hits = new Set(["C:\\tools\\npm.CMD"]);
const out = prepareSpawn(["npm", "install"], {
platform: "win32",
env: { PATH: "C:\\tools", PATHEXT: ".EXE;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
// No spaces in the path ⇒ no surrounding quotes; cmd.exe parses
// backslashes literally. UTF-8 codepage prefix is always inserted.
expect(out.args[3]).toBe("chcp 65001 >nul & C:\\tools\\npm.CMD install");
});
it("wraps .bat files too", () => {
const hits = new Set(["C:\\bin\\gradle.BAT"]);
const out = prepareSpawn(["gradle", "build"], {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".BAT" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out.bin).toBe("cmd.exe");
expect(out.args[3]).toMatch(/^chcp 65001 >nul & .*gradle\.BAT/);
});
it("spawns .exe directly (no cmd.exe wrapping)", () => {
const hits = new Set(["C:\\Program Files\\nodejs\\node.EXE"]);
const out = prepareSpawn(["node", "--version"], {
platform: "win32",
env: { PATH: "C:\\Program Files\\nodejs", PATHEXT: ".EXE;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out.bin).toBe("C:\\Program Files\\nodejs\\node.EXE");
expect(out.args).toEqual(["--version"]);
expect(out.spawnOverrides).toEqual({});
});
it("cmd.exe-wrapping quotes args containing metacharacters", () => {
const hits = new Set(["C:\\tools\\tool.CMD"]);
const out = prepareSpawn(["tool", "a&b", "c|d"], {
platform: "win32",
env: { PATH: "C:\\tools", PATHEXT: ".CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out.args[3]).toBe('chcp 65001 >nul & C:\\tools\\tool.CMD "a&b" "c|d"');
});
it("routes bare unresolved Windows commands through cmd.exe (builtins)", () => {
// `dir`, `echo`, `type`, `ver`, … are cmd.exe built-ins — they
// don't exist as standalone exes, so PATHEXT lookup misses and a
// direct spawn ENOENTs. Wrapping in cmd.exe lets them resolve,
// and gives unknown commands a proper "'x' is not recognized"
// exit code instead of a raw spawn failure.
const out = prepareSpawn(["dir", ".reasonix"], {
platform: "win32",
env: { PATH: "C:\\nope", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out.bin).toBe("cmd.exe");
expect(out.args).toEqual(["/d", "/s", "/c", "chcp 65001 >nul & dir .reasonix"]);
expect(out.spawnOverrides.windowsVerbatimArguments).toBe(true);
});
it("cmd.exe builtin wrapping quotes metacharacter args", () => {
const out = prepareSpawn(["echo", "a & b"], {
platform: "win32",
env: { PATH: "C:\\nope", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out.bin).toBe("cmd.exe");
expect(out.args[3]).toBe('chcp 65001 >nul & echo "a & b"');
});
it("does not wrap paths-with-separators through cmd.exe", () => {
// Absolute or slash-containing inputs are NOT bare names; they're
// explicit disk paths — if the user points at a nonexistent one
// we want the spawn to ENOENT plainly, not through cmd.exe.
const out = prepareSpawn(["C:\\missing\\tool.exe", "arg"], {
platform: "win32",
env: { PATH: "", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out.bin).toBe("C:\\missing\\tool.exe");
expect(out.args).toEqual(["arg"]);
});
it("injects UTF-8 prelude into powershell -Command invocations", () => {
// Uppercase .EXE in the hit set so resolveExecutable's PATHEXT
// probe finds it (matches existing .CMD test convention).
const hits = new Set(["C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.EXE"]);
const out = prepareSpawn(["powershell", "-Command", "Get-ChildItem -Path tests"], {
platform: "win32",
env: {
PATH: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0",
PATHEXT: ".EXE",
},
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out.bin).toMatch(/powershell\.exe$/i);
// args = [-Command, "<prelude>Get-ChildItem -Path tests"]
expect(out.args[0]).toBe("-Command");
expect(out.args[1]).toMatch(/^\[Console\]::OutputEncoding=/);
expect(out.args[1]).toContain("Get-ChildItem -Path tests");
// No cmd.exe wrapping for powershell — direct spawn.
expect(out.spawnOverrides).toEqual({});
});
it("injectPowerShellUtf8 leaves unrelated invocations untouched", () => {
// No -Command flag → can't safely inject; we leave it alone.
expect(injectPowerShellUtf8(["-File", "script.ps1"])).toBeNull();
// -c (alias) still gets the prelude.
const out = injectPowerShellUtf8(["-c", "Write-Host hi"]);
expect(out).not.toBeNull();
expect(out![1]).toMatch(/^\[Console\]::OutputEncoding=.*Write-Host hi$/);
});
it("does not wrap already-extensioned commands", () => {
// `node.exe` with no PATH hit → user passed an explicit name;
// pass it straight to spawn (will ENOENT if truly absent).
const out = prepareSpawn(["node.exe", "-v"], {
platform: "win32",
env: { PATH: "", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out.bin).toBe("node.exe");
expect(out.args).toEqual(["-v"]);
});
});
describe("NeedsConfirmationError", () => {
it("carries the rejected command on the instance", () => {
const e = new NeedsConfirmationError("rm -rf /");
+350
View File
@@ -0,0 +1,350 @@
/**
* Tests for the Skills store + prefix-index composer. Every test runs
* against a temp `homeDir` (global scope) and a temp `projectRoot`
* (project scope) so we never touch the developer's real skill dirs.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { SkillStore, applySkillsIndex } from "../src/skills.js";
const BASE = "You are a test assistant.";
type SkillRoot = "project" | "global";
function writeSkillDir(
root: string,
which: SkillRoot,
name: string,
frontmatter: Record<string, string>,
body: string,
homeOrProject: string,
): string {
const parent =
which === "global"
? join(homeOrProject, ".reasonix", "skills")
: join(root, ".reasonix", "skills");
const dir = join(parent, name);
mkdirSync(dir, { recursive: true });
const fmLines = ["---"];
for (const [k, v] of Object.entries(frontmatter)) fmLines.push(`${k}: ${v}`);
fmLines.push("---", "");
const path = join(dir, "SKILL.md");
writeFileSync(path, `${fmLines.join("\n")}${body}\n`, "utf8");
return path;
}
function writeFlatSkill(
dir: string,
name: string,
frontmatter: Record<string, string>,
body: string,
): string {
const skills = join(dir, ".reasonix", "skills");
mkdirSync(skills, { recursive: true });
const fmLines = ["---"];
for (const [k, v] of Object.entries(frontmatter)) fmLines.push(`${k}: ${v}`);
fmLines.push("---", "");
const path = join(skills, `${name}.md`);
writeFileSync(path, `${fmLines.join("\n")}${body}\n`, "utf8");
return path;
}
describe("SkillStore", () => {
let home: string;
let projectRoot: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-skills-home-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-skills-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
});
it("returns an empty list when no skill dirs exist", () => {
const store = new SkillStore({ homeDir: home, projectRoot, disableBuiltins: true });
expect(store.list()).toEqual([]);
});
it("hasProjectScope reflects constructor argument", () => {
expect(new SkillStore({ homeDir: home, disableBuiltins: true }).hasProjectScope()).toBe(false);
expect(
new SkillStore({ homeDir: home, projectRoot, disableBuiltins: true }).hasProjectScope(),
).toBe(true);
});
it("parses a SKILL.md dir-layout entry from the global scope", () => {
writeSkillDir(
projectRoot,
"global",
"review",
{ name: "review", description: "Review a pull request" },
"Run `git diff` and summarize risks.",
home,
);
const skills = new SkillStore({ homeDir: home, projectRoot, disableBuiltins: true }).list();
expect(skills).toHaveLength(1);
expect(skills[0]?.name).toBe("review");
expect(skills[0]?.scope).toBe("global");
expect(skills[0]?.body).toContain("git diff");
});
it("reads flat <name>.md files as well", () => {
writeFlatSkill(home, "ship-it", { description: "Commit and push changes" }, "body");
const skills = new SkillStore({ homeDir: home, projectRoot, disableBuiltins: true }).list();
expect(skills.map((s) => s.name)).toEqual(["ship-it"]);
expect(skills[0]?.description).toBe("Commit and push changes");
});
it("surfaces project-scope skills from <projectRoot>/.reasonix/skills", () => {
writeSkillDir(
projectRoot,
"project",
"deploy",
{ description: "Deploy to staging" },
"Run the staging pipeline.",
home,
);
const list = new SkillStore({ homeDir: home, projectRoot, disableBuiltins: true }).list();
expect(list).toHaveLength(1);
expect(list[0]?.scope).toBe("project");
expect(list[0]?.path).toContain(projectRoot);
});
it("project scope wins on a name collision with global", () => {
writeSkillDir(projectRoot, "global", "review", { description: "global one" }, "G", home);
writeSkillDir(projectRoot, "project", "review", { description: "project one" }, "P", home);
const store = new SkillStore({ homeDir: home, projectRoot, disableBuiltins: true });
const list = store.list();
expect(list).toHaveLength(1);
expect(list[0]?.scope).toBe("project");
expect(list[0]?.description).toBe("project one");
expect(store.read("review")?.body).toBe("P");
});
it("without projectRoot the store only reads the global scope", () => {
// Put a skill in the project dir and a skill in the global dir.
writeSkillDir(projectRoot, "project", "deploy", { description: "proj" }, "P", home);
writeSkillDir(projectRoot, "global", "review", { description: "glob" }, "G", home);
const store = new SkillStore({ homeDir: home, disableBuiltins: true }); // no projectRoot
const names = store.list().map((s) => s.name);
expect(names).toEqual(["review"]);
expect(store.hasProjectScope()).toBe(false);
});
it("rejects invalid skill names on read()", () => {
const store = new SkillStore({ homeDir: home, projectRoot, disableBuiltins: true });
expect(store.read("../etc/passwd")).toBeNull();
expect(store.read("foo/bar")).toBeNull();
expect(store.read("")).toBeNull();
});
it("skips dotfiles that would masquerade as skills", () => {
writeSkillDir(projectRoot, "global", "ok", { description: "fine" }, "body", home);
const dotDir = join(home, ".reasonix", "skills");
writeFileSync(join(dotDir, ".hidden.md"), "---\ndescription: x\n---\nbody\n", "utf8");
const list = new SkillStore({ homeDir: home, projectRoot, disableBuiltins: true }).list();
expect(list.map((s) => s.name)).toEqual(["ok"]);
});
});
describe("applySkillsIndex", () => {
let home: string;
let projectRoot: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-skills-idx-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-skills-idx-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
});
it("returns the prompt unchanged when no skills exist", () => {
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot, disableBuiltins: true });
expect(out).toBe(BASE);
});
it("emits a Skills section with one-liners but not bodies", () => {
writeSkillDir(
projectRoot,
"global",
"review",
{ description: "Review a pull request" },
"BODY-THAT-MUST-NOT-APPEAR",
home,
);
writeSkillDir(
projectRoot,
"global",
"init",
{ description: "Initialize a CLAUDE.md" },
"ALSO-SECRET",
home,
);
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot, disableBuiltins: true });
expect(out).toContain("# Skills");
expect(out).toContain("- init — Initialize a CLAUDE.md");
expect(out).toContain("- review — Review a pull request");
expect(out).not.toContain("BODY-THAT-MUST-NOT-APPEAR");
expect(out).not.toContain("ALSO-SECRET");
});
it("merges project + global skills into a single index", () => {
writeSkillDir(projectRoot, "global", "hello", { description: "global hello" }, "x", home);
writeSkillDir(projectRoot, "project", "deploy", { description: "project deploy" }, "y", home);
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot, disableBuiltins: true });
expect(out).toContain("- deploy — project deploy");
expect(out).toContain("- hello — global hello");
});
it("omits skills with blank descriptions from the pinned index", () => {
writeSkillDir(projectRoot, "global", "has-desc", { description: "I have one" }, "body", home);
writeSkillDir(projectRoot, "global", "no-desc", {}, "body", home);
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot, disableBuiltins: true });
expect(out).toContain("- has-desc —");
expect(out).not.toContain("- no-desc");
});
it("is byte-stable across two calls with the same filesystem state", () => {
writeSkillDir(projectRoot, "global", "a", { description: "one" }, "x", home);
writeSkillDir(projectRoot, "global", "b", { description: "two" }, "y", home);
const first = applySkillsIndex(BASE, { homeDir: home, projectRoot, disableBuiltins: true });
const second = applySkillsIndex(BASE, { homeDir: home, projectRoot, disableBuiltins: true });
expect(first).toBe(second);
});
it("marks subagent-runAs skills with the 🧬 prefix in the index", () => {
writeSkillDir(
projectRoot,
"global",
"lookup",
{ description: "Look something up", runAs: "subagent" },
"body",
home,
);
writeSkillDir(
projectRoot,
"global",
"fmt",
{ description: "Format the codebase", runAs: "inline" },
"body",
home,
);
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot, disableBuiltins: true });
expect(out).toContain("- 🧬 lookup — Look something up");
expect(out).toContain("- fmt — Format the codebase");
expect(out).not.toContain("- 🧬 fmt");
});
});
describe("Skill frontmatter — runAs", () => {
let home: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-skills-runas-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
});
it("defaults runAs to inline when frontmatter omits it", () => {
writeSkillDir(home, "global", "plain", { description: "plain skill" }, "body", home);
const skill = new SkillStore({ homeDir: home, disableBuiltins: true }).read("plain");
expect(skill?.runAs).toBe("inline");
});
it("parses runAs: subagent from frontmatter", () => {
writeSkillDir(
home,
"global",
"deep",
{ description: "deep dive", runAs: "subagent" },
"body",
home,
);
const skill = new SkillStore({ homeDir: home, disableBuiltins: true }).read("deep");
expect(skill?.runAs).toBe("subagent");
});
it("falls back to inline for any unknown runAs value", () => {
writeSkillDir(home, "global", "weird", { description: "?", runAs: "parallel" }, "body", home);
const skill = new SkillStore({ homeDir: home, disableBuiltins: true }).read("weird");
expect(skill?.runAs).toBe("inline");
});
it("captures a deepseek-* model override and ignores anything else", () => {
writeSkillDir(
home,
"global",
"rsr",
{ description: "...", runAs: "subagent", model: "deepseek-reasoner" },
"body",
home,
);
writeSkillDir(
home,
"global",
"wrong",
{ description: "...", runAs: "subagent", model: "gpt-4" },
"body",
home,
);
const store = new SkillStore({ homeDir: home, disableBuiltins: true });
expect(store.read("rsr")?.model).toBe("deepseek-reasoner");
expect(store.read("wrong")?.model).toBeUndefined();
});
});
describe("Built-in skills", () => {
let home: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-skills-builtins-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
});
it("ships explore + research as subagent-runAs builtins", () => {
const store = new SkillStore({ homeDir: home }); // builtins ON
const names = store.list().map((s) => s.name);
expect(names).toContain("explore");
expect(names).toContain("research");
const explore = store.read("explore");
expect(explore?.runAs).toBe("subagent");
expect(explore?.scope).toBe("builtin");
const research = store.read("research");
expect(research?.runAs).toBe("subagent");
});
it("user-authored skills override a builtin with the same name", () => {
writeSkillDir(home, "global", "explore", { description: "my own" }, "custom body", home);
const store = new SkillStore({ homeDir: home });
const explore = store.read("explore");
expect(explore?.scope).toBe("global");
expect(explore?.body).toBe("custom body");
});
it("disableBuiltins hides them entirely", () => {
const store = new SkillStore({ homeDir: home, disableBuiltins: true });
expect(store.read("explore")).toBeNull();
expect(store.list()).toEqual([]);
});
it("builtins surface with the 🧬 marker in applySkillsIndex", () => {
const out = applySkillsIndex(BASE, { homeDir: home }); // builtins ON
expect(out).toContain("# Skills");
expect(out).toContain("🧬 explore");
expect(out).toContain("🧬 research");
});
});
+147 -8
View File
@@ -11,6 +11,7 @@ import {
import { DeepSeekClient, Usage } from "../src/client.js";
import { CacheFirstLoop } from "../src/loop.js";
import { ImmutablePrefix } from "../src/memory.js";
import { VERSION } from "../src/version.js";
function makeLoop() {
const client = new DeepSeekClient({
@@ -473,19 +474,63 @@ describe("handleSlash", () => {
"discard",
"undo",
"commit",
"plan",
"apply-plan",
]) {
expect(names, `registry missing /${required}`).toContain(required);
}
});
it("suggestSlashCommands filters by prefix", () => {
expect(suggestSlashCommands("h").map((s) => s.cmd)).toEqual(["help", "harvest"]);
expect(suggestSlashCommands("h").map((s) => s.cmd)).toEqual(["help", "harvest", "hooks"]);
// Case-insensitive.
expect(suggestSlashCommands("HE").map((s) => s.cmd)).toEqual(["help"]);
// Empty prefix returns everything (non-contextual).
expect(suggestSlashCommands("").length).toBeGreaterThan(5);
});
describe("/update", () => {
it("reports pending check when latestVersion is null (offline / in flight)", () => {
const r = handleSlash("update", [], makeLoop(), { latestVersion: null });
expect(r.info).toMatch(/current: reasonix/);
expect(r.info).toMatch(/not yet resolved/);
expect(r.info).toMatch(/reasonix update/);
});
it("reports up-to-date when current matches latest", () => {
const r = handleSlash("update", [], makeLoop(), { latestVersion: VERSION });
expect(r.info).toMatch(/on the latest/);
expect(r.info).not.toMatch(/npm install/);
});
it("prints shell command when latest is newer than current", () => {
const r = handleSlash("update", [], makeLoop(), { latestVersion: "99.99.99" });
expect(r.info).toMatch(/99\.99\.99/);
expect(r.info).toMatch(/reasonix update/);
expect(r.info).toMatch(/npm install -g reasonix@latest/);
});
it("is surfaced by suggestSlashCommands", () => {
const names = suggestSlashCommands("up").map((s) => s.cmd);
expect(names).toContain("update");
});
});
describe("/stats", () => {
it("prints a how-to when the usage log is empty / missing", () => {
// Use the real ~ here — if a real log exists (developer machine),
// this test would see real data. We assert only on a substring
// that's present either way: the path is always mentioned.
const r = handleSlash("stats", [], makeLoop());
expect(r.info).toMatch(/usage\.jsonl|turns/);
});
it("is surfaced by suggestSlashCommands", () => {
const names = suggestSlashCommands("sta").map((s) => s.cmd);
expect(names).toContain("stats");
});
});
it("suggestSlashCommands hides code-mode-only entries when codeMode=false", () => {
const names = suggestSlashCommands("", false).map((s) => s.cmd);
expect(names).not.toContain("apply");
@@ -602,20 +647,20 @@ describe("handleSlash", () => {
}
});
it("prints a how-to when no REASONIX.md exists", () => {
it("prints a how-to when no memory (REASONIX.md or ~/.reasonix/memory) exists", () => {
const r = handleSlash("memory", [], makeLoop(), { memoryRoot: root });
expect(r.info).toMatch(/no REASONIX\.md in/);
expect(r.info).toMatch(/pin notes/);
expect(r.info).toMatch(/no memory pinned/);
expect(r.info).toMatch(/REASONIX\.md/);
});
it("prints the file contents + path when present", () => {
it("prints the REASONIX.md contents + path when present", () => {
writeFileSync(
join(root, "REASONIX.md"),
"# House rules\nSnake case only in this repo.\n",
"utf8",
);
const r = handleSlash("memory", [], makeLoop(), { memoryRoot: root });
expect(r.info).toMatch(/▸ project memory:/);
expect(r.info).toMatch(/▸ REASONIX\.md:/);
expect(r.info).toContain("Snake case only");
expect(r.info).toMatch(/chars/);
});
@@ -624,12 +669,106 @@ describe("handleSlash", () => {
writeFileSync(join(root, "REASONIX.md"), "content", "utf8");
process.env.REASONIX_MEMORY = "off";
const r = handleSlash("memory", [], makeLoop(), { memoryRoot: root });
expect(r.info).toMatch(/project memory is disabled/);
expect(r.info).toMatch(/memory is disabled/);
});
it("refuses to guess a root when memoryRoot is absent", () => {
const r = handleSlash("memory", [], makeLoop());
expect(r.info).toMatch(/no project root/);
expect(r.info).toMatch(/no working directory/);
});
});
describe("/plan + /apply-plan", () => {
it("/plan replies 'only in code mode' when setPlanMode callback is missing", () => {
const r = handleSlash("plan", [], makeLoop());
expect(r.info).toMatch(/only available inside `reasonix code`/);
});
it("/plan toggles when called with no args", () => {
const calls: boolean[] = [];
const r1 = handleSlash("plan", [], makeLoop(), {
planMode: false,
setPlanMode: (on) => calls.push(on),
});
expect(calls).toEqual([true]);
expect(r1.info).toMatch(/plan mode ON/);
const r2 = handleSlash("plan", [], makeLoop(), {
planMode: true,
setPlanMode: (on) => calls.push(on),
});
expect(calls).toEqual([true, false]);
expect(r2.info).toMatch(/plan mode OFF/);
});
it("/plan on / off / true / false / 0 / 1 parse correctly", () => {
const check = (arg: string, expected: boolean) => {
const calls: boolean[] = [];
handleSlash("plan", [arg], makeLoop(), {
planMode: !expected, // start from the opposite
setPlanMode: (on) => calls.push(on),
});
expect(calls, `arg=${arg}`).toEqual([expected]);
};
check("on", true);
check("true", true);
check("1", true);
check("off", false);
check("false", false);
check("0", false);
});
it("/plan explains the stronger-constraint relationship with autonomous submit_plan", () => {
const r = handleSlash("plan", ["on"], makeLoop(), {
setPlanMode: () => {},
planMode: false,
});
// The info text should be explicit that submit_plan can also fire
// outside plan mode (autonomous) — plan mode is the *stronger*
// constraint, not the only path.
expect(r.info).toMatch(/stronger/);
expect(r.info).toMatch(/submit_plan/);
});
it("/apply-plan replies 'only in code mode' when setPlanMode is missing", () => {
const r = handleSlash("apply-plan", [], makeLoop());
expect(r.info).toMatch(/only available inside `reasonix code`/);
});
it("/apply-plan flips plan mode off, clears pending, and resubmits the implement-now synthetic", () => {
const setCalls: boolean[] = [];
const clearCalls: number[] = [];
const r = handleSlash("apply-plan", [], makeLoop(), {
setPlanMode: (on) => setCalls.push(on),
clearPendingPlan: () => {
clearCalls.push(1);
},
});
expect(setCalls).toEqual([false]);
expect(clearCalls).toEqual([1]);
expect(r.info).toMatch(/plan approved/);
expect(r.resubmit).toMatch(/Implement it now/);
expect(r.resubmit).toMatch(/out of plan mode/);
});
it("/apply-plan works without a clearPendingPlan callback (only setPlanMode required)", () => {
const setCalls: boolean[] = [];
const r = handleSlash("apply-plan", [], makeLoop(), {
setPlanMode: (on) => setCalls.push(on),
// clearPendingPlan omitted — /apply-plan must still work
});
expect(setCalls).toEqual([false]);
expect(r.resubmit).toMatch(/Implement it now/);
});
it("/status surfaces plan mode when it's on", () => {
const r = handleSlash("status", [], makeLoop(), { planMode: true });
expect(r.info).toMatch(/plan\s+ON/);
});
it("/status hides the plan line when plan mode is off", () => {
const r = handleSlash("status", [], makeLoop(), { planMode: false });
expect(r.info).not.toMatch(/plan\s+ON/);
});
});
});
+366
View File
@@ -0,0 +1,366 @@
/**
* Subagent tool — registration, child-loop isolation, fork-registry
* exclusion rules, error path, abort propagation, plan-mode inheritance.
*
* The DeepSeek client is faked so we never hit the network. Same shape
* as `tests/loop.test.ts` so the wire-level expectations stay aligned
* with the loop's real behavior.
*/
import { describe, expect, it, vi } from "vitest";
import { DeepSeekClient } from "../src/client.js";
import { ToolRegistry } from "../src/tools.js";
import {
type SubagentEvent,
type SubagentSink,
forkRegistryExcluding,
registerSubagentTool,
} from "../src/tools/subagent.js";
interface FakeResponseShape {
content?: string;
reasoning_content?: string;
tool_calls?: any[];
usage?: Record<string, number>;
}
function fakeFetch(responses: FakeResponseShape[]): typeof fetch {
let i = 0;
return vi.fn(async (_url: any, init: any) => {
const body = init?.body ? JSON.parse(init.body) : {};
const resp = responses[i++] ?? responses[responses.length - 1]!;
return new Response(
JSON.stringify({
_echo_messages: body.messages,
choices: [
{
index: 0,
message: {
role: "assistant",
content: resp.content ?? "",
reasoning_content: resp.reasoning_content ?? null,
tool_calls: resp.tool_calls ?? undefined,
},
finish_reason: resp.tool_calls ? "tool_calls" : "stop",
},
],
usage: resp.usage ?? {
prompt_tokens: 100,
completion_tokens: 20,
total_tokens: 120,
prompt_cache_hit_tokens: 0,
prompt_cache_miss_tokens: 100,
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}) as unknown as typeof fetch;
}
function makeClient(responses: FakeResponseShape[]) {
return new DeepSeekClient({
apiKey: "sk-test",
fetch: fakeFetch(responses),
});
}
function makeSink(): { sink: SubagentSink; events: SubagentEvent[] } {
const events: SubagentEvent[] = [];
const sink: SubagentSink = {
current: (ev) => {
events.push(ev);
},
};
return { sink, events };
}
describe("registerSubagentTool", () => {
it("registers spawn_subagent into the parent registry", () => {
const parent = new ToolRegistry();
const client = makeClient([{ content: "ok" }]);
registerSubagentTool(parent, { client });
expect(parent.has("spawn_subagent")).toBe(true);
});
it("returns a structured success payload with the subagent's final answer", async () => {
const parent = new ToolRegistry();
const client = makeClient([{ content: "the answer is 42" }]);
registerSubagentTool(parent, { client });
const out = await parent.dispatch(
"spawn_subagent",
JSON.stringify({ task: "what is the answer?" }),
);
const parsed = JSON.parse(out);
expect(parsed.success).toBe(true);
expect(parsed.output).toBe("the answer is 42");
expect(parsed.turns).toBe(1);
expect(parsed.tool_iters).toBe(0);
expect(typeof parsed.elapsed_ms).toBe("number");
});
it("rejects an empty task with a structured error", async () => {
const parent = new ToolRegistry();
const client = makeClient([{ content: "won't be called" }]);
registerSubagentTool(parent, { client });
const out = await parent.dispatch("spawn_subagent", JSON.stringify({ task: " \n " }));
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/non-empty 'task'/);
});
it("emits start → end events through the sink", async () => {
const parent = new ToolRegistry();
const client = makeClient([{ content: "done" }]);
const { sink, events } = makeSink();
registerSubagentTool(parent, { client, sink });
await parent.dispatch(
"spawn_subagent",
JSON.stringify({ task: "this task is over thirty characters long" }),
);
expect(events[0]?.kind).toBe("start");
expect(events[events.length - 1]?.kind).toBe("end");
// task preview truncated to 30 chars + ellipsis
expect(events[0]?.task).toMatch(/…$/);
expect(events[0]?.task.length).toBeLessThanOrEqual(31);
// end event carries the summary + turn count
const end = events[events.length - 1]!;
expect(end.summary).toBe("done");
expect(end.turns).toBe(1);
expect(end.error).toBeUndefined();
});
it("emits a progress event for each tool result inside the child loop", async () => {
const parent = new ToolRegistry();
parent.register({
name: "noop",
readOnly: true,
fn: () => "noop-result",
});
const client = makeClient([
{
content: "",
tool_calls: [
{
id: "call_1",
type: "function",
function: { name: "noop", arguments: "{}" },
},
],
},
{ content: "all done" },
]);
const { sink, events } = makeSink();
registerSubagentTool(parent, { client, sink });
await parent.dispatch("spawn_subagent", JSON.stringify({ task: "use noop" }));
const progress = events.filter((e) => e.kind === "progress");
expect(progress.length).toBe(1);
expect(progress[0]?.iter).toBe(1);
});
it("surfaces a child-loop error in the structured result + end event", async () => {
const parent = new ToolRegistry();
// 401 from the fake fetch → DeepSeekClient throws inside the child step()
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: vi.fn(async () => new Response("unauthorized", { status: 401 })) as any,
retry: { maxAttempts: 1 },
});
const { sink, events } = makeSink();
registerSubagentTool(parent, { client, sink });
const out = await parent.dispatch("spawn_subagent", JSON.stringify({ task: "fail please" }));
const parsed = JSON.parse(out);
expect(parsed.success).toBe(false);
expect(parsed.error).toBeTruthy();
const end = events[events.length - 1]!;
expect(end.kind).toBe("end");
expect(end.error).toBeTruthy();
expect(end.summary).toBeUndefined();
});
it("truncates oversized output and signals the truncation", async () => {
const parent = new ToolRegistry();
const huge = "x".repeat(20_000);
const client = makeClient([{ content: huge }]);
registerSubagentTool(parent, { client, maxResultChars: 100 });
const out = await parent.dispatch("spawn_subagent", JSON.stringify({ task: "spew" }));
const parsed = JSON.parse(out);
expect(parsed.output.length).toBeLessThan(huge.length);
expect(parsed.output).toMatch(/truncated/);
});
it("never registers spawn_subagent itself into the child registry (no recursion)", async () => {
// We can't easily peek at the child registry from outside the tool,
// but we CAN observe the child loop's prefix.toolSpecs via the
// request body the fake fetch sees. Tools advertised in the request
// are exactly the child registry's specs.
const parent = new ToolRegistry();
parent.register({ name: "harmless", readOnly: true, fn: () => "ok" });
parent.register({ name: "submit_plan", readOnly: true, fn: () => "ok" });
const seenToolNames: string[][] = [];
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: vi.fn(async (_url: any, init: any) => {
const body = init?.body ? JSON.parse(init.body) : {};
const tools = (body.tools ?? []) as Array<{ function: { name: string } }>;
seenToolNames.push(tools.map((t) => t.function.name));
return new Response(
JSON.stringify({
choices: [
{
index: 0,
message: { role: "assistant", content: "fine" },
finish_reason: "stop",
},
],
usage: { prompt_tokens: 10, completion_tokens: 1, total_tokens: 11 },
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}) as any,
});
registerSubagentTool(parent, { client });
await parent.dispatch("spawn_subagent", JSON.stringify({ task: "go" }));
expect(seenToolNames.length).toBe(1);
const childTools = seenToolNames[0]!;
// Inherited the harmless tool, but NOT spawn_subagent or submit_plan.
expect(childTools).toContain("harmless");
expect(childTools).not.toContain("spawn_subagent");
expect(childTools).not.toContain("submit_plan");
});
it("respects a custom system prompt passed in the tool args", async () => {
const seenSystems: string[] = [];
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: vi.fn(async (_url: any, init: any) => {
const body = init?.body ? JSON.parse(init.body) : {};
const sys = (body.messages ?? []).find((m: any) => m.role === "system");
if (sys) seenSystems.push(sys.content);
return new Response(
JSON.stringify({
choices: [
{
index: 0,
message: { role: "assistant", content: "ok" },
finish_reason: "stop",
},
],
usage: { prompt_tokens: 10, completion_tokens: 1, total_tokens: 11 },
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}) as any,
});
const parent = new ToolRegistry();
registerSubagentTool(parent, { client });
await parent.dispatch(
"spawn_subagent",
JSON.stringify({ task: "go", system: "You are a custom subagent." }),
);
expect(seenSystems[0]).toBe("You are a custom subagent.");
});
it("falls back to the default model when the model arg is invalid", async () => {
const seenModels: string[] = [];
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: vi.fn(async (_url: any, init: any) => {
const body = init?.body ? JSON.parse(init.body) : {};
seenModels.push(body.model);
return new Response(
JSON.stringify({
choices: [
{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" },
],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}) as any,
});
const parent = new ToolRegistry();
registerSubagentTool(parent, { client });
// "gpt-4" is not a deepseek-* model — should be ignored.
await parent.dispatch("spawn_subagent", JSON.stringify({ task: "go", model: "gpt-4" }));
expect(seenModels[0]).toBe("deepseek-chat");
});
it("aborts the child when the parent's tool ctx signal fires", async () => {
const parent = new ToolRegistry();
// Slow client — sleeps 200ms before responding so the abort beats it.
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: vi.fn(async (_url: any, init: any) => {
const signal: AbortSignal | undefined = init?.signal;
await new Promise<void>((resolve, reject) => {
const t = setTimeout(resolve, 200);
signal?.addEventListener("abort", () => {
clearTimeout(t);
reject(new DOMException("aborted", "AbortError"));
});
});
return new Response(
JSON.stringify({
choices: [
{ index: 0, message: { role: "assistant", content: "late" }, finish_reason: "stop" },
],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}) as any,
retry: { maxAttempts: 1 },
});
registerSubagentTool(parent, { client });
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 20);
const out = await parent.dispatch("spawn_subagent", JSON.stringify({ task: "slow" }), {
signal: ctrl.signal,
});
const parsed = JSON.parse(out);
expect(parsed.success).toBe(false);
});
});
describe("forkRegistryExcluding", () => {
it("copies all tools except the excluded names", () => {
const parent = new ToolRegistry();
parent.register({ name: "a", fn: () => "a" });
parent.register({ name: "b", fn: () => "b" });
parent.register({ name: "c", fn: () => "c" });
const child = forkRegistryExcluding(parent, new Set(["b"]));
expect(child.has("a")).toBe(true);
expect(child.has("b")).toBe(false);
expect(child.has("c")).toBe(true);
expect(child.size).toBe(2);
});
it("propagates plan-mode state from the parent", () => {
const parent = new ToolRegistry();
parent.register({ name: "x", readOnly: true, fn: () => "x" });
parent.setPlanMode(true);
const child = forkRegistryExcluding(parent, new Set());
expect(child.planMode).toBe(true);
});
it("child registry's plan mode defaults off when parent's is off", () => {
const parent = new ToolRegistry();
parent.register({ name: "x", fn: () => "x" });
const child = forkRegistryExcluding(parent, new Set());
expect(child.planMode).toBe(false);
});
it("dispatching a copied tool still runs its fn", async () => {
const parent = new ToolRegistry();
let calls = 0;
parent.register({
name: "counter",
fn: () => {
calls++;
return `n=${calls}`;
},
});
const child = forkRegistryExcluding(parent, new Set());
const out = await child.dispatch("counter", "{}");
expect(out).toBe("n=1");
});
});
+181
View File
@@ -0,0 +1,181 @@
/**
* Tests for the `remember` / `forget` / `recall_memory` tool surface.
* Dispatches through ToolRegistry like R1 would, so refusals surface
* as JSON-encoded `{ error: ... }` strings (matching dispatch semantics).
*/
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import { registerMemoryTools } from "../src/tools/memory.js";
import { MemoryStore } from "../src/user-memory.js";
describe("memory tools", () => {
let home: string;
let projectRoot: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-memtools-home-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-memtools-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
});
describe("remember", () => {
it("writes a global memory and returns a human-readable confirmation", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("remember", {
type: "feedback",
scope: "global",
name: "pref_one",
description: "User prefers tabs",
content: "Always use tabs for indentation.",
});
expect(out).toMatch(/REMEMBERED \(global\/pref_one\)/);
expect(out).toMatch(/User prefers tabs/);
// Verify the store actually has it.
const store = new MemoryStore({ homeDir: home });
const listed = store.list();
expect(listed.map((e) => e.name)).toContain("pref_one");
});
it("refuses scope='project' when no projectRoot is configured", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("remember", {
type: "project",
scope: "project",
name: "xyz_abc",
description: "d",
content: "c",
});
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/scope='project'/);
});
it("allows scope='project' when projectRoot is configured", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home, projectRoot });
const out = await reg.dispatch("remember", {
type: "project",
scope: "project",
name: "bun_build",
description: "Build is bun run build",
content: "On this machine, no npm — only bun.",
});
expect(out).toMatch(/REMEMBERED \(project\/bun_build\)/);
});
it("returns an error (not a throw) for invalid names", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "../bad",
description: "d",
content: "c",
});
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/invalid memory name/);
});
it("returns an error when description is empty", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "nonempty_name",
description: "",
content: "body",
});
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/description/);
});
});
describe("forget", () => {
it("removes an existing memory and reports so", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "delete_me",
description: "d",
content: "c",
});
const out = await reg.dispatch("forget", { scope: "global", name: "delete_me" });
expect(out).toMatch(/forgot \(global\/delete_me\)/);
const store = new MemoryStore({ homeDir: home });
expect(store.list().map((e) => e.name)).not.toContain("delete_me");
});
it("is idempotent on a missing memory (reports 'no such memory')", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("forget", { scope: "global", name: "ghost_one" });
expect(out).toMatch(/no such memory/);
});
});
describe("recall_memory", () => {
it("returns the body of an existing memory (with header)", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
await reg.dispatch("remember", {
type: "feedback",
scope: "global",
name: "deep_detail",
description: "short one-liner",
content: "Full body with **markdown** and multiple paragraphs.\n\nSecond paragraph.",
});
const out = await reg.dispatch("recall_memory", {
scope: "global",
name: "deep_detail",
});
expect(out).toContain("deep_detail");
expect(out).toContain("Full body with **markdown**");
expect(out).toContain("Second paragraph.");
});
it("returns an error (not a throw) on missing name", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("recall_memory", { scope: "global", name: "ghost_one" });
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/recall failed/);
});
it("is marked readOnly (available in plan mode)", () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const tool = reg.get("recall_memory");
expect(tool?.readOnly).toBe(true);
});
});
describe("registration", () => {
it("registers all three tools", () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
expect(reg.has("remember")).toBe(true);
expect(reg.has("forget")).toBe(true);
expect(reg.has("recall_memory")).toBe(true);
});
it("remember / forget are NOT marked readOnly (gated in plan mode)", () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
expect(reg.get("remember")?.readOnly).not.toBe(true);
expect(reg.get("forget")?.readOnly).not.toBe(true);
});
});
});
+194
View File
@@ -0,0 +1,194 @@
/**
* Tests for the `run_skill` tool. Uses a temp `homeDir` and optional
* `projectRoot` so the tool never reads real skill dirs.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import { registerSkillTools } from "../src/tools/skills.js";
/**
* Write a skill under `<baseDir>/.reasonix/skills/<name>/SKILL.md`.
* Callers pass their home tmpdir for global-scope skills, or their
* projectRoot tmpdir for project-scope skills — the on-disk layout is
* the same either way, only the base directory differs.
*/
function writeSkill(baseDir: string, name: string, description: string, body: string): void {
const dir = join(baseDir, ".reasonix", "skills", name);
mkdirSync(dir, { recursive: true });
writeFileSync(
join(dir, "SKILL.md"),
`---\nname: ${name}\ndescription: ${description}\n---\n\n${body}\n`,
"utf8",
);
}
/**
* Write a skill with arbitrary frontmatter — used for subagent-runAs
* tests where we need `runAs: subagent` and an optional `model:` line.
*/
function writeSkillWithFrontmatter(
baseDir: string,
name: string,
fm: Record<string, string>,
body: string,
): void {
const dir = join(baseDir, ".reasonix", "skills", name);
mkdirSync(dir, { recursive: true });
const lines = ["---", `name: ${name}`];
for (const [k, v] of Object.entries(fm)) lines.push(`${k}: ${v}`);
lines.push("---", "");
writeFileSync(join(dir, "SKILL.md"), `${lines.join("\n")}${body}\n`, "utf8");
}
describe("run_skill tool", () => {
let home: string;
let projectRoot: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-skilltool-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-skilltool-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
});
it("registers run_skill as a read-only tool", () => {
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home, disableBuiltins: true });
const tool = reg.get("run_skill");
expect(tool).toBeDefined();
expect(tool?.readOnly).toBe(true);
});
it("returns the skill body when the name resolves (global scope)", async () => {
writeSkill(home, "review", "Review a PR", "Step 1: diff. Step 2: comment.");
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home, disableBuiltins: true });
const out = await reg.dispatch("run_skill", { name: "review" });
expect(out).toContain("# Skill: review");
expect(out).toContain("Review a PR");
expect(out).toContain("scope: global");
expect(out).toContain("Step 1: diff");
});
it("resolves project-scope skills when projectRoot is passed", async () => {
writeSkill(projectRoot, "deploy", "Deploy to staging", "Run pipeline.");
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home, projectRoot, disableBuiltins: true });
const out = await reg.dispatch("run_skill", { name: "deploy" });
expect(out).toContain("scope: project");
expect(out).toContain("Run pipeline");
});
it("appends a forwarded 'Arguments:' line when provided", async () => {
writeSkill(home, "greet", "Greet someone", "Say hello to the name in args.");
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home, disableBuiltins: true });
const out = await reg.dispatch("run_skill", { name: "greet", arguments: "Alice" });
expect(out).toContain("Arguments: Alice");
});
it("returns a structured error with available names on unknown skill", async () => {
writeSkill(home, "review", "Review a PR", "...");
writeSkill(home, "ship-it", "Push commit", "...");
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home, disableBuiltins: true });
const out = await reg.dispatch("run_skill", { name: "nope" });
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/unknown skill/);
expect(parsed.available).toContain("review");
expect(parsed.available).toContain("ship-it");
});
it("rejects an empty name", async () => {
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home, disableBuiltins: true });
const out = await reg.dispatch("run_skill", { name: "" });
expect(JSON.parse(out).error).toMatch(/requires a 'name'/);
});
it("dispatches subagent-runAs skills through subagentRunner", async () => {
writeSkillWithFrontmatter(
home,
"deepdive",
{ description: "deep dive subagent", runAs: "subagent" },
"You are a deep-dive agent. Investigate the task and return a one-line answer.",
);
const reg = new ToolRegistry();
let received: { skillName: string; skillBody: string; task: string } | null = null;
registerSkillTools(reg, {
homeDir: home,
disableBuiltins: true,
subagentRunner: async (skill, task) => {
received = { skillName: skill.name, skillBody: skill.body, task };
return JSON.stringify({ success: true, output: "subagent-said-this" });
},
});
const out = await reg.dispatch("run_skill", {
name: "deepdive",
arguments: "find all tests that touch the loop",
});
expect(received?.skillName).toBe("deepdive");
expect(received?.skillBody).toContain("deep-dive agent");
expect(received?.task).toBe("find all tests that touch the loop");
const parsed = JSON.parse(out);
expect(parsed.output).toBe("subagent-said-this");
});
it("returns a configured-error when a subagent skill fires without a runner", async () => {
writeSkillWithFrontmatter(
home,
"needs-runner",
{ description: "needs a runner", runAs: "subagent" },
"...",
);
const reg = new ToolRegistry();
// Note: NO subagentRunner.
registerSkillTools(reg, { homeDir: home, disableBuiltins: true });
const out = await reg.dispatch("run_skill", {
name: "needs-runner",
arguments: "do the thing",
});
expect(JSON.parse(out).error).toMatch(/no subagent runner is configured/);
});
it("requires arguments for subagent skills (subagent has no other context)", async () => {
writeSkillWithFrontmatter(
home,
"needs-args",
{ description: "needs args", runAs: "subagent" },
"...",
);
const reg = new ToolRegistry();
registerSkillTools(reg, {
homeDir: home,
disableBuiltins: true,
subagentRunner: async () => "should-not-be-called",
});
const out = await reg.dispatch("run_skill", { name: "needs-args" });
expect(JSON.parse(out).error).toMatch(/requires 'arguments'/);
});
it("inline skills don't go through subagentRunner even when one exists", async () => {
writeSkill(home, "inline-skill", "plain", "Step 1, Step 2.");
const reg = new ToolRegistry();
let runnerCalls = 0;
registerSkillTools(reg, {
homeDir: home,
disableBuiltins: true,
subagentRunner: async () => {
runnerCalls++;
return "x";
},
});
const out = await reg.dispatch("run_skill", { name: "inline-skill" });
expect(out).toContain("Step 1, Step 2.");
expect(runnerCalls).toBe(0);
});
});
+143
View File
@@ -0,0 +1,143 @@
/**
* Tests for the `reasonix update` command — pure decision function
* + the CLI orchestrator with every side effect mocked via its
* test seams. No network, no spawn, no process.exit.
*/
import { describe, expect, it } from "vitest";
import { planUpdate, updateCommand } from "../src/cli/commands/update.js";
import { VERSION } from "../src/version.js";
describe("planUpdate", () => {
it("up-to-date when current === latest", () => {
const plan = planUpdate({ current: "0.4.22", latest: "0.4.22" });
expect(plan.action).toBe("up-to-date");
expect(plan.command).toBeUndefined();
});
it("newer-local when current > latest (dev build)", () => {
const plan = planUpdate({ current: "0.5.0", latest: "0.4.22" });
expect(plan.action).toBe("newer-local");
expect(plan.command).toBeUndefined();
});
it("npx-hint when current < latest and running via npx", () => {
const plan = planUpdate({ current: "0.4.21", latest: "0.4.22", npx: true });
expect(plan.action).toBe("npx-hint");
expect(plan.command).toBeUndefined();
expect(plan.message).toContain("npx");
});
it("run-npm-install when current < latest and not npx", () => {
const plan = planUpdate({ current: "0.4.21", latest: "0.4.22", npx: false });
expect(plan.action).toBe("run-npm-install");
expect(plan.command).toEqual(["npm", "install", "-g", "reasonix@latest"]);
});
});
describe("updateCommand", () => {
function harness() {
const output: string[] = [];
let exitCode: number | undefined;
const spawnCalls: string[][] = [];
return {
output,
get exitCode() {
return exitCode;
},
spawnCalls,
write: (m: string) => {
output.push(m);
},
exit: (c: number) => {
exitCode = c;
},
spawnInstall: async (argv: string[]) => {
spawnCalls.push(argv);
return 0;
},
};
}
it("prints up-to-date and does NOT spawn when current === latest", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => VERSION,
isNpx: () => false,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
expect(h.output.join("")).toContain("up to date");
expect(h.spawnCalls).toHaveLength(0);
expect(h.exitCode).toBeUndefined();
});
it("prints npx hint and does NOT spawn when running under npx", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => "99.99.99",
isNpx: () => true,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
const joined = h.output.join("");
expect(joined).toContain("99.99.99");
expect(joined).toContain("npx");
expect(h.spawnCalls).toHaveLength(0);
});
it("spawns npm install -g when global install is behind latest", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => "99.99.99",
isNpx: () => false,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
expect(h.spawnCalls).toEqual([["npm", "install", "-g", "reasonix@latest"]]);
expect(h.exitCode).toBeUndefined();
});
it("--dry-run prints the command but does not spawn", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => "99.99.99",
isNpx: () => false,
dryRun: true,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
expect(h.spawnCalls).toHaveLength(0);
expect(h.output.join("")).toContain("(dry run)");
});
it("exits non-zero when the registry is unreachable", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => null,
isNpx: () => false,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
expect(h.output.join("")).toContain("could not reach");
expect(h.exitCode).toBe(1);
});
it("surfaces non-zero npm exit via the exit seam", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => "99.99.99",
isNpx: () => false,
write: h.write,
exit: h.exit,
spawnInstall: async () => 127,
});
expect(h.exitCode).toBe(127);
expect(h.output.join("")).toContain("did not complete");
});
});
+289
View File
@@ -0,0 +1,289 @@
/**
* Tests for the usage log + aggregator.
*
* Covered:
* - appendUsage round-trips (record → file → readUsageLog)
* - readUsageLog tolerates malformed tail lines + missing file
* - aggregateUsage rolls records into today / week / month / all
* using rolling windows against an injected `now`
* - bucketCacheHitRatio / bucketSavingsFraction handle zero-denominator
* - stats dashboard render contains the expected rows
*/
import { appendFileSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { renderDashboard } from "../src/cli/commands/stats.js";
import { Usage } from "../src/client.js";
import {
type UsageRecord,
aggregateUsage,
appendUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
readUsageLog,
} from "../src/usage.js";
function usage(overrides: Partial<Usage> = {}): Usage {
return new Usage(
overrides.promptTokens ?? 100,
overrides.completionTokens ?? 20,
overrides.totalTokens ?? 120,
overrides.promptCacheHitTokens ?? 80,
overrides.promptCacheMissTokens ?? 20,
);
}
describe("appendUsage + readUsageLog", () => {
let dir: string;
let path: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "reasonix-usage-"));
path = join(dir, "usage.jsonl");
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
it("round-trips a single record", () => {
const record = appendUsage({
session: "default",
model: "deepseek-reasoner",
usage: usage(),
now: 1_700_000_000_000,
path,
});
expect(record.session).toBe("default");
expect(record.costUsd).toBeGreaterThan(0);
expect(record.claudeEquivUsd).toBeGreaterThan(record.costUsd);
const loaded = readUsageLog(path);
expect(loaded).toHaveLength(1);
expect(loaded[0]?.ts).toBe(1_700_000_000_000);
expect(loaded[0]?.session).toBe("default");
});
it("returns [] when the log does not exist", () => {
expect(readUsageLog(path)).toEqual([]);
});
it("tolerates a malformed trailing line (skips it)", () => {
appendUsage({ session: null, model: "deepseek-chat", usage: usage(), path });
mkdirSync(dirname(path), { recursive: true });
appendFileSync(path, "{ not valid json\n", "utf8");
const loaded = readUsageLog(path);
expect(loaded).toHaveLength(1);
});
it("creates the parent directory if missing", () => {
const deep = join(dir, "a", "b", "usage.jsonl");
appendUsage({ session: null, model: "deepseek-chat", usage: usage(), path: deep });
expect(readUsageLog(deep)).toHaveLength(1);
});
it("swallows write failure silently (best-effort contract)", () => {
// Point at a path under a FILE, not a directory — mkdirSync will
// blow up and appendUsage should absorb it without throwing.
const blocker = join(dir, "blocker");
appendFileSync(blocker, "not a dir");
expect(() =>
appendUsage({
session: null,
model: "deepseek-chat",
usage: usage(),
path: join(blocker, "usage.jsonl"),
}),
).not.toThrow();
});
});
describe("aggregateUsage", () => {
const NOW = 1_700_000_000_000; // fixed epoch for all windows below
const DAY = 24 * 60 * 60 * 1000;
function rec(partial: Partial<UsageRecord> & { ts: number }): UsageRecord {
return {
session: null,
model: "deepseek-reasoner",
promptTokens: 100,
completionTokens: 20,
cacheHitTokens: 80,
cacheMissTokens: 20,
costUsd: 0.001,
claudeEquivUsd: 0.01,
...partial,
};
}
it("empty input → empty buckets, null firstSeen/lastSeen", () => {
const agg = aggregateUsage([], { now: NOW });
expect(agg.buckets.map((b) => b.turns)).toEqual([0, 0, 0, 0]);
expect(agg.firstSeen).toBeNull();
expect(agg.lastSeen).toBeNull();
});
it("rolls records into today / week / month / all by age", () => {
const records = [
rec({ ts: NOW - 60_000 }), // 1 min ago → today
rec({ ts: NOW - 2 * DAY }), // 2 days ago → week + month + all
rec({ ts: NOW - 10 * DAY }), // 10 days → month + all
rec({ ts: NOW - 90 * DAY }), // 90 days → only all-time
];
const agg = aggregateUsage(records, { now: NOW });
const [today, week, month, all] = agg.buckets;
expect(today?.turns).toBe(1);
expect(week?.turns).toBe(2);
expect(month?.turns).toBe(3);
expect(all?.turns).toBe(4);
});
it("sums token + cost fields across records in each window", () => {
const records = [
rec({
ts: NOW - 60_000,
costUsd: 0.5,
claudeEquivUsd: 5,
cacheHitTokens: 1,
cacheMissTokens: 0,
}),
rec({
ts: NOW - 60_001,
costUsd: 0.25,
claudeEquivUsd: 2,
cacheHitTokens: 1,
cacheMissTokens: 1,
}),
];
const agg = aggregateUsage(records, { now: NOW });
const today = agg.buckets[0];
expect(today?.costUsd).toBeCloseTo(0.75);
expect(today?.claudeEquivUsd).toBeCloseTo(7);
expect(today?.cacheHitTokens).toBe(2);
expect(today?.cacheMissTokens).toBe(1);
});
it("byModel + bySession sort descending and group nulls under (ephemeral)", () => {
const records = [
rec({ ts: NOW - 60_000, model: "deepseek-chat", session: "a" }),
rec({ ts: NOW - 60_000, model: "deepseek-reasoner", session: "a" }),
rec({ ts: NOW - 60_000, model: "deepseek-reasoner", session: "b" }),
rec({ ts: NOW - 60_000, model: "deepseek-reasoner", session: null }),
];
const agg = aggregateUsage(records, { now: NOW });
expect(agg.byModel[0]?.model).toBe("deepseek-reasoner");
expect(agg.byModel[0]?.turns).toBe(3);
expect(agg.bySession[0]?.session).toBe("a");
expect(agg.bySession.find((s) => s.session === "(ephemeral)")?.turns).toBe(1);
});
});
describe("bucket helpers", () => {
it("cache hit ratio — zero denominator → 0", () => {
const b = aggregateUsage([], { now: 1 }).buckets[0]!;
expect(bucketCacheHitRatio(b)).toBe(0);
});
it("cache hit ratio — 80 hit / 20 miss → 0.8", () => {
const agg = aggregateUsage(
[
{
ts: 1_700_000_000_000,
session: null,
model: "deepseek-chat",
promptTokens: 100,
completionTokens: 0,
cacheHitTokens: 80,
cacheMissTokens: 20,
costUsd: 0,
claudeEquivUsd: 0,
},
],
{ now: 1_700_000_000_000 },
);
const today = agg.buckets[0]!;
expect(bucketCacheHitRatio(today)).toBeCloseTo(0.8);
});
it("savings fraction — zero Claude cost → 0 (no division)", () => {
const b = aggregateUsage([], { now: 1 }).buckets[0]!;
expect(bucketSavingsFraction(b)).toBe(0);
});
it("savings fraction — cost $1 vs Claude $10 → 0.9", () => {
const agg = aggregateUsage(
[
{
ts: 1_700_000_000_000,
session: null,
model: "deepseek-chat",
promptTokens: 0,
completionTokens: 0,
cacheHitTokens: 0,
cacheMissTokens: 0,
costUsd: 1,
claudeEquivUsd: 10,
},
],
{ now: 1_700_000_000_000 },
);
expect(bucketSavingsFraction(agg.buckets[0]!)).toBeCloseTo(0.9);
});
});
describe("renderDashboard", () => {
it("includes the four window labels + header", () => {
const agg = aggregateUsage(
[
{
ts: 1_700_000_000_000,
session: "s",
model: "deepseek-reasoner",
promptTokens: 1,
completionTokens: 1,
cacheHitTokens: 1,
cacheMissTokens: 0,
costUsd: 0.001,
claudeEquivUsd: 0.1,
},
],
{ now: 1_700_000_000_000 },
);
const out = renderDashboard(agg, "/tmp/fake.jsonl");
expect(out).toContain("today");
expect(out).toContain("week");
expect(out).toContain("month");
expect(out).toContain("all-time");
expect(out).toContain("cache hit");
expect(out).toContain("vs Claude");
expect(out).toContain("most used model:");
expect(out).toContain("top session:");
expect(out).toContain("tracked since:");
});
it("renders em-dashes for empty buckets rather than $0.000000", () => {
const agg = aggregateUsage(
[
{
ts: 1_700_000_000_000 - 365 * 24 * 60 * 60 * 1000,
session: null,
model: "deepseek-chat",
promptTokens: 1,
completionTokens: 1,
cacheHitTokens: 1,
cacheMissTokens: 0,
costUsd: 0.001,
claudeEquivUsd: 0.01,
},
],
{ now: 1_700_000_000_000 },
);
const out = renderDashboard(agg, "/tmp/fake.jsonl");
// today / week / month should all be empty because the only record
// is a year old. The all-time row still has a cost.
// Each em-dash represents an empty cell.
const emDashCount = (out.match(/—/g) ?? []).length;
expect(emDashCount).toBeGreaterThan(0);
});
});
+396
View File
@@ -0,0 +1,396 @@
/**
* Tests for the `~/.reasonix/memory/` store and its prefix-loading
* composer. All I/O goes through a temp `homeDir` so the suite never
* touches the developer's actual memory files.
*/
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { applyProjectMemory } from "../src/project-memory.js";
import {
MEMORY_INDEX_FILE,
MEMORY_INDEX_MAX_CHARS,
MemoryStore,
applyMemoryStack,
applyUserMemory,
projectHash,
sanitizeMemoryName,
} from "../src/user-memory.js";
const BASE = "You are a test assistant.";
describe("user-memory", () => {
let home: string;
let projectRoot: string;
const originalEnv = process.env.REASONIX_MEMORY;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-umem-home-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-umem-proj-"));
// biome-ignore lint/performance/noDelete: avoid leaking "undefined" into env
delete process.env.REASONIX_MEMORY;
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
if (originalEnv === undefined) {
// biome-ignore lint/performance/noDelete: same
delete process.env.REASONIX_MEMORY;
} else {
process.env.REASONIX_MEMORY = originalEnv;
}
});
describe("sanitizeMemoryName", () => {
it("accepts simple identifiers", () => {
expect(sanitizeMemoryName("foo_bar")).toBe("foo_bar");
expect(sanitizeMemoryName("abc-def.9")).toBe("abc-def.9");
expect(sanitizeMemoryName(" padded ")).toBe("padded");
});
it("rejects path-separator injection", () => {
expect(() => sanitizeMemoryName("../etc/passwd")).toThrow(/invalid memory name/);
expect(() => sanitizeMemoryName("foo/bar")).toThrow();
expect(() => sanitizeMemoryName("foo\\bar")).toThrow();
});
it("rejects leading dot / too-short / too-long names", () => {
expect(() => sanitizeMemoryName(".hidden")).toThrow();
expect(() => sanitizeMemoryName("ab")).toThrow();
expect(() => sanitizeMemoryName("a".repeat(41))).toThrow();
});
});
describe("projectHash", () => {
it("returns a stable 16-hex-char digest for the same path", () => {
const a = projectHash("/tmp/whatever");
const b = projectHash("/tmp/whatever");
expect(a).toBe(b);
expect(a).toMatch(/^[0-9a-f]{16}$/);
});
it("differs across paths", () => {
expect(projectHash("/tmp/a")).not.toBe(projectHash("/tmp/b"));
});
});
describe("MemoryStore basic I/O", () => {
it("writes a global memory and regenerates MEMORY.md", () => {
const store = new MemoryStore({ homeDir: home });
store.write({
name: "snake_case",
type: "feedback",
scope: "global",
description: "User prefers snake_case for new Python modules",
body: "Rule.\n\n**Why:** PEP 8.\n\n**How to apply:** new .py files default to snake_case.",
});
const file = join(home, "memory", "global", "snake_case.md");
expect(existsSync(file)).toBe(true);
const raw = readFileSync(file, "utf8");
expect(raw).toMatch(/^---\nname: snake_case\n/);
expect(raw).toContain("Rule.");
const indexPath = join(home, "memory", "global", MEMORY_INDEX_FILE);
expect(existsSync(indexPath)).toBe(true);
const index = readFileSync(indexPath, "utf8");
expect(index).toContain("[snake_case](snake_case.md)");
expect(index).toContain("User prefers snake_case");
});
it("round-trips write → read → list → delete for global scope", () => {
const store = new MemoryStore({ homeDir: home });
store.write({
name: "one",
type: "user",
scope: "global",
description: "First memory",
body: "content one",
});
store.write({
name: "two",
type: "reference",
scope: "global",
description: "Second memory",
body: "content two",
});
const listed = store.list();
expect(listed.map((e) => e.name).sort()).toEqual(["one", "two"]);
const one = store.read("global", "one");
expect(one.body).toBe("content one");
expect(one.type).toBe("user");
expect(one.description).toBe("First memory");
expect(one.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}$/);
const removed = store.delete("global", "one");
expect(removed).toBe(true);
expect(store.list().map((e) => e.name)).toEqual(["two"]);
// MEMORY.md should no longer reference "one".
const index = readFileSync(join(home, "memory", "global", MEMORY_INDEX_FILE), "utf8");
expect(index).not.toContain("one.md");
expect(index).toContain("two.md");
});
it("returns false when deleting a nonexistent memory", () => {
const store = new MemoryStore({ homeDir: home });
expect(store.delete("global", "ghost")).toBe(false);
});
it("removes MEMORY.md entirely when the last memory is deleted", () => {
const store = new MemoryStore({ homeDir: home });
store.write({
name: "only",
type: "project",
scope: "global",
description: "d",
body: "b",
});
store.delete("global", "only");
const indexPath = join(home, "memory", "global", MEMORY_INDEX_FILE);
expect(existsSync(indexPath)).toBe(false);
});
it("refuses project scope without a projectRoot", () => {
const store = new MemoryStore({ homeDir: home });
expect(store.hasProjectScope()).toBe(false);
expect(() =>
store.write({
name: "nope",
type: "project",
scope: "project",
description: "d",
body: "b",
}),
).toThrow(/projectRoot/);
});
it("routes project scope into the hashed subdir", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
expect(store.hasProjectScope()).toBe(true);
store.write({
name: "bun_build",
type: "project",
scope: "project",
description: "Build command is `bun run build` on this machine",
body: "Body here.",
});
const hashDir = join(home, "memory", projectHash(projectRoot));
const file = join(hashDir, "bun_build.md");
expect(existsSync(file)).toBe(true);
// Global scope dir should NOT contain the project file.
expect(existsSync(join(home, "memory", "global", "bun_build.md"))).toBe(false);
});
it("validates description / body non-empty", () => {
const store = new MemoryStore({ homeDir: home });
expect(() =>
store.write({ name: "x_y_z", type: "user", scope: "global", description: "", body: "b" }),
).toThrow(/description/);
expect(() =>
store.write({
name: "x_y_z",
type: "user",
scope: "global",
description: "d",
body: " \n",
}),
).toThrow(/body/);
});
it("loadIndex returns null for absent scope, content + flag for present", () => {
const store = new MemoryStore({ homeDir: home });
expect(store.loadIndex("global")).toBeNull();
store.write({
name: "x_y_z",
type: "user",
scope: "global",
description: "hi",
body: "b",
});
const idx = store.loadIndex("global");
expect(idx).not.toBeNull();
expect(idx?.truncated).toBe(false);
expect(idx?.content).toContain("x_y_z");
});
it("loadIndex truncates with a visible marker past the cap", () => {
const store = new MemoryStore({ homeDir: home });
// Write many entries so MEMORY.md crosses the cap.
for (let i = 0; i < 80; i++) {
store.write({
name: `entry_${String(i).padStart(3, "0")}`,
type: "user",
scope: "global",
description: "x".repeat(120),
body: "b",
});
}
const idx = store.loadIndex("global");
expect(idx?.truncated).toBe(true);
expect(idx?.content).toMatch(/truncated \d+ chars/);
expect(idx?.content.length).toBeLessThan(MEMORY_INDEX_MAX_CHARS + 64);
});
it("list() skips malformed frontmatter gracefully", () => {
const store = new MemoryStore({ homeDir: home });
const dir = store.dir("global");
writeFileSync(join(dir, "broken.md"), "no frontmatter here, just text\n", "utf8");
store.write({
name: "sane",
type: "user",
scope: "global",
description: "ok",
body: "b",
});
const entries = store.list();
expect(entries.map((e) => e.name).sort()).toContain("sane");
});
it("regenerated MEMORY.md is byte-stable for identical file sets (cache-prefix safety)", () => {
const storeA = new MemoryStore({ homeDir: home });
storeA.write({ name: "a_one", type: "user", scope: "global", description: "d1", body: "b1" });
storeA.write({ name: "b_two", type: "user", scope: "global", description: "d2", body: "b2" });
const first = readFileSync(join(home, "memory", "global", MEMORY_INDEX_FILE), "utf8");
// Delete + re-write in reverse order — sorted index should match.
storeA.delete("global", "a_one");
storeA.delete("global", "b_two");
storeA.write({ name: "b_two", type: "user", scope: "global", description: "d2", body: "b2" });
storeA.write({ name: "a_one", type: "user", scope: "global", description: "d1", body: "b1" });
const second = readFileSync(join(home, "memory", "global", MEMORY_INDEX_FILE), "utf8");
expect(second).toBe(first);
});
});
describe("applyUserMemory", () => {
it("is a no-op when both scopes are empty", () => {
expect(applyUserMemory(BASE, { homeDir: home, projectRoot })).toBe(BASE);
});
it("appends only the global block when no project memory exists", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "pref_one",
type: "user",
scope: "global",
description: "prefers tabs",
body: "b",
});
const out = applyUserMemory(BASE, { homeDir: home, projectRoot });
expect(out).toContain("# User memory — global");
expect(out).not.toContain("# User memory — this project");
expect(out).toContain("pref_one");
});
it("appends both blocks when both scopes populated", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "global_one",
type: "user",
scope: "global",
description: "g",
body: "b",
});
store.write({
name: "project_one",
type: "project",
scope: "project",
description: "p",
body: "b",
});
const out = applyUserMemory(BASE, { homeDir: home, projectRoot });
expect(out).toContain("# User memory — global");
expect(out).toContain("# User memory — this project");
expect(out).toContain("global_one");
expect(out).toContain("project_one");
// Global precedes project — stable ordering for cache hash.
expect(out.indexOf("global_one")).toBeLessThan(out.indexOf("project_one"));
});
it("is deterministic — identical state ⇒ identical output (cache-safe)", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "stable",
type: "user",
scope: "global",
description: "d",
body: "b",
});
const a = applyUserMemory(BASE, { homeDir: home, projectRoot });
const b = applyUserMemory(BASE, { homeDir: home, projectRoot });
expect(a).toBe(b);
});
it("respects REASONIX_MEMORY=off", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "pref_one",
type: "user",
scope: "global",
description: "d",
body: "b",
});
process.env.REASONIX_MEMORY = "off";
expect(applyUserMemory(BASE, { homeDir: home, projectRoot })).toBe(BASE);
});
it("skips the project block when no projectRoot is configured", () => {
const store = new MemoryStore({ homeDir: home });
store.write({
name: "global_only",
type: "user",
scope: "global",
description: "d",
body: "b",
});
const out = applyUserMemory(BASE, { homeDir: home });
expect(out).toContain("# User memory — global");
expect(out).not.toContain("# User memory — this project");
});
});
describe("applyMemoryStack", () => {
it("composes REASONIX.md → global memory → project memory", () => {
writeFileSync(join(projectRoot, "REASONIX.md"), "Pinned by REASONIX.md\n", "utf8");
// applyMemoryStack uses ~/.reasonix by default — redirect via HOME
// isn't portable across Windows; use the public applyUserMemory
// directly for the global/project part and compose manually to
// check ordering is what the helper produces.
const withProj = applyProjectMemory(BASE, projectRoot);
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "g_pref",
type: "user",
scope: "global",
description: "global pref",
body: "b",
});
store.write({
name: "p_fact",
type: "project",
scope: "project",
description: "project fact",
body: "b",
});
const out = applyUserMemory(withProj, { homeDir: home, projectRoot });
// Order: REASONIX.md content → global → project. Each unique
// string should appear, and in that order.
const iReasonix = out.indexOf("Pinned by REASONIX.md");
const iGlobal = out.indexOf("g_pref");
const iProject = out.indexOf("p_fact");
expect(iReasonix).toBeGreaterThan(BASE.length - 1);
expect(iGlobal).toBeGreaterThan(iReasonix);
expect(iProject).toBeGreaterThan(iGlobal);
});
it("applyMemoryStack injects no memory blocks when no memory is set", () => {
// No REASONIX.md, no HOME memory → no memory blocks. The bundled
// builtin skills (`explore`, `research`) still inject a Skills
// index, so we assert the absence of the memory-specific blocks
// rather than raw equality with BASE.
const out = applyMemoryStack(BASE, projectRoot);
expect(out).toContain(BASE);
expect(out).not.toMatch(/# Project memory/);
expect(out).not.toMatch(/# User memory/);
});
});
});
+193
View File
@@ -0,0 +1,193 @@
/**
* Tests for the version module — semver compare, npx detection, and
* the cached latest-version fetcher. Network is fully mocked: every
* `fetch` call goes through an injected stub so tests work offline
* and across CI providers without flake risk.
*/
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
LATEST_CACHE_TTL_MS,
VERSION,
compareVersions,
getLatestVersion,
isNpxInstall,
} from "../src/version.js";
describe("VERSION", () => {
it("matches the published package.json version", () => {
const pkgPath = join(process.cwd(), "package.json");
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
expect(VERSION).toBe(pkg.version);
});
});
describe("compareVersions", () => {
it("compares major/minor/patch numerically", () => {
expect(compareVersions("0.4.22", "0.4.22")).toBe(0);
expect(compareVersions("0.4.21", "0.4.22")).toBeLessThan(0);
expect(compareVersions("0.4.22", "0.4.21")).toBeGreaterThan(0);
expect(compareVersions("0.5.0", "0.4.99")).toBeGreaterThan(0);
expect(compareVersions("1.0.0", "0.99.99")).toBeGreaterThan(0);
});
it("treats pre-release suffix as lower than bare version", () => {
expect(compareVersions("0.4.22-rc.1", "0.4.22")).toBeLessThan(0);
expect(compareVersions("0.4.22", "0.4.22-rc.1")).toBeGreaterThan(0);
expect(compareVersions("0.4.22-alpha.1", "0.4.22-alpha.1")).toBe(0);
expect(compareVersions("0.4.22-alpha.1", "0.4.22-alpha.2")).toBeLessThan(0);
});
it("tolerates mismatched part counts", () => {
expect(compareVersions("1", "1.0.0")).toBe(0);
expect(compareVersions("1.2", "1.2.0")).toBe(0);
expect(compareVersions("1.2.0", "1.2.1")).toBeLessThan(0);
});
});
describe("isNpxInstall", () => {
const originalArgv1 = process.argv[1];
const originalUa = process.env.npm_config_user_agent;
afterEach(() => {
process.argv[1] = originalArgv1;
if (originalUa === undefined) {
// biome-ignore lint/performance/noDelete: restore missing env var exactly
delete process.env.npm_config_user_agent;
} else {
process.env.npm_config_user_agent = originalUa;
}
});
it("detects _npx path fragment", () => {
process.argv[1] = "/Users/x/.npm/_npx/abc123/node_modules/.bin/reasonix";
// biome-ignore lint/performance/noDelete: cover the no-env case
delete process.env.npm_config_user_agent;
expect(isNpxInstall()).toBe(true);
});
it("detects npx via user-agent string", () => {
process.argv[1] = "/usr/local/bin/reasonix";
process.env.npm_config_user_agent = "npx/10.2.4 npm/10.2.4 node/v20.10.0";
expect(isNpxInstall()).toBe(true);
});
it("returns false for plain global install", () => {
process.argv[1] = "/usr/local/lib/node_modules/reasonix/dist/cli/index.js";
// biome-ignore lint/performance/noDelete: cover the no-env case
delete process.env.npm_config_user_agent;
expect(isNpxInstall()).toBe(false);
});
});
describe("getLatestVersion", () => {
let home: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-version-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
});
function makeFetch(
body: unknown,
{ ok = true, status = 200 }: { ok?: boolean; status?: number } = {},
): typeof fetch {
return (async () =>
({
ok,
status,
json: async () => body,
}) as unknown as Response) as typeof fetch;
}
it("fetches from the registry and caches the result", async () => {
let calls = 0;
const fetchImpl = (async () => {
calls++;
return { ok: true, json: async () => ({ version: "0.9.9" }) } as unknown as Response;
}) as typeof fetch;
const v1 = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v1).toBe("0.9.9");
expect(calls).toBe(1);
// Within TTL, no second network call.
const v2 = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v2).toBe("0.9.9");
expect(calls).toBe(1);
// Cache file exists and parses.
const cacheFile = join(home, ".reasonix", "version-cache.json");
expect(existsSync(cacheFile)).toBe(true);
const parsed = JSON.parse(readFileSync(cacheFile, "utf8"));
expect(parsed.version).toBe("0.9.9");
expect(typeof parsed.checkedAt).toBe("number");
});
it("force:true bypasses the cache", async () => {
writeFileSync(join(home, ".reasonix-cache-preseed.json"), ""); // just ensures the tmp dir is real
// Preseed the cache directly.
const { mkdirSync } = await import("node:fs");
mkdirSync(join(home, ".reasonix"), { recursive: true });
writeFileSync(
join(home, ".reasonix", "version-cache.json"),
JSON.stringify({ version: "0.1.0", checkedAt: Date.now() }),
);
const fetchImpl = makeFetch({ version: "0.9.9" });
const v = await getLatestVersion({ homeDir: home, fetchImpl, force: true });
expect(v).toBe("0.9.9");
});
it("honors an expired cache entry as stale and refetches", async () => {
const { mkdirSync } = await import("node:fs");
mkdirSync(join(home, ".reasonix"), { recursive: true });
writeFileSync(
join(home, ".reasonix", "version-cache.json"),
JSON.stringify({
version: "0.1.0",
checkedAt: Date.now() - LATEST_CACHE_TTL_MS - 1000,
}),
);
const fetchImpl = makeFetch({ version: "0.9.9" });
const v = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v).toBe("0.9.9");
});
it("returns null when fetch throws (offline)", async () => {
const fetchImpl = (async () => {
throw new Error("ENOTFOUND");
}) as unknown as typeof fetch;
const v = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v).toBeNull();
});
it("returns null when the registry returns non-OK", async () => {
const fetchImpl = makeFetch({}, { ok: false, status: 500 });
const v = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v).toBeNull();
});
it("returns null when the body has no version string", async () => {
const fetchImpl = makeFetch({ notVersion: true });
const v = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v).toBeNull();
});
it("swallows cache write failures silently", async () => {
// Point homeDir at a file (not a directory) — mkdirSync will
// fail and writeCache should ignore the error. Returned version
// is still the freshly fetched one.
const fetchImpl = makeFetch({ version: "0.9.9" });
const busted = join(home, "not-a-dir");
writeFileSync(busted, "blocker");
const v = await getLatestVersion({ homeDir: busted, fetchImpl });
expect(v).toBe("0.9.9");
});
});