fix(tui): add plain text format support to session export command #3303
Labels
Clear labels
auto/needs-reevaluation
controller-managed
overdue
auto/blocked-by-deps
auto/ci-timeout
auto/claimed-implementer
auto/claimed-merge
auto/claimed-reviewer
auto/driver-down
auto/invariant-violation
auto/last-attempt-tier-0
auto/last-attempt-tier-1
auto/last-attempt-tier-2
auto/last-attempt-tier-min
Automation Tracking
auto/needs-conflict-resolution
auto/needs-implementer
auto/postmortem
auto/ready-to-merge
auto/restart-throttled
auto/revert
auto/sentinel
auto/stale-inactivity
auto/unstable
Blocked
Needs Feedback
Signed-off: Owner
Signed-off: Scrum Master
Signed-off: Tech Lead
Spike
Controller deferred this PR; awaiting Phase 6+ scope-evaluator or operator re-enablement.
Auto-agents controller manages this PR/issue (see tools/controller/deploy/RUNBOOK.md). Remove this label to abandon controller management.
PR blocked by an open issue dependency. Operator must close the dep (or remove the dependency link) before the merge driver can act. Auto-cleared by merge_drive when no open deps remain.
Most recent merge cycle hit CI timeout. Driver excludes this PR while last merge_cycle row is < 30 min old; label persists thereafter as visible history.
Currently being processed by an implementer worker.
Currently being processed by the merge driver.
Currently being processed by a reviewer worker.
Merge driver heartbeat stale; pipeline halted. Closed automatically on next clean tick.
Detected master commit violating the strict merge invariant. Tracked as an issue (not a PR label); kept here for label completeness.
In-cycle escalation: most recent attempt ran at the Tier 0 slot (`tier-0`). Slot's model defined in .opencode/models/tiers.yaml.
In-cycle escalation: most recent attempt ran at the Tier 1 slot (`tier-1`). Slot's model defined in .opencode/models/tiers.yaml.
In-cycle escalation: most recent attempt ran at the Tier 2 slot (`tier-2`). Slot's model defined in .opencode/models/tiers.yaml. Gated behind IMPLEMENTER_ESCALATION_TIER2_ENABLED.
In-cycle escalation: most recent attempt ran at the Tier -1 slot (`tier-min`). Slot's model defined in .opencode/models/tiers.yaml. Suffix is ``-min`` (not ``--1``) so the Forgejo UI reads naturally.
Tracking issues used by the AI Automation system for agents to communicate and report.
Rebase conflict needs LLM conflict-resolver.
Failing CI needs implementer attention.
Documenting a driver incident or rollback.
Reviewer has APPROVED this PR and no later REQUEST_CHANGES is outstanding. The merge driver requires this label to even consider a PR for merging. Set by the reviewer worker on APPROVE; cleared on REQUEST_CHANGES.
Train repeatedly lost master-tempo races. Driver excludes via merge_cycle until cooldown elapses; label persists as visible history.
Revert PR backing out an invariant violation. Fast-tracked through the merge driver.
Sentinel PR duplicated from upstream into a personal fork by tools/duplicate_prs_to_fork.py for pipeline testing. Lives only in the fork; the canonical pipeline never sees it.
No implementer activity for N days. Flagged for human review. Auto-cleared on next push to head branch.
Repeatedly fails on current master (>= 3 ci-fail-on-rebased-sha releases in 12 h). Excluded from driver until human triage.
A ticket in a blocked state and unable to complete until some other task is completed first.
Bounty
$100
A bounty of $100 for any open-source contributor who provides a MR that solves this issue
Bounty
$1000
A bounty of $1000 for any open-source contributor who provides a MR that solves this issue
Bounty
$10000
A bounty of $10000 for any open-source contributor who provides a MR that solves this issue
Bounty
$20
A bounty of $20 for any open-source contributor who provides a MR that solves this issue
Bounty
$2000
A bounty of $2000 for any open-source contributor who provides a MR that solves this issue
Bounty
$250
A bounty of $250 for any open-source contributor who provides a MR that solves this issue
Bounty
$50
A bounty of $50 for any open-source contributor who provides a MR that solves this issue
Bounty
$500
A bounty of $500 for any open-source contributor who provides a MR that solves this issue
Bounty
$5000
A bounty of $5000 for any open-source contributor who provides a MR that solves this issue
Bounty
$750
A bounty of $750 for any open-source contributor who provides a MR that solves this issue
MoSCoW
Could have
Could have feature in order to satisfy the epic/legendary.
MoSCoW
Must have
Must have feature in order to satisfy the epic/legendary.
MoSCoW
Should have
Should have feature in order to satisfy the epic/legendary.
There are questions in the ticket that can not be completed until the project owner provides clarity.
Points
1
1 man-hours worth of work for an expert with no learning curve.
Points
13
13 man-hours worth of work for an expert with no learning curve.
Points
2
2 man-hours worth of work for an expert with no learning curve.
Points
21
21 man-hours worth of work for an expert with no learning curve.
Points
3
3 man-hours worth of work for an expert with no learning curve.
Points
34
34 man-hours worth of work for an expert with no learning curve.
Points
5
5 man-hours worth of work for an expert with no learning curve.
Points
55
55 man-hours worth of work for an expert with no learning curve.
Points
8
8 man-hours worth of work for an expert with no learning curve.
Points
88
88 man-hours worth of work for an expert with no learning curve.
Priority
Backlog
This ticket has backlogged priority and is not to be worked on yet
Priority
CI Blocker
Critical priority issue that blocks CI/CD pipeline and prevents PR merges
Priority
Critical
The priority is critical
Priority
High
The priority is high
Priority
Low
The priority is low
Priority
Medium
The priority is medium
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
A ticket for learning a tool or technology that is needed to be able to do future planning and design.
State
Completed
The ticket has been fully implemented, completed, and merged with the source code. This label should only be applied once a ticket is closed.
State
Duplicate
A ticket that represents the same content as an existing ticket.
State
In Progress
A ticket that is actively being developed.
State
In Review
A ticket that has had some code completed to implement but is waiting to pass peer review and is not yet merged in.
State
Paused
This ticket's work started but wasn't finished. It's on hold (likely in a feature branch) and will be resumed later, either due to a blocker or a delay.
State
Unverified
All new tickets start in this state. A developer may set it to show the ticket is unverified. This means we haven't agreed to work on it. It will either move to a verified state or be closed as wontdo.
State
Verified
The issue has been verified by a developer as legitimate. It will be worked on and verified tickets are now considered part of the backlog.
State
Wont Do
This ticket has been decided it wont be done. This may mean the bug has been determined to not be real (cant verify) or the feature is one we have decided we dont want to adopt.
Type
Automation
Any edits or discussion about the AI automated coding system.
Type
Bug
Something that doesnt work as intended.
Type
Discussion
Anytime a ticket represents a discussion about a subject and doesnt fall into one of the other categories.
Type
Documentation
An error or improvement needed in the documentation.
Type
Epic
Any first tier epic. That is, an epic which contains only issues as children and will not have sub-epics.
Type
Feature
Some new functionality not present.
Type
Legendary
A type of Epic which will contain other Epics.
Type
Refactor
A code change that restructures existing code without changing its external behavior.
Type
Support
Someone needs help using the project.
Type
Task
A generic task that doesnt fit into the other type categories.
Type
Testing
Work exclusively focusing on fixing or expanding testing.
No Label
Projects
Clear projects
No project
Assignees
aditya (Aditya Chhabra)
aleenaumair (Aleena Umair)
brent.edwards (Brent Edwards)
CoreRasurae (Luis Mendes)
drew (Drew Morris)
eugen.thaci (Eugen Thaci)
freemo (Jeffrey Phillips Freeman)
HAL9000 (HAL 9000)
HAL9001 (HAL9001)
hamza.khyari (Hamza Khyari)
hurui200320 (Rui Hu)
justin.morris
khird (Kyle Hird)
org.cleveragents
Clear assignees
No Assignees
Notifications
Due Date
No due date set.
Blocks
Reference: cleveragents/cleveragents-core#3303
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Delete Branch "fix/tui-conversation-export-plain-text"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Adds plain text (
.txt) as a supported export format for the TUI/session:exportcommand, resolving a gap identified in UAT where users could export sessions as JSON or Markdown but had no format-agnostic plain text option. The new format produces a clean, human-readable transcript without any Markdown syntax.Changes
src/cleveragents/domain/models/core/session.py— AddedSession.as_export_plain_text()method that renders a session as a plain text transcript. The output begins with a structured header block (Session ID, Actor, Namespace, Created, Updated timestamps), followed by a"-" * 40separator line, and then each message rendered as[seq] ROLE (timestamp):\ncontent. When the session contains no messages, a(no messages)placeholder line is emitted instead of the Markdown-styled*(no messages)*used by the existingmdbranch.src/cleveragents/tui/commands.py— ExtendedTuiCommandRouter._session_export()to recognise"txt"as a valid format alongside the pre-existing"json"and"md"values. Added anelif fmt == "txt":dispatch branch that callssession.as_export_plain_text()and routes the result through the same file-write / success-message path used by the other formats. Updated the user-facing validation error message from"Use 'json' or 'md'."to"Use 'json', 'md', or 'txt'."so the help text stays accurate.features/tui_session_export_import.feature— Added 5 new BDD scenarios:/session:export txtreturns a success message/session:export txt <file>writes a file containing plain text(no messages)placeholdertxtas an accepted valuefeatures/steps/tui_session_export_import_steps.py— Added step definitions for all five new BDD scenarios, covering success-message assertions, file-content assertions, and error-message assertions.Design Decisions
No Markdown in plain text output. The
txtformat is intentionally free of Markdown syntax so it can be read, diffed, or processed by tools that do not understand Markdown. Separator lines use"-" * 40dashes rather than---(which is a Markdown horizontal rule).Consistent message reconstruction pattern. The
as_export_plain_text()method reuses the same message-iteration logic already present in themdexport branch, keeping the two implementations easy to compare and maintain.(no messages)vs*(no messages)*. The plain text branch omits the Markdown emphasis asterisks used by themdbranch, keeping the output format-neutral and consistent with the "no Markdown" contract of thetxtformat.Minimal surface-area change. The format dispatch in
_session_export()is a straightforwardelifextension; no existing code paths were altered, reducing regression risk.Testing
nox -e typecheck): 0 errors, 0 warningsnox -e lint): All checks passedModules Affected
src/cleveragents/domain/models/core/session.pyas_export_plain_text()methodsrc/cleveragents/tui/commands.pytxtformat dispatch + updated error messagefeatures/tui_session_export_import.featurefeatures/steps/tui_session_export_import_steps.pyCloses #3036
Automated by CleverAgents Bot
Supervisor: Implementation | Agent: ca-issue-worker
Review Summary
Reviewed PR #3303 with focus on performance-implications, resource-usage, and scalability.
This PR adds plain text (
txt) export format support to the TUI/session:exportcommand, resolving a spec gap identified in UAT (issue #3036). The implementation adds aSession.as_export_plain_text()domain method and extends the TUI command router to dispatch to it.Standard Criteria
✅ Specification Compliance: The spec states sessions should be exportable to "Markdown, JSON, and plain text." This PR closes the gap by implementing the missing
txtformat.✅ Commit Message Format: Single atomic commit following Conventional Changelog format (
fix(tui): add plain text format support to session export command) withISSUES CLOSED: #3036footer.✅ PR Metadata:
Closes #3036present, milestone v3.7.0 matches issue,Type/Buglabel applied.✅ Type Safety: No
# type: ignoresuppressions. All new methods have proper return type annotations. Imports at top of file (deferred imports in_session_exportfollow the pre-existing pattern for themdbranch).✅ Error Handling: The new
txtbranch follows the same error handling pattern as the existingmdbranch, with the broadexcept Exceptioncatch in_session_exportproviding user-friendly error messages.✅ Test Quality: 5 new BDD scenarios covering: TUI command success, file output, content verification (header + messages), empty session placeholder, and error message validation. Step definitions are clean and well-structured.
✅ Code Correctness: The
as_export_plain_text()method correctly produces format-neutral output without Markdown syntax. The(no messages)placeholder correctly omits the Markdown emphasis asterisks used by themdbranch.Deep Dive: Performance, Resource Usage, Scalability
Given special attention to performance implications:
1. Redundant Service Calls (Pre-existing, Non-blocking)
Location:
src/cleveragents/tui/commands.py,_session_export()methodFor
mdandtxtformats, the code makes two service calls where one would suffice:service.export_session(session_id)— called unconditionally before the format branchservice.get(session_id)— called inside themd/txtbranchesThe
service.get()call returns aSessionobject that already contains all messages. The code then unnecessarily reconstructsSessionMessageobjects from theexport_datadict and overwritessession.messages. Formd/txtformats, onlyservice.get()is needed — the session object has everythingas_export_markdown()andas_export_plain_text()require.This means 2 database round-trips for
md/txtexports where 1 would suffice. For typical session sizes this is negligible, but for sessions with thousands of messages, the redundant serialization/deserialization adds unnecessary overhead.Note: This is a pre-existing issue from the
mdbranch — the PR correctly follows the established pattern. A follow-up refactor could restructure the method to callexport_session()only forjsonformat andget()only formd/txt.2. String Building Pattern (Acceptable)
The
as_export_plain_text()method useslist[str]+"\n".join()for string building, which is the correct O(n) approach. For sessions with very large message counts, this scales linearly. No concerns here.3. Memory Usage (Acceptable)
The plain text export builds the entire output string in memory before writing. For extremely large sessions (10K+ messages with long content), this could consume significant memory. However, this is the same pattern used by
as_export_markdown()andas_export_dict(), so it's consistent. Streaming export would be a separate enhancement if needed.Non-blocking Suggestions
[DRY] Duplicated message reconstruction (
commands.py): Thetxtbranch copies ~15 lines verbatim from themdbranch (deferred import,service.get(), message reconstruction loop,session.messagesassignment). Consider extracting a shared helper like_get_session_with_export_messages()to reduce duplication. This would also make adding future formats (e.g.,csv,html) cleaner.[TEST] Missing linked plans scenario: The markdown export has a dedicated test for linked plan IDs in the output (
Scenario: Markdown export includes linked plan IDs), but the plain text export does not. Theas_export_plain_text()method does handle linked plans — consider adding a parallel scenario to verify.[FILE SIZE] session.py approaching limits: The file grew from ~21KB to ~23KB with this change. The project guideline is files under 500 lines. The export methods (
as_export_dict,as_export_markdown,as_export_plain_text) could potentially be extracted to a dedicatedsession_export.pymodule in a future refactor, keeping the core domain model leaner.[MINOR] Separator constant: The
"-" * 40separator string is computed each timeas_export_plain_text()is called. While trivially cheap, it could be a module-level constant (like_PLAIN_TEXT_SEPARATOR = "-" * 40) for consistency with the existingEXPORT_SCHEMA_VERSIONconstant pattern.Verdict
The implementation is correct, well-tested, and follows established patterns. The performance concerns identified are pre-existing and do not warrant blocking this bug fix. The "minimal surface-area change" design decision is appropriate for a targeted fix.
Decision: APPROVED ✅
Automated by CleverAgents Bot
Supervisor: PR Review | Agent: ca-pr-self-reviewer
df70ca4c9eto8d49a3b242CI Fix: Ruff Format Violation in
session.pyThe
CI / lintcheck was failing due to aruff formatviolation insrc/cleveragents/domain/models/core/session.py.Root cause: A multi-line
lines.append(...)call inas_export_plain_text()was split across 3 lines but ruff's formatter collapses it to a single line since it fits within the line length limit:Fix applied: Ran
ruff formatonsession.pyand amended the commit. All checks now pass locally:ruff check: ✅ All checks passedruff format --check: ✅ 3 files already formattedCI re-triggered on the updated commit. Monitoring until all checks pass and PR is ready to merge.
Automated by CleverAgents Bot
Supervisor: Implementation | Agent: ca-issue-worker
Review Summary
Reviewed PR #3303 with focus on error-handling-patterns, edge-cases, and boundary-conditions.
This PR adds plain text (
txt) export format support to the TUI/session:exportcommand, closing the spec gap identified in issue #3036. The implementation adds aSession.as_export_plain_text()domain method and extends the TUI command router to dispatch to it.Standard Criteria
✅ Specification Compliance: The spec states sessions should be exportable to "Markdown, JSON, and plain text." This PR implements the missing
txtformat, closing the gap.✅ Commit Message Format: Single atomic commit following Conventional Changelog format (
fix(tui): add plain text format support to session export command) withISSUES CLOSED: #3036footer.✅ PR Metadata:
Closes #3036present in body, milestone v3.7.0 matches issue,Type/Buglabel applied.✅ Type Safety: No
# type: ignoresuppressions. All new methods have proper return type annotations (-> str,-> None). Imports at top of file; deferred imports in_session_exportfollow the pre-existing pattern from themdbranch.✅ Code Correctness: The
as_export_plain_text()method correctly produces format-neutral output without Markdown syntax. The(no messages)placeholder correctly omits the Markdown emphasis asterisks used by themdbranch. String building useslist[str]+"\n".join()— the correct O(n) approach.✅ Test Quality: 5 new BDD scenarios covering: TUI command success, file output, content verification (header + messages), empty session placeholder, and error message validation. Step definitions are clean, well-typed, and follow existing patterns.
Deep Dive: Error Handling Patterns
Given special attention to error handling:
1.
as_export_plain_text()— Pure Transformation (Correct)The new domain method is a pure data transformation on a Pydantic model with no I/O or external calls. All accessed fields (
session_id,actor_name,namespace,created_at,updated_at,linked_plan_ids,messages) are guaranteed to exist by Pydantic validation at construction time. There are no error paths to handle, which is correct — the fail-fast principle is satisfied by the model validators.2. TUI Command Handler — Follows Established Pattern (Acceptable)
The
txtbranch in_session_export()follows the sameexcept Exception as exc:catch pattern as the pre-existingmdandjsonbranches. While broad exception catching is generally discouraged by the project's error handling rules, this is a TUI command handler where the recovery action (returning a user-friendly error string) is meaningful. The pattern is pre-existing and consistent.3. Edge Cases Properly Handled
if not self.messages:→ outputs(no messages)placeholderself.actor_name or '(none)'fallbackif self.linked_plan_ids:skips the line entirely"txt"in the allowed set; error message updated to list all three formats4. Boundary Conditions Examined
elif fmt == "txt":branch is correctly placed betweenmdand theelse(json) branch. No fall-through risk.txtbranch correctly reuses the same file-write logic (Path.write_text()withencoding="utf-8") as the other formats.export_data.get("messages", [])pattern safely handles missing keys. Them["timestamp"]access is safe becauseexport_session()always produces this field. (Pre-existing pattern frommdbranch.)Non-blocking Suggestions
[TEST] Missing linked plans scenario for plain text: The markdown export has a dedicated test (
Scenario: Markdown export includes linked plan IDs), but the plain text export does not. Theas_export_plain_text()method does handle linked plans — consider adding a parallel scenario to verify theLinked Plans:line appears in plain text output. This would improve edge case coverage parity between the two lossy export formats.[TEST] Missing actor name scenario for plain text: Similarly, the markdown export has
Scenario: Markdown export includes actor and namespacebut there's no equivalent for plain text. Consider adding a scenario that verifiesActor: openai/gpt-4appears in the plain text output.[TEST] File content verification: The
Scenario: TUI session export with --format txt to file writes plain textonly asserts the file exists, not that its content is valid plain text. Consider adding a step that reads the file and checks for expected content (e.g.,And the tui exported file "/tmp/tui_test_export.txt" should contain "Session:").[DRY] Duplicated message reconstruction (
commands.py): Thetxtbranch copies ~15 lines verbatim from themdbranch (deferred import,service.get(), message reconstruction loop,session.messagesassignment). Consider extracting a shared helper like_get_session_with_export_messages()to reduce duplication. This would also make adding future formats (e.g.,csv,html) cleaner. (Pre-existing issue amplified by this PR.)[MINOR] Separator constant: The
"-" * 40separator string is computed each timeas_export_plain_text()is called. While trivially cheap, it could be a module-level constant (like_PLAIN_TEXT_SEPARATOR = "-" * 40) for consistency with the existingEXPORT_SCHEMA_VERSIONconstant pattern.Verdict
The implementation is correct, well-tested, and follows established patterns. The error handling is appropriate for a TUI command handler context. All critical edge cases (empty messages, missing actor, missing plans) are properly handled. The boundary conditions around format validation and dispatch are clean. The non-blocking suggestions above would improve test parity with the markdown export but are not required for this targeted bug fix.
Decision: APPROVED ✅
Automated by CleverAgents Bot
Supervisor: PR Review | Agent: ca-pr-self-reviewer