@alexwkleung/reika 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +15 -0
  2. package/README.zh-CN.md +15 -0
  3. package/dist/agent/bashread.js +177 -0
  4. package/dist/agent/compaction.js +5 -0
  5. package/dist/agent/compactionreport.js +184 -0
  6. package/dist/agent/loop.js +172 -45
  7. package/dist/agent/noteslotmonitor.js +82 -0
  8. package/dist/agent/prefillcost.js +16 -0
  9. package/dist/agent/prompt.js +5 -2
  10. package/dist/agent/readtrace.js +18 -8
  11. package/dist/check/typecheck.js +29 -0
  12. package/dist/cli.js +2 -2
  13. package/dist/config.js +30 -17
  14. package/dist/context/bootstrap.js +4 -2
  15. package/dist/debug.js +15 -0
  16. package/dist/{headless.js → headless/headless.js} +182 -48
  17. package/dist/{headlessargs.js → headless/headlessargs.js} +12 -2
  18. package/dist/headless/headlessprompt.js +132 -0
  19. package/dist/mcp/client.js +97 -5
  20. package/dist/mcp/manager.js +15 -2
  21. package/dist/provider/client.js +28 -0
  22. package/dist/provider/latches.js +3 -0
  23. package/dist/provider/noteslot.js +239 -0
  24. package/dist/provider/templatekwargs.js +31 -0
  25. package/dist/provider/toolcall.js +22 -1
  26. package/dist/provider/transport.js +12 -9
  27. package/dist/session.js +21 -1
  28. package/dist/{skills.js → skills/skills.js} +93 -13
  29. package/dist/store/sessions.js +39 -2
  30. package/dist/store/transcript.js +35 -0
  31. package/dist/tools/_carriers.js +119 -0
  32. package/dist/tools/_danger.js +539 -90
  33. package/dist/tools/_readonly.js +13 -12
  34. package/dist/ui/App.js +183 -70
  35. package/dist/ui/Approval.js +80 -33
  36. package/dist/ui/Confirm.js +1 -27
  37. package/dist/ui/DiffView.js +23 -12
  38. package/dist/ui/Question.js +152 -19
  39. package/dist/ui/ResumeSelect.js +3 -2
  40. package/dist/ui/Status.js +19 -7
  41. package/dist/ui/commands.js +47 -1
  42. package/dist/ui/dialogspecs.js +38 -0
  43. package/dist/ui/layout.js +118 -0
  44. package/package.json +1 -1
  45. /package/dist/{skillmatch.js → skills/skillmatch.js} +0 -0
@@ -1,13 +1,16 @@
1
1
  import { buildSystemPrompt } from './prompt.js';
2
2
  import { callModel } from '../provider/client.js';
3
3
  import { latchesFor } from '../provider/latches.js';
4
+ import { observeNoteSlot, reasoningCharsBehindNote } from './noteslotmonitor.js';
5
+ import { isLocalEngine } from '../provider/templatekwargs.js';
4
6
  import { estimateRequestTokens, estimateTokens } from '../provider/tokens.js';
5
7
  import { computeMaxTokens, NATIVE_IMAGE_TOKEN_ALLOWANCE, shouldRetryTruncated, } from '../provider/budget.js';
6
8
  import { compactHistory, shouldCompact, compactThreshold, gatherPlanFindings, distillPlanHandoff, batchAgePayloads, AGE_LOW_FRACTION, } from './compaction.js';
7
9
  import { droppedPayloadCount, findFreshToolBlockStart, hasDroppedPayloads, lastUserMessageIndex, taskSpecIndex, toolsToChatTools, } from '../provider/toolcall.js';
8
10
  import { ReadTrace } from './readtrace.js';
11
+ import { traceBashRead, traceReadPath } from './bashread.js';
9
12
  import { PrefixTrace } from './prefixtrace.js';
10
- import { PrefillRate, formatPrefillCost, reprocessedTokens, sampleTokens } from './prefillcost.js';
13
+ import { PrefillRate, formatMeasuredPrefill, formatPrefillCost, reprocessedTokens, sampleTokens, } from './prefillcost.js';
11
14
  import { DecodeRate, decodeSample, formatRate } from './decoderate.js';
12
15
  import { GenReserve, resolveGenReserve, withGenReserve } from './genreserve.js';
13
16
  import { selfRepeatRatio, repeatedSelfShingles, ReasoningTrace, liveSpinSignal, verbatimAbortThreshold, } from './reasoningtrace.js';
@@ -27,12 +30,12 @@ import { recordFollowed, spillStatsEnabled } from '../tools/_spillstats.js';
27
30
  import { seedPlanProgress, parsePlanSteps, planChanged, refineTarget, applyEdit as applyPlanEdit, applyCommand as applyPlanCommand, buildPlanProgressLedger, decidePlanGate, waiveUnchecked, ranSuccessfully, MAX_PLAN_GATE_ROUNDS, } from './plantrack.js';
28
31
  import { ReadFirstGate, buildReadFirstDirective, probeWouldLand } from './readfirst.js';
29
32
  import { SUBAGENT_REPORT_DIRECTIVE, SUBAGENT_REPORT_FRAME, SUBAGENT_HOLD_NOTE, MAX_SUBAGENTS_PER_TURN, MAX_SUBAGENTS_PER_ROUND, buildCoverageNote, } from './subagentreport.js';
30
- import { COMPACTION_REPORT_RETRY, buildCompactionReportDirective, clampCompactionNote, compactionReportEnabled, } from './compactionreport.js';
33
+ import { COMPACTION_REPORT_RETRY, compactionNotePrefill, notePrefillEnabled, prefilledNoteStream, prefilledReply, refusedCallTurn, buildCompactionReportDirective, clampCompactionNote, compactionNoteContent, compactionReportEnabled, pickCompactionNote, } from './compactionreport.js';
31
34
  import { buildSubagentAffordance, filesInResult, subagentPressureEnabled, underPressure, } from './subagentpressure.js';
32
35
  import { foldAfterShed, wouldFold } from './compaction.js';
33
36
  import { ceilingPressure, planFill, planPressureFor, planPressureLine, planRoundCeiling, } from './planpressure.js';
34
37
  import { debugEnabled, debugLog } from '../debug.js';
35
- import { decideTypecheckGate, detectTsProject, runTypecheck, } from '../check/typecheck.js';
38
+ import { decideTypecheckGate, detectTsProject, runTypecheck, stopTypecheckReport, } from '../check/typecheck.js';
36
39
  // Navigation/inspection tools whose repeats we watch for loops. Re-issuing one and getting
37
40
  // the same result is a no-progress loop. `bash` is included because weak models run `grep`/
38
41
  // `ls` through it; its summary carries the output byte count, so a repeat only fires on
@@ -375,6 +378,13 @@ const DROPPED_LEDGER = process.env.REIKA_DROPPED_LEDGER !== '0';
375
378
  // runs as-is), suspended while inspection tools are withdrawn (the directed read would be refused).
376
379
  // The `would-land=` field on the bounce debug line is the measurement. See agent/readfirst.ts.
377
380
  const READ_FIRST = process.env.REIKA_READ_FIRST !== '0';
381
+ // EXPERIMENT (#867): keep the offered tool list unchanged while inspection is withdrawn, enforcing
382
+ // the pause at dispatch and through the ledger only. The template renders the tools ahead of the
383
+ // system prompt, so dropping them makes the withdrawal round and the lift round each a full
384
+ // re-prefill (`cause=tools-changed`). On by default since 2026-10-29 (`=0` is the baseline arm): on
385
+ // T2 with lfm2.5 it cut engine prefill per round by a third and refused calls per pause went down,
386
+ // not up — a model that still sees read/grep did not keep reaching for them.
387
+ const WITHDRAW_KEEP_TOOLS = process.env.REIKA_WITHDRAW_KEEP_TOOLS !== '0';
378
388
  // EXPERIMENT (plan mode): the force-write turn is a *transformation*, not another exploration
379
389
  // round. Asking the exploring model to "stop and write prose" fights its action prior and lets
380
390
  // the plan it already has decay across turns; but the plan is reliably in its reasoning. So at
@@ -828,6 +838,20 @@ export function shouldWithdrawInspection(opts) {
828
838
  return false;
829
839
  return !opts.editRecovery;
830
840
  }
841
+ // Rounds a withdrawal is held after the loop goes quiet (#808). Refused reads are not recorded, so a
842
+ // complying model's loop leaves the recency window and the pause used to lift on the next round —
843
+ // and since coverage depth never resets on an unchanged file, its next read re-flagged it. One round
844
+ // without inspection, then the cycle again, each switch of the tool list a full re-prefill (~22 in
845
+ // one 163-round run). Held until the tree changes instead, capped so a model that has declared
846
+ // itself stuck gets reads back.
847
+ export const WITHDRAW_HOLD_ROUNDS = 5;
848
+ // Whether a withdrawal already in force stays on this round although the loop no longer reads as
849
+ // active. `since` is the round it began; `mutated` is whether the tree has changed since then.
850
+ export function holdWithdrawal(opts) {
851
+ if (opts.since === undefined || opts.mutated || opts.editRecovery)
852
+ return false;
853
+ return opts.round - opts.since < WITHDRAW_HOLD_ROUNDS;
854
+ }
831
855
  // Agent-mode counterpart to the plan ledger: a persistent, non-aging stop signal for a confirmed
832
856
  // loop — either a tight read repeat (ReadTrace.loopingReads, which names the files via `looping`) or
833
857
  // cross-round reasoning rumination (caller passes an empty `looping`, so the message names the symptom
@@ -991,6 +1015,7 @@ export async function runTurn(opts) {
991
1015
  opts.history.push(userMsg);
992
1016
  opts.onMessage(userMsg);
993
1017
  }
1018
+ await opts.beforeFirstRequest?.();
994
1019
  // The gates and minimal must match what buildRoundZeroPrefix passes, or the warm prefix
995
1020
  // diverges from round 0. A subagent is never warmed, so its report frame can't cause that drift.
996
1021
  const promptForMode = buildSystemPrompt({
@@ -1122,6 +1147,9 @@ export async function runTurn(opts) {
1122
1147
  // LOOP_WITHDRAW_AFTER the directive has demonstrably been ignored, so we escalate to withdrawing
1123
1148
  // the inspection tools. Resets the moment the loop clears, restoring normal exploration.
1124
1149
  let loopActiveRounds = 0;
1150
+ // The round the current withdrawal began, and whether the tree has changed since (#808).
1151
+ let withdrawnSince;
1152
+ let mutatedSinceWithdrawal = false;
1125
1153
  // Verbatim auto-abort bookkeeping: how many times this turn we've cut a degenerate reasoning stream
1126
1154
  // (bounded by MAX_VERBATIM_RECOVERIES so the cut→recover cycle can't loop), and a one-shot flag set
1127
1155
  // when a plan-mode cut should force the plan write on the next iteration. See VERBATIM_ABORT.
@@ -1131,6 +1159,11 @@ export async function runTurn(opts) {
1131
1159
  // so the next round's plan force-write can bias off it (the block itself is discarded). Empty unless a
1132
1160
  // verbatim abort just set forceVerbatimPlanWrite. See the plan force-write branch + logitrecovery.ts.
1133
1161
  let verbatimRepeatedSpan = [];
1162
+ // The tool list the last request of this turn actually sent. A round that forbids calls (the
1163
+ // compaction note, a subagent's report) sends it rather than this round's: the template renders
1164
+ // the list into the system turn, so a withdrawal starting or lifting on that round re-prefilled
1165
+ // the whole prompt (#816: ~27k tokens on a 32k run) for a list the model could not call from.
1166
+ let lastSentTools;
1134
1167
  // Whether the model has made any edit/write this turn. Tool withdrawal exists to force the
1135
1168
  // explore→act transition; once the model has acted, that job is done. After the first edit a
1136
1169
  // re-read is usually edit-recovery (re-fetching exact bytes to build old_string after the content
@@ -1285,6 +1318,23 @@ export async function runTurn(opts) {
1285
1318
  // else about the gate is unchanged: non-TS projects still fail open, and tsc never runs for a
1286
1319
  // project without a tsconfig even when the flag is on.
1287
1320
  const typecheckEnabled = opts.config.typecheck !== false;
1321
+ // A turn the harness ends itself (loop stop, edit-recovery stop, round cap) never reaches the
1322
+ // isFinal gate, and those are the turns likeliest to leave the tree broken (#830). Run the final
1323
+ // check there too and report it: the returned text rides the stop message, the notice the UI.
1324
+ const reportTypecheckAtStop = async () => {
1325
+ // The baseline is captured at the first call that MIGHT mutate (a test run counts), so a turn
1326
+ // that never edited could still reach here and print "no new type errors from your edits".
1327
+ if (!editingStarted)
1328
+ return '';
1329
+ if (!typecheckEnabled || typecheckBaseline === null || opts.signal?.aborted)
1330
+ return '';
1331
+ const report = stopTypecheckReport(typecheckBaseline, await typecheck());
1332
+ debugLog(`[reika:debug] typecheck-at-stop tone=${report.tone ?? 'skipped'}\n`);
1333
+ if (report.userNotice) {
1334
+ opts.onMessage({ role: 'system', tone: report.tone ?? 'info', content: report.userNotice });
1335
+ }
1336
+ return report.addendum ?? '';
1337
+ };
1288
1338
  // EXPERIMENT (plan→agent handoff): one-shot pre-pass before the round loop. Folds the plan-mode
1289
1339
  // exploration that produced the plan into a compact digest so the executing agent sees the plan
1290
1340
  // verbatim plus findings, not the full transcript. Operates on the per-turn opts.history copy
@@ -1511,10 +1561,24 @@ export async function runTurn(opts) {
1511
1561
  // Any confirmed loop that survives the ledger withdraws, regardless of type — UNLESS there's an
1512
1562
  // unresolved failed edit, where the model needs reading to recover and withdrawal would only
1513
1563
  // force more failing edits. See shouldWithdrawInspection.
1514
- withdrawInspection = shouldWithdrawInspection({
1564
+ const withdrawNow = shouldWithdrawInspection({
1515
1565
  loopActiveRounds,
1516
1566
  editRecovery: lastEditFailed,
1517
1567
  });
1568
+ const held = !withdrawNow &&
1569
+ holdWithdrawal({
1570
+ round: i,
1571
+ since: withdrawnSince,
1572
+ mutated: mutatedSinceWithdrawal,
1573
+ editRecovery: lastEditFailed,
1574
+ });
1575
+ withdrawInspection = withdrawNow || held;
1576
+ if (!withdrawInspection)
1577
+ withdrawnSince = undefined;
1578
+ else if (withdrawnSince === undefined) {
1579
+ withdrawnSince = i;
1580
+ mutatedSinceWithdrawal = false;
1581
+ }
1518
1582
  // Edit-recovery dead-end: a persistent reasoning loop on top of an unresolved failed edit is the
1519
1583
  // model retrying an edit it can't apply. It ignores the failure message (crossSim≈1.0) and
1520
1584
  // re-reading on its own never produces a matching old_string (observed: it oscillated
@@ -1553,7 +1617,8 @@ export async function runTurn(opts) {
1553
1617
  content: `I kept trying to edit ${file ? `\`${file}\`` : 'the file'} but the text I expected ` +
1554
1618
  `isn't in the file, so the change can't be applied as planned — the plan may reference ` +
1555
1619
  `code that doesn't exist there. I've stopped instead of looping. Please confirm the ` +
1556
- `change belongs in that file, or point me at the right location.`,
1620
+ `change belongs in that file, or point me at the right location.` +
1621
+ (await reportTypecheckAtStop()),
1557
1622
  durationMs: Date.now() - turnStart,
1558
1623
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
1559
1624
  };
@@ -1616,14 +1681,14 @@ export async function runTurn(opts) {
1616
1681
  }
1617
1682
  else {
1618
1683
  debugLog(`[reika:debug] round=${i} logit-recovery unavailable — stopping\n`);
1619
- commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted);
1684
+ commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted, await reportTypecheckAtStop());
1620
1685
  return;
1621
1686
  }
1622
1687
  }
1623
1688
  else {
1624
1689
  debugLog(`[reika:debug] round=${i} agent-loop-stop loopActiveRounds=${loopActiveRounds} ` +
1625
1690
  `edited=${editingStarted}\n`);
1626
- commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted);
1691
+ commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted, await reportTypecheckAtStop());
1627
1692
  return;
1628
1693
  }
1629
1694
  }
@@ -1651,7 +1716,7 @@ export async function runTurn(opts) {
1651
1716
  if (editRecoveryGrounding) {
1652
1717
  suffixParts.push(buildEditRecoveryLedger(editRecoveryGrounding));
1653
1718
  }
1654
- else if (loopDetected) {
1719
+ else if (loopDetected || withdrawInspection) {
1655
1720
  suffixParts.push(buildAgentLoopLedger(looping, withdrawInspection, toolNames));
1656
1721
  }
1657
1722
  // Last, so the strongest directive sits closest to generation. (Composed here rather than
@@ -1675,21 +1740,21 @@ export async function runTurn(opts) {
1675
1740
  else {
1676
1741
  system = baseSystem + suffix;
1677
1742
  }
1678
- if (loopDetected) {
1743
+ if (loopDetected || withdrawInspection) {
1679
1744
  debugLog(`[reika:debug] round=${i} loop-active reads=${looping.length} reasoning=${reasoningLoop} ` +
1680
- `loopActiveRounds=${loopActiveRounds} withdrawn=${withdrawInspection} ` +
1745
+ `loopActiveRounds=${loopActiveRounds} withdrawn=${withdrawInspection} held=${held} ` +
1681
1746
  `editRecovery=${lastEditFailed}\n`);
1682
1747
  }
1683
1748
  }
1684
1749
  // Empty tool lists are already a supported path (chat mode with no search provider). On a loop
1685
- // break, drop the inspection tools so the offered set steers a tool-list-respecting model
1686
- // straight to edit/write; the dispatch layer enforces it for one that emits reads in-band.
1750
+ // break the dispatch layer refuses inspection calls; with REIKA_WITHDRAW_KEEP_TOOLS=0 the
1751
+ // inspection tools are also dropped from the offered set (the pre-#867 behaviour).
1687
1752
  // The subagent's report round keeps the list and forbids calls with `tool_choice` instead
1688
1753
  // (#426): the template renders the tool list into the system turn, so withholding it would
1689
1754
  // re-prefill the subagent's whole context on its last round.
1690
1755
  const callTools = planForceWrite
1691
1756
  ? []
1692
- : withdrawInspection
1757
+ : withdrawInspection && !WITHDRAW_KEEP_TOOLS
1693
1758
  ? opts.tools.filter(t => !INSPECTION_TOOLS.has(t.name))
1694
1759
  : opts.tools;
1695
1760
  const planTransformBudget = window ? planTransformBudgetChars(window) : Number.MAX_SAFE_INTEGER;
@@ -1844,18 +1909,30 @@ export async function runTurn(opts) {
1844
1909
  content: '/compact cancelled — nothing was folded.',
1845
1910
  });
1846
1911
  };
1912
+ const noteTools = lastSentTools ?? callTools;
1913
+ const noteLatches = latchesFor(opts.config);
1914
+ // Local engines only: a hosted API rejects a final assistant message or answers after it, and
1915
+ // the hosted models seen so far write the note when asked (#806).
1916
+ const prefill = notePrefillEnabled() && isLocalEngine(opts.config.baseURL) && !noteLatches.assistantPrefill
1917
+ ? compactionNotePrefill(n)
1918
+ : undefined;
1847
1919
  try {
1848
- const report = (suffix) => callModel({
1920
+ const send = (suffix, appended, assistantPrefill) => callModel({
1849
1921
  system: prefixStable ? baseSystem : directiveAsTail ? system : system + '\n\n' + suffix,
1850
- history: opts.history,
1922
+ history: appended.length ? [...opts.history, ...appended] : opts.history,
1851
1923
  // The same tools the round would send, with calls forbidden by `tool_choice` (#426).
1852
1924
  // Sending none rendered a different system turn: on the measured 24k runs the note
1853
1925
  // round re-prefilled the entire request (~7–11k tokens) immediately before the fold
1854
1926
  // re-prefilled it again — two full prefills per fold, one of them for nothing.
1855
- tools: callTools,
1927
+ tools: noteTools,
1856
1928
  toolChoice: 'none',
1929
+ assistantPrefill,
1857
1930
  config: withGenReserve(opts.config, genReserve),
1858
- onContentDelta: opts.onContentDelta,
1931
+ // Streamed through the reading the finished reply gets, or the thinking and call
1932
+ // after the note draw and then vanish (#819).
1933
+ onContentDelta: assistantPrefill && opts.onContentDelta
1934
+ ? prefilledNoteStream(assistantPrefill, opts.onContentDelta)
1935
+ : opts.onContentDelta,
1859
1936
  onReasoningDelta: opts.onReasoningDelta,
1860
1937
  signal: opts.signal,
1861
1938
  calibration,
@@ -1891,10 +1968,10 @@ export async function runTurn(opts) {
1891
1968
  ? msgs => {
1892
1969
  const d = prefixTrace.record(msgs, {
1893
1970
  trailingNote: directiveAsTail,
1894
- tools: toolsToChatTools(callTools),
1971
+ tools: toolsToChatTools(noteTools),
1895
1972
  });
1896
1973
  const pct = d.totalChars > 0 ? Math.round((d.stableChars / d.totalChars) * 100) : 100;
1897
- const tok = reprocessedTokens(d, Math.round(rawEstimate(opts.history, callTools) * calibration));
1974
+ const tok = reprocessedTokens(d, Math.round(rawEstimate(opts.history, noteTools) * calibration));
1898
1975
  debugLog(`[reika:debug] prefix-cache round=${i} phase=report cause=${d.cause} ` +
1899
1976
  `stable=${d.stableChars}/${d.totalChars}c (${pct}%) ` +
1900
1977
  `msgs=${d.stableMessages}/${d.totalMessages}` +
@@ -1903,7 +1980,25 @@ export async function runTurn(opts) {
1903
1980
  }
1904
1981
  : undefined,
1905
1982
  });
1906
- let rep = await report(directive);
1983
+ // A failed prefilled request is asked again the plain way, and the prefill is latched off for
1984
+ // the endpoint only if that one succeeds: a 400 the plain request shares (an over-long
1985
+ // prompt) is not the prefill's, and latching on it would cost every later fold its note.
1986
+ const report = async (suffix, appended = []) => {
1987
+ if (!prefill || noteLatches.assistantPrefill)
1988
+ return send(suffix, appended);
1989
+ try {
1990
+ return prefilledReply(await send(suffix, appended, prefill), prefill);
1991
+ }
1992
+ catch (err) {
1993
+ if (opts.signal?.aborted)
1994
+ throw err;
1995
+ const plain = await send(suffix, appended);
1996
+ noteLatches.assistantPrefill = true;
1997
+ debugLog(`[reika:debug] round=${i} compaction-report prefill rejected, latched err=${String(err)}\n`);
1998
+ return plain;
1999
+ }
2000
+ };
2001
+ const rep = await report(directive);
1907
2002
  if (rep.usage)
1908
2003
  opts.onUsage?.(rep.usage);
1909
2004
  // callModel returns what streamed before a ctrl-c rather than throwing, so an aborted note
@@ -1915,25 +2010,22 @@ export async function runTurn(opts) {
1915
2010
  // Diagnosable from the log: an empty content channel with a recovered in-band call is the
1916
2011
  // model trying to read instead of writing; a `length` stop is the budget.
1917
2012
  const describe = (r) => `finish=${r.finishReason ?? '?'} content=${r.content?.trim().length ?? 0}c ` +
1918
- `reasoning=${r.reasoning?.trim().length ?? 0}c inband=${r.toolCalls?.length ?? 0}`;
1919
- let retried = false;
1920
- if (!rep.content?.trim() && !opts.signal?.aborted) {
1921
- debugLog(`[reika:debug] round=${i} compaction-report n=${n} empty ${describe(rep)}; retrying\n`);
2013
+ `reasoning=${r.reasoning?.trim().length ?? 0}c inband=${r.toolCalls?.length ?? 0}` +
2014
+ ('callsDropped' in r && r.callsDropped ? ` dropped=${r.callsDropped}` : '');
2015
+ let retry;
2016
+ if (!compactionNoteContent(rep) && !opts.signal?.aborted) {
2017
+ debugLog(`[reika:debug] round=${i} compaction-report n=${n} no-note ${describe(rep)}; retrying\n`);
1922
2018
  opts.onReasoningReset?.();
1923
- retried = true;
1924
- const again = await report(`${directive}\n\n${COMPACTION_REPORT_RETRY}`);
1925
- if (again.usage)
1926
- opts.onUsage?.(again.usage);
2019
+ retry = await report(`${directive}\n\n${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
2020
+ if (retry.usage)
2021
+ opts.onUsage?.(retry.usage);
1927
2022
  if (opts.signal?.aborted) {
1928
2023
  commitNoteRoundAbort();
1929
2024
  return;
1930
2025
  }
1931
- // Keep whichever reply has a note in the content channel; failing both, the first
1932
- // reasoning is the better fallback (it is the longer, less nagged thinking).
1933
- if (again.content?.trim())
1934
- rep = again;
1935
2026
  }
1936
- const text = clampCompactionNote(rep.content?.trim() || rep.reasoning?.trim() || '');
2027
+ const picked = pickCompactionNote(rep, retry);
2028
+ const text = clampCompactionNote(picked.text);
1937
2029
  if (text) {
1938
2030
  note = { n, text };
1939
2031
  // UI only, never history: the note renders as markdown WITH its reasoning — the trace of
@@ -1942,13 +2034,13 @@ export async function runTurn(opts) {
1942
2034
  opts.onMessage({
1943
2035
  role: 'assistant',
1944
2036
  content: text,
1945
- reasoning: rep.reasoning?.trim() || undefined,
2037
+ reasoning: picked.reasoning,
1946
2038
  compactionNote: true,
1947
2039
  });
1948
2040
  }
1949
- debugLog(`[reika:debug] round=${i} compaction-report n=${n} chars=${text.length}` +
1950
- `${rep.content?.trim() ? '' : rep.reasoning?.trim() ? ' src=reasoning' : ' src=empty'}` +
1951
- `${retried ? ' retried=1' : ''} ${describe(rep)}\n`);
2041
+ debugLog(`[reika:debug] round=${i} compaction-report n=${n} chars=${text.length} src=${picked.src}` +
2042
+ `${retry ? ' retried=1' : ''} prefill=${!prefill ? 'off' : noteLatches.assistantPrefill ? 'rejected' : 'on'}` +
2043
+ ` ${describe(retry ?? rep)}\n`);
1952
2044
  }
1953
2045
  catch (err) {
1954
2046
  if (opts.signal?.aborted) {
@@ -2063,7 +2155,9 @@ export async function runTurn(opts) {
2063
2155
  opts.onContextEstimate?.(Math.round(rawEstimate() * calibration));
2064
2156
  return;
2065
2157
  }
2066
- const sentEstimate = rawEstimate(callHistory, callTools);
2158
+ const sentTools = subagentForceReport && lastSentTools ? lastSentTools : callTools;
2159
+ lastSentTools = sentTools;
2160
+ const sentEstimate = rawEstimate(callHistory, sentTools);
2067
2161
  opts.onContextEstimate?.(Math.round(sentEstimate * calibration));
2068
2162
  // Live reasoning-spin hint (human-only): accumulate THIS round's reasoning and, debounced every
2069
2163
  // SPIN_DEBOUNCE chars, flag when it looks like it's spinning so the UI can prompt abort-or-wait.
@@ -2138,7 +2232,7 @@ export async function runTurn(opts) {
2138
2232
  const response = await callModel({
2139
2233
  system,
2140
2234
  history: callHistory,
2141
- tools: callTools,
2235
+ tools: sentTools,
2142
2236
  config: withGenReserve(opts.config, genReserve),
2143
2237
  onContentDelta: opts.onContentDelta,
2144
2238
  onReasoningDelta,
@@ -2200,7 +2294,7 @@ export async function runTurn(opts) {
2200
2294
  // churn — without it every append reads as `mid-history firstChanged=assistant` (#253).
2201
2295
  const d = prefixTrace.record(msgs, {
2202
2296
  trailingNote: !!roundSuffix,
2203
- tools: toolsToChatTools(callTools),
2297
+ tools: toolsToChatTools(sentTools),
2204
2298
  });
2205
2299
  const pct = d.totalChars > 0 ? Math.round((d.stableChars / d.totalChars) * 100) : 100;
2206
2300
  roundReprocessTokens = reprocessedTokens(d, Math.round(sentEstimate * calibration));
@@ -2236,6 +2330,23 @@ export async function runTurn(opts) {
2236
2330
  opts.onCalibration?.(calibration);
2237
2331
  }
2238
2332
  }
2333
+ // #827: the note-slot probe's live backstop. Compares this round's real count against what it
2334
+ // would be if the reasoning behind a user-role note had rendered, and moves the note to the
2335
+ // tool result from the next round when it clearly did not. loadConfig sessions only, like the
2336
+ // probe: a hand-built Config never latches an endpoint another test shares.
2337
+ if (opts.config.noteSlotProbe && prefixStable && response.usage?.promptTokens) {
2338
+ const check = observeNoteSlot({
2339
+ config: opts.config,
2340
+ promptTokens: response.usage.promptTokens,
2341
+ estimate: sentEstimate,
2342
+ noteSent: !!roundSuffix,
2343
+ reasoningChars: roundSuffix ? reasoningCharsBehindNote(callHistory) : 0,
2344
+ });
2345
+ if (check.kind === 'tested') {
2346
+ debugLog(`[reika:debug] round=${i} note-slot check hidden=${check.hidden} streak=${check.streak} ` +
2347
+ `switched=${check.switched}\n`);
2348
+ }
2349
+ }
2239
2350
  // Same idea one layer down: time-to-first-token is what those reprocessed tokens cost, so the
2240
2351
  // round that just paid teaches the rate the next round's line quotes. Only fires under
2241
2352
  // REIKA_DEBUG (roundReprocessTokens stays 0 otherwise), and rejects samples too small to
@@ -2277,6 +2388,7 @@ export async function runTurn(opts) {
2277
2388
  `completion=${completion} finishReason=${response.finishReason ?? '?'} ` +
2278
2389
  `decode=${formatRate(sample?.rate)} smoothed=${formatRate(decodeThroughput.get())} ` +
2279
2390
  `src=${sample?.source ?? '?'} reserve=${reserve.tokens} reserveSrc=${reserve.source} ` +
2391
+ `${formatMeasuredPrefill(response.usage, response.enginePrompt, roundReprocessTokens)} ` +
2280
2392
  // Process uptime, not turn time: on a fanless machine the rates sag with sustained load
2281
2393
  // and recover across idle gaps, so separating that from context growth needs wall clock.
2282
2394
  `t=${process.uptime().toFixed(0)}s\n`);
@@ -3083,17 +3195,28 @@ export async function runTurn(opts) {
3083
3195
  // Instrument re-reads (debug only): is this a fresh read, a redundant loop, or a rational
3084
3196
  // refetch of content that aged out? Recorded for every read regardless of REIKA_DEBUG (cheap,
3085
3197
  // and the live/aged label depends on round order), but only emitted under the flag.
3198
+ const shellRead = !refused && call.name === 'bash' && exitCode === 0
3199
+ ? await traceBashRead(String(call.args.command ?? ''), opts.bundle.cwd)
3200
+ : undefined;
3086
3201
  if (!refused && call.name === 'read' && contentHash) {
3087
3202
  // Read-first (#72): the model now holds this file's bytes (or knows its true length, for an
3088
3203
  // offset-past-end read). Grounding is applied after the tool message is pushed, since it
3089
3204
  // keys on that message's index — the bytes ground edits only while they are still being sent.
3090
3205
  groundsPath = String(call.args.path ?? '');
3091
- const { cls, repeats } = readTrace.record(String(call.args.path ?? ''), Number(call.args.offset ?? 1), contentHash, i,
3206
+ const { cls, repeats } = readTrace.record(traceReadPath(opts.bundle.cwd, String(call.args.path ?? '')), Number(call.args.offset ?? 1), contentHash, i,
3092
3207
  // Resolved exactly as the tool resolves it, so a default-window read followed by an
3093
3208
  // explicit narrower one is seen as narrowing rather than as a repeat (#184).
3094
3209
  Math.max(1, Number(call.args.limit ?? READ_DEFAULT_LIMIT)));
3095
3210
  debugLog(`[reika:debug] read-trace round=${i} class=${cls} repeats=${repeats} ${summary}\n`);
3096
3211
  }
3212
+ else if (shellRead) {
3213
+ // A one-file read through the shell deepens the same per-file count as `read` (#801), and
3214
+ // grounds the read-first gate like one (#825): its payload carries the file's bytes, and
3215
+ // ignoring it bounced 12 of 14 edits on lfm2.5 T2 runs, 10 of 11 that would have landed.
3216
+ groundsPath = shellRead.path;
3217
+ const { cls, repeats } = readTrace.record(shellRead.path, shellRead.offset, shellRead.hash, i, shellRead.limit, 'bash');
3218
+ debugLog(`[reika:debug] read-trace round=${i} class=${cls} repeats=${repeats} via=bash ${shellRead.path}\n`);
3219
+ }
3097
3220
  else if (debugEnabled() && !refused && call.name !== 'read') {
3098
3221
  // Non-read tool calls have no read-trace line, so a reasoning loop circling on grep/glob/list
3099
3222
  // (the observed case, where read-trace was silent but payloads kept growing) is otherwise
@@ -3120,8 +3243,10 @@ export async function runTurn(opts) {
3120
3243
  // edit/write-only — `lastEditFailed`, the read-first grounding, and applyPlanEdit all read
3121
3244
  // fields (old_string failures, args.path, a rendered diff) that a shell command has no
3122
3245
  // analogue for.
3123
- if (!bouncedBlindEdit && didMutate(call.name, changes))
3246
+ if (!bouncedBlindEdit && didMutate(call.name, changes)) {
3124
3247
  editingStarted = true;
3248
+ mutatedSinceWithdrawal = true;
3249
+ }
3125
3250
  if (!bouncedBlindEdit && MUTATING_TOOLS.has(call.name)) {
3126
3251
  // Track edit-recovery state: a failed edit (old_string not in the file, etc.) keeps the model
3127
3252
  // needing a re-read; a successful one clears it. Drives the withdrawal exemption + dead-end
@@ -3275,7 +3400,8 @@ export async function runTurn(opts) {
3275
3400
  }
3276
3401
  const exhausted = {
3277
3402
  role: 'assistant',
3278
- content: `(reached max turns of ${opts.config.maxTurns}; ask me to continue or raise the turn limit)`,
3403
+ content: `(reached max turns of ${opts.config.maxTurns}; ask me to continue or raise the turn limit)` +
3404
+ (await reportTypecheckAtStop()),
3279
3405
  durationMs: Date.now() - turnStart,
3280
3406
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
3281
3407
  };
@@ -3348,7 +3474,7 @@ reason = 'loop') {
3348
3474
  // bash). Ends the turn honestly rather than running to maxTurns. If the turn made edits, the work is
3349
3475
  // already on disk — frame it as "done but stopped re-checking" and name the edited files; otherwise
3350
3476
  // it's a stuck-without-progress stop. Mirrors commitSpiralStop (plan mode).
3351
- function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited) {
3477
+ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited, typecheckAddendum = '') {
3352
3478
  const files = new Set();
3353
3479
  for (const m of opts.history) {
3354
3480
  // A shell edit names its files in the tool message's git-backed `changes`, not in the call's
@@ -3372,7 +3498,8 @@ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited) {
3372
3498
  const content = edited
3373
3499
  ? `I made changes${fileList} but then kept repeating the same checks without making progress, so ` +
3374
3500
  `I've stopped to avoid looping. The edits are saved — review them and ask me to continue if ` +
3375
- `anything's off.`
3501
+ `anything's off.` +
3502
+ typecheckAddendum
3376
3503
  : `I kept repeating the same step without making progress, so I've stopped rather than loop. Let ` +
3377
3504
  `me know how you'd like to proceed.`;
3378
3505
  const m = {
@@ -0,0 +1,82 @@
1
+ import { latchesFor } from '../provider/latches.js';
2
+ import { noteRidesToolResult } from '../provider/toolcall.js';
3
+ // The live backstop for the note-slot probe (#827). The probe can be wrong or silent: an engine
4
+ // that reports no usage, a real history its synthetic one doesn't match. So every round that sent a
5
+ // user-role note tests the engine's prompt-token count against the two things it could be: the
6
+ // estimate at the session's baseline density (the reasoning behind the note rendered) or that
7
+ // minus the reasoning (it was dropped). The baseline comes from rounds with no note, where nothing
8
+ // hides anything. Conservative on purpose, because content density also shifts after a shed
9
+ // (aged payloads become prose summaries; working setups measured about 10% lower): a round counts
10
+ // as hidden only when at least three quarters of the reasoning is missing and the reasoning is a
11
+ // quarter of the request, and two such rounds in a row switch the slot. One-way, like the probe.
12
+ const BASELINE_SAMPLES = 8;
13
+ const MIN_BASELINE = 2;
14
+ const MIN_REASONING_SHARE = 0.25;
15
+ const MISSING_SHARE = 0.75;
16
+ const HIDDEN_ROUNDS_TO_SWITCH = 2;
17
+ const states = new Map();
18
+ function stateFor(config) {
19
+ const key = `${config.baseURL.replace(/\/+$/, '')}\n${config.model}`;
20
+ let state = states.get(key);
21
+ if (!state) {
22
+ state = { baseline: [], hiddenStreak: 0 };
23
+ states.set(key, state);
24
+ }
25
+ return state;
26
+ }
27
+ function median(xs) {
28
+ const sorted = [...xs].sort((a, b) => a - b);
29
+ const mid = Math.floor(sorted.length / 2);
30
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
31
+ }
32
+ // Characters of reasoning a request carries behind its trailing note: the assistant messages after
33
+ // the newest user-role message, which a template that hides reasoning drops once a note follows
34
+ // them. Reasoning batch aging already dropped is not sent at all.
35
+ export function reasoningCharsBehindNote(history) {
36
+ let chars = 0;
37
+ for (let i = history.length - 1; i >= 0; i--) {
38
+ const m = history[i];
39
+ if (m.role === 'user')
40
+ break;
41
+ if (m.role === 'assistant' && m.reasoning && !m.reasoningAged)
42
+ chars += m.reasoning.length;
43
+ }
44
+ return chars;
45
+ }
46
+ export function observeNoteSlot(obs) {
47
+ const latches = latchesFor(obs.config);
48
+ if (noteRidesToolResult(latches))
49
+ return { kind: 'skipped', reason: 'tool-slot' };
50
+ if (process.env.REIKA_NOTE_SLOT === 'user')
51
+ return { kind: 'skipped', reason: 'forced' };
52
+ if (obs.estimate <= 0 || obs.promptTokens <= 0)
53
+ return { kind: 'skipped', reason: 'no-count' };
54
+ const state = stateFor(obs.config);
55
+ const factor = obs.promptTokens / obs.estimate;
56
+ if (!obs.noteSent) {
57
+ state.baseline.push(factor);
58
+ if (state.baseline.length > BASELINE_SAMPLES)
59
+ state.baseline.shift();
60
+ return { kind: 'baseline', factor };
61
+ }
62
+ if (state.baseline.length < MIN_BASELINE)
63
+ return { kind: 'skipped', reason: 'no-baseline' };
64
+ const reasoningTokens = obs.reasoningChars / 4;
65
+ if (reasoningTokens < obs.estimate * MIN_REASONING_SHARE) {
66
+ return { kind: 'skipped', reason: 'little-reasoning' };
67
+ }
68
+ const base = median(state.baseline);
69
+ const missing = base * obs.estimate - obs.promptTokens;
70
+ const hidden = missing >= base * reasoningTokens * MISSING_SHARE;
71
+ state.hiddenStreak = hidden ? state.hiddenStreak + 1 : 0;
72
+ const switched = state.hiddenStreak >= HIDDEN_ROUNDS_TO_SWITCH;
73
+ // Session-only: unlike the probe's exact counts, this rests on thresholds drawn from one model's
74
+ // runs, so a wrong switch is kept to the session that made it rather than written to the cache.
75
+ if (switched)
76
+ latches.noteOnToolResult = true;
77
+ return { kind: 'tested', hidden, streak: state.hiddenStreak, switched };
78
+ }
79
+ // Tests only.
80
+ export function resetNoteSlotMonitor() {
81
+ states.clear();
82
+ }
@@ -77,3 +77,19 @@ export function formatPrefillCost(tokens, rate, bounded = false) {
77
77
  function formatSeconds(s) {
78
78
  return s >= 10 ? `${Math.round(s)}s` : `${s.toFixed(1)}s`;
79
79
  }
80
+ // The `round=` line's measured half (#868): what the provider and the engine reported about this
81
+ // request's prefill, beside the estimate the `prefix-cache` line printed before the call. `cached=?`
82
+ // rather than `0` when the provider reports no cache accounting — zero would claim a cold cache. The
83
+ // engine fields appear only when llama.cpp sent them, and `prompt_n` carries the estimate it should
84
+ // be read against (`reprocessEst=`), since that line was written before the count existed.
85
+ export function formatMeasuredPrefill(usage, engine, reprocessEstimate) {
86
+ const parts = [`cached=${usage?.cachedTokens ?? '?'}`];
87
+ if (engine?.promptN != null) {
88
+ parts.push(`prompt_n=${engine.promptN}`, `reprocessEst=${reprocessEstimate}`);
89
+ }
90
+ if (engine?.promptMs != null)
91
+ parts.push(`prompt_ms=${Math.round(engine.promptMs)}`);
92
+ if (engine?.cacheN != null)
93
+ parts.push(`cache_n=${engine.cacheN}`);
94
+ return parts.join(' ');
95
+ }
@@ -325,7 +325,9 @@ function buildAgentPrompt(opts) {
325
325
  // "only if asked" because on a small model a named path is an attractor for unrelated exploration.
326
326
  // Deliberately omitted: `~/.config/reika/.env` (API keys — naming it invites a `cat` that lands
327
327
  // them in context and the saved transcript), the chrome profile, and the binary (`reika -p` from
328
- // bash is a nested agent outside the subagent cap).
328
+ // bash is a nested agent outside the subagent cap). Both history paths are spelled out in full: named
329
+ // as `history/` alone, a model listed the root's /save files and never found projects/, where most
330
+ // sessions are.
329
331
  // `REIKA_SELF_AWARE=0` is the baseline arm: the prompt without the line, byte-for-byte.
330
332
  function selfLineParts() {
331
333
  return process.env.REIKA_SELF_AWARE === '0' ? [] : [reikaSelfLine()];
@@ -334,7 +336,8 @@ export function reikaSelfLine(docsDir = DOCS_DIR) {
334
336
  const where = [
335
337
  ...(docsDir ? [`its reference docs are in ${docsDir}`] : []),
336
338
  'user skills in ~/.config/reika/skills/ (project skills in .reika/skills/)',
337
- 'saved sessions in ~/.config/reika/history/',
339
+ 'auto-saved sessions in ~/.config/reika/history/projects/ (one subdirectory per project)',
340
+ '/save transcripts in ~/.config/reika/history/',
338
341
  ];
339
342
  return `You are running inside reika ${VERSION}. Only if the user asks about reika itself: ${where.join(', ')}.`;
340
343
  }