@alexwkleung/reika 0.6.0 → 0.7.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.
@@ -1,11 +1,14 @@
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
13
  import { PrefillRate, formatPrefillCost, reprocessedTokens, sampleTokens } from './prefillcost.js';
11
14
  import { DecodeRate, decodeSample, formatRate } from './decoderate.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
@@ -828,6 +831,20 @@ export function shouldWithdrawInspection(opts) {
828
831
  return false;
829
832
  return !opts.editRecovery;
830
833
  }
834
+ // Rounds a withdrawal is held after the loop goes quiet (#808). Refused reads are not recorded, so a
835
+ // complying model's loop leaves the recency window and the pause used to lift on the next round —
836
+ // and since coverage depth never resets on an unchanged file, its next read re-flagged it. One round
837
+ // without inspection, then the cycle again, each switch of the tool list a full re-prefill (~22 in
838
+ // one 163-round run). Held until the tree changes instead, capped so a model that has declared
839
+ // itself stuck gets reads back.
840
+ export const WITHDRAW_HOLD_ROUNDS = 5;
841
+ // Whether a withdrawal already in force stays on this round although the loop no longer reads as
842
+ // active. `since` is the round it began; `mutated` is whether the tree has changed since then.
843
+ export function holdWithdrawal(opts) {
844
+ if (opts.since === undefined || opts.mutated || opts.editRecovery)
845
+ return false;
846
+ return opts.round - opts.since < WITHDRAW_HOLD_ROUNDS;
847
+ }
831
848
  // Agent-mode counterpart to the plan ledger: a persistent, non-aging stop signal for a confirmed
832
849
  // loop — either a tight read repeat (ReadTrace.loopingReads, which names the files via `looping`) or
833
850
  // cross-round reasoning rumination (caller passes an empty `looping`, so the message names the symptom
@@ -991,6 +1008,7 @@ export async function runTurn(opts) {
991
1008
  opts.history.push(userMsg);
992
1009
  opts.onMessage(userMsg);
993
1010
  }
1011
+ await opts.beforeFirstRequest?.();
994
1012
  // The gates and minimal must match what buildRoundZeroPrefix passes, or the warm prefix
995
1013
  // diverges from round 0. A subagent is never warmed, so its report frame can't cause that drift.
996
1014
  const promptForMode = buildSystemPrompt({
@@ -1122,6 +1140,9 @@ export async function runTurn(opts) {
1122
1140
  // LOOP_WITHDRAW_AFTER the directive has demonstrably been ignored, so we escalate to withdrawing
1123
1141
  // the inspection tools. Resets the moment the loop clears, restoring normal exploration.
1124
1142
  let loopActiveRounds = 0;
1143
+ // The round the current withdrawal began, and whether the tree has changed since (#808).
1144
+ let withdrawnSince;
1145
+ let mutatedSinceWithdrawal = false;
1125
1146
  // Verbatim auto-abort bookkeeping: how many times this turn we've cut a degenerate reasoning stream
1126
1147
  // (bounded by MAX_VERBATIM_RECOVERIES so the cut→recover cycle can't loop), and a one-shot flag set
1127
1148
  // when a plan-mode cut should force the plan write on the next iteration. See VERBATIM_ABORT.
@@ -1131,6 +1152,11 @@ export async function runTurn(opts) {
1131
1152
  // so the next round's plan force-write can bias off it (the block itself is discarded). Empty unless a
1132
1153
  // verbatim abort just set forceVerbatimPlanWrite. See the plan force-write branch + logitrecovery.ts.
1133
1154
  let verbatimRepeatedSpan = [];
1155
+ // The tool list the last request of this turn actually sent. A round that forbids calls (the
1156
+ // compaction note, a subagent's report) sends it rather than this round's: the template renders
1157
+ // the list into the system turn, so a withdrawal starting or lifting on that round re-prefilled
1158
+ // the whole prompt (#816: ~27k tokens on a 32k run) for a list the model could not call from.
1159
+ let lastSentTools;
1134
1160
  // Whether the model has made any edit/write this turn. Tool withdrawal exists to force the
1135
1161
  // explore→act transition; once the model has acted, that job is done. After the first edit a
1136
1162
  // re-read is usually edit-recovery (re-fetching exact bytes to build old_string after the content
@@ -1285,6 +1311,23 @@ export async function runTurn(opts) {
1285
1311
  // else about the gate is unchanged: non-TS projects still fail open, and tsc never runs for a
1286
1312
  // project without a tsconfig even when the flag is on.
1287
1313
  const typecheckEnabled = opts.config.typecheck !== false;
1314
+ // A turn the harness ends itself (loop stop, edit-recovery stop, round cap) never reaches the
1315
+ // isFinal gate, and those are the turns likeliest to leave the tree broken (#830). Run the final
1316
+ // check there too and report it: the returned text rides the stop message, the notice the UI.
1317
+ const reportTypecheckAtStop = async () => {
1318
+ // The baseline is captured at the first call that MIGHT mutate (a test run counts), so a turn
1319
+ // that never edited could still reach here and print "no new type errors from your edits".
1320
+ if (!editingStarted)
1321
+ return '';
1322
+ if (!typecheckEnabled || typecheckBaseline === null || opts.signal?.aborted)
1323
+ return '';
1324
+ const report = stopTypecheckReport(typecheckBaseline, await typecheck());
1325
+ debugLog(`[reika:debug] typecheck-at-stop tone=${report.tone ?? 'skipped'}\n`);
1326
+ if (report.userNotice) {
1327
+ opts.onMessage({ role: 'system', tone: report.tone ?? 'info', content: report.userNotice });
1328
+ }
1329
+ return report.addendum ?? '';
1330
+ };
1288
1331
  // EXPERIMENT (plan→agent handoff): one-shot pre-pass before the round loop. Folds the plan-mode
1289
1332
  // exploration that produced the plan into a compact digest so the executing agent sees the plan
1290
1333
  // verbatim plus findings, not the full transcript. Operates on the per-turn opts.history copy
@@ -1511,10 +1554,24 @@ export async function runTurn(opts) {
1511
1554
  // Any confirmed loop that survives the ledger withdraws, regardless of type — UNLESS there's an
1512
1555
  // unresolved failed edit, where the model needs reading to recover and withdrawal would only
1513
1556
  // force more failing edits. See shouldWithdrawInspection.
1514
- withdrawInspection = shouldWithdrawInspection({
1557
+ const withdrawNow = shouldWithdrawInspection({
1515
1558
  loopActiveRounds,
1516
1559
  editRecovery: lastEditFailed,
1517
1560
  });
1561
+ const held = !withdrawNow &&
1562
+ holdWithdrawal({
1563
+ round: i,
1564
+ since: withdrawnSince,
1565
+ mutated: mutatedSinceWithdrawal,
1566
+ editRecovery: lastEditFailed,
1567
+ });
1568
+ withdrawInspection = withdrawNow || held;
1569
+ if (!withdrawInspection)
1570
+ withdrawnSince = undefined;
1571
+ else if (withdrawnSince === undefined) {
1572
+ withdrawnSince = i;
1573
+ mutatedSinceWithdrawal = false;
1574
+ }
1518
1575
  // Edit-recovery dead-end: a persistent reasoning loop on top of an unresolved failed edit is the
1519
1576
  // model retrying an edit it can't apply. It ignores the failure message (crossSim≈1.0) and
1520
1577
  // re-reading on its own never produces a matching old_string (observed: it oscillated
@@ -1553,7 +1610,8 @@ export async function runTurn(opts) {
1553
1610
  content: `I kept trying to edit ${file ? `\`${file}\`` : 'the file'} but the text I expected ` +
1554
1611
  `isn't in the file, so the change can't be applied as planned — the plan may reference ` +
1555
1612
  `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.`,
1613
+ `change belongs in that file, or point me at the right location.` +
1614
+ (await reportTypecheckAtStop()),
1557
1615
  durationMs: Date.now() - turnStart,
1558
1616
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
1559
1617
  };
@@ -1616,14 +1674,14 @@ export async function runTurn(opts) {
1616
1674
  }
1617
1675
  else {
1618
1676
  debugLog(`[reika:debug] round=${i} logit-recovery unavailable — stopping\n`);
1619
- commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted);
1677
+ commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted, await reportTypecheckAtStop());
1620
1678
  return;
1621
1679
  }
1622
1680
  }
1623
1681
  else {
1624
1682
  debugLog(`[reika:debug] round=${i} agent-loop-stop loopActiveRounds=${loopActiveRounds} ` +
1625
1683
  `edited=${editingStarted}\n`);
1626
- commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted);
1684
+ commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted, await reportTypecheckAtStop());
1627
1685
  return;
1628
1686
  }
1629
1687
  }
@@ -1651,7 +1709,7 @@ export async function runTurn(opts) {
1651
1709
  if (editRecoveryGrounding) {
1652
1710
  suffixParts.push(buildEditRecoveryLedger(editRecoveryGrounding));
1653
1711
  }
1654
- else if (loopDetected) {
1712
+ else if (loopDetected || withdrawInspection) {
1655
1713
  suffixParts.push(buildAgentLoopLedger(looping, withdrawInspection, toolNames));
1656
1714
  }
1657
1715
  // Last, so the strongest directive sits closest to generation. (Composed here rather than
@@ -1675,9 +1733,9 @@ export async function runTurn(opts) {
1675
1733
  else {
1676
1734
  system = baseSystem + suffix;
1677
1735
  }
1678
- if (loopDetected) {
1736
+ if (loopDetected || withdrawInspection) {
1679
1737
  debugLog(`[reika:debug] round=${i} loop-active reads=${looping.length} reasoning=${reasoningLoop} ` +
1680
- `loopActiveRounds=${loopActiveRounds} withdrawn=${withdrawInspection} ` +
1738
+ `loopActiveRounds=${loopActiveRounds} withdrawn=${withdrawInspection} held=${held} ` +
1681
1739
  `editRecovery=${lastEditFailed}\n`);
1682
1740
  }
1683
1741
  }
@@ -1844,18 +1902,30 @@ export async function runTurn(opts) {
1844
1902
  content: '/compact cancelled — nothing was folded.',
1845
1903
  });
1846
1904
  };
1905
+ const noteTools = lastSentTools ?? callTools;
1906
+ const noteLatches = latchesFor(opts.config);
1907
+ // Local engines only: a hosted API rejects a final assistant message or answers after it, and
1908
+ // the hosted models seen so far write the note when asked (#806).
1909
+ const prefill = notePrefillEnabled() && isLocalEngine(opts.config.baseURL) && !noteLatches.assistantPrefill
1910
+ ? compactionNotePrefill(n)
1911
+ : undefined;
1847
1912
  try {
1848
- const report = (suffix) => callModel({
1913
+ const send = (suffix, appended, assistantPrefill) => callModel({
1849
1914
  system: prefixStable ? baseSystem : directiveAsTail ? system : system + '\n\n' + suffix,
1850
- history: opts.history,
1915
+ history: appended.length ? [...opts.history, ...appended] : opts.history,
1851
1916
  // The same tools the round would send, with calls forbidden by `tool_choice` (#426).
1852
1917
  // Sending none rendered a different system turn: on the measured 24k runs the note
1853
1918
  // round re-prefilled the entire request (~7–11k tokens) immediately before the fold
1854
1919
  // re-prefilled it again — two full prefills per fold, one of them for nothing.
1855
- tools: callTools,
1920
+ tools: noteTools,
1856
1921
  toolChoice: 'none',
1922
+ assistantPrefill,
1857
1923
  config: withGenReserve(opts.config, genReserve),
1858
- onContentDelta: opts.onContentDelta,
1924
+ // Streamed through the reading the finished reply gets, or the thinking and call
1925
+ // after the note draw and then vanish (#819).
1926
+ onContentDelta: assistantPrefill && opts.onContentDelta
1927
+ ? prefilledNoteStream(assistantPrefill, opts.onContentDelta)
1928
+ : opts.onContentDelta,
1859
1929
  onReasoningDelta: opts.onReasoningDelta,
1860
1930
  signal: opts.signal,
1861
1931
  calibration,
@@ -1891,10 +1961,10 @@ export async function runTurn(opts) {
1891
1961
  ? msgs => {
1892
1962
  const d = prefixTrace.record(msgs, {
1893
1963
  trailingNote: directiveAsTail,
1894
- tools: toolsToChatTools(callTools),
1964
+ tools: toolsToChatTools(noteTools),
1895
1965
  });
1896
1966
  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));
1967
+ const tok = reprocessedTokens(d, Math.round(rawEstimate(opts.history, noteTools) * calibration));
1898
1968
  debugLog(`[reika:debug] prefix-cache round=${i} phase=report cause=${d.cause} ` +
1899
1969
  `stable=${d.stableChars}/${d.totalChars}c (${pct}%) ` +
1900
1970
  `msgs=${d.stableMessages}/${d.totalMessages}` +
@@ -1903,7 +1973,25 @@ export async function runTurn(opts) {
1903
1973
  }
1904
1974
  : undefined,
1905
1975
  });
1906
- let rep = await report(directive);
1976
+ // A failed prefilled request is asked again the plain way, and the prefill is latched off for
1977
+ // the endpoint only if that one succeeds: a 400 the plain request shares (an over-long
1978
+ // prompt) is not the prefill's, and latching on it would cost every later fold its note.
1979
+ const report = async (suffix, appended = []) => {
1980
+ if (!prefill || noteLatches.assistantPrefill)
1981
+ return send(suffix, appended);
1982
+ try {
1983
+ return prefilledReply(await send(suffix, appended, prefill), prefill);
1984
+ }
1985
+ catch (err) {
1986
+ if (opts.signal?.aborted)
1987
+ throw err;
1988
+ const plain = await send(suffix, appended);
1989
+ noteLatches.assistantPrefill = true;
1990
+ debugLog(`[reika:debug] round=${i} compaction-report prefill rejected, latched err=${String(err)}\n`);
1991
+ return plain;
1992
+ }
1993
+ };
1994
+ const rep = await report(directive);
1907
1995
  if (rep.usage)
1908
1996
  opts.onUsage?.(rep.usage);
1909
1997
  // callModel returns what streamed before a ctrl-c rather than throwing, so an aborted note
@@ -1915,25 +2003,22 @@ export async function runTurn(opts) {
1915
2003
  // Diagnosable from the log: an empty content channel with a recovered in-band call is the
1916
2004
  // model trying to read instead of writing; a `length` stop is the budget.
1917
2005
  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`);
2006
+ `reasoning=${r.reasoning?.trim().length ?? 0}c inband=${r.toolCalls?.length ?? 0}` +
2007
+ ('callsDropped' in r && r.callsDropped ? ` dropped=${r.callsDropped}` : '');
2008
+ let retry;
2009
+ if (!compactionNoteContent(rep) && !opts.signal?.aborted) {
2010
+ debugLog(`[reika:debug] round=${i} compaction-report n=${n} no-note ${describe(rep)}; retrying\n`);
1922
2011
  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);
2012
+ retry = await report(`${directive}\n\n${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
2013
+ if (retry.usage)
2014
+ opts.onUsage?.(retry.usage);
1927
2015
  if (opts.signal?.aborted) {
1928
2016
  commitNoteRoundAbort();
1929
2017
  return;
1930
2018
  }
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
2019
  }
1936
- const text = clampCompactionNote(rep.content?.trim() || rep.reasoning?.trim() || '');
2020
+ const picked = pickCompactionNote(rep, retry);
2021
+ const text = clampCompactionNote(picked.text);
1937
2022
  if (text) {
1938
2023
  note = { n, text };
1939
2024
  // UI only, never history: the note renders as markdown WITH its reasoning — the trace of
@@ -1942,13 +2027,13 @@ export async function runTurn(opts) {
1942
2027
  opts.onMessage({
1943
2028
  role: 'assistant',
1944
2029
  content: text,
1945
- reasoning: rep.reasoning?.trim() || undefined,
2030
+ reasoning: picked.reasoning,
1946
2031
  compactionNote: true,
1947
2032
  });
1948
2033
  }
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`);
2034
+ debugLog(`[reika:debug] round=${i} compaction-report n=${n} chars=${text.length} src=${picked.src}` +
2035
+ `${retry ? ' retried=1' : ''} prefill=${!prefill ? 'off' : noteLatches.assistantPrefill ? 'rejected' : 'on'}` +
2036
+ ` ${describe(retry ?? rep)}\n`);
1952
2037
  }
1953
2038
  catch (err) {
1954
2039
  if (opts.signal?.aborted) {
@@ -2063,7 +2148,9 @@ export async function runTurn(opts) {
2063
2148
  opts.onContextEstimate?.(Math.round(rawEstimate() * calibration));
2064
2149
  return;
2065
2150
  }
2066
- const sentEstimate = rawEstimate(callHistory, callTools);
2151
+ const sentTools = subagentForceReport && lastSentTools ? lastSentTools : callTools;
2152
+ lastSentTools = sentTools;
2153
+ const sentEstimate = rawEstimate(callHistory, sentTools);
2067
2154
  opts.onContextEstimate?.(Math.round(sentEstimate * calibration));
2068
2155
  // Live reasoning-spin hint (human-only): accumulate THIS round's reasoning and, debounced every
2069
2156
  // SPIN_DEBOUNCE chars, flag when it looks like it's spinning so the UI can prompt abort-or-wait.
@@ -2138,7 +2225,7 @@ export async function runTurn(opts) {
2138
2225
  const response = await callModel({
2139
2226
  system,
2140
2227
  history: callHistory,
2141
- tools: callTools,
2228
+ tools: sentTools,
2142
2229
  config: withGenReserve(opts.config, genReserve),
2143
2230
  onContentDelta: opts.onContentDelta,
2144
2231
  onReasoningDelta,
@@ -2200,7 +2287,7 @@ export async function runTurn(opts) {
2200
2287
  // churn — without it every append reads as `mid-history firstChanged=assistant` (#253).
2201
2288
  const d = prefixTrace.record(msgs, {
2202
2289
  trailingNote: !!roundSuffix,
2203
- tools: toolsToChatTools(callTools),
2290
+ tools: toolsToChatTools(sentTools),
2204
2291
  });
2205
2292
  const pct = d.totalChars > 0 ? Math.round((d.stableChars / d.totalChars) * 100) : 100;
2206
2293
  roundReprocessTokens = reprocessedTokens(d, Math.round(sentEstimate * calibration));
@@ -2236,6 +2323,23 @@ export async function runTurn(opts) {
2236
2323
  opts.onCalibration?.(calibration);
2237
2324
  }
2238
2325
  }
2326
+ // #827: the note-slot probe's live backstop. Compares this round's real count against what it
2327
+ // would be if the reasoning behind a user-role note had rendered, and moves the note to the
2328
+ // tool result from the next round when it clearly did not. loadConfig sessions only, like the
2329
+ // probe: a hand-built Config never latches an endpoint another test shares.
2330
+ if (opts.config.noteSlotProbe && prefixStable && response.usage?.promptTokens) {
2331
+ const check = observeNoteSlot({
2332
+ config: opts.config,
2333
+ promptTokens: response.usage.promptTokens,
2334
+ estimate: sentEstimate,
2335
+ noteSent: !!roundSuffix,
2336
+ reasoningChars: roundSuffix ? reasoningCharsBehindNote(callHistory) : 0,
2337
+ });
2338
+ if (check.kind === 'tested') {
2339
+ debugLog(`[reika:debug] round=${i} note-slot check hidden=${check.hidden} streak=${check.streak} ` +
2340
+ `switched=${check.switched}\n`);
2341
+ }
2342
+ }
2239
2343
  // Same idea one layer down: time-to-first-token is what those reprocessed tokens cost, so the
2240
2344
  // round that just paid teaches the rate the next round's line quotes. Only fires under
2241
2345
  // REIKA_DEBUG (roundReprocessTokens stays 0 otherwise), and rejects samples too small to
@@ -3083,17 +3187,28 @@ export async function runTurn(opts) {
3083
3187
  // Instrument re-reads (debug only): is this a fresh read, a redundant loop, or a rational
3084
3188
  // refetch of content that aged out? Recorded for every read regardless of REIKA_DEBUG (cheap,
3085
3189
  // and the live/aged label depends on round order), but only emitted under the flag.
3190
+ const shellRead = !refused && call.name === 'bash' && exitCode === 0
3191
+ ? await traceBashRead(String(call.args.command ?? ''), opts.bundle.cwd)
3192
+ : undefined;
3086
3193
  if (!refused && call.name === 'read' && contentHash) {
3087
3194
  // Read-first (#72): the model now holds this file's bytes (or knows its true length, for an
3088
3195
  // offset-past-end read). Grounding is applied after the tool message is pushed, since it
3089
3196
  // keys on that message's index — the bytes ground edits only while they are still being sent.
3090
3197
  groundsPath = String(call.args.path ?? '');
3091
- const { cls, repeats } = readTrace.record(String(call.args.path ?? ''), Number(call.args.offset ?? 1), contentHash, i,
3198
+ const { cls, repeats } = readTrace.record(traceReadPath(opts.bundle.cwd, String(call.args.path ?? '')), Number(call.args.offset ?? 1), contentHash, i,
3092
3199
  // Resolved exactly as the tool resolves it, so a default-window read followed by an
3093
3200
  // explicit narrower one is seen as narrowing rather than as a repeat (#184).
3094
3201
  Math.max(1, Number(call.args.limit ?? READ_DEFAULT_LIMIT)));
3095
3202
  debugLog(`[reika:debug] read-trace round=${i} class=${cls} repeats=${repeats} ${summary}\n`);
3096
3203
  }
3204
+ else if (shellRead) {
3205
+ // A one-file read through the shell deepens the same per-file count as `read` (#801), and
3206
+ // grounds the read-first gate like one (#825): its payload carries the file's bytes, and
3207
+ // ignoring it bounced 12 of 14 edits on lfm2.5 T2 runs, 10 of 11 that would have landed.
3208
+ groundsPath = shellRead.path;
3209
+ const { cls, repeats } = readTrace.record(shellRead.path, shellRead.offset, shellRead.hash, i, shellRead.limit, 'bash');
3210
+ debugLog(`[reika:debug] read-trace round=${i} class=${cls} repeats=${repeats} via=bash ${shellRead.path}\n`);
3211
+ }
3097
3212
  else if (debugEnabled() && !refused && call.name !== 'read') {
3098
3213
  // Non-read tool calls have no read-trace line, so a reasoning loop circling on grep/glob/list
3099
3214
  // (the observed case, where read-trace was silent but payloads kept growing) is otherwise
@@ -3120,8 +3235,10 @@ export async function runTurn(opts) {
3120
3235
  // edit/write-only — `lastEditFailed`, the read-first grounding, and applyPlanEdit all read
3121
3236
  // fields (old_string failures, args.path, a rendered diff) that a shell command has no
3122
3237
  // analogue for.
3123
- if (!bouncedBlindEdit && didMutate(call.name, changes))
3238
+ if (!bouncedBlindEdit && didMutate(call.name, changes)) {
3124
3239
  editingStarted = true;
3240
+ mutatedSinceWithdrawal = true;
3241
+ }
3125
3242
  if (!bouncedBlindEdit && MUTATING_TOOLS.has(call.name)) {
3126
3243
  // Track edit-recovery state: a failed edit (old_string not in the file, etc.) keeps the model
3127
3244
  // needing a re-read; a successful one clears it. Drives the withdrawal exemption + dead-end
@@ -3275,7 +3392,8 @@ export async function runTurn(opts) {
3275
3392
  }
3276
3393
  const exhausted = {
3277
3394
  role: 'assistant',
3278
- content: `(reached max turns of ${opts.config.maxTurns}; ask me to continue or raise the turn limit)`,
3395
+ content: `(reached max turns of ${opts.config.maxTurns}; ask me to continue or raise the turn limit)` +
3396
+ (await reportTypecheckAtStop()),
3279
3397
  durationMs: Date.now() - turnStart,
3280
3398
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
3281
3399
  };
@@ -3348,7 +3466,7 @@ reason = 'loop') {
3348
3466
  // bash). Ends the turn honestly rather than running to maxTurns. If the turn made edits, the work is
3349
3467
  // already on disk — frame it as "done but stopped re-checking" and name the edited files; otherwise
3350
3468
  // it's a stuck-without-progress stop. Mirrors commitSpiralStop (plan mode).
3351
- function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited) {
3469
+ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited, typecheckAddendum = '') {
3352
3470
  const files = new Set();
3353
3471
  for (const m of opts.history) {
3354
3472
  // A shell edit names its files in the tool message's git-backed `changes`, not in the call's
@@ -3372,7 +3490,8 @@ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited) {
3372
3490
  const content = edited
3373
3491
  ? `I made changes${fileList} but then kept repeating the same checks without making progress, so ` +
3374
3492
  `I've stopped to avoid looping. The edits are saved — review them and ask me to continue if ` +
3375
- `anything's off.`
3493
+ `anything's off.` +
3494
+ typecheckAddendum
3376
3495
  : `I kept repeating the same step without making progress, so I've stopped rather than loop. Let ` +
3377
3496
  `me know how you'd like to proceed.`;
3378
3497
  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
+ }
@@ -32,6 +32,7 @@ export class ReadTrace {
32
32
  unique: 0,
33
33
  changed: 0,
34
34
  narrowed: 0,
35
+ regrounded: 0,
35
36
  'dup-live': 0,
36
37
  'dup-aged': 0,
37
38
  };
@@ -39,16 +40,23 @@ export class ReadTrace {
39
40
  // is correct: the fresh block only spans the active turn's history, so liveness is a within-turn
40
41
  // notion. `hash` is the whole-file hash from the read result. Returns the class plus the running
41
42
  // repeat count for this region (1 = first/just-changed), so the caller can log and detect loops.
42
- record(path, offset, hash, round, limit) {
43
+ record(path, offset, hash, round, limit, via = 'read') {
43
44
  const key = `${path}\0${offset}`;
44
45
  const prior = this.seen.get(key);
46
+ const file = this.files.get(path);
45
47
  // An absent (or nonsensical) limit reads as unbounded, so it is never *narrower* than anything
46
48
  // and callers that don't track windows keep the pre-carve-out behaviour exactly.
47
49
  const window = typeof limit === 'number' && Number.isFinite(limit) && limit > 0 ? limit : Infinity;
48
50
  let cls;
49
51
  let repeats;
50
52
  let narrowings;
51
- if (!prior) {
53
+ if (via === 'read' && file?.hash === hash && file.lastVia === 'bash') {
54
+ // The read-first gate asked for these bytes again; the run stays where the shell read left it.
55
+ cls = 'regrounded';
56
+ repeats = prior?.hash === hash ? prior.repeats : 1;
57
+ narrowings = prior?.hash === hash ? prior.narrowings : 0;
58
+ }
59
+ else if (!prior) {
52
60
  cls = 'unique';
53
61
  repeats = 1;
54
62
  narrowings = 0;
@@ -89,7 +97,7 @@ export class ReadTrace {
89
97
  lastLive: cls === 'dup-live',
90
98
  });
91
99
  this.counts[cls]++;
92
- this.recordFile(path, offset, window, hash, round, cls);
100
+ this.recordFile(path, offset, window, hash, round, cls, via);
93
101
  return { cls, repeats };
94
102
  }
95
103
  // The per-file coverage depth (#341). A changed hash resets the file: the model edited it, so
@@ -99,15 +107,16 @@ export class ReadTrace {
99
107
  // `narrowed` read is recorded (later reads see its range) but never deepens: it is the sanctioned
100
108
  // descent into a capped page, already bounded per region by MAX_NARROWINGS, and the #184
101
109
  // transcript (300 → 70 → 35 → 18 at one offset) would otherwise be depth 4 by construction.
102
- recordFile(path, offset, window, hash, round, cls) {
110
+ recordFile(path, offset, window, hash, round, cls, via) {
103
111
  const lo = Math.max(1, offset);
104
112
  const hi = window === Infinity ? Infinity : lo + window - 1;
105
113
  let f = this.files.get(path);
106
114
  if (!f || f.hash !== hash) {
107
- f = { hash, ranges: [], depth: 0, lastRound: round };
115
+ f = { hash, ranges: [], depth: 0, lastRound: round, lastVia: via };
108
116
  this.files.set(path, f);
109
117
  }
110
- if (cls !== 'narrowed') {
118
+ f.lastVia = via;
119
+ if (cls !== 'narrowed' && cls !== 'regrounded') {
111
120
  const points = [lo, ...f.ranges.map(([a]) => a).filter(a => a >= lo && a <= hi)];
112
121
  let depth = 1;
113
122
  for (const p of points) {
@@ -159,7 +168,7 @@ export class ReadTrace {
159
168
  }
160
169
  total() {
161
170
  const c = this.counts;
162
- return c.unique + c.changed + c.narrowed + c['dup-live'] + c['dup-aged'];
171
+ return c.unique + c.changed + c.narrowed + c.regrounded + c['dup-live'] + c['dup-aged'];
163
172
  }
164
173
  summary() {
165
174
  const c = this.counts;
@@ -176,6 +185,7 @@ export class ReadTrace {
176
185
  if (f.depth >= FILE_OVERLAP_DEPTH)
177
186
  overlapped++;
178
187
  return (`unique=${c.unique} changed=${c.changed} dup-live=${c['dup-live']} dup-aged=${c['dup-aged']} ` +
179
- `narrowed=${c.narrowed} maxrepeat=${maxRepeat} looped=${looped} overlapped=${overlapped}`);
188
+ `narrowed=${c.narrowed} maxrepeat=${maxRepeat} looped=${looped} overlapped=${overlapped} ` +
189
+ `regrounded=${c.regrounded}`);
180
190
  }
181
191
  }
@@ -92,6 +92,35 @@ export function decideTypecheckGate(args) {
92
92
  userNotice: `Typecheck: ${n} type ${word} from this turn still unresolved after ${maxRounds} attempts — finishing anyway.`,
93
93
  };
94
94
  }
95
+ // How many introduced errors a stop message quotes. The full list is the next turn's gate's job;
96
+ // the stop only has to say the tree is broken and where to start.
97
+ const STOP_REPORT_SHOWN = 2;
98
+ // The gate's final check, reported rather than enforced, for a turn the harness ended itself (a
99
+ // loop stop, the round cap — #830). No send-back: a stop fires because the model stopped acting on
100
+ // directives, so a typecheck retry would land on the same loop. Empty when the check didn't run.
101
+ export function stopTypecheckReport(baseline, final) {
102
+ if (!final.ran)
103
+ return {};
104
+ const introduced = introducedDiagnostics(baseline, final.diagnostics);
105
+ const n = introduced.length;
106
+ if (n === 0) {
107
+ return { tone: 'info', userNotice: 'Typecheck passed — no new type errors from your edits.' };
108
+ }
109
+ const word = n === 1 ? 'error' : 'errors';
110
+ const shown = introduced
111
+ .slice(0, STOP_REPORT_SHOWN)
112
+ // tsc's own period dropped: the sentence closes the list, so it would print `….`.
113
+ .map(d => {
114
+ const msg = d.message.slice(0, MAX_MESSAGE_CHARS).replace(/\.$/, '');
115
+ return `\`${d.file}:${d.line} ${d.code}: ${msg}\``;
116
+ });
117
+ const more = n > shown.length ? `, +${n - shown.length} more` : '';
118
+ return {
119
+ addendum: ` The edits also introduced ${n} new type ${word}: ${shown.join(', ')}${more}.`,
120
+ tone: 'warn',
121
+ userNotice: `Typecheck: the edits introduced ${n} new type ${word}, left unfixed by the stop.`,
122
+ };
123
+ }
95
124
  // ── impure shell ──────────────────────────────────────────────────────────────────────────────
96
125
  // Resolve the tsconfig that governs an edit. Three layers, every one fail-open — any uncertainty
97
126
  // resolves to null, which disables the gate (the same no-op as a project with no tsconfig at all)