@alexwkleung/reika 0.5.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';
@@ -15,6 +18,7 @@ import { ContinuationGate, continuationGate, continuationTail } from './continua
15
18
  import { biasableShingles, buildRuminationLogitBias } from './logitrecovery.js';
16
19
  import { EntropyTrace, formatEntropyReading } from './entropytrace.js';
17
20
  import { extractPlanReferences, verifyPlanReferences, buildGroundingNote, shouldSuppressGrounding, } from './groundcheck.js';
21
+ import { withDeclineFeedback } from '../approval.js';
18
22
  import { collectSourcedUrls } from '../tools/_exfil.js';
19
23
  import { groundUrlsForPlan } from '../tools/_urls.js';
20
24
  import { referencesSpill } from '../tools/_spill.js';
@@ -26,12 +30,12 @@ import { recordFollowed, spillStatsEnabled } from '../tools/_spillstats.js';
26
30
  import { seedPlanProgress, parsePlanSteps, planChanged, refineTarget, applyEdit as applyPlanEdit, applyCommand as applyPlanCommand, buildPlanProgressLedger, decidePlanGate, waiveUnchecked, ranSuccessfully, MAX_PLAN_GATE_ROUNDS, } from './plantrack.js';
27
31
  import { ReadFirstGate, buildReadFirstDirective, probeWouldLand } from './readfirst.js';
28
32
  import { SUBAGENT_REPORT_DIRECTIVE, SUBAGENT_REPORT_FRAME, SUBAGENT_HOLD_NOTE, MAX_SUBAGENTS_PER_TURN, MAX_SUBAGENTS_PER_ROUND, buildCoverageNote, } from './subagentreport.js';
29
- 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';
30
34
  import { buildSubagentAffordance, filesInResult, subagentPressureEnabled, underPressure, } from './subagentpressure.js';
31
35
  import { foldAfterShed, wouldFold } from './compaction.js';
32
36
  import { ceilingPressure, planFill, planPressureFor, planPressureLine, planRoundCeiling, } from './planpressure.js';
33
37
  import { debugEnabled, debugLog } from '../debug.js';
34
- import { decideTypecheckGate, detectTsProject, runTypecheck, } from '../check/typecheck.js';
38
+ import { decideTypecheckGate, detectTsProject, runTypecheck, stopTypecheckReport, } from '../check/typecheck.js';
35
39
  // Navigation/inspection tools whose repeats we watch for loops. Re-issuing one and getting
36
40
  // the same result is a no-progress loop. `bash` is included because weak models run `grep`/
37
41
  // `ls` through it; its summary carries the output byte count, so a repeat only fires on
@@ -827,6 +831,20 @@ export function shouldWithdrawInspection(opts) {
827
831
  return false;
828
832
  return !opts.editRecovery;
829
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
+ }
830
848
  // Agent-mode counterpart to the plan ledger: a persistent, non-aging stop signal for a confirmed
831
849
  // loop — either a tight read repeat (ReadTrace.loopingReads, which names the files via `looping`) or
832
850
  // cross-round reasoning rumination (caller passes an empty `looping`, so the message names the symptom
@@ -990,6 +1008,7 @@ export async function runTurn(opts) {
990
1008
  opts.history.push(userMsg);
991
1009
  opts.onMessage(userMsg);
992
1010
  }
1011
+ await opts.beforeFirstRequest?.();
993
1012
  // The gates and minimal must match what buildRoundZeroPrefix passes, or the warm prefix
994
1013
  // diverges from round 0. A subagent is never warmed, so its report frame can't cause that drift.
995
1014
  const promptForMode = buildSystemPrompt({
@@ -1121,6 +1140,9 @@ export async function runTurn(opts) {
1121
1140
  // LOOP_WITHDRAW_AFTER the directive has demonstrably been ignored, so we escalate to withdrawing
1122
1141
  // the inspection tools. Resets the moment the loop clears, restoring normal exploration.
1123
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;
1124
1146
  // Verbatim auto-abort bookkeeping: how many times this turn we've cut a degenerate reasoning stream
1125
1147
  // (bounded by MAX_VERBATIM_RECOVERIES so the cut→recover cycle can't loop), and a one-shot flag set
1126
1148
  // when a plan-mode cut should force the plan write on the next iteration. See VERBATIM_ABORT.
@@ -1130,6 +1152,11 @@ export async function runTurn(opts) {
1130
1152
  // so the next round's plan force-write can bias off it (the block itself is discarded). Empty unless a
1131
1153
  // verbatim abort just set forceVerbatimPlanWrite. See the plan force-write branch + logitrecovery.ts.
1132
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;
1133
1160
  // Whether the model has made any edit/write this turn. Tool withdrawal exists to force the
1134
1161
  // explore→act transition; once the model has acted, that job is done. After the first edit a
1135
1162
  // re-read is usually edit-recovery (re-fetching exact bytes to build old_string after the content
@@ -1284,6 +1311,23 @@ export async function runTurn(opts) {
1284
1311
  // else about the gate is unchanged: non-TS projects still fail open, and tsc never runs for a
1285
1312
  // project without a tsconfig even when the flag is on.
1286
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
+ };
1287
1331
  // EXPERIMENT (plan→agent handoff): one-shot pre-pass before the round loop. Folds the plan-mode
1288
1332
  // exploration that produced the plan into a compact digest so the executing agent sees the plan
1289
1333
  // verbatim plus findings, not the full transcript. Operates on the per-turn opts.history copy
@@ -1510,10 +1554,24 @@ export async function runTurn(opts) {
1510
1554
  // Any confirmed loop that survives the ledger withdraws, regardless of type — UNLESS there's an
1511
1555
  // unresolved failed edit, where the model needs reading to recover and withdrawal would only
1512
1556
  // force more failing edits. See shouldWithdrawInspection.
1513
- withdrawInspection = shouldWithdrawInspection({
1557
+ const withdrawNow = shouldWithdrawInspection({
1514
1558
  loopActiveRounds,
1515
1559
  editRecovery: lastEditFailed,
1516
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
+ }
1517
1575
  // Edit-recovery dead-end: a persistent reasoning loop on top of an unresolved failed edit is the
1518
1576
  // model retrying an edit it can't apply. It ignores the failure message (crossSim≈1.0) and
1519
1577
  // re-reading on its own never produces a matching old_string (observed: it oscillated
@@ -1552,7 +1610,8 @@ export async function runTurn(opts) {
1552
1610
  content: `I kept trying to edit ${file ? `\`${file}\`` : 'the file'} but the text I expected ` +
1553
1611
  `isn't in the file, so the change can't be applied as planned — the plan may reference ` +
1554
1612
  `code that doesn't exist there. I've stopped instead of looping. Please confirm the ` +
1555
- `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()),
1556
1615
  durationMs: Date.now() - turnStart,
1557
1616
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
1558
1617
  };
@@ -1615,14 +1674,14 @@ export async function runTurn(opts) {
1615
1674
  }
1616
1675
  else {
1617
1676
  debugLog(`[reika:debug] round=${i} logit-recovery unavailable — stopping\n`);
1618
- commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted);
1677
+ commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted, await reportTypecheckAtStop());
1619
1678
  return;
1620
1679
  }
1621
1680
  }
1622
1681
  else {
1623
1682
  debugLog(`[reika:debug] round=${i} agent-loop-stop loopActiveRounds=${loopActiveRounds} ` +
1624
1683
  `edited=${editingStarted}\n`);
1625
- commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted);
1684
+ commitAgentLoopStop(opts, turnStart, fetchedUrls, editingStarted, await reportTypecheckAtStop());
1626
1685
  return;
1627
1686
  }
1628
1687
  }
@@ -1650,7 +1709,7 @@ export async function runTurn(opts) {
1650
1709
  if (editRecoveryGrounding) {
1651
1710
  suffixParts.push(buildEditRecoveryLedger(editRecoveryGrounding));
1652
1711
  }
1653
- else if (loopDetected) {
1712
+ else if (loopDetected || withdrawInspection) {
1654
1713
  suffixParts.push(buildAgentLoopLedger(looping, withdrawInspection, toolNames));
1655
1714
  }
1656
1715
  // Last, so the strongest directive sits closest to generation. (Composed here rather than
@@ -1674,9 +1733,9 @@ export async function runTurn(opts) {
1674
1733
  else {
1675
1734
  system = baseSystem + suffix;
1676
1735
  }
1677
- if (loopDetected) {
1736
+ if (loopDetected || withdrawInspection) {
1678
1737
  debugLog(`[reika:debug] round=${i} loop-active reads=${looping.length} reasoning=${reasoningLoop} ` +
1679
- `loopActiveRounds=${loopActiveRounds} withdrawn=${withdrawInspection} ` +
1738
+ `loopActiveRounds=${loopActiveRounds} withdrawn=${withdrawInspection} held=${held} ` +
1680
1739
  `editRecovery=${lastEditFailed}\n`);
1681
1740
  }
1682
1741
  }
@@ -1843,18 +1902,30 @@ export async function runTurn(opts) {
1843
1902
  content: '/compact cancelled — nothing was folded.',
1844
1903
  });
1845
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;
1846
1912
  try {
1847
- const report = (suffix) => callModel({
1913
+ const send = (suffix, appended, assistantPrefill) => callModel({
1848
1914
  system: prefixStable ? baseSystem : directiveAsTail ? system : system + '\n\n' + suffix,
1849
- history: opts.history,
1915
+ history: appended.length ? [...opts.history, ...appended] : opts.history,
1850
1916
  // The same tools the round would send, with calls forbidden by `tool_choice` (#426).
1851
1917
  // Sending none rendered a different system turn: on the measured 24k runs the note
1852
1918
  // round re-prefilled the entire request (~7–11k tokens) immediately before the fold
1853
1919
  // re-prefilled it again — two full prefills per fold, one of them for nothing.
1854
- tools: callTools,
1920
+ tools: noteTools,
1855
1921
  toolChoice: 'none',
1922
+ assistantPrefill,
1856
1923
  config: withGenReserve(opts.config, genReserve),
1857
- 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,
1858
1929
  onReasoningDelta: opts.onReasoningDelta,
1859
1930
  signal: opts.signal,
1860
1931
  calibration,
@@ -1890,10 +1961,10 @@ export async function runTurn(opts) {
1890
1961
  ? msgs => {
1891
1962
  const d = prefixTrace.record(msgs, {
1892
1963
  trailingNote: directiveAsTail,
1893
- tools: toolsToChatTools(callTools),
1964
+ tools: toolsToChatTools(noteTools),
1894
1965
  });
1895
1966
  const pct = d.totalChars > 0 ? Math.round((d.stableChars / d.totalChars) * 100) : 100;
1896
- const tok = reprocessedTokens(d, Math.round(rawEstimate(opts.history, callTools) * calibration));
1967
+ const tok = reprocessedTokens(d, Math.round(rawEstimate(opts.history, noteTools) * calibration));
1897
1968
  debugLog(`[reika:debug] prefix-cache round=${i} phase=report cause=${d.cause} ` +
1898
1969
  `stable=${d.stableChars}/${d.totalChars}c (${pct}%) ` +
1899
1970
  `msgs=${d.stableMessages}/${d.totalMessages}` +
@@ -1902,7 +1973,25 @@ export async function runTurn(opts) {
1902
1973
  }
1903
1974
  : undefined,
1904
1975
  });
1905
- 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);
1906
1995
  if (rep.usage)
1907
1996
  opts.onUsage?.(rep.usage);
1908
1997
  // callModel returns what streamed before a ctrl-c rather than throwing, so an aborted note
@@ -1914,25 +2003,22 @@ export async function runTurn(opts) {
1914
2003
  // Diagnosable from the log: an empty content channel with a recovered in-band call is the
1915
2004
  // model trying to read instead of writing; a `length` stop is the budget.
1916
2005
  const describe = (r) => `finish=${r.finishReason ?? '?'} content=${r.content?.trim().length ?? 0}c ` +
1917
- `reasoning=${r.reasoning?.trim().length ?? 0}c inband=${r.toolCalls?.length ?? 0}`;
1918
- let retried = false;
1919
- if (!rep.content?.trim() && !opts.signal?.aborted) {
1920
- 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`);
1921
2011
  opts.onReasoningReset?.();
1922
- retried = true;
1923
- const again = await report(`${directive}\n\n${COMPACTION_REPORT_RETRY}`);
1924
- if (again.usage)
1925
- 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);
1926
2015
  if (opts.signal?.aborted) {
1927
2016
  commitNoteRoundAbort();
1928
2017
  return;
1929
2018
  }
1930
- // Keep whichever reply has a note in the content channel; failing both, the first
1931
- // reasoning is the better fallback (it is the longer, less nagged thinking).
1932
- if (again.content?.trim())
1933
- rep = again;
1934
2019
  }
1935
- const text = clampCompactionNote(rep.content?.trim() || rep.reasoning?.trim() || '');
2020
+ const picked = pickCompactionNote(rep, retry);
2021
+ const text = clampCompactionNote(picked.text);
1936
2022
  if (text) {
1937
2023
  note = { n, text };
1938
2024
  // UI only, never history: the note renders as markdown WITH its reasoning — the trace of
@@ -1941,13 +2027,13 @@ export async function runTurn(opts) {
1941
2027
  opts.onMessage({
1942
2028
  role: 'assistant',
1943
2029
  content: text,
1944
- reasoning: rep.reasoning?.trim() || undefined,
2030
+ reasoning: picked.reasoning,
1945
2031
  compactionNote: true,
1946
2032
  });
1947
2033
  }
1948
- debugLog(`[reika:debug] round=${i} compaction-report n=${n} chars=${text.length}` +
1949
- `${rep.content?.trim() ? '' : rep.reasoning?.trim() ? ' src=reasoning' : ' src=empty'}` +
1950
- `${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`);
1951
2037
  }
1952
2038
  catch (err) {
1953
2039
  if (opts.signal?.aborted) {
@@ -2062,7 +2148,9 @@ export async function runTurn(opts) {
2062
2148
  opts.onContextEstimate?.(Math.round(rawEstimate() * calibration));
2063
2149
  return;
2064
2150
  }
2065
- const sentEstimate = rawEstimate(callHistory, callTools);
2151
+ const sentTools = subagentForceReport && lastSentTools ? lastSentTools : callTools;
2152
+ lastSentTools = sentTools;
2153
+ const sentEstimate = rawEstimate(callHistory, sentTools);
2066
2154
  opts.onContextEstimate?.(Math.round(sentEstimate * calibration));
2067
2155
  // Live reasoning-spin hint (human-only): accumulate THIS round's reasoning and, debounced every
2068
2156
  // SPIN_DEBOUNCE chars, flag when it looks like it's spinning so the UI can prompt abort-or-wait.
@@ -2137,7 +2225,7 @@ export async function runTurn(opts) {
2137
2225
  const response = await callModel({
2138
2226
  system,
2139
2227
  history: callHistory,
2140
- tools: callTools,
2228
+ tools: sentTools,
2141
2229
  config: withGenReserve(opts.config, genReserve),
2142
2230
  onContentDelta: opts.onContentDelta,
2143
2231
  onReasoningDelta,
@@ -2199,7 +2287,7 @@ export async function runTurn(opts) {
2199
2287
  // churn — without it every append reads as `mid-history firstChanged=assistant` (#253).
2200
2288
  const d = prefixTrace.record(msgs, {
2201
2289
  trailingNote: !!roundSuffix,
2202
- tools: toolsToChatTools(callTools),
2290
+ tools: toolsToChatTools(sentTools),
2203
2291
  });
2204
2292
  const pct = d.totalChars > 0 ? Math.round((d.stableChars / d.totalChars) * 100) : 100;
2205
2293
  roundReprocessTokens = reprocessedTokens(d, Math.round(sentEstimate * calibration));
@@ -2235,6 +2323,23 @@ export async function runTurn(opts) {
2235
2323
  opts.onCalibration?.(calibration);
2236
2324
  }
2237
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
+ }
2238
2343
  // Same idea one layer down: time-to-first-token is what those reprocessed tokens cost, so the
2239
2344
  // round that just paid teaches the rate the next round's line quotes. Only fires under
2240
2345
  // REIKA_DEBUG (roundReprocessTokens stays 0 otherwise), and rejects samples too small to
@@ -2856,6 +2961,8 @@ export async function runTurn(opts) {
2856
2961
  subagentCalls.inRound = 0;
2857
2962
  }
2858
2963
  const subagentInRound = roundHasSubagent && subagentCalls.rounds <= MAX_SUBAGENTS_PER_TURN;
2964
+ // Reasons the user typed while declining this round's calls, sent after its results (below).
2965
+ const roundDeclineFeedback = [];
2859
2966
  for (const call of toolCalls) {
2860
2967
  if (opts.signal?.aborted)
2861
2968
  return;
@@ -2908,6 +3015,8 @@ export async function runTurn(opts) {
2908
3015
  let contentHash;
2909
3016
  let toolNotice;
2910
3017
  let editFailure;
3018
+ // The reason a user typed when declining this call, appended to its summary after the run.
3019
+ let declineFeedback;
2911
3020
  // Read-first (#72): path this call put file bytes in front of the model for, and whether the
2912
3021
  // model authored them (`write`) rather than being handed them. Applied once the tool message
2913
3022
  // exists, since handed-back grounding keys on its history index. See readfirst.ts.
@@ -2995,7 +3104,14 @@ export async function runTurn(opts) {
2995
3104
  groundedUrls,
2996
3105
  sourcedUrls: () => collectSourcedUrls(opts.history),
2997
3106
  askedQuestions,
2998
- requestApproval: opts.requestApproval,
3107
+ requestApproval: opts.requestApproval &&
3108
+ (async (req) => {
3109
+ const answer = await opts.requestApproval(req);
3110
+ if (typeof answer === 'boolean')
3111
+ return answer;
3112
+ declineFeedback = answer.feedback;
3113
+ return false;
3114
+ }),
2999
3115
  requestQuestion,
3000
3116
  onProgress: opts.onToolProgress && (chunk => opts.onToolProgress(chunk, tool.name)),
3001
3117
  spawnSubagent: makeSpawnSubagent(opts, subagentCalls, decodeThroughput, genReserve),
@@ -3005,8 +3121,12 @@ export async function runTurn(opts) {
3005
3121
  unattended: opts.isUnattended?.() ?? opts.config.unattended,
3006
3122
  signal: opts.signal,
3007
3123
  });
3008
- summary = result.summary;
3124
+ summary = declineFeedback
3125
+ ? withDeclineFeedback(result.summary, declineFeedback)
3126
+ : result.summary;
3009
3127
  payload = result.payload;
3128
+ if (declineFeedback)
3129
+ roundDeclineFeedback.push(declineFeedback);
3010
3130
  diff = result.diff;
3011
3131
  command = result.command;
3012
3132
  changes = result.changes;
@@ -3067,17 +3187,28 @@ export async function runTurn(opts) {
3067
3187
  // Instrument re-reads (debug only): is this a fresh read, a redundant loop, or a rational
3068
3188
  // refetch of content that aged out? Recorded for every read regardless of REIKA_DEBUG (cheap,
3069
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;
3070
3193
  if (!refused && call.name === 'read' && contentHash) {
3071
3194
  // Read-first (#72): the model now holds this file's bytes (or knows its true length, for an
3072
3195
  // offset-past-end read). Grounding is applied after the tool message is pushed, since it
3073
3196
  // keys on that message's index — the bytes ground edits only while they are still being sent.
3074
3197
  groundsPath = String(call.args.path ?? '');
3075
- 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,
3076
3199
  // Resolved exactly as the tool resolves it, so a default-window read followed by an
3077
3200
  // explicit narrower one is seen as narrowing rather than as a repeat (#184).
3078
3201
  Math.max(1, Number(call.args.limit ?? READ_DEFAULT_LIMIT)));
3079
3202
  debugLog(`[reika:debug] read-trace round=${i} class=${cls} repeats=${repeats} ${summary}\n`);
3080
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
+ }
3081
3212
  else if (debugEnabled() && !refused && call.name !== 'read') {
3082
3213
  // Non-read tool calls have no read-trace line, so a reasoning loop circling on grep/glob/list
3083
3214
  // (the observed case, where read-trace was silent but payloads kept growing) is otherwise
@@ -3104,8 +3235,10 @@ export async function runTurn(opts) {
3104
3235
  // edit/write-only — `lastEditFailed`, the read-first grounding, and applyPlanEdit all read
3105
3236
  // fields (old_string failures, args.path, a rendered diff) that a shell command has no
3106
3237
  // analogue for.
3107
- if (!bouncedBlindEdit && didMutate(call.name, changes))
3238
+ if (!bouncedBlindEdit && didMutate(call.name, changes)) {
3108
3239
  editingStarted = true;
3240
+ mutatedSinceWithdrawal = true;
3241
+ }
3109
3242
  if (!bouncedBlindEdit && MUTATING_TOOLS.has(call.name)) {
3110
3243
  // Track edit-recovery state: a failed edit (old_string not in the file, etc.) keeps the model
3111
3244
  // needing a re-read; a successful one clears it. Drives the withdrawal exemption + dead-end
@@ -3239,6 +3372,19 @@ export async function runTurn(opts) {
3239
3372
  opts.onMessage({ role: 'system', tone: 'info', content: planCheckoff });
3240
3373
  }
3241
3374
  }
3375
+ // The user's own words, as a user message rather than inside the declined call's result: in a
3376
+ // tool result even a framed quote read to lfm2.5-24b as the environment refusing ("maybe the
3377
+ // environment doesn't support it"), 0/3 on a reason asking for an answer instead of a command.
3378
+ // `harness`: not a turn boundary, so the task-spec pin stays put (#287). History only — the
3379
+ // declined call's row already shows the quote. The words go verbatim: opening with "I declined
3380
+ // `<command>`." gained nothing on a terse reason and buried an explicit one behind a long `cd`.
3381
+ if (roundDeclineFeedback.length > 0) {
3382
+ opts.history.push({
3383
+ role: 'user',
3384
+ content: roundDeclineFeedback.join('\n\n'),
3385
+ harness: true,
3386
+ });
3387
+ }
3242
3388
  // A round that added no new keys (all re-reads of already-seen sections / repeat searches) is a
3243
3389
  // stall; enough consecutive stalls trip the adaptive force-write on the next iteration.
3244
3390
  const roundLearned = seenReadOnly.size > seenBeforeRound || seenWebLookups.size > seenWebBeforeRound;
@@ -3246,7 +3392,8 @@ export async function runTurn(opts) {
3246
3392
  }
3247
3393
  const exhausted = {
3248
3394
  role: 'assistant',
3249
- 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()),
3250
3397
  durationMs: Date.now() - turnStart,
3251
3398
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
3252
3399
  };
@@ -3319,7 +3466,7 @@ reason = 'loop') {
3319
3466
  // bash). Ends the turn honestly rather than running to maxTurns. If the turn made edits, the work is
3320
3467
  // already on disk — frame it as "done but stopped re-checking" and name the edited files; otherwise
3321
3468
  // it's a stuck-without-progress stop. Mirrors commitSpiralStop (plan mode).
3322
- function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited) {
3469
+ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited, typecheckAddendum = '') {
3323
3470
  const files = new Set();
3324
3471
  for (const m of opts.history) {
3325
3472
  // A shell edit names its files in the tool message's git-backed `changes`, not in the call's
@@ -3343,7 +3490,8 @@ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited) {
3343
3490
  const content = edited
3344
3491
  ? `I made changes${fileList} but then kept repeating the same checks without making progress, so ` +
3345
3492
  `I've stopped to avoid looping. The edits are saved — review them and ask me to continue if ` +
3346
- `anything's off.`
3493
+ `anything's off.` +
3494
+ typecheckAddendum
3347
3495
  : `I kept repeating the same step without making progress, so I've stopped rather than loop. Let ` +
3348
3496
  `me know how you'd like to proceed.`;
3349
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
+ }