Skip to content

fix: flush StreamRedactor tail before stopping Slack stream - #4762

Closed
jiapingzeng wants to merge 1 commit into
kirodotdev:mainfrom
jiapingzeng:fix-slack-stream-truncation
Closed

jiapingzeng wants to merge 1 commit into
kirodotdev:mainfrom
jiapingzeng:fix-slack-stream-truncation

Conversation

@jiapingzeng

@jiapingzeng jiapingzeng commented Aug 20, 2026 •

Copy link
Copy Markdown

Problem / Motivation

Goal: Streamed Slack replies arrive complete, and the credential redaction on the stream stays as strong as it is today.

The last word of a streamed Slack reply goes missing. When the agent calls a tool mid-reply, the last word before the tool card lands in its own block after the card instead.

Missing last word

Why it matters

Any reply whose final characters are letters, digits or punctuation (almost every reply) loses its last word on the wire. Replies that use tools also show stray one-word lines between task cards. Users read incomplete or broken-up answers, and the only workaround is to ask the agent to repeat itself.

Not a goal

  • Changing how StreamRedactor decides what to withhold.
  • Changing delivery accounting for clean-text turns whose stream appends were all refused (the existing test_native_stream_all_appends_refused_books_failure rule stays).

What changed (motivation → approach → change)

Boundary Render of the full text so far is clean Render redacted something
End of turn withheld tail is appended tail is dropped; the final overwrite posts the complete redacted text
wait (message is stopped) tail is appended before the stop tail is dropped; the stopped message is overwritten with the redacted pre-wait render
Tool task card tail is appended before the card tail is dropped; the end-of-turn overwrite posts the complete redacted text

StreamRedactor holds back the trailing run of credential-class characters in case a credential is split across chunks. The handler assumed stop_stream would post the complete text, but SlackClient.stop_stream never sends final_text, so that tail was dropped. The tail was also released only with the next chunk, so before a tool card it landed after the card.

In slack/handler.py, _flush_sred_tail now settles the tail at each boundary above, gated on a render of the complete visible text (thinking, control comments and OPTIONS removed, as at end of turn). The render normalises ANSI and zero-width obfuscation, which the per-chunk scan does not. So a flushed tail can never complete an obfuscated credential whose prefix already streamed. A tail that lands counts as a delivery (_stream_delivered). A tail whose append and rotated retry both fail where the segment ends drops the turn out of stream mode, so the complete text is posted by overwrite; before a task card the stream stays live and the loss is recorded as delivery debt, like any refused delta. A wait call skips the task-card flush and settles its tail at the wait boundary. When a redacted reply streamed no text at all, the end-of-turn overwrite is its only delivery: it runs with raise_on_primary_failure and books the answer as reached.

Backwards compatibility

Compatible: no config, API or wire-format change; Slack messages gain the text they were losing.

Tests

test/test_slack_handler.py:

  • test_trailing_run_survives_on_stream_wire -- the append frames carry the whole reply.
  • test_redacted_render_drops_flushed_tail_from_wire, test_exfil_url_in_flushed_tail_is_redacted -- a redacting end-of-turn render keeps the withheld half of an ANSI-split key / split URL off the wire; the overwrite carries the redacted text.
  • test_wait_boundary_does_not_flush_uncorrectable_tail, test_tail_buffered_before_wait_never_flushed_after_it -- a redacted pre-wait tail is never appended, before or after the wait.
  • test_clean_tail_flushed_into_pre_wait_message -- a clean pre-wait tail lands in the pre-wait message.
  • test_redacted_pre_wait_turn_overwritten_not_truncated, test_lost_pre_wait_tail_overwrites_the_stopped_message -- the stopped pre-wait message is overwritten when its tail was redacted or lost.
  • test_pre_wait_overwrite_excludes_thinking_text -- that overwrite renders only what the stream showed (no inline thinking).
  • test_clean_tail_lands_before_task_card, test_redacted_tail_not_flushed_before_task_card -- the tool-card boundary appends a clean tail before the card; a redacted one reaches no append frame, before or after the card.
  • test_flush_retry_failure_falls_back_to_final_update -- a tail that fails append and retry is recovered by the final update.
  • test_refused_tail_before_task_card_keeps_streaming -- a tail refused twice before a task card leaves the stream live and discloses the loss as debt.
  • test_tail_only_reply_is_not_booked_a_delivery_failure, test_redacted_credential_only_reply_is_not_booked_a_failure -- a reply delivered only by the flush, or only by the redacted overwrite, is not booked a failure.

Manual verification

Ran on a local build against a real Slack workspace; replies arrive complete.

Before:
Before

After:
After

Screenshots / video

N/A -- no dashboard UI change; Slack before/after is under Manual verification.

Related Issues

no linked issue: symptom reported directly (screenshot above).

Pattern harvest

Rule candidate: review-prompt
Pattern: a buffering filter in front of an append-only sink must be drained at every point the sink's segment ends (stop, rotation, interleaved non-text frames), gated on the strongest verdict available there.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@iamwhatever

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

2 similar comments
@iamwhatever

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@bolichen97

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention labels Aug 20, 2026
@jiapingzeng
jiapingzeng force-pushed the fix-slack-stream-truncation branch from c5ab712 to 73f09c2 Compare August 20, 2026 21:29
@iamwhatever

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@jiapingzeng
jiapingzeng marked this pull request as ready for review August 20, 2026 21:32
@jiapingzeng
jiapingzeng requested a review from a team August 20, 2026 21:32
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Aug 20, 2026
@jiapingzeng
jiapingzeng force-pushed the fix-slack-stream-truncation branch from 73f09c2 to cc8f1e8 Compare August 20, 2026 22:36
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Aug 20, 2026
@jiapingzeng
jiapingzeng force-pushed the fix-slack-stream-truncation branch from 99b18b6 to 810a4a4 Compare August 20, 2026 23:20
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Aug 20, 2026
@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — 🔴 changes requested (blocking)

Reviewed ca033fff5c58e2081f53aabb5d458a2a0423f06e via the fork AI-review pipeline; updated in place on each push.

1 of 1 blocking finding(s) are security-class and were withheld from adjudication, so the blocking verdict stands.

BLOCKING -- src/kiro_crew/slack/handler.py:5452 -- stale redactor tail can disclose a credential after an error
await _flush_sred_tail(_render_redacted)
ANSI-split credential followed by AcpError -> error replaces accumulated but _sred retains credential bytes -> clean error verdict flushes the raw credential suffix to Slack.
Anchor: backend-security-controls
Fix: On model-error paths, reset _sred instead of flushing a tail not covered by the final render.
[BLOCK-MERGE] ca033ff
[GPT-REVIEWED] ca033ff

Adjudication (Opus 5) — is blocking on each finding proportionate?

UNBOUNDED (credential disclosure). Conditions confirmed: the per-chunk redactor withholds the trailing credential-class run and flush() redacts only that isolated suffix, without the canonicalisation that catches ANSI/zero-width splitting (src/kiro_crew/security/__init__.py:605, :766); the error arms replace the streamed text outright (src/kiro_crew/slack/handler.py:4856, :4862, :4868), and the finalize render derives _render_redacted from that replacement (:5102-:5104), which the new call at the anchor then reads as proof the stale tail is clean.

Recovery: none — the overwrite gate (:5342, widened in the diff) needs _stream_had_redaction/_render_redacted/warnings/not use_slack_stream, all False in this combination, and the PR's own reasoning states an appended frame is visible the instant it lands, so a later overwrite cannot recall it.

Real fix cost: one _sred.reset() on the error arms, or passing a had_error verdict into the existing flush helper — small, local, and inside the mechanism this PR already builds; far below the harm.

[ADJUDICATION] ca033ff total=0 uphold=0 downgrade=0
[GPT-ADJUDICATED] ca033ff

[ADJUDICATION-FENCED] ca033ff fenced=1 flagged=0
UPHOLD-FENCED F1 src/kiro_crew/slack/handler.py:5452 -- A mid-turn transport error is routine and the ANSI/zero-width-split credential is this PR's own stated threat model, so the combination is plausible, it discloses credential bytes to a channel with no recovery path, and the fix is a local reset inside the mechanism the PR already adds.
[GPT-ADJUDICATED-FENCED] ca033ff

@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5, fork) — ✅ PASS

Premise-level review of ca033fff5c58e2081f53aabb5d458a2a0423f06e via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: PASS

Verify the new tests fail on base — the defect's only provenance is a screenshot plus tests this lane could read but not run.

Every load-bearing premise checked out against the base checkout: SlackClient.stop_stream (src/kiro_crew/slack/client.py:744-748) really never sends final_text, and its comment records the deliberate no-chat.update decision, so fixing in the handler is the right level; the base handler contains zero calls to _sred.flush()/_sred.reset() (grepped: 0 matches) while StreamRedactor.flush()'s own docstring says to call it "when the stream/segment ends" — the fix uses the mechanism the redactor was designed with; _safe_final_update already carries raise_on_primary_failure; the rewritten "no data loss" comment was factually wrong on base, and the description says so. The redaction gating on every flush is mandated by the frozen Goal and the external-content boundary. The ## Not a goal pin test_native_stream_all_appends_refused_books_failure exists on base (test/test_slack_success_after_delivery_10050.py) and is untouched.

What this change ships

Inventory (10 items) — 10 justified

Intent: streamed Slack replies arrive complete without weakening stream redaction — a FIX.

  1. Streamed replies keep their final word at end of turn — justified
  2. Text before a tool card lands before the card, not as a stray block after it — justified
  3. A clean withheld tail is appended into the pre-wait message before it stops — justified
  4. A redacted or undeliverable pre-wait message is overwritten with the complete redacted render — justified
  5. A pre-wait withheld tail can no longer resurface in the post-wait message — justified
  6. A tail failing append and rotated retry at end of turn falls back to the full-text update — justified
  7. A tail refused before a task card keeps the stream live and discloses the loss as debt — justified
  8. A reply that is entirely one withheld run now counts as delivered, not a booked failure — justified
  9. A redacted reply that streamed nothing is delivered by the overwrite and booked as reached — justified
  10. A tail the full-text render redacts never reaches the wire; the overwrite carries the redacted text — justified

[FIRST-PRINCIPLES-REVIEWED] ca033ff

Description read

[DESCRIPTION-READ] 76701c916db1c589cfe238a9c6da5c93773fc3669481c442fe5c7b736bbf13ec

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — 🟡 CONCERNS

Design-level review of ca033fff5c58e2081f53aabb5d458a2a0423f06e via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

Tail dropped at a tool-card boundary is restored only if the end-of-turn render also redacts — a prefix-only redaction verdict loses text silently.

Watch

  • The tool-card comment claims "the end-of-turn overwrite (its render still covers these bytes) restores the text", but the drop path (if render_redacted: _sred.reset(); return) sets no flag, and the overwrite gate is _stream_had_redaction or _render_redacted or exfil_warnings or cred_warnings or not use_slack_stream. If the mid-turn render over the prefix redacts (a boundary-sensitive credential/URL match at end-of-string) while the full-text render at end of turn comes back clean, no overwrite runs and the reset tail vanishes from the wire — the exact silent-truncation class this PR exists to fix, resurfacing in a rarer corner. The wait boundary enforces its own recovery unconditionally; only the tool-card boundary trusts verdict monotonicity.
    Clears when: dropping a tail at the tool-card boundary sets a needs-overwrite flag (or _stream_had_redaction) so the end-of-turn overwrite is unconditional for those bytes, or a test pins that a redacted→clean verdict flip cannot lose the tail.

Suggestions

  • Skip the per-tool-call render_one_for_slack(_visible_segment_text(accumulated)) when _sred holds no withheld tail (expose a cheap pending-peek): it avoids a full render + redaction scan of the whole accumulated text on every tool event in long agentic turns.

[DESIGN-REVIEWED] ca033ff

Description read

[DESCRIPTION-READ] 1bb89ebec3ffe30129cc681c51c7ca787fb45ce2d3f7631eec2f7385577e0778

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5 Review (fork) — ✅ no blocking findings

Reviewed 45a5ba9ed653bda96a7b439afbad8381b8917ff5 via the fork AI-review pipeline; updated in place on each push.

Review details

A turn whose answer is delivered only by the tail-abandon overwrite is still booked a delivery failure.

FINDING — src/kiro_crew/slack/handler.py:5518 — when the end-of-turn _flush_sred_tail loses the tail on both the append and its rotated retry it sets use_slack_stream = False, so on a reply that streamed nothing confirmed (a whole-reply credential-class run such as 42, where every feed() withholds and _append_stream returns early without raising _stream_delivered) the new or not use_slack_stream clause enters the overwrite and delivers the complete text, but _sole_delivery = _render_redacted and not _answer_reached is False on a clean render, so _answer_reached stays False and finalize calls _book_failure() — advancing the consecutive-failure breaker toward a session reset for a turn the reader fully received → Fix: _sole_delivery = (_render_redacted or not use_slack_stream) and not _answer_reached.

[OPUS-REVIEWED] 45a5ba9

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Aug 21, 2026
@jiapingzeng
jiapingzeng force-pushed the fix-slack-stream-truncation branch 2 times, most recently from c0021fb to 0c700f1 Compare August 21, 2026 17:25
@github-actions github-actions Bot removed the readiness: action required A blocking check or review needs attention label Aug 21, 2026
@chenmingwei23

Copy link
Copy Markdown
Contributor

Kiro Crew [operator: chenmingwei23#de330d0c]: Pushed 8cf0df9 addressing both GPT round-3 BLOCKING findings on 07f146b (both verified real):

  1. Wait boundary discarded ordinary trailing text (handler.py:3526): the round-2 unconditional _sred.reset() re-created the PR's own truncation bug at wait boundaries -- a clean reply ending in a credential-class run (a word, a number) lost its last token. Fix as prescribed: the boundary now renders the COMPLETE pre-wait text and gates on that verdict -- clean flushes the tail into the pre-wait message before it stops (no truncation); redacted resets (a stopped message has no overwrite to correct it). Same rule as the end-of-turn flush, one owner (_flush_sred_tail). New test test_clean_tail_flushed_into_pre_wait_message: fails on 07f146b ('The answer is ' + '42' + wait lost the 42), passes now; the two redacted-case wait tests still pass (verdict redacted -> reset).

  2. Failed retry silently lost the tail (handler.py:3017): _flush_sred_tail ignored the post-rotation retry result. Fix as prescribed: a failed retry sets use_slack_stream=False so the existing end-of-turn final-update fallback posts the complete text. New test test_flush_retry_failure_falls_back_to_final_update (append refuses the tail frame twice, rotation succeeds): fails on 07f146b (no complete-text update posted), passes now.

Module 189/189 green; isort/flake8/black gate pass (baseline intact). Single commit amended; head is now 8cf0df9.

@chenmingwei23
chenmingwei23 force-pushed the fix-slack-stream-truncation branch from 8cf0df9 to 73c920b Compare August 31, 2026 21:46
@chenmingwei23

Copy link
Copy Markdown
Contributor

Kiro Crew [operator: chenmingwei23#de330d0c]: Pushed 73c920b addressing the GPT round-4 BLOCKING finding on 8cf0df9 (verified real): a REDACTED pre-wait turn silently lost its safe trailing text -- the withheld tail was dropped and, worse, the already-streamed obfuscated credential stayed visible in the stopped message with nothing correcting it. Fix as prescribed: after stopping a redacted pre-wait stream, overwrite it with the complete redacted render via _safe_final_update -- the exact recovery the end-of-turn stop already uses -- so safe text survives and only credential spans are masked. New test test_redacted_pre_wait_turn_overwritten_not_truncated (fails on 8cf0df9, passes now). Module 190/190; isort/flake8/black gate pass, baseline intact.

Round table for this function span (each round a DIFFERENT cell of the clean/redacted x flush/overwrite space, none re-opened):

  • r1 (57491b2): end-of-turn flush could complete an obfuscated credential -> gate flush on the end-of-turn render verdict.
  • r2 (7d2cd30/07f146b): tail buffered before a wait leaked into the post-wait message -> resolve the tail AT the boundary.
  • r3 (07f146b/8cf0df9): unconditional boundary reset dropped CLEAN trailing text; flush retry result ignored -> verdict-gated boundary flush + non-stream fallback.
  • r4 (8cf0df9/73c920b): REDACTED boundary reset dropped safe trailing text and left the streamed obfuscated credential uncorrected -> overwrite the stopped message with the redacted render.

The state space is now fully covered: clean turns append the proven-safe tail (no truncation); redacted turns never append unverified bytes and always receive the complete redacted overwrite, at both the wait boundary and end of turn. If a further blocking finding lands in this span, we will escalate to the maintainer with this table rather than continue point-patching.

@chenmingwei23

Copy link
Copy Markdown
Contributor

Kiro Crew [operator: chenmingwei23#de330d0c]: STOPPING the automated fix loop on this PR per the consecutive-rounds rule -- GPT round 5 is the 5th consecutive blocking round inside the same ~40-line span (_flush_sred_tail + the wait boundary), and this round's advisory finding asks to REMOVE the wait-boundary flush that round 3's blocking finding required us to ADD. The reviewer is no longer converging on this span; a maintainer call is needed.

Round table:

  • r1 (57491b2): end-of-turn flush could complete an obfuscated credential -> gated the flush on the end-of-turn render verdict. FIXED.
  • r2 (7d2cd30): tail buffered before a wait leaked into the post-wait message -> resolve the tail at the boundary (GPT and Opus both prescribed reset). FIXED.
  • r3 (07f146b): the unconditional boundary reset dropped CLEAN trailing text (re-creating the PR's own truncation bug); the flush retry result was ignored -> verdict-gated boundary flush + non-stream fallback. FIXED as GPT prescribed.
  • r4 (8cf0df9): the REDACTED boundary reset dropped safe trailing text and left the streamed obfuscated credential uncorrected -> overwrite the stopped message with the redacted render. FIXED as GPT prescribed.
  • r5 (73c920b): BLOCKING: a clean pre-wait tail whose append AND rotated retry BOTH fail skips the fallback overwrite (it is gated on the redacted flag), truncating the reply. Real but a narrow double-failure edge. ADVISORY: remove the wait-boundary flush entirely -- the direct reversal of r3.

Assessment: r5's blocking finding is a genuine but progressively narrower edge (requires two consecutive Slack API append failures with a successful rotation in between, at a wait boundary, on a clean render). Each round has been a different cell of the state space and every prescribed fix so far came from the reviewer itself; r5 now points in two directions at once (extend the boundary overwrite vs delete the boundary flush).

Options for the maintainer:

  1. Approve extending the r4 overwrite to the double-failure case (one-line condition change: overwrite when the tail could not be delivered, not only when redacted). Smallest diff, keeps the r3 no-truncation guarantee.
  2. Rule that wait-boundary tail handling is out of scope for this PR: revert to the r2 state (reset at boundary, documented data-loss tradeoff) and file the truncation edge as a follow-up issue.
  3. Human review of the span as-is; /ai-review override gpt if the double-failure edge is judged acceptable residual risk for this fix.

The branch is NOT push-frozen; whoever picks an option can direct the next step. All other lanes are clean on this head (Design, First Principles, UX green; Opus round 4 was in flight at freeze). CI is fully green (two unrelated flakes -- test_sel Windows, test_safety_override 3.10 -- cleared on attempt-3 retry).

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 1, 2026
@bolichen97
bolichen97 disabled auto-merge September 3, 2026 21:29
@bolichen97
bolichen97 enabled auto-merge (squash) September 3, 2026 21:30
@bolichen97
bolichen97 force-pushed the fix-slack-stream-truncation branch from 73c920b to d9d3e43 Compare September 8, 2026 15:30
@bolichen97

Copy link
Copy Markdown
Contributor

Rebased onto main 9c2b4b6 by a maintainer as part of the 2026-09-08 open-PR audit (branch was 1019 commits behind). Old head 73c920b, new head d9d3e43.

Clean rebase, no conflicts. The end-of-turn flush site survived #9260's rewrite of _append_stream/_rotate_stream unchanged, and the diff is still +361/-6 in the same two files.

Gates run locally on the changed files only: isort pass, flake8 pass, pytest test/test_slack_handler.py 196 passed. black --check fails on one hunk of this PR's own code (_pre_wait_render should collapse to one line at 100 cols) - that was already failing on the old head, so it is left for you rather than silently edited.

Please review the rebase. A maintainer push makes the maintainer the last pusher, so a second approver is needed under the repo's last-push rule. Reply if anything looks wrong.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 8, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

Rebased onto current origin/main (17c96c7ab) and force-pushed as 33204aad7. The previous head 67d0e13fa (the maintainer rebase) had gone CONFLICTING; the PR is MERGEABLE again. Still 2 files, single commit on base, and every deleted line is one this PR deliberately rewrites — no upstream code dropped (symbol diff of ^def/^class between origin/main and HEAD is empty for both files).

Conflicts resolved

1. The wait boundary (handler.py) — main has since added two things here: a comment hold settled against the source before it is discarded (_resolve_comment_hold + an _append_stream of the release), and a try/except around stop_stream so a raising stop cannot fake a terminal error on a live turn. Both are kept, and the release is appended before the tail is settled so its bytes pass through _sred first. The PR's pre-wait render, _flush_sred_tail, and the redacted-render overwrite sit around main's now-guarded stop_stream.

2. The end-of-turn stop (handler.py) — main restructured this region substantially: the two former if use_slack_stream and stream_ts: blocks are now one block inside a try: that books the turn a delivery failure, with _answer_reached / _stream_delivered accounting and a try/except around stop_stream. Main's version was taken whole and this PR's one added line, await _flush_sred_tail(_render_redacted), re-inserted at its intended place — immediately after the stream_buffer append, before the stop.

Two follow-on fixes the restructure required

Both are integration with main's new shape, not changes to what this PR does.

  • _flush_sred_tail must not raise. Its docstring says it mirrors _append_stream, and main has since made _append_stream catch a raising append_stream (a raise is the same event as a refusal — the text is not on the stream). _flush_sred_tail still called slack.append_stream bare, and both its call sites now sit under the catch-all that posts "Something went wrong delivering the reply", so a rate-limited tail flush turned a delivered answer into a terminal error. This reddened main's own test_append_retry_raise_after_successful_rotation_still_delivers. Each append is now wrapped exactly as _append_stream wraps its own.

  • The tail-abandon case needs the final overwrite. At this PR's base, use_slack_stream = False from a failed flush was re-read by the second if use_slack_stream and stream_ts:, which fell through to the elif stream_ts: legacy _safe_final_update — that is how the complete text still reached the reader. Main merged the two blocks, so that re-read is gone and the flag no longer routes delivery anywhere. or not use_slack_stream is added to main's overwrite gate, which reproduces the base outcome with the same text (_convert_tables(clean_text)). This is what test_flush_retry_failure_falls_back_to_final_update asserts.

Tests

Interpreter-only run (no editable install on this host), -n0:

  • test/test_slack_handler.py — 210 passed, 0 failed. origin/main alone is 202 passed, so this PR's 8 new tests are the delta and nothing regressed.
  • Every other test file touching stop_stream / use_slack_stream / _stream_delivered / _book_failure, because the overwrite-gate change is on main's delivery path: test_credential_redaction_notice.py, test_review_mode.py, test_slack_backports.py, test_slack_golden_transcript.py, test_slack_handler_more_coverage.py, test_slack_mirror_unlink.py, test_slack_renderer.py, test_slack_success_after_delivery_10050.py, test_slack_transport_integration.py — 295 passed, 0 failed.

Gates: isort --check-only clean, flake8 clean, mypy src/kiro_crew/ clean (1673 files), scripts/check_black_formatting.py passes, scripts/check_comment_history.py passes against origin/main. handler.py is not in the black baseline, so it must be fully formatted; black's only complaint was one collapsible conditional on a line this PR adds, and applying it changed nothing else in the file.

Left open

Whether the flushed tail should additionally be sent as final_text on the stop call is not decided here — that is the reviewers' and author's call. This push is the minimal rebase: flush before stop, wire fields unchanged.

@iamwhatever

Copy link
Copy Markdown
Contributor

Pushed 62e693a74 (amend of 33204aad7, same rebase onto 17c96c7ab) addressing both GPT 5.6 blocking findings. Both were on the seams where this PR meets main's restructured delivery accounting, and both are mechanical — nothing about what the PR does changed.

F1 — handler.py:3540, tail-only replies booked as failures. Upheld and fixed. _flush_sred_tail declared nonlocal _stream_had_redaction, use_slack_stream and omitted _stream_delivered, which main's finalize reads as _answer_reached. For a reply that is entirely a credential-class run (a bare word, a number) every streamed delta is withheld as a possible partial credential and returns early without confirming, so the flush is the only append that lands text — the reader got the answer while the turn was booked a delivery failure. _stream_delivered is now in the nonlocal and set when the tail append succeeds, on the same rule _append_stream uses.

F2 — handler.py:4251, a lost pre-wait tail stays truncated. Upheld and fixed. The wait-boundary overwrite was gated on _pre_wait_redacted alone, so on the clean path a tail that landed on neither the append nor its rotated retry left the wire copy truncated with nothing behind it: the message is stopped just below and accumulated resets, so no later render verdict covers those bytes. The gate now also fires when the flush dropped out of stream mode (_pre_wait_tail_lost), overwriting with the complete pre-wait render — the same recovery the redacted verdict already had, and symmetric with the or not use_slack_stream gate at end-of-turn.

Non-blocking finding — handler.py:3392. Fixed. The _sred comment still claimed the tail is "Never flushed at the mid-turn wait boundary", which this PR's own wait-boundary flush contradicts. It now describes the actual rule: the boundary settles the tail against its own complete pre-wait text, clean appends, redacted resets and overwrites.

Red-before

Both fixes are pinned by new tests, and both tests were confirmed to FAIL with only the two behaviour changes reverted (tests kept in place):

  • test_tail_only_reply_is_not_booked_a_delivery_failure — a one-chunk 42 reply; asserts the flush delivered it, record_failure was never called, and no terminal error text reached the thread.
  • test_lost_pre_wait_tail_overwrites_the_stopped_message — a clean pre-wait tail refused on both attempts; asserts an update carrying the complete Result: 12345.

Verification on this head

  • test/test_slack_handler.py plus every other file touching stop_stream / use_slack_stream / _stream_delivered / _book_failure — 507 passed, 0 failed (-n0).
  • isort, flake8, mypy src/kiro_crew/ (1673 files), scripts/check_black_formatting.py, scripts/check_comment_history.py against origin/main — all clean.
  • Single commit on base, 2 files, and all 7 deleted lines are ones this change rewrites; ^def/^class symbol diff against origin/main is empty for both files.

The previous head was 82 checks passing with GPT the only blocking lane, so this push carries only the two findings above.

The final_text question is still untouched and still the author's and reviewers' to decide.

@iamwhatever

Copy link
Copy Markdown
Contributor

Stopping the automated fix loop here and handing back. The rebase itself is done and sound: on 62e693a74 the PR is MERGEABLE against 17c96c7ab with 82 checks passing, 11 skipped, and GPT 5.6 Review the only real failure (PR Readiness just follows it). Everything below is about that one lane.

Why I am not pushing a third round

Round 1's two blocking findings were on the code the rebase itself had to add. Round 2's F1 is on the line I added to fix round 1's F2. That is the compounding shape this PR already hit once — an earlier operator stopped the automated loop here after four such rounds — and both remaining findings are security-class fenced, which the lane itself says adjudication cannot clear:

The security fence keeps these findings blocking regardless of adjudication; the only clearance path is a human override recorded by a repository writer, who must independently verify a rationale before recording it.

So a machine cannot clear these, and I am not recording an override on a security-class finding on my own reading. Both also sit on the PR's design rather than on the rebase.

F2 — handler.py:4260, pre-wait render truncation. This is main's own behaviour.

The flagged line is this PR's original render_one_for_slack(accumulated, keep_tables=True), and the concern is that its 39,000-char truncation is fed into the split-capable _safe_final_update. Main does exactly this on every turn:

  • origin/main:src/kiro_crew/slack/handler.py:4643 — _render = render_one_for_slack(_body_text, keep_tables=actually_streamed), default limit=SLACK_MAX_TEXT.
  • That render becomes final_text → clean_text, which is what main hands to both stop_stream and its own _safe_final_update redaction overwrite.

So the wait-boundary overwrite reuses main's established pattern verbatim — deliberately, per its comment ("the same recovery the end-of-turn stop uses"). Raising the limit only at the wait boundary would make this PR's recovery diverge from the end-of-turn path it is modelled on, and where Slack splitting should sit is a design call for this repo, not a rebase decision. If the truncation is wrong it is wrong main-wide and belongs in its own change.

F1 — handler.py:5004, or not use_slack_stream. Adjudicator flagged it as acceptable residual.

This is a line I added during the rebase, and the adjudicator's own note is the clearest statement of its size:

Reaching the session reset requires five consecutive tail-only replies that each doubly-fail the flush yet succeed on the final update with no success between (self-correcting on any success), so a human would plausibly accept the residual risk.

The suggested fix — make the fallback update raise on primary failure and set _answer_reached = True — extends main's delivery accounting, which is outside a rebase.

Worth noting for whoever picks this up: main now documents the doubly-failed append as accepted delivery debt ("A delta that failed both the append and the post-rotation retry is not re-delivered … tracked as its own issue"). This PR's _flush_sred_tail instead invents a stronger recovery for its own tail — abandon streaming, force an overwrite — and that extra machinery is what produced round 1's F2 and round 2's F1. Cutting it to match main's accepted policy would delete both findings and shrink the diff, but it also drops test_flush_retry_failure_falls_back_to_final_update and changes what the PR does, so it is the author's and reviewers' call, not mine.

What is needed

Either a repository writer independently verifies and records /ai-review override gpt 62e693a74d2b593c5f35e9c64a1672dee781f9d4: <reason>, or the author decides which of the two design questions above to settle — whether the wait-boundary recovery keeps main's render limit, and whether the tail flush keeps its stronger-than-main recovery.

Also still open and still untouched: whether the flushed tail should be sent as final_text on the stop call.

One non-blocking finding still outstanding

handler.py:3529 — the _flush_sred_tail docstring still says a stopped message "has no overwrite to correct it", which the wait-boundary overwrite added for round 1's F2 now contradicts. It arrived after this push, so it is not fixed here; it is comment-only and costs nothing to fold into whichever push settles the two questions above. Round 2's sibling stale line at :3392 ("Never flushed at the mid-turn wait boundary") IS corrected in this head.

@iamwhatever

Copy link
Copy Markdown
Contributor

Both fenced findings dispositioned — I built the fix for F1 and then deleted it

I tried to fix F1 exactly as suggested, proved it worked, and then removed it because it silently overturns a main-owned accounting invariant protected by an issue-specific regression test. Details below so the next reader does not rebuild it.

No code change is pushed: this head is unchanged.

F1 handler.py:5004 — "Successful fallback delivery is recorded as failure" (adjudicated FLAG)

Real, and the mechanism is as described: on a strictly tail-only reply (one whose whole body is a credential-class run, e.g. a bare number), no streamed delta confirms anything, so if the tail flush's append and its rotated retry both fail, use_slack_stream drops, the end-of-turn overwrite delivers the complete text, and _answer_reached stays False — the turn books a failure for an answer the reader received.

The suggested fix is the right shape and I implemented it: pass raise_on_primary_failure=True when that overwrite is the sole delivery, and set _answer_reached = True when it returns — which is exactly the rule main's own legacy elif stream_ts: branch already applies to the same situation. It works, and I pinned it red-before.

Why it is not here. It makes two main-owned tests fail, both asserting the opposite rule:

  • test_slack_handler.py::test_append_retry_raise_after_successful_rotation_still_delivers
  • test_slack_success_after_delivery_10050.py::test_native_stream_all_appends_refused_books_failure — "booked success for a stream that delivered no answer text"

That second file is a regression suite for a specific shipped fix to turn-success accounting. Its invariant ("no append landed → the turn is a failure") and the author's fallback ("the abandoned-stream update posts the complete text") cannot both hold once the fallback actually reaches the reader. Choosing between them is a product decision about the session failure breaker, not something this PR — whose purpose is stopping a streamed reply from losing its last word — should decide by editing an issue's regression test.

So the conservative accounting stays: the bytes reach the reader, and the verdict stays pessimistic. The adjudicator's own note bounds the residual — the breaker resets a session only at 5 consecutive failures and any successful turn zeroes the counter, so reaching a reset needs five straight bare-token replies each doubly-failing the flush while the final update succeeds.

Suggested clearance:

/ai-review override gpt 62e693a74d2b593c5f35e9c64a1672dee781f9d4: Fixing this requires overturning the turn-accounting invariant that test_slack_success_after_delivery_10050.py protects (no append landed -> failure), a product decision outside this PR; the residual needs five consecutive bare-token replies that each doubly-fail the tail flush yet succeed on the final update, and any successful turn zeroes the breaker.

F2 handler.py:4260 — "Pre-wait overwrite truncates long responses" (adjudicated UPHOLD-FENCED)

Real, and I reproduced the loss directly: a 58,357-char body containing a credential renders to exactly 39,000 chars, redacted=True, and the end marker is gone before any update call — render_one_for_slack truncates and appends the "…truncated (N chars total)" notice, so the bytes are already absent from the value handed on to the split-capable _safe_final_update.

This is not introduced by this PR, and not by the author. The identical pattern is on base at the end-of-turn site, untouched here:

base handler.py:4643  _render = render_one_for_slack(_body_text, keep_tables=actually_streamed)
base handler.py:4644  final_text = _render.text or _NO_RESPONSE
base handler.py:4656  clean_text = final_text          -> fed to _safe_final_update

The author's pre-wait branch mirrors that exactly. So a >39,000-char redacted reply already loses its suffix at end of turn on main, with no mid-turn wait involved.

Fixing only the pre-wait site would make the two boundaries disagree and leave the base site losing the same bytes; fixing both is a change to the product's render ceiling, which is a separate PR with its own evidence. I would rather file that than smuggle it in here.

If you agree it belongs elsewhere:

/ai-review override gpt 62e693a74d2b593c5f35e9c64a1672dee781f9d4: The truncate-then-split-capable-update pattern is base behaviour at the end-of-turn site (handler.py:4643-4656 on base), so a >39,000-char redacted reply already loses its suffix on main without any wait boundary; the pre-wait branch mirrors it rather than adding it, and lifting the render ceiling belongs in its own change.

Only one /ai-review override gpt <sha> is needed to clear the lane; the reasons for both findings are above.

The two advisory CONCERNS are correct — the description is stale

Design Review and First Principles both flag that the description says the mid-turn wait boundary "never flushes" while the diff flushes there and overwrites the stopped message. They are right, and it is the author's original wording. The shipped rule is: at the wait boundary a clean tail is appended into the pre-wait message; a redacted verdict drops the tail and the stopped message is overwritten with the complete redacted render. Also undeclared: a landed tail now raises _stream_delivered, so a tail-only reply is no longer booked a delivery failure. I have not edited the description, since that is the author's record to correct and a body edit would not re-run the lanes that flagged it.

@iamwhatever

Copy link
Copy Markdown
Contributor

/ai-review override gpt 62e693a: Both fenced findings verified at this head. F1's fix flips two main-owned tests (test_native_stream_all_appends_refused_books_failure, test_append_retry_raise_after_successful_rotation_still_delivers): StreamRedactor withholds a tail even for plain text, so both DO reach the tail-abandon branch and assert no-append-landed => failure -- a product decision. F2's truncate-then-_safe_final_update pattern is base behaviour (handler.py:4643,4656,4869). Residual accepted by the maintainer.

Recording this after checking both fenced findings against the code at this head. One of my own working hypotheses was wrong and the check is what caught it, so both are written out.

F1 handler.py:5004 — the accounting collision is real

I first suspected the disposition was overstating it. The PR's added condition is or not use_slack_stream, so a fix could plausibly be scoped to that branch alone, and the two tests the disposition names both drive ordinary text ("the answer is 42" / "The answer is 42") with no credential — no _render_redacted, no _stream_had_redaction. If use_slack_stream stayed True in them, they would never enter the new block and a narrowly-scoped fix would be free.

It does not stay True, and the reason is StreamRedactor's safety cut. Phase A walks the buffer back over trailing _CRED_CLASS characters, and digits are in that class, so ordinary text leaves a withheld tail:

chunk fed feed() emits flush() tail
The answer is 42 The answer is 42
the answer is 42 the answer is 42
hello world hello world

So _flush_sred_tail has a non-empty tail in both tests. _AllAppendsRefusedSlack refuses every append and AlwaysRaisingAppendSlack raises on every append; MockSlackClient.start_stream succeeds on rotation (neither sets _start_stream_fails), so rotation lands, the retry fails again, and use_slack_stream = False (handler.py:3580). Both tests therefore DO reach the tail-abandon branch, and both assert success == 0, failure == 1. There is no narrower scoping available — the tests' scenario is the tail-abandon scenario.

Main also holds the opposite rule on the sibling arm: test_transport_stream_all_appends_refused_but_fallback_delivers_stays_success asserts "the fallback chat.update delivered the answer, so the turn is a success". The native and transport arms genuinely disagree, and picking one is a product decision about the consecutive-failure breaker, not something a PR about a dropped stream tail should settle by editing an issue's regression suite. The residual is bounded as the adjudicator described: the breaker trips only at 5 consecutive failures and any successful turn zeroes it.

F2 handler.py:4260 — base behaviour, verbatim, including the redaction gate

Confirmed on the PR's base (0140fdd57), not inferred from the diff:

  • render_one_for_slack hard-truncates at SLACK_MAX_TEXT = 39_000 and appends the "…truncated (N chars total)" notice (format.py:16, format.py:934-941).
  • handler.py:4643 renders into _render, 4644 takes _render.text, 4656 assigns clean_text.
  • handler.py:4867 gates on _stream_had_redaction or _render_redacted or exfil_warnings or cred_warnings and feeds that already-truncated clean_text into _safe_final_update (base handler.py:4869), which is itself pre-existing and split-capable (base handler.py:6092, and the comment at 6081 says so).

So on main today a >39,000-char redacted reply loses its suffix at the end-of-turn overwrite, with no mid-turn wait anywhere in it, under the same redaction condition the finding names. The pre-wait branch mirrors that site rather than adding the loss. Fixing only the pre-wait site would leave the two boundaries disagreeing while base keeps losing the same bytes; lifting the render ceiling is its own change with its own evidence.

Clearing the lane on this head. Both residuals are accepted as maintainer decisions, not as refutations of the findings — F1 is real and F2 is real; neither is introduced by this PR's own code.

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded

@iamwhatever marked the gpt AI finding as false positive, not applicable, or explicitly accepted for 62e693a74d2b593c5f35e9c64a1672dee781f9d4.

Both fenced findings verified at this head. F1's fix flips two main-owned tests (test_native_stream_all_appends_refused_books_failure, test_append_retry_raise_after_successful_rotation_still_delivers): StreamRedactor withholds a tail even for plain text, so both DO reach the tail-abandon branch and assert no-append-landed => failure -- a product decision. F2's truncate-then-_safe_final_update pattern is base behaviour (handler.py:4643,4656,4869). Residual accepted by the maintainer.

This decision applies only to this commit. A new push requires a new judgment.

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded, but the following reviewer lane(s) could not be re-run automatically: GPT 5.6. Re-run the lane's latest workflow run for 62e693a74d2b593c5f35e9c64a1672dee781f9d4 manually from the Actions tab.

@jiapingzeng

Copy link
Copy Markdown
Author

Hi team, this issue is still present on the latest version. Please let me know what I need to do to get this PR to merge as the LLM reviews on this repo seem unreliable. I have verified on my local fork that this PR fixes the bug.

Before:
Screenshot 2026-09-28 at 7 49 28 PM

After:
Screenshot 2026-09-28 at 8 28 53 PM

@github-actions

Copy link
Copy Markdown
Contributor

Security Scope Review (fork) — 🔴 BLOCK (blocking)

Which legitimate operations does dabf967138bd15104126f86948fc9fa72915a64f newly refuse? Model proposes, scripts/deny_diff.py decides — updated in place on each push. A script-confirmed regression blocks PR readiness.

no leg reported, and this was not the nothing-to-adjudicate short circuit

Scope-Verdict: CONCERNS

TIGHTENING: the Slack stream-tail disclosure rule in _flush_sred_tail (src/kiro_crew/slack/handler.py) — the withheld credential-class tail is now dropped from the append wire whenever the full-text render verdict is redacted, at three boundaries (end of turn, wait, pre-task-card): "when that render redacted anything the tail is dropped and the guaranteed final overwrite posts the complete redacted text instead — an appended frame is visible the instant it lands, so 'overwritten later' is not a defense" (if render_redacted: _sred.reset(); return). The ONE threat it refuses: an appended tail frame completing a credential or exfil URL whose ANSI/zero-width-obfuscated prefix already streamed raw — visible and capturable the instant it lands, unrecallable by the later _safe_final_update overwrite.

ADJUDICATED: 10 candidates, 0 confirmed newly-refused
No confirmed rows were handed back for this run. The adjudicated surface is consistent with that: the diff's only edit under src/kiro_crew/security/ is a read-only has_pending property on StreamRedactor — no path fence, sensitive-command tier, exfiltration shape, or rule-catalog pattern changes between df0ea79 and dabf967, so the shell composite's classifications should be identical at both refs. The candidates probe the touched area's real maintenance operations (Slack-handler test runs in both platform spellings, path-scoped log/diff naming the governance tree, read-only greps for the redaction tag and the documented AWS example-key fixture) as the sanity net for that claim.

PLATFORM COVERAGE: posix (interpreter path .venv/bin/python, ls, grep, git grep rows over the touched packages), windows (.venv\Scripts\python.exe test lane, Get-ChildItem listing — the two spellings whose loss the corpus documents as the lock-in mode), and any (path-scoped git log/git diff rows). The diff itself makes no path, separator, argv, interpreter, or environment-variable assumption — its assumptions are about in-message text encodings (ANSI escapes, zero-width characters), which are host-neutral — so no assumed platform lacks a candidate. Per-leg verdicts are the deterministic fold's to report, not mine.

UNADJUDICATED: The tightening does not live in the tool-call deny composite at all; the classifier can attest nothing about it, and the zero-confirmed adjudicated set above is NOT evidence for this guard. The guard: _flush_sred_tail(render_redacted) plus the pre-tool-card gate if _sred.has_pending and accumulated and not _is_wait and the wait-boundary verdict _pre_wait_redacted. The call path an input takes: LLM text_chunk events → _sred.feed() withholds the trailing credential-class run from append_stream → at end-of-turn, wait, or a tool's task card, render_one_for_slack(_visible_segment_text(accumulated)).redacted decides whether the tail is appended (clean) or dropped/withheld (redacted), with the dropped case recovered by the guaranteed _safe_final_update overwrite of the complete redacted text. The candidate legitimate inputs I would have submitted, had a classifier existed for this surface: a reply ending in a credential-class run ("The answer is 42" before a wait); a reply that is entirely one such run ("42", where the tail flush is the only delivery and must not book a failure); a clean tail arriving just before a task card; a redacted turn whose SAFE trailing text must survive via the overwrite; a pre-wait tail whose append is refused twice. The PR's own new tests exercise each of these and assert the legitimate text reaches the reader. Two narrowings I can argue but not confirm, hence the verdict: (1) the drop rule keys on the render verdict over the WHOLE accumulated turn, so any redaction anywhere — e.g. one legitimately-masked URL early in a long reply — suppresses a wholly-unrelated clean tail's append; the text is not lost (the overwrite carries it) but live-wire delivery of the tail degrades to edit-time for every partially-redacted turn. (2) At the pre-task-card boundary a redacted verdict leaves the tail withheld rather than settled, so on a turn that redacts early and then runs many tools, trailing text lags one boundary behind until a clean verdict or end-of-turn settles it. Both are delay-not-loss by construction, which is why neither is claimed as a regression.

[SCOPE-REVIEWED] dabf967

Slack's stop_stream ignores final_text, so the StreamRedactor's withheld
tail was silently dropped at end-of-turn, truncating the visible reply.
Flush it as an append frame -- but ONLY when the end-of-turn full-text
render proved the turn clean. When that render redacted anything, a
flushed tail could complete a display-obfuscated credential whose prefix
already streamed (the per-chunk redactor does not normalise ANSI or
zero-width obfuscation), and an appended frame is visible and capturable
the instant it lands -- the later overwrite cannot recall it. In that
case the tail is reset and the guaranteed _safe_final_update overwrite
posts the complete, fully-redacted text, so nothing is lost.

The mid-turn wait boundary never flushes: that message is stopped and
never re-rendered, so a leak there would be final.

Original fix authored by Jiaping Zeng (@jiapingzeng); hardened per the
GPT 5.6 review finding on the prior head (a redacted-render tail flush
could briefly stream a credential before the final overwrite corrected
it).

Co-authored-by: Kiro Crew <noreply@kirodotdev.github.io>
@iamwhatever

Copy link
Copy Markdown
Contributor

Thank you for this fix, @jiapingzeng — the diagnosis is right: the stream can stop before the withheld StreamRedactor tail is settled, and the "stop_stream supersedes the held tail" assumption does not hold.

Since this PR was opened, main moved the Slack streaming path out of handle_message into a StreamController class (src/kiro_crew/slack/handler_runtime/stream.py), so the inline _sred / _flush_sred_tail patch here no longer applies to the current code. The underlying bug still exists on main (the controller never flushes or resets the redactor at seal()), so I've opened #16984 to track it against the new structure. Your work and reasoning carried directly into that issue.

Copy link
Copy Markdown
Contributor

Open-PR triage (2026-10-05) — #4762

I read the full diff at head ca033fff5 against its merge base df0ea7909 and compared it with current origin/main (af1eb612d).

1. Needs a port, not a rebase. #16908 (merged 2026-10-05) moved the native Slack streaming path out of handle_message into StreamController (src/kiro_crew/slack/handler_runtime/stream.py). This PR's _flush_sred_tail, its call sites (pre-task-card, wait, end of turn) and _visible_segment_text all target code that is no longer on main, so the PR now conflicts (mergeable_state: dirty). The bug is still on main: StreamController.append() feeds self.redactor, but nothing calls redactor.flush() before on_tool_call's wait stop_stream or before seal(), and SlackClient.stop_stream still never sends final_text. Issue #16984 tracks this. Please re-implement the fix against StreamController.finish()/seal()/on_tool_call() rather than resolving conflicts in handler.py.

2. Credential-disclosure finding still applies to this head (open, not new). I checked the GPT 5.6 blocking finding against ca033fff5, and it holds. The error arms (except AcpError → accumulated = f"❌ {e}", plus AcpPromptBusy, UnknownMemoryStore and timeout) replace accumulated but never call _sred.reset(). The end-of-turn render then runs over the error text, comes back clean, and await _flush_sred_tail(_render_redacted) appends the stale withheld tail from the pre-error stream. That tail is exactly the ANSI/zero-width-split credential suffix this PR's gating exists to keep off the wire. The port should reset the redactor (or pass a had_error verdict) on every error/replacement path before the tail is settled. The design review's tool-card concern also needs a test or a flag: a redacted→clean verdict flip drops the tail with no overwrite.

3. Overlap with #10192 (merge discussion). #10192 (pako links) also adds a withheld-tail flush before stop_stream, via _append_stream("", flush=True) at the wait boundary and at end of turn. Its flush is unconditional, while this PR gates it on the full-text render verdict. Same mechanism, different scope, and both are now stale against StreamController. Whichever lands first should own the tail-settling rule, so the other doesn't ship a second, weaker variant.

Recommendation: keep open / continue development (port onto StreamController, closing #16984). This is not a duplicate and is not superseded.

@bolichen97 bolichen97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P0] Error arms flush the redactor's withheld credential tail to Slack

Class: Redaction bypass (credential leak to Slack).

Mechanism: On the error arms the reply text is replaced but the stream redactor's withheld tail is not reset. The end-of-turn render then reads only the error text, reports clean, and the new tail flush appends the withheld, unredacted tail to the Slack stream.

User impact: A credential the redactor was holding back can reach the Slack thread when a turn ends in an error.

Location: src/kiro_crew/slack/handler.py:5454 @ ca033fff5c58e2081f53aabb5d458a2a0423f06e

Minimum fix: Do not treat the error-text render as proof the tail is clean: drop or reset the withheld tail on every error / replacement arm (e.g. _flush_sred_tail(_render_redacted or _had_error)).

How to verify: A handler test that streams a split secret, then raises AcpError (and AcpPromptBusy), and asserts the secret is absent from all streamed frames. It fails on this head and passes after the fix.

Exploit details are left out on purpose. They are available to maintainers through the repo's private security reporting.

Independently re-verified on head ca033fff5c with a focused local reproduction.

if stream_buffer:
stream_buffer, _ = strip_thinking_tags(stream_buffer, strip_whitespace=False)
await _append_stream(stream_buffer)
await _flush_sred_tail(_render_redacted)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P0] Error arms flush the redactor's withheld credential tail to Slack — see the review summary for mechanism, fix and test.

@bolichen97

Copy link
Copy Markdown
Contributor

Thanks for this. The Slack stream code moved into slack/handler_runtime/stream.py after this branch was cut, so the same change is now carried there in #17897.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor) merge conflict Branch has merge conflicts with its base — author must resolve before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants