Skip to content

fix: cut advice notes and next-prompt suggestions on a word boundary - #157

Merged
btspoony merged 5 commits into
mainfrom
fix/word-boundary-truncation
Nov 17, 2026
Merged

btspoony merged 5 commits into
mainfrom
fix/word-boundary-truncation

Conversation

@btspoony

Copy link
Copy Markdown
Member

Supersedes #156. Closes #155.

Both user-visible advisor text caps were hardcoded and cut mid-word: the
stored next-prompt suggestion silently at 120 code points with no marker, the
delivered advice note at 768 with a marker. This takes the shaping fix and the
two config keys from #156, but bounds them and drops the unbounded opt-out.

What changed vs #156

#156 this PR
nextPromptMaxChars 0–2000, 0 = unbounded 50–2000, default 120
noteMaxChars 0–20000, 0 = unbounded 128–4096, default 768
limitText maxChars <= 0 returns the text no 0 branch
Card empty input treated as 0 (= no bound) treated as "leave unchanged"

Why no 0: since the 2026-10-18 ruling removed maxTokens, the extraction cap
is the only output bound left — src/advisor-runtime.ts:186-205 states this
explicitly. A note is delivered as a user-role message and concern/blocker
go through agent.steer, which wakes the primary agent. The emission guard
bounds frequency and duplication, never length. So the setting may shorten or
modestly grow the bound but must not remove it. Each key gets its own floor and
ceiling rather than a shared bound or an unbounded switch.

Kept from #156

  • src/text-limit.ts limitText: code-point counted, cuts on a word boundary,
    appends … with the marker counting toward the bound, falls back to a hard
    cut when a single token exceeds the budget or the boundary would keep less
    than 60% of it.
  • Both keys wired through schema + CONFIG_KEYS + resolved snapshot + gateway
    get/set + /advisor config readback + web card + en/zh locales.
  • nextPromptMaxChars read live per prediction attempt (one snapshot feeds both
    the predictor prompt budget and the shaping step); noteMaxChars folded into
    runtimeSignature, like proseFallback.
  • The predictor system prompt now states the budget it enforces.

Defaults keep the historical limits, so an absent key changes only the cut
shape — the suggestion now lands on a word boundary with a marker instead of a
silent mid-word slice.

Verification

  • pnpm typecheck — pass (main + client + spec configs)
  • pnpm build — pass
  • pnpm test — pass: 28 files, 765 tests

New coverage: tests/text-limit.test.ts (defaults/floors/ceilings, word
boundary, 60% fallback, maxChars = 1, code points, idempotence), plus
per-surface cases in tests/config.test.ts (defaults, floors, ceilings, 0
rejected, null, unknown near-miss), tests/next-prompt.test.ts (custom bound,
live per-attempt read, prompt budget), tests/advisor-runtime.test.ts (runtime
option + extraction functions), tests/advisor-store.test.ts (draft seeding,
patch, clamping) and tests/gateway.test.ts (wire round-trip at the floors).

Docs: README.md / README.zh.md, docs/configuration.md,
docs/consumer-api.md, CONCEPTS.md.

Co-authored-by: triagmas [email protected]

Both user-visible advisor caps were hardcoded and cut mid-word: the stored
next-prompt suggestion silently at 120 code points with no marker, the
delivered advice note at 768 with a marker. Make both configurable and give
every bounded cut one shape.

- `nextPromptMaxChars` (integer 50..2000, default 120) is read live per
  prediction attempt; one snapshot feeds both the predictor prompt budget and
  the shaping step.
- `noteMaxChars` (integer 128..4096, default 768) is a runtime construction
  constant folded into `runtimeSignature`, so an edit rebuilds the session
  runtime once, like `proseFallback`.
- No `0`/unbounded setting: the note bound is the only output bound left after
  the 2026-10-18 `maxTokens` removal, so both keys carry a schema floor.
- One shared helper, `src/text-limit.ts` `limitText`: code-point counted, cuts
  on a word boundary, appends `...` (the marker counts toward the bound), and
  falls back to a hard cut when a single token exceeds the budget or the
  boundary would keep less than 60% of it.

Defaults keep the historical limits, so an absent key changes only the cut
shape; the suggestion now lands on a word boundary with a marker instead of a
silent mid-word slice, and the predictor system prompt states the budget.

Closes #155

Co-authored-by: triagmas <[email protected]>
@m-inspector

m-inspector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

✅ Verdict: ship it · Score 98% (mergeable)

Findings Count
🔴 must-fix 0
🟠 should-fix 0
🟡 may-fix 0
🔵 nit 1

📋 Review

What this PR does: This PR replaces the two hardcoded advisor text caps with configurable per-key bounds (nextPromptMaxChars 50–2000, default 120; noteMaxChars 128–4096, default 768) and routes both surfaces through a shared limitText helper that counts code points, cuts on a word boundary, appends … within the bound, and hard-cuts a single over-long word. The keys are wired through the config schema, the resolved snapshot, the gateway get/set wire, the /advisor config readback, the web settings card and the en/zh locales, with nextPromptMaxChars read live per prediction attempt and noteMaxChars folded into runtimeSignature. It supersedes #156, closes #155, and deliberately drops #156's 0 = unbounded opt-out so the note cap stays the only output bound after the maxTokens removal.

Findings

🔵 Clamp writeback introduces a second draft-update idiom instead of the file's immutable schema writer

  • Evidence:

    [DEBT-01] Clamp writeback introduces a second draft-update idiom instead of the file's immutable schema writer

    • Evidence: src/client/advisor-store.ts:988-992 — the new clamp writeback rebuilds the draft with an object spread plus two conditional spreads.
    • Evidence: src/client/advisor-store.ts:1131 — setField writes a draft field through this.schema.setPath(...) (the immutable path writer the file documents as the canonical write face at src/client/advisor-store.ts:63-65).
    • Evidence: src/client/advisor-store.ts:1140 — clearField uses the matching this.schema.deletePath(...).
    • Impact: None at runtime — the spread and two schema.setPath calls produce an equal plain object, and both replace the draft reference (which is the change's actual point). The cost is a third write idiom for the same modified draft, so a future change to the schema write path (e.g. a path-validation or prototype rule added in ui-settings) silently skips this site. Every other draft edit in the file (src/client/advisor-store.ts:840, 1131, 1140) goes through the schema writer; this hunk is the only manual field-by-field rebuild.
    • Effort: XS — replace the spread with two nested this.schema.setPath(s.draft, ['nextPromptMaxChars'|'noteMaxChars'], bound) calls, each guarded by the same !== undefined test already present.
    • Risk: LOW — the two forms are behaviorally identical for the two plain number keys involved.
    • Confidence: MED (read both sites; the equivalence is static, not executed).
    • Merge class: nit
    • Fix sketch: Keep the conditional per-key application but express it via the existing immutable schema.setPath used by setField/clearField, so a single write convention owns draft mutation. Convention-only; the diff introduces the divergence and an in-file exemplar exists.
  • Location: src/client/advisor-store.ts:988-992

  • Category: tech-debt

  • Merge class: nit

Revalidated findings

Reassessed 3/5 prior finding(s) this round · 0 invalid-output · 2 omitted · 0 over cap · 5 recheckable · context coverage: complete

finding disposition evidence thread
[coverage] changeset-1-src seat — truncated coverage declaration (not a finding) unverifiable (no-evidence) - -
[BUG-01] Text-bound renderer prints raw bounds while the gateway fallback still propagates unvalidated values unverifiable (context-incomplete) - -
Seat coverage declaration (not a code finding) — truncated scope unverifiable (no-evidence) - -
Clamp write-back mutates nested draft fields in place, breaking this store's replace-the-draft update convention addressed (verified-fix) current-code not yet resolved
[BUG-02] apply() rewrites the operator's staged bound before the read-only guard refuses the write addressed (verified-fix) current-code -

Linked-issue AC

[met] nextPromptMaxChars configurable with default 120 — src/config.ts:271-272 declares an integer schema default 120; range tightened to 50–2000.
[met] noteMaxChars configurable with default 768 — src/config.ts:273-274; range tightened to 128–4096 (proposal said 0–20000).
[cut] 0 = keep the full text / no truncation (issue title) — no 0 branch in limitText; the PR deliberately keeps a positive bound because the note cap is the only output bound left after the maxTokens removal.
[met] Both keys .volatile() and registered in CONFIG_KEYS / the resolved snapshot — .volatile() at src/config.ts:271-274, key set at :192-194, resolved fields at :165-167; noteMaxChars additionally joins runtimeSignature.
[met] Both keys wired through gateway write payload, settings card, and en/zh locales — src/gateway.ts:757-758,796-797; src/client/advisor-card.tsx:463-496; src/client/locales.ts:34-37,133-136.
[met] One bound snapshot per attempt feeds both the predictor prompt budget and the shaping step — src/next-prompt.ts:409-415; covered by tests/next-prompt.test.ts:767-812.
[met] Bounded cut lands on a word boundary with … counting toward the cap, hard-cut fallback — src/text-limit.ts:74-97; cases in tests/text-limit.test.ts.
[met] Predictor system prompt states the budget — src/prompts.ts:59-60, wired at src/next-prompt.ts:481.
[unmet] Debug log on truncation carrying only rawLength / truncated, never the text — no such log exists in src/text-limit.ts, src/next-prompt.ts, or src/advisor-runtime.ts; truncation is silent. This review did not raise it as a finding.

✅ Verified

- src/client/advisor-store.ts:988-992 read: the clamp writeback rebuilds the draft with an object spread plus two conditional spreads — the DEBT-01 evidence.
- src/client/advisor-store.ts:1131,1140 read: setField writes via this.schema.setPath, clearField via this.schema.deletePath, matching the canonical writer documented at :63-65.
- Prior finding "clamp write-back mutates nested draft fields in place" — addressed (verified-fix) per the revalidation table.
- Prior finding [BUG-02] "apply() rewrites the staged bound before the read-only guard refuses the write" — addressed (verified-fix); the clamp now sits below both refusal guards (:959-989).
- ❓ [BUG-01] renderer prints raw bounds while the gateway fallback propagates unvalidated values — unverifiable (context-incomplete) per the revalidation table.
- ❓ pnpm typecheck / pnpm build / pnpm test (28 files, 765 tests) — claimed in the PR body; the review document shows no run.
- ❓ docs/configuration.md:35 prose still says noteMaxChars … "0 = 无上限", contradicting the no-0 table on the same page — outside the settled findings; the doc owner should confirm.

🗑️ Considered & rejected

- The manual spread as a runtime defect — rejected: the spread and two schema.setPath calls produce the same plain object and both replace the draft reference, so behavior is identical; only the write-convention divergence remains (graded nit).
- The dropped 0 = unbounded opt-out as a defect — rejected: deliberate and documented (PR body, src/text-limit.ts header); the note cap is the only output bound after the maxTokens removal, so an always-positive bound is the intended design, recorded as a cut of #155's proposal rather than a regression.
- Sharing one maxChars key across both surfaces — rejected by the issue's own alternatives and by the diff: the suggestion (web tip line) and the note (durable user-role injection) have different jobs, so the PR keeps per-key floors and ceilings.

🛠️ Plan to fix

Expand fix plan
1. **Rewrite the clamp writeback onto the schema writer** — `src/client/advisor-store.ts`, clamp block at `:988-992`. Inside the existing `this.store.update` callback, start from `s.draft` and apply each present bound through `this.schema.setPath(...)` (the same immutable face as `setField` `:1131` / `clearField` `:1140`), keeping the existing `!== undefined` guard per key; assign the final object once to `s.draft` and recompute `dirty` once. This removes the manual spread + conditional-spread idiom.

   ```ts
   this.store.update((s) => {
     let draft = s.draft
     if (nextBound !== undefined) {
       draft = this.schema.setPath(draft as unknown as Record<string, unknown>, ['nextPromptMaxChars'], nextBound) as unknown as AdvisorDraft
     }
     if (noteBound !== undefined) {
       draft = this.schema.setPath(draft as unknown as Record<string, unknown>, ['noteMaxChars'], noteBound) as unknown as AdvisorDraft
     }
     s.draft = draft
     s.dirty = this.recomputeDirty(s.draft)
   })
   ```

2. **Preserve the surrounding semantics exactly** — keep the entry condition `nextBound !== pending.draft.nextPromptMaxChars || noteBound !== pending.draft.noteMaxChars`; `undefined` must still mean "leave unchanged" (card empty-input semantics); do not move the clamp above the read-only and gate refusals, so a refused save still never rewrites the staged draft (the BUG-02 fix). Keep the casts already used by `setField`/`clearField` rather than widening `AdvisorDraft`.

3. **Targeted verification** — `pnpm typecheck`, then `vitest run tests/advisor-store.test.ts`: the clamp-on-apply patch expectation at `:1738-1756`, the refused-save case at `:1371-1388`, and the seeding/only-changed-bounds cases at `:1687-1719`.

4. **Full gate** — `pnpm test` (28 files / 765 tests per the PR body; not evidenced in this review) and `pnpm build` before merge.

5. **No doc or locale churn** — the change is convention-only; no README, locale, or schema edits are required.

Review 5 · commit 3ac3235 · since 2e2c576

@m-inspector m-inspector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mstar-inspector line comments · round 1 · 9f1eda1

Comment thread src/client/advisor-store.ts Resolved
Comment thread src/advisor-runtime.ts Resolved
Comment thread src/commands.ts Resolved
Comment thread src/gateway.ts Resolved
Comment thread src/advisor-runtime.ts Resolved
Comment thread tests/next-prompt.test.ts Resolved
Review round 1 on #157:

- The bound inputs floored per keystroke but also range-clamped, so typing
  "200" rewrote the field to 50 on the first digit and "128" walked up to
  the ceiling. They now floor only; `apply()` clamps to the schema range
  once and writes the result back so the card shows what was sent.
- `AdvisorRuntimeOptions.noteMaxChars`, `ADVISOR_NOTE_MAX_CHARS` and
  `extractProseFallbackNote` still documented a `0` opt-out that the helper
  and the schema deny.
- `/advisor config` still rendered an unreachable `unbounded` branch.
- The S1 gateway fallback hardcoded 120/768 instead of the shared defaults.
- Renamed a test that claimed "no budget line" while asserting one.

@m-inspector m-inspector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mstar-inspector line comments · round 2 · 6005d81

Comment thread src/commands.ts
// GitHub issue #155: the two text bounds are plain positive numbers on every
// composed read (schema floors), so they always render.
lines.push(`nextPromptMaxChars: ${config.nextPromptMaxChars}`)
lines.push(`noteMaxChars: ${config.noteMaxChars}`)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[BUG-01] Text-bound renderer prints raw bounds while the gateway fallback still propagates unvalidated values · 🟡 may-fix

[BUG-01] Text-bound renderer prints raw bounds while the gateway fallback still propagates unvalidated values

  • Evidence: src/commands.ts:696-698 — the two bound lines now render the number verbatim (nextPromptMaxChars: ${config.nextPromptMaxChars}, noteMaxChars: ${config.noteMaxChars}); the removed branch mapped 0 to 'unbounded'. The new comment asserts the values are "plain positive numbers on every composed read (schema floors)". src/gateway.ts:744-750 — the S1 fallback arm (which only runs after resolveAdvisorConfig rejected the entry config) seeds those two keys straight from the unvalidated raw source: nextPromptMaxChars: raw?.nextPromptMaxChars ?? DEFAULT_NEXT_PROMPT_MAX_CHARS, noteMaxChars: raw?.noteMaxChars ?? DEFAULT_ADVISOR_NOTE_MAX_CHARS. src/config.ts:271-274 shows the schema bounds (min(50) / min(128)), so 0 (the value src/advisor-runtime.ts:159-166 previously documented as the opt-out and which the pre-diff comment at commands.ts called "0 reads as unbounded") is exactly the kind of raw value that lands on that arm; src/gateway.ts:787-789 then puts it on the wire verbatim, and src/index.ts:1070 copies it into AdvisorComposedConfig.
  • Impact: For a stored config the resolver rejects (e.g. noteMaxChars: 0 written under the previous documented semantics, or 5000), /advisor config now prints noteMaxChars: 0 / nextPromptMaxChars: 5000 — a value the schema and the runtime cannot honor (src/text-limit.ts:76-88 with maxChars: 0 returns just …). The readback states a bound that is neither the effective nor a valid one, and the "schema floors every composed read" justification in the new comment does not hold on the fallback arm.
  • Effort: XS — the fix is a guard in the renderer or in the fallback seeding.
  • Risk: LOW — the renderer is a readback surface only; ch…

s.dirty = this.recomputeDirty(s.draft)
})
}
const state = this.store.getSnapshot()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[BUG-02] apply() rewrites the operator's staged bound before the read-only guard refuses the write · 🟡 may-fix

[BUG-02] apply() rewrites the operator's staged bound before the read-only guard refuses the write

  • Evidence: src/client/advisor-store.ts:949-965 — the new clamp/write-back block runs first (this.store.update((s) => { … s.draft.nextPromptMaxChars = nextBound … }) at 960-964), and only afterwards does the method read const state = this.store.getSnapshot() (966) and reach the guard if (!state.writable) { … 'advisor: settings service is read-only …' } (the W-1 comment block immediately below states the guard "comes FIRST — before the client gate check AND the empty-patch shortcut"; the new block is now above it).
  • Impact: The documented mid-session flip ("invalidation refresh returns writable=false while staged edits survive") is exactly the state this ordering mishandles: an apply in read-only rewrites the operator's unsaved bound entry (e.g. the partial 2 the per-keystroke floor preserves) to the clamped 50/128 and then reports the read-only error — the staged value is lost although nothing was written. The guard's stated invariant ("a write must never be issued") is honored, but the draft mutation it was placed ahead of now happens before it.
  • Effort: XS — move the clamp block below the writable guard.
  • Risk: LOW — the clamp must still precede gateFailure/patchFor; only the read-only branch changes.
  • Confidence: MED — the block order and the guard text are read verbatim; the wrong outcome needs the writable-flip state the same comment documents.
  • Merge class: may-fix
  • Fix sketch: Run the clamp/write-back after the read-only early return so a refused write leaves the draft untouched.

Seat coverage (changeset-1-src, truncated): reviewed src/advisor-runtime.ts, src/client/advisor-store.ts, src/commands.ts, src/gateway.ts against /workspace/pr.diff; src/advisor-runtime.ts and `src…

…clamp order

Review round 2 on #157:

- Both containment arms (`src/index.ts` `safeFallback`, `src/gateway.ts`
  readConfig) seeded the bounds straight from the unvalidated raw source, so
  a stored `noteMaxChars: 0` or an over-ceiling value reached `/advisor
  config` and the web card as a bound nothing honors. They now clamp through
  the new `coerceTextBound` helper.
- `apply()` clamped and rewrote the staged bound before the read-only guard,
  so a refused write still mutated the operator's draft. The clamp block now
  runs after the guard and before `gateFailure`/`patchFor`.

@m-inspector m-inspector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mstar-inspector line comments · round 3 · 907ad66

Comment thread src/client/advisor-store.ts Resolved
Review round 3 on #157: the clamp block moved after the read-only guard but
still ran before the gate check, so a gate-refused save (incomplete
provider/model pair) rewrote an out-of-range staged bound and recomputed
dirty. It now runs after both refusing guards, so no refused save mutates
the operator's draft.

@m-inspector m-inspector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mstar-inspector line comments · round 4 · 2e2c576

Comment thread src/client/advisor-store.ts Resolved
Review round 4 on #157: the clamp write-back mutated `s.draft` in place
while every other draft write in this store replaces the reference. Spread
the draft instead, so snapshot consumers see the same update shape here as
everywhere else.

@m-inspector m-inspector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mstar-inspector line comments · round 5 · 3ac3235

...s.draft,
...(nextBound === undefined ? {} : { nextPromptMaxChars: nextBound }),
...(noteBound === undefined ? {} : { noteMaxChars: noteBound }),
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clamp writeback introduces a second draft-update idiom instead of the file's immutable schema writer · 🔵 nit

[DEBT-01] Clamp writeback introduces a second draft-update idiom instead of the file's immutable schema writer

  • Evidence: src/client/advisor-store.ts:988-992 — the new clamp writeback rebuilds the draft with an object spread plus two conditional spreads.
  • Evidence: src/client/advisor-store.ts:1131 — setField writes a draft field through this.schema.setPath(...) (the immutable path writer the file documents as the canonical write face at src/client/advisor-store.ts:63-65).
  • Evidence: src/client/advisor-store.ts:1140 — clearField uses the matching this.schema.deletePath(...).
  • Impact: None at runtime — the spread and two schema.setPath calls produce an equal plain object, and both replace the draft reference (which is the change's actual point). The cost is a third write idiom for the same modified draft, so a future change to the schema write path (e.g. a path-validation or prototype rule added in ui-settings) silently skips this site. Every other draft edit in the file (src/client/advisor-store.ts:840, 1131, 1140) goes through the schema writer; this hunk is the only manual field-by-field rebuild.
  • Effort: XS — replace the spread with two nested this.schema.setPath(s.draft, ['nextPromptMaxChars'|'noteMaxChars'], bound) calls, each guarded by the same !== undefined test already present.
  • Risk: LOW — the two forms are behaviorally identical for the two plain number keys involved.
  • Confidence: MED (read both sites; the equivalence is static, not executed).
  • Merge class: nit
  • Fix sketch: Keep the conditional per-key application but express it via the existing immutable schema.setPath used by setField/clearField, so a single write convention owns draft mutation. Convention-only; the diff introduces the divergence and an in-file exemplar exists.

@btspoony
btspoony merged commit 97c12eb into main Nov 17, 2026
2 checks passed
@btspoony
btspoony deleted the fix/word-boundary-truncation branch November 17, 2026 05:24
@btspoony btspoony mentioned this pull request Nov 17, 2026
@btspoony btspoony mentioned this pull request Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: configurable text limits for advice notes and next-prompt suggestions (0 = no truncation)

1 participant