Skip to content

fix(hooks): preserve usage records at transcript tail boundaries - #3657

Merged
haelyra merged 1 commit into
affaan-m:mainfrom
CandyK1sses:fix/transcript-tail-boundary
Oct 29, 2026
Merged

haelyra merged 1 commit into
affaan-m:mainfrom
CandyK1sses:fix/transcript-tail-boundary

Conversation

@CandyK1sses

@CandyK1sses CandyK1sses commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What Changed

Preserve complete usage records at the beginning of the requested transcript tail. readLatestContextTokens() reads one preceding byte to distinguish a newline boundary from a partial record. The optional raw byteLength result from readFileTail() keeps that decision correct when a transcript ends with unfinished UTF-8; existing callers retain the same default result shape.

Add six reader regressions, two raw-byte reader checks, and a real suggest-compact hook regression. Include an Unreleased changelog entry.

Why This Change

Previously, any truncated tail unconditionally discarded its first line. If a complete assistant usage record begins exactly at the default 256 KiB boundary and later records contain only tool results, context detection returns null and the strategic-compact reminder never fires—even at 170,000 tokens.

The boundary-aligned regressions fail before the change. With this fix the same transcript emits hookSpecificOutput.additionalContext containing Context ~170k tokens. Partial and out-of-window records remain excluded.

Testing Done

  • Reproduced the missing usage result before applying the fix.
  • Targeted reader and hook suites: 102 passed, 0 failed.
  • Coverage for the two affected modules: 99.01% lines, 92.38% branches, 100% functions; both modules individually exceed 80%.
  • ESLint on all changed JavaScript files: no errors; the existing large hook-test runner retains its complexity warning.
  • Markdownlint for CHANGELOG.md and git diff --check passed.
  • Independent review passed after fixing its incomplete-UTF-8 finding; the reviewer also exercised UTF-8 cuts, CRLF, missing final newlines, and file-size boundaries.
  • Full npm test is green: the final-tree parallel run reported 8,854 passed / 2 failed across 428 files. The two failing installation suites both passed on isolated reruns: repo-scan-install 38/38 and setup 30/30; the parallel setup failure was a subprocess ETIMEDOUT. An earlier run while the source was still changing reported 8,887 passed / 2 failed (install-executor and install-apply), which also passed individually, 26/26 and 48/48. All validators passed. A clean full-suite run is not claimed; hosted CI remains the full integration check.

Type of Change

  • fix: Bug fix

Security & Quality Checklist

  • No secrets, credentials, or personal paths added.
  • Existing reader result shape is preserved unless raw byte metadata is requested.
  • Conventional commit format.
  • No dependency, registry, or generated catalog changes.

Documentation

  • Updated CHANGELOG.md and comments explaining the byte-boundary handling.

@CandyK1sses
CandyK1sses requested a review from affaan-m as a code owner October 21, 2026 07:07
@ecc-tools

ecc-tools Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

ECC Tools / Security Evidence

Commit: db29f112ffe807fd272626ee9723c1866438636f

Security scanner evidence required (action_required)

Detected 1 security-sensitive predictive risk signal(s) without scanner evidence.

Mode: enforce

Findings:

  • Security-sensitive changes may ship without scanner evidence: The PR touches billing, secrets, auth, webhooks, agent, or CI-sensitive surfaces without adding obvious security scanner, code scanning, or security-focused validation evidence. (1 security-sensitive paths changed; 0 security scanner or security-focused validation artifacts changed)

Touched security-sensitive paths:

  • tests/hooks/suggest-compact.test.js

Expected evidence:

  • Security scanner, code scanning, secret scanning, dependency/security review, or focused security regression output.
  • SARIF/code-scanning upload or equivalent pass/fail gate for the changed surface.

Check publication was denied or unavailable. An app owner must enable Checks: read and write, and the installation owner must approve the updated permission.

@ecc-tools

ecc-tools Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

ECC Tools / PR Risk Taxonomy

Commit: db29f112ffe807fd272626ee9723c1866438636f

PR taxonomy review recommended (neutral)

Detected 2 PR taxonomy bucket(s): Security Evidence, CI/CD Recommendation.

Scanned 6 changed file(s).

Roadmap taxonomy buckets:

Security Evidence

Security-sensitive changes should carry explicit scanner, code-scanning, or focused regression evidence.

Signals:

  • Security-sensitive changes may ship without scanner evidence
  • 0 security-sensitive path(s) changed

Paths:

  • CHANGELOG.md
  • scripts/lib/file-tail.js
  • scripts/lib/transcript-context.js

CI/CD Recommendation

CI, dependency, coverage, and contract signals should be routed into follow-up checks or verification work.

Signals:

  • 3 CI or workflow path(s) changed

Paths:

  • tests/hooks/suggest-compact.test.js
  • tests/lib/file-tail.test.js
  • tests/lib/transcript-context.test.js

Check publication was denied or unavailable. An app owner must enable Checks: read and write, and the installation owner must approve the updated permission.

@ecc-tools

ecc-tools Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

ECC Tools / Reference Set Readiness

Commit: db29f112ffe807fd272626ee9723c1866438636f

Reference set readiness gaps detected (neutral)

Reference evidence present for 0/7 areas (0%) across 6 changed file(s).

This check is based on files changed in this PR. Repository-level readiness is still reported by /ecc-tools analyze comments and generated manifests.

Area Status Evidence / Next Step
Deep analyzer corpus Missing Add analyzer fixture, golden, benchmark, or reference-set files that can catch analyzer regressions.
RAG/evaluator comparison Missing Add retrieval or evaluator reference-set comparison fixtures with expected ranking behavior.
PR salvage/review corpus Missing Add stale-PR, review-thread, reopen-flow, or salvage reference cases for queue cleanup automation.
Discussion triage corpus Missing Add public discussion triage fixtures, golden cases, or reference sets for informational, answered, and no-response classifications.
Harness compatibility Missing Add cross-harness, adapter-compliance, or harness-audit evidence for Claude, Codex, OpenCode, Zed, dmux, and agent surfaces.
Security evidence Missing Attach security evidence such as SBOMs, SARIF, audit reports, or AgentShield evidence packs.
CI failure-mode evidence Missing Add captured CI failure logs, dry-run fixtures, or troubleshooting docs for common workflow failure modes.

Check publication was denied or unavailable. An app owner must enable Checks: read and write, and the installation owner must approve the updated permission.

@ecc-tools

ecc-tools Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

ECC Tools / Hosted Promotion Readiness

Commit: db29f112ffe807fd272626ee9723c1866438636f

Hosted promotion readiness passed (success)

No hosted promotion evidence gaps detected across 6 changed file(s); 0 corpus scenarios had matching evidence.

This check compares PR file changes against the evaluator/RAG promotion corpus in src/analyzers/fixtures/evaluator-rag-corpus.ts.
Hosted output scoring inspected 0 completed cached hosted job results.

No evaluator corpus scenarios matched this PR.

Check publication was denied or unavailable. An app owner must enable Checks: read and write, and the installation owner must approve the updated permission.

@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: affaan-m/ECC/.coderabbit.yaml
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 2113eb54-56fd-40e1-9ea1-c9a38c4c1cc1
📥 Commits

Reviewing files that changed from the base of the PR and between 90606c8 and db29f11.

📒 Files selected for processing: 6
  • CHANGELOG.md
  • scripts/lib/file-tail.js
  • scripts/lib/transcript-context.js
  • tests/hooks/suggest-compact.test.js
  • tests/lib/file-tail.test.js
  • tests/lib/transcript-context.test.js

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📜 Recent review details
⏰ Context from checks skipped due to timeout: 1
  • GitHub Check: Greptile Review
🧰 Additional context used
📚 Code guidelines: 5
.cursor/rules/typescript-security.md — auto-discovered
.cursor/rules/common-hooks.md — auto-discovered
.cursor/rules/typescript-coding-style.md — auto-discovered
.claude/rules/node.md — auto-discovered
.cursor/rules/typescript-hooks.md — auto-discovered
📓 Path-based instructions: 6
Focus on command injection, unsafe subprocess usage, path traversal, SSRF, secret exposure, and missing tests for new CLI behavior.

⚙️ CodeRabbit configuration file

Files:

  • scripts/lib/file-tail.js
  • scripts/lib/transcript-context.js
Source excerpt: Source excerpt: Use **security-reviewer** skill for comprehensive security audits

📄 CodeRabbit inference engine (.cursor/rules/typescript-security.md)

Files:

  • tests/lib/file-tail.test.js
  • tests/hooks/suggest-compact.test.js
  • scripts/lib/file-tail.js
  • tests/lib/transcript-context.test.js
  • scripts/lib/transcript-context.js
Source excerpt: Use with caution: Source excerpt: Use with caution: Enable for trusted, well-defined plans Source excerpt: Use with caution: Disable for exploratory work Source excerpt: Use with caution: Never use dangerously-skip-permissio...

📄 CodeRabbit inference engine (.cursor/rules/common-hooks.md)

Files:

  • CHANGELOG.md
  • tests/lib/file-tail.test.js
  • tests/hooks/suggest-compact.test.js
  • scripts/lib/file-tail.js
  • tests/lib/transcript-context.test.js
  • scripts/lib/transcript-context.js
Source excerpt: Use spread operator for immutable updates: Source excerpt: Use async/await with try-catch: Source excerpt: Use Zod for schema-based validation: Source excerpt: Use proper logging libraries instead

📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)

Files:

  • tests/lib/file-tail.test.js
  • tests/hooks/suggest-compact.test.js
  • scripts/lib/file-tail.js
  • tests/lib/transcript-context.test.js
  • scripts/lib/transcript-context.js
Source excerpt: New scripts in `scripts/lib/` require a matching test in `tests/lib/`

📄 CodeRabbit inference engine (.claude/rules/node.md)

Files:

  • scripts/lib/file-tail.js
  • scripts/lib/transcript-context.js
Source excerpt: **console.log audit**: Check all modified files for `console.log` before session ends

📄 CodeRabbit inference engine (.cursor/rules/typescript-hooks.md)

Files:

  • CHANGELOG.md
  • tests/lib/file-tail.test.js
  • tests/hooks/suggest-compact.test.js
  • scripts/lib/file-tail.js
  • tests/lib/transcript-context.test.js
  • scripts/lib/transcript-context.js
🪛 ast-grep (0.45.3)
tests/lib/file-tail.test.js

[warning] 59-59: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.writeFileSync(incomplete, Buffer.from([0xe4, 0xb8]))
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename)

tests/hooks/suggest-compact.test.js

[warning] 722-722: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.readFileSync(transcript, 'utf8')
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename)

[warning] 727-727: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.writeFileSync(transcript, '{}\n' + usageLine + paddedResult + '\n')
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename)

[warning] 736-736: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.readFileSync(ctx.bucketFile, 'utf8')
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename)

tests/lib/transcript-context.test.js

[warning] 189-192: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.writeFileSync(file, Buffer.concat([
Buffer.from(record + 'x'.repeat(padding)),
Buffer.from([0xe4, 0xb8])
]))
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename)

📝 Summary

Summary by CodeRabbit

  • Bug Fixes
    • Improved context-size detection near transcript boundaries so complete usage records are retained.
    • Context reminders now trigger reliably when usage reaches the relevant threshold, including records positioned at the transcript-tail boundary.
    • Partial or incomplete transcript records continue to be excluded, preventing inaccurate context estimates.

readFileTail can report raw byte length. Transcript context parsing uses the extra boundary byte to retain complete usage records and exclude partial records. Tests cover boundary handling and the resulting context reminder.

Changes: Transcript Tail Handling

Layer / File(s) Summary
Tail byte-length reporting
scripts/lib/file-tail.js, tests/lib/file-tail.test.js
readFileTail accepts an option to include raw byte length in successful results. Tests cover empty files and incomplete UTF-8 input.
Transcript boundary parsing
scripts/lib/transcript-context.js, tests/lib/transcript-context.test.js, tests/hooks/suggest-compact.test.js, CHANGELOG.md
readLatestContextTokens reads one extra byte and skips the first line when the tail boundary may cut through a record. Tests cover complete and partial records, UTF-8 tails, lookbehind limits, and a context reminder at the default tail boundary. The changelog records the reminder behavior.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix

Suggested reviewers: affaan-m, montjeffrey

Merge Risk: ⚪ Minimal · up to db29f

The boundary fix has targeted regression coverage and no identified merge-blocking issue. The full test suite was not reported green, so complete the normal test checks before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 5 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the main fix: preserving usage records at transcript tail boundaries.
Description check Passed The description directly explains the transcript-tail fix, its purpose, test coverage, and known full-suite test limitations.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 5 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] No blocking or non-blocking findings remain; the validated reader and hook behavior supports merging this change.

Summary

The change preserves complete usage records that start exactly at the requested transcript tail boundary while continuing to exclude partial and out-of-window records. The optional raw byte count keeps this decision correct when a transcript ends with incomplete UTF-8, without changing existing callers’ default result shape. The changelog describes the fix.

Validation passed all 102 focused reader and hook tests. An additional 18 fixtures passed all 72 assertions against the updated code. The same fixtures reproduced missing boundary-aligned reminders on the base revision. With the fix, all in-window fixtures returned the expected 170,000-token usage and emitted the real compact reminder; out-of-window fixtures remained excluded.

No actionable issues were found. The change is safe to merge based on the validated scope. The full repository test suite was not rerun.

  • Context scans keep complete usage records at the transcript tail boundary.

Reviews (1) · Last reviewed commit: "fix(hooks): preserve usage records at tr..." · Reviewed by Greptile

@haelyra
haelyra merged commit c7db9b4 into affaan-m:main Oct 29, 2026
4 checks passed
@haelyra

haelyra commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

Thank you for retaining a complete usage record at a transcript-tail boundary. This is now merged through #3806, with your contributor head preserved. I also isolated transcript fixtures in private temporary storage after code scanning caught a shared-path risk.

The combined integration and exact resulting main passed CI, CodeQL and a fresh supply-chain scan (CI, main 91b5f6a3). We appreciate the focused contribution.

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.

2 participants