Skip to content

feat(chat-folders): opt-in delete_contents removes a folder subtree in one step - #13878

Closed
ash663 wants to merge 2 commits into
kirodotdev:mainfrom
ash663:folder-delete-contents
Closed

ash663 wants to merge 2 commits into
kirodotdev:mainfrom
ash663:folder-delete-contents

Conversation

@ash663

@ash663 ash663 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Delete a chat folder together with everything in it in one step, opt-in, without ever hard-deleting a conversation and without changing what today's delete does.

DELETE /api/chat/folders/{id} (kiro_crew/dashboard/chat_folders.py, api_chat_folder_delete) only ever removes the one folder row. Its _remove callback re-parents direct child folders to the top level (f["parent_id"] = "") and the unfile loop before it moves the folder's live sessions to the top level. That is the right default, but a folder holding a subtree cannot be removed in one step: deleting an oncall shift folder that holds ~100 <TICKET-ID> subfolders (one per incident session) spills a hundred ticket folders onto the top level, each of which then has to be deleted by hand. Archived sessions filed in the deleted folder are never touched, so their folder_id keeps naming a folder that is gone (the resume path drops the dangling id, chat_handlers.py:11312).

Why it matters

Any workflow that files many sessions under a disposable parent -- a shift, a sprint, a batch import -- has no way to clean up after itself except one folder at a time, and the person doing it is the one who has to click a hundred times. The artifact library already solved this for its folders (DELETE /api/artifact-folders/{id}?delete_contents=<bool>); chat folders, which hold far more rows in practice, have no equivalent.

Not a goal

  • The sidebar's own "Delete folder and everything in it" dialog (client variant, destructive-confirm string, count text): a separate frontend PR.
  • A repository-wide single lock-checked assignment write-point for every slot/channel folder write: declined -- disproportionate for an opt-in flag (the attempt touched about twenty call sites across eight modules).
  • Hard-deleting transcripts from a folder action, or widening the delete route to app agents and crew members: the route refuses both, as before.
  • The cascade's commit structure itself: a folder-store write that is cancelled (only gateway shutdown cancels a handler here), and a tab close that popped its slot before the cascade and saves a removed id afterwards (a dangling id, which every reader renders as unfiled). Both predate this PR's freeze; recorded, not changed.

What changed (motivation -> approach -> change)

Goal: remove a folder subtree in one request without ever hard-deleting a conversation, and without changing what today's delete does.

Approach: the same route gains an opt-in ?delete_contents=true, mirroring the artifact-folder delete -- same flag name, same truthy spellings (1|true|yes), same "the default is the safe path" contract -- rather than a new route or an MCP verb. "Delete everything in it" for a session means the session leaves the sidebar, and the only sanctioned way a live session leaves the sidebar is the tab-close path, so live sessions in the subtree are archived through chat_handlers.close_slot, the exact function api_chat_slot_delete (the tab ✕) calls: saved to history as closed, resumable from History later, no transcript touched other than by that ordinary close. Alternatives considered: hard-deleting the sessions (rejected -- irreversible, and nothing in the product deletes transcripts from a folder action); a separate POST .../delete-subtree route (rejected -- the artifact API already established the flag shape).

Change, in api_chat_folder_delete:

  • default (flag absent or falsy): unchanged behaviour -- unfile live sessions, re-parent direct children to the top level, remove one row, answer {ok: true} byte-identical to today.
  • delete_contents=true:
    • the subtree ids are computed ONCE under the folder-store lock (_subtree_folder_ids, the cycle-guarded walk _is_descendant already uses) and FROZEN there for the request's duration -- see "The subtree is frozen" below; every live slot filed anywhere in it is closed with close_slot (a slot already is_closing is skipped -- another ✕ or the idle sweep owns it), passing close_slot a synchronous pre_pop_check that re-reads registration and subtree membership at the point of no return, so a session moved out of the subtree while the close awaited unwinds its close and stays live where the person put it, and the cascade goes on without it;
    • a SlotCloseError from any close stops the cascade with that close's own code and a literal 500 (archived_sessions so far and the failing session in the body): the folder tree is untouched and the sessions archived before it are in History, still filed under their (still existing) folders -- the same recoverable state the ✕ leaves, and the person retries;
    • the existing unfile loop (with its existing rollback) now tests membership in the subtree, so a straggler another close owned, or a session filed while the closes awaited, ends up live and unfiled rather than archived by a racing second pass; it walks a list snapshot of the slot table with a per-entry registration re-check, so a close popping the table while a save awaits cannot raise RuntimeError outside the rollback;
    • _remove removes exactly the frozen set (which, frozen, is still the subtree under the lock) and returns it; a folder-store write that fails after the archive pass is audited (outcome="error", archived=N) and leaves the same retryable state a refused close leaves;
    • after the commit succeeded: icon-epoch and pending-icon-task cleanup for every removed id, then _clear_archived_folder_assignments runs off the event loop -- for every history session filed under a removed id, update_metadata_if(key, {"folder_id": ""}, guard=<still under a removed id>, require_existing=True), a compare-and-set under the transcript's flock that cannot recreate a deleted session; a failed write is logged and skipped (the dangling id degrades to unfiled everywhere);
    • the response reports the counts: {ok, delete_contents, deleted_folder_ids, unfiled_sessions, archived_sessions, unfiled_history_sessions}; the SEL chat.folder_delete row carries them too.

Guards unchanged and evaluated before the flag is read: 404 for an unknown folder, 403 folder_not_owned / folder_delete_forbidden for app callers (the cascade opens no second door for an app), and the unattributable-caller refusal.

The subtree is frozen for the cascade's duration. The sessions live in a different store from the folders, so no reading of "what is in this folder" can be atomic with its removal; three review rounds each found one more mutation that could land in the cascade's await windows (a child created under the subtree, a session moved out, a child reparented out, a session filed in during the final commit). Instead of a re-check per race, the tree is held still: api_chat_folder_delete computes the set it empties (the one row on the safe path, the whole subtree on the cascade) under the store lock and records it in a frozen set the store's callbacks consult under the same lock (_deleting_folder_ids). While frozen: a child create under a frozen folder is refused with 400 folder_parent_deleting; a rename/reparent of a frozen folder, a reparent into one, a reorder naming one and a second delete of one are refused with 409 folder_deleting; and every filing path that consults the store (_unhide_folder -- the slot-folder PATCH, slot create with folder_id, resume -- arrival_folder_exists, and the session-control create/fork existence checks, which test presence synchronously and assign in the same window) report a frozen folder absent to a NEW filing, so filing into it gets the existing 400 folder_not_found refusal. Frozen is not gone, though: the two callers that hold a STORED filing and would erase it on "absent" -- the resume (chat_handlers.py's hydrate) and the import repair (session_transfer.py) -- ask _unhide_folder / arrival_folder_exists with frozen_is_present=True and keep the filing (the frozen row is never written either); if the delete commits, its commit-time sweep unfiles the slot, and if it aborts the session is still rightly in a folder that exists. The archive pass therefore walks exactly the set _remove deletes. A session moved OUT of the subtree meanwhile is a rescue the delete honours: close_slot's synchronous pre_pop_check unwinds that close. A slot an active close owns is left to that close by the route's two pre-commit passes (the unfile loop and the commit callback's sweep skip is_closing, as the archive pass does): every save the route could make for it is refused by the close fence and only marks it dirty, while the close's own archival save is unguarded -- an in-memory unfile would be persisted by that save and, the commit then failing, could not be restored, leaving an archived conversation durably unfiled from a folder that still exists. Its closing save carries the folder it sat in; a committed cascade's post-commit pass clears that row, and the post-commit sweep still unfiles it live. A session moved INTO it is never provisionally there: every writer that files a LIVE slot after an awaited verdict -- the slot-folder PATCH (api_chat_slot_folder), the chat-turn filing by name (chat_handlers), the revive's filing (session_control.revive_session) -- awaits its destination's verdict (_unhide_folder, under the store lock) before assigning slot.folder_id, so no folder_id the route may yet reject is live for the cascade's membership pass or close_slot's point of no return to read -- the verdict True, the coroutine resumes without suspending and assigns; a refusal leaves nothing to roll back. The freeze is released synchronously in a finally whichever way the request ends (success, refused close, failed commit, or a store failure inside the freeze call itself -- the callback records what it took, and the thaw awaits nothing so a broken store cannot leave the tree frozen). The cron placement now consults the freeze too (cron_inject.chat_folder_exists) and re-asks synchronously at its assignment. The arrival resolver (arrival_folders.arrival_folder_id) refuses a frozen adopted group or sender folder under the lock -- the empty filing every refusal path answers -- so a sender folder cannot be appended under Imported while a delete of it runs and outlive it re-parented to the top level. And the removal callback _remove is the last word: in the same synchronous step as the commit, under the store lock, it sweeps the live slot table and unfiles any slot still naming a removed folder (a fork inheriting its parent's folder, a channel default, a placement that raced the freeze), then persists those slots with the same pinned forced save the unfile loop uses -- so the commit can never leave a live or persisted assignment pointing at a folder it removed, regardless of interleaving.

Late-assignment window: closed at its one site, with the design kept. A filing whose folder verdict preceded an await -- the resume's stored filing, the channel reconcile's filing write -- could be published after a delete committed inside that await: the commit-time sweep walks the live slot table, and the slot did not exist yet (the residual GPT named at chat_folders.py:470). The frozen-subtree + commit-time-sweep design and the call-site checks stay as they are; the window is closed at the assignment itself. chat_folders.folder_is_gone is the synchronous last word -- not in the committed tree AND not frozen -- asked with nothing between the answer and the assignment: the resume asks it right before the build (chat_handlers.py, bound_folder_id above _materialise_slot_from_history) and again before the hook path's re-publish (before state._slots[slot.key] = slot), and the channel surface asks it for both the stored and the just-filed folder (channel_slots.surface_channel_session). GONE, the session publishes unfiled. FROZEN IS NOT GONE: a stored filing into a frozen folder is kept -- the slot publishes with it (so the delete's commit-time sweep unfiles it if the delete commits), nothing is written, the hydrate never clears a frozen folder's id whatever its verdict, and DashboardState.serialize_slot projects the filing as unfiled for as long as the folder is frozen; a delete that aborts by its designed 500 thaws and re-publishes, and the filing renders again -- in memory, on disk and in the payload. The commit also sweeps once more, synchronously, right before the thaw, so a slot published while the store's disk write was in flight is unfiled too. A dangling folder_id is made harmless at the same read chokepoint: an id no folder record carries projects as unfiled (full list, slot_patch frame, single-slot answers) -- and so does a stored value that is not a string at all, since the record comes back from a file an agent's tools can edit; nothing is written from the read path, and the slot's next folder write replaces the stored id. The same shape rule holds wherever a stored folder_id is hashed or asked about: is_folder_id gates folder_is_deleting, folder_is_gone and _unhide_folder (a list or a dict is not frozen, is gone and reads absent, so the resume's own drop clears it -- the resume answers 200 with the value cleared instead of a TypeError on every attempt), the delete route's membership tests go through _filed_in (such a slot is filed nowhere, so no folder delete fails on it), and the removal callback re-parents only a string parent_id. The channel filing writers (reconcile_channel_slots, backfill_channel_folder) re-ask the folder at their commit boundary: the update_metadata_if guard, evaluated under the transcript's lock right before the write, refuses a folder that is frozen or gone, so a write stalled across a delete lands no deleted id (_filing_write_guard); and because the folder store has its own lock and the write itself is a transcript rewrite off the loop, the folder is asked once more on the loop the moment the write is known to have landed (_filing_stands_after_the_write): gone by then, the filing is withdrawn with a compare-and-set on the value the pass wrote (folder cleared, marker taken back), so the conversation stays unfiled and eligible; frozen by then, the pass waits for the running delete's verdict (the route thaws in a finally, so the wait is bounded by the delete) rather than guessing -- a commit withdraws, an abort keeps the filing like every other stored filing. The withdrawal's verdict is read back from the row, not taken from the conditional write's boolean: a row another writer settled stands, a row still naming the folder is retried once, and a withdrawal that still cannot be confirmed is returned as such -- the reconcile surfaces the conversation unfiled and the backfill reports it as a failed write, never as a move. The guard resolves the frozen set on the loop when it is built and the worker only reads it, so a first attach from a worker thread cannot race the loop's first freeze. The repository-wide single assignment write-point (tried on f494d4602 / b36b60b82: about twenty call sites, red shards, two further findings) is declined and no follow-up for it is scheduled.

Not a product-shape change: the default is untouched (body included) and nothing user-facing is removed or replaced; the flag is additive.

Consumer. The flag ships with its agent-facing consumer: chat_folder_delete on the dashboard MCP server (mcp_dashboard.py, beside chat_folder_create), args folder (id or human path) and delete_contents (default false). The default is the route's safe delete; delete_contents=true removes the whole subtree and archives every session in it, and the tool description tells the agent to echo the affected count to the user first, mirroring artifact_folder_delete. A thin wrapper over the route: the verified caller key rides on the DELETE (mcp_core._delete gains the session_key / timeout keywords _patch already has), so an app agent's call gets the route's own 403 folder_delete_forbidden and a crew member's is refused by the member gate (no DELETE is admitted on the folder routes); the person's own sessions delete. The set-grant ratchet (test_mcp_dashboard_registration.py::TestWhatThisSetGrants) records the decision and why the verb's blast radius stays the route's: for every agent principal it deletes nothing, and for the person its cascade archives sessions through the same close_slot path session_close in the same set already grants. Documented in docs/architecture/mcp.md and docs/session-control.md.

Docs: the route's line in docs/system-specs/modules/learn-cron-dashboard.md now describes both modes and the response shape.

UI, left for a follow-up: website/src/pages/ChatSidebar.tsx has a single confirm() behind the folder ⋯ menu's Delete item (deleteFolderMutation -> api.deleteChatFolder(id)). Offering "Delete folder and everything in it" as a second confirm step showing the counts needs an api.deleteChatFolder(id, {deleteContents}) client variant, a new destructive-confirm string (the destructiveConfirm.test.ts ratchet plus en.json via the codemod and all twelve translation catalogs) and the count text; the sidebar can compute the counts locally from the folder tree, the live slots and each folder's history_count, so no preview endpoint is needed. Kept out so this PR stays a backend change with tests.

Backwards compatibility

Compatible: without the flag the route does exactly what it did (same unfile loop, same rollback, same re-parenting, same audit row); the response body is unchanged ({ok: true}); the counts are returned on the cascade only, and the only client (website/src/api/client.ts deleteChatFolder) ignores the body. The flag is parsed from the query string, so a caller that never sends it cannot reach the new path. No stored format changes: an archived session's folder_id was already writable to "" by the slot save.

Tests

test/test_chat_folder_delete_contents.py (new):

  • test_default_reparents_children_and_unfiles_slots_as_before["" | ?delete_contents=false | ?delete_contents=0] -- one row removed, the child re-parented to the top level, the live session stays live and unfiled, body exactly {ok: true}.
  • test_delete_contents_removes_nested_folders_and_archives_sessions -- a three-deep subtree with live sessions at every level plus a pre-archived one: every subtree folder gone; the three live sessions are out of the live table and in history as closed with folder_id == "" and their transcripts intact; the pre-archived session is unfiled and still closed; an unrelated folder's live and archived sessions are untouched; archived_sessions=3, unfiled_sessions=0, unfiled_history_sessions=4.
  • test_delete_contents_refuses_an_unknown_folder -- 404, nothing touched.
  • test_a_refused_close_stops_the_cascade_and_leaves_the_tree -- close_slot raising SlotCloseError(code="history_write_running") yields a 500 with that code, archived_sessions=0 and the failing session named; folders and the session's filing untouched.
  • test_delete_contents_on_a_leaf_folder_reports_zero_counts -- exact response body for an empty folder.
  • test_a_child_created_under_the_frozen_subtree_is_refused -- a child create under the subtree from inside the first close_slot: 400 folder_parent_deleting, the cascade removes exactly its snapshot, the frozen set is empty afterwards.
  • test_reparenting_a_child_out_of_the_frozen_subtree_is_refused -- PATCH {parent_id: ""} on a child mid-cascade: 409 folder_deleting; the child goes with the cascade and its session is archived and unfiled.
  • test_reparenting_a_folder_into_the_frozen_subtree_is_refused -- 409 folder_deleting; the outside folder stays where it was.
  • test_filing_a_session_into_the_frozen_subtree_is_refused_and_nothing_dangles -- slot-folder PATCH into a frozen folder mid-cascade: 400 folder_not_found; the session stays live and unfiled, nothing persisted names the deleted folder; filing into the deleted id after the cascade is the plain 400.
  • test_a_second_delete_of_a_frozen_folder_is_refused -- 409 folder_deleting.
  • test_the_freeze_is_released_when_a_refused_close_aborts_the_cascade -- after the 500 the frozen set is empty and the surviving folders accept a reparent and a child create.
  • test_session_control.py::test_create_refuses_a_folder_frozen_by_a_running_delete and test_session_control_fork.py::test_a_folder_frozen_by_a_running_delete_refuses_the_whole_fork -- the session-birth existence checks read a frozen folder as absent (folder_not_found, nothing allocated); thawed, the same folder accepts the create.
  • test_a_frozen_folder_reads_absent_to_a_new_filing_and_present_to_a_stored_one -- both readings of _unhide_folder and arrival_folder_exists, neither writing the frozen row; thawed, the un-hide lands.
  • test_resume_publishes_hydrated_slot.py::test_a_resume_into_a_folder_a_running_delete_has_frozen_keeps_the_filing and test_session_transfer.py::test_an_arrival_folder_frozen_during_the_save_keeps_the_filing -- the two erasing callers keep a stored filing when the folder is frozen (both fail when the frozen reading is absent).
  • test_the_commit_itself_unfiles_a_slot_filed_after_the_unfile_snapshot[default | cascade] -- a slot filed into the subtree right before the removal callback runs: unfiled by the commit, live, persisted metadata carries no folder, nothing in the slot table names a removed folder.
  • test_cron_chat_folder.py::test_a_folder_frozen_by_a_running_delete_is_not_placed_into -- the cron placement's synchronous re-check reads a frozen folder as absent; the tab stays where it is and nothing is written.
  • test_forced_save_history_key_pin.py::test_restore_unfiled_refusal_marks_dirty_and_keeps_restored_field (existing) -- its failing store now fails only the removal commit, since the delete first freezes through the same store method with a no-write callback.
  • test_a_session_moved_out_of_the_subtree_during_its_close_is_not_archived -- a move committed inside the close's await window: the session stays live in its new folder, not closing; the sibling in the subtree is archived.
  • test_a_slot_popped_while_the_unfile_loop_awaits_does_not_crash_the_cascade -- a begin_close()-fenced slot whose pop lands during the unfile save: the cascade completes and the folders go.
  • test_the_archived_unfile_is_a_compare_and_set_that_recreates_nothing -- a session refiled between listing and write is left alone, a deleted one is not recreated, every call passes require_existing=True.
  • test_a_failed_folder_commit_after_the_archive_pass_is_audited_and_retryable -- mutate_folders raising after the archive pass: sessions in History still filed under existing folders, SEL error row with archived=1, the retry converges.

test/test_chat_folder_ownership.py:

  • test_the_cascade_flag_opens_no_second_door_for_an_app -- an app caller gets the same 403 folder_delete_forbidden with the flag set; neither save_slot_off_loop nor close_slot is awaited.

test/test_chat_folder_delete_contents.py::test_the_committed_ids_are_thawed_before_the_post_commit_tidy[default | cascade] -- the committed ids leave the freeze the moment _remove returns, so the resume's frozen_is_present reading finds a removed folder absent during the post-commit tidy.

Late-assignment window: test_resume_publishes_hydrated_slot.py::test_a_folder_deleted_between_the_verdict_and_the_build_is_not_published (the folder is committed away inside the resume's awaits; the session publishes unfiled), ::test_a_resume_into_a_folder_a_running_delete_has_frozen_keeps_the_stored_filing (frozen: kept in memory and on disk, projected unfiled while frozen, rendered again after the thaw, the frozen row never written), ::test_the_hydrate_never_clears_a_frozen_folders_id_whatever_the_verdict_says, test_session_control_revive.py::test_a_folder_deleted_while_the_hook_awaits_is_not_published_on_the_revived_slot (the hook path's re-publish), test_channel_folders.py::TestFilingOnSurface::test_a_stored_filing_into_a_folder_that_is_gone_surfaces_unfiled and ::test_a_filing_into_a_folder_a_running_delete_has_frozen_is_kept_for_the_sweep (the channel restore half). test_chat_folder_delete_contents.py::test_a_cascade_that_aborts_retains_a_filing_resumed_while_it_ran (a session resumed mid-cascade keeps its stored filing through the designed 500: memory, disk, and the payload after the thaw), ::test_a_cascade_that_commits_unfiles_a_filing_resumed_while_it_ran, ::test_a_slot_published_during_the_commits_disk_write_is_swept_before_the_thaw[default | cascade], ::test_a_failed_commit_leaves_a_mid_close_sessions_folder_on_its_transcript[before-the-commit | during-the-write] (the other close's save lands with the slot's live folder right before the commit callback, or during the failing disk write after the callback's sweep ran over the still-registered slot: the archived transcript keeps its folder), ::test_a_committed_cascade_clears_a_mid_close_sessions_row_after_the_commit, ::test_a_cascade_racing_a_move_into_its_subtree_never_archives_the_moved_session (the cascade runs to completion inside the PATCH's verdict await: the moving session is filed nowhere, stays live, the move is rejected), ::test_a_confirmed_move_still_lands_after_its_verdict, test_session_control_revive.py::test_revive_assigns_the_folder_only_after_its_verdict, test_chat_slot_create_folder.py::TestCreateInFolder::test_the_folder_is_assigned_only_after_its_verdict. Channel writers' commit boundary: test_channel_folders.py::TestReconcilePassFiling::test_a_filing_write_stalled_across_the_folders_delete_lands_no_deleted_id, ::test_a_filing_write_stalled_across_a_running_delete_is_skipped, ::test_a_filing_that_landed_as_its_folder_was_deleted_is_withdrawn[gone | frozen-then-committed | frozen-then-aborted], ::test_the_withdrawal_is_a_compare_and_set_on_what_this_pass_wrote, TestFilingWriteBoundary (the guard reads the freeze the loop owns; the withdrawal reads its verdict back from the row: a transient refusal is retried, a row another writer settled is left alone, an unconfirmed withdrawal is reported as such and logged by key, a frozen folder is waited for), TestBackfillChannelFolder::test_a_folder_deleted_mid_pass_strands_nothing (now zero stranded), ::test_a_filing_that_landed_as_its_folder_was_deleted_is_withdrawn_and_not_counted and ::test_an_unconfirmed_withdrawal_is_a_failed_write_in_the_report. test_arrival_folders.py::test_a_frozen_group_takes_no_new_sender_folder, ::test_a_frozen_sender_folder_is_the_deletes_to_decide. test/test_chat_folder_dangling_id.py (new): a dangling id projects as unfiled in every view and in the slot_patch frame, a frozen one only while frozen, a stored value of the wrong shape projects as unfiled instead of raising, the freeze predicates never hash such a value, a folder delete survives a live slot carrying one (both modes), nothing is written from the read, and the slot's next folder write replaces a dangling id. test_resume_publishes_hydrated_slot.py::test_a_stored_folder_id_of_the_wrong_shape_resumes_unfiled_and_is_cleared[list | dict | int]; test_arrival_folders.py::test_a_frozen_hidden_group_owes_no_unhide.

Consumer: test_mcp_dashboard_folders.py::TestFolderDelete -- both modes' call shape and counts, the resolved id quoted as one path segment (an id carrying ? cannot turn a safe delete into a cascade), the verified key on the write, root and unknown-folder refusals, the endpoint's app and member refusals surfaced verbatim in both modes, the unverifiable-caller refusal, schema validation and the description contract; the registration and advertised-set ratchets carry the verb.

Run on d8aece2ad: scripts/check_black_formatting.py, scripts/check_subprocess_encoding.py and scripts/check_comment_history.py pass; isort --check-only src/kiro_crew test and flake8 src/kiro_crew test clean; mypy src/kiro_crew -> no issues; pytest over the 34 folder / session-control / transfer / channel / resume test files -> 2645 passed, 0 failed. CI on d8aece2ad: every Backend Tests shard, Backend Lint and the Coverage Gate green.

Run on 7fda1864a (rebased onto main 64b0a33c9): scripts/check_black_formatting.py, scripts/check_subprocess_encoding.py, scripts/check_comment_history.py (COMMENT_HISTORY_BASE_REF=origin/main), scripts/check_brand_name.py and scripts/docs-lint.sh pass; isort --check-only src/kiro_crew test and flake8 src/kiro_crew test clean; mypy src/kiro_crew -> no issues; the folder / session-control / transfer / channel / resume / MCP-folder test modules -> 2611 passed, 0 failed (26 modules); scripts/local-gate.py -> four related backend batches, 35691 + 39044 + 41644 + 5014 passed; of the 109 reds, 105 fail identically on a clean origin/main worktree run over the same files (host-sandbox baseline: test_ledger_sync_git.py, test_cli.py, test_file_explorer_app.py, test_design_tweak_*.py, test_apps_registry.py, test_agent_backend_recheck_e2e.py, test_stop_hook_continuation.py, test_sandbox_argv.py, test_home_pin_survives_monkeypatch_undo.py, test_store_ancestor_chain.py, auto_improvement test_runner.py), 3 are parallel-order flakes that pass 3/3 in isolation on both trees (test_cli_doctor.py, test_installer_distro.py, test_slack_sessions_view.py), and 1 was this change's -- the session-control page's tool count -- fixed.

Manual verification

N/A -- unit coverage sufficient: the cascade test drives the real close_slot and the real ConversationLog on disk (closed flag, cleared folder_id, intact transcript), which is the whole production path minus the HTTP client. The frontend is untouched, so there is nothing to verify by hand there.

Related Issues

None.

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) -- docs/system-specs/modules/learn-cron-dashboard.md
  • No secrets, credentials, or internal references in the diff

@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 Sep 25, 2026
@dwu96

dwu96 commented Sep 25, 2026

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.

@ash663
ash663 marked this pull request as ready for review September 25, 2026 17:30
@ash663
ash663 requested review from a team and bolichen97 September 25, 2026 17:30
@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — 🟡 CONCERNS

Design-level review of d7c564f437bf7a093faabc4de88bc0274f8662d3 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

One MCP call now mass-archives a subtree's sessions and deletes its folder rows, guarded only by a prompt-level instruction, reversing the old "cleanup is the person's" stance.

Watch

  • The route work is sound, but the diff also ships chat_folder_delete as an agent-facing MCP verb whose cascade safeguard is a sentence in the tool description ("echo the affected count to the user before doing so"). The base comment it rewrites reasoned "no MCP tool exposes folder deletion … cleanup is the person's" — a deliberate stance, consciously re-pinned in test_mcp_dashboard_registration.py, but the new argument only bounds agent principals (apps/crew refused). The person's own session — reachable by allow-listed non-owner humans on messaging surfaces and by untrusted channel/web content steering the agent — can now archive every live session in a ~100-folder subtree and delete the hierarchy in one call. Sessions are resumable from History; the folder structure has no undo endpoint. The human path gets a confirm dialog (deferred to a separate PR); the agent path ships first with none enforced.
    Clears when: a maintainer confirms the artifact-folder precedent (agent-callable cascade, advisory confirm only) is the intended bar for chat folders too, or the tool enforces an ack step.

Suggestions

  • Make the MCP cascade's confirm enforceable, not advisory: require the caller to pass the expected folder/session counts (from chat_folder_tree) and refuse on mismatch — the server-side twin of the dashboard dialog's second confirm step the response counts already anticipate.

[DESIGN-REVIEWED] d7c564f

Description read

[DESCRIPTION-READ] 1b0920703ce5933575420b78d3562a6b9a2c169e3d12034454f2fcffee53e3bd

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 Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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

Premise-level review of d7c564f437bf7a093faabc4de88bc0274f8662d3 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 accepting the two rewritten pins — mcp.md's withheld delete verb and the registration ratchet — whose evidence is the freeze that closes the pinned race class.

Both pins recorded "the verb is withheld because the emptiness/removal race class was not closable"; this change removes that cause (_deleting_folder_ids holds the tree still for the request), keeps the app 403 and the member gate (verified on base: DELETE is not in the admitted folder-route methods), and rewrites both pins in the same commit with that evidence — the legitimate reversal, but the acceptance is a human's to confirm.

What this change ships

Inventory (10 items) — 10 justified

Intent: ADDITION — delete a chat folder and everything in it in one opt-in step, archiving (never hard-deleting) sessions, with today's delete unchanged.

  1. ?delete_contents=true on folder DELETE removes the subtree, archives its live sessions, reports counts — justified
  2. New MCP tool chat_folder_delete (both modes; the PR's one consumer of the flag, sidebar dialog deferred) — justified
  3. Folder-freeze during any delete: concurrent create/rename/reparent/reorder/second delete newly refused (400/409) — justified
  4. Dangling folder ids now render as unfiled in every slot payload; channel restore drops a gone folder's filing — justified
  5. Non-string stored folder_id reads as unfiled instead of crashing the feed or the delete — justified
  6. Channel filings re-checked at and after the write; old one-stranded-row tolerance tightened to zero — justified
  7. Cron placement re-asks folder existence synchronously at commit — justified
  8. Create/fork/revive/move file only after the destination's verdict — justified
  9. Resume/import keep a frozen folder's stored filing for the delete's commit to decide — justified
  10. _delete helper gains session-key/timeout plumbing; docs count 24→25 — justified

[FIRST-PRINCIPLES-REVIEWED] d7c564f

Description read

[DESCRIPTION-READ] 5b0944f2b7f2d8fb1f314de8232939d2359fdb0702e2065a0810f3a5e299eec4

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 Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — ✅ no blocking findings (all downgraded on adjudication)

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

Opus 5 adjudication downgraded every blocking finding to advisory. Adjudication downgraded all 1 blocking finding(s) to advisory: the remedy each one requires is disproportionate to the harm it prevents. Read them as advice, not as merge conditions.

Review details

BLOCKING -- src/kiro_crew/dashboard/chat_folders.py:2676 -- Live filing is cleared before folder deletion commits (origin: validation)

slot.folder_id = ""
surfaced channel slot during a slow, failing folder write -> _remove clears it -> concurrent turn omits valid folder steering before rollback
Anchor: persist-before-you-publish
Fix: Collect matching slots in _remove, but clear them only after mutate_folders succeeds.
[BLOCK-MERGE-DOWNGRADED] d7c564f
[GPT-REVIEWED] d7c564f

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

LOW — one turn's [FOLDER] breadcrumb omitted, or a brief top-level render, during the folder store's disk write; nothing durable, since the swept slots' saves run only after mutate_folders returns (patch: for name, slot in swept: after the commit).
Conditions: slot filed into a target folder after the unfile loop already cleared every filed non-closing slot (chat_folders.py unfile loop, base equivalent 2168) and not is_closing (new 2670); the only await between the clear and commit-or-rollback is folder_repository.py:86; the consumer must be a context-new or _folder_changed turn landing in that window (chat_runner.py:12651-12652); and the write must fail (folder_repository.py:87-89) for the omission to be wrong rather than correct. Recovery: list rolled back at folder_repository.py:88, _restore_unfiled puts previous back at chat_folders.py:2200 with a pinned forced save (2202) or _dirty for the flush (2222) and republishes (2229), plus the route's own finally push.
Real fix cost: deferring the clear past mutate_folders removes the sweep's synchronous-with-commit atomicity — the stated reason it lives inside the callback ("nothing can interleave between this sweep and the commit ... so the commit cannot leave a live slot naming a folder it removes") — so the author must re-divide which of the pre-commit and post-commit sweeps owns which window and re-derive the rollback bookkeeping against a new ordering contract, a permanent comprehension load on the freeze/commit/thaw sequence, to prevent a millisecond, self-healing label omission on a failing write. The clear-then-commit-then-restore ordering is also the module's pre-existing documented contract, with a strictly wider window in the loop above.

[ADJUDICATION] d7c564f437bf7a093faabc4de88bc0274f8662d3 total=1 uphold=0 downgrade=1
DOWNGRADE F1 src/kiro_crew/dashboard/chat_folders.py:2676 reason=disproportionate-remedy
[GPT-ADJUDICATED] d7c564f437bf7a093faabc4de88bc0274f8662d3

@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5 Review (fork) — ✅ no blocking findings

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

Review details

A refused PUT /api/chat/slots/{slot}/folder now leaves the destination folder durably un-hidden; nothing here blocks the merge.

FINDING — src/kiro_crew/dashboard/chat_folders.py:2968 — if not await _unhide_folder(state, folder_id): was moved ahead of the session_gone re-authorization arm, so _unhide_folder's f["hidden"] = False + store rewrite has already committed when that arm returns 409 (deterministic, not just a race: chat_folder_file_self / chat_folder_move_session send expected_created, and a stale slot generation or a closed tab fails state._slots.get(name) is not slot after the un-hide landed) → a folder the person deliberately hid becomes permanently visible on a request the server refused, and the old previous/previous_changed restore never covered hidden → Fix: keep the _unhide_folder verdict after the re-authorization block and before the slot.folder_id assignment — that preserves the hunk's purpose (no provisional folder_id live across the await) without committing the un-hide for a request that is about to be rejected.

[OPUS-REVIEWED] d7c564f

@ash663

ash663 commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Round 1 replies, all applied in 4040b3c37 on this branch:

GPT 5.6 F2 — chat_folders.py:2116 concurrent slot removal crashes the cascade. Right. The unfile loop iterated the live state._slots view and awaited a save inside it; a close popping the table meanwhile raised RuntimeError: dictionary changed size during iteration on the next step, outside the rollback try (the iteration predates this PR on main, the cascade's is_closing skip made it reachable). The loop now walks list(state._slots.items()) and re-checks state._slots.get(name) is slot per entry, the way the archive pass already does. Regression test test_a_slot_popped_while_the_unfile_loop_awaits_does_not_crash_the_cascade (a begin_close()-fenced slot whose pop lands during the unfile save) reproduces the RuntimeError on the previous head and passes now.

GPT 5.6 F1 — chat_folders.py:2191 concurrent descendants deleted without archiving their sessions. Right. _remove now deletes target_ids & _subtree_folder_ids(folders, fid) — only the folders the archive and unfile passes emptied and that are still under the root — and re-parents to the top level any surviving folder whose parent is removed. A folder created under the subtree during a close therefore survives with its sessions live and still filed in it ("preserve and reparent"); no session is left naming a folder that is gone. Regression test test_a_child_created_during_the_cascade_survives_with_its_session creates a child and files a session into it from inside close_slot; on the previous head the child was in deleted_folder_ids, now it is the sole surviving top-level folder.

GPT 5.6 finding — tests do not pin in folder_ids / require_existing=True. Added test_the_archived_unfile_is_a_compare_and_set_that_recreates_nothing: a session refiled between the listing and the write is left alone (guard refuses), a session deleted meanwhile is not recreated as a stub, and every call passes require_existing=True.

Opus 5 — archive pass runs before mutate_folders. Kept the order, because a refused close must leave the tree intact (tab-✕ parity the cascade documents); reordering would leave live sessions under folders already gone whenever a close refuses. Two of the three named triggers do not apply: handler_cancellation is off on the dashboard app (server.py:4968 passes only client_max_size; aiohttp 3.14 default is False), so a client disconnect does not cancel the handler. The remaining one — a failed folders.json write — leaves exactly the state a refused close leaves (sessions in History, filed under folders that still exist), and a retry finds nothing live left and commits. What was missing was the audit row: the escape now logs outcome="error" with archived=N. Pinned by test_a_failed_folder_commit_after_the_archive_pass_is_audited_and_retryable, which also asserts the retry converges.

First Principles — Item 2 (default response gains three keys with no reader). Taken: the safe path answers {ok: true} byte-identical to before this PR; the counts are returned on the cascade only (test_default_reparents_children_and_unfiles_slots_as_before pins the body). Item 1 (zero consumers of delete_contents=true) stands as declared: the sidebar consumer (second confirm step showing these counts) is the follow-up, and this route is the contract it consumes.

Backend Lint & Type Check (3.12) on 371bfa2. Not a lint result: the black step was SIGTERM'd at 8m22s with no gate output (##[error]Process completed with exit code 143 at 17:42:48Z, job 108179717935, 25-min job budget unreached). The same gates (black ratchet, isort, flake8, mypy) pass locally on this head.

@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 Sep 25, 2026
@ash663
ash663 force-pushed the folder-delete-contents branch from 4040b3c to ac9fbe3 Compare September 25, 2026 19:44
@ash663

ash663 commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Round 2 reply, applied in ac9fbe305 on this branch. History note: the branch was squashed to ONE commit (371bfa275 + 4040b3c37 + the round-2 fix -> ac9fbe305, tree identical to the three-commit head) because PR Hygiene's Enforce commit count allows at most two; the lane comments above that name 371bfa275 / 4040b3c37 refer to earlier revisions of this same change.

GPT 5.6 F1 — chat_folders.py:2077 cascade archives sessions that leave the subtree during close. Right, and the mirror of round 1's late-child race: the archive pass read slot.folder_id before close_slot awaited (nudge retirement, app hook) and nothing re-checked it at the pop. The cascade now passes close_slot the existing synchronous pre_pop_check seam (chat_handlers.py:6166, the way session_control.close_target does): immediately before the pop it re-reads state._slots.get(name) is slot and slot.folder_id in target_ids, and a session that moved out (or a re-minted name) raises a cascade-internal SlotCloseError code that the loop catches and skips — close_slot unwinds the teardown (nudge loop restored, app dismissal taken back, fence released), the session stays live in the folder the person moved it to, and the cascade goes on with the rest. Regression test test_a_session_moved_out_of_the_subtree_during_its_close_is_not_archived commits the move inside the close's await window; on 4040b3c37 the session was popped (state._slots.get("moving") was None), now it is live with folder_id == keep, not closing, and the sibling in the subtree is still archived.

First Principles — item 1 (zero consumers) / item 6 (unfile-loop hardening rides along). Item 1 stands as declared: the sidebar's second confirm step is the follow-up and this route is its contract. Item 6 is the round-1 blocker F2's fix — the loop is shared by both paths, so the hardening necessarily lands on the default path too; it is tested and changes no default-path outcome.

Backend Lint & Type Check (3.12) on 4040b3c37 — not our code. Job 108208094143: the black step (Check formatting (black, baselined)) ran 18:57:21Z–19:04:45Z and was killed with exit 143 (SIGTERM) before the gate printed a result; the job's 25-min budget was not reached. The same step died the same way in the same hour on four unrelated PRs' runs (e.g. job 108210651501 on feat/cron-project-dir, runs 36176089561, 36176063571, 36175788953), and on #13879's head (job 108204268023). The black ratchet, isort, flake8 and mypy pass locally on this head.

@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 Sep 25, 2026
@ash663
ash663 force-pushed the folder-delete-contents branch from ac9fbe3 to ebde372 Compare September 25, 2026 20:36
@ash663

ash663 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Round 3 reply, applied in ebde372d2 on this branch (one squashed commit, replacing ac9fbe305; PR Hygiene's commit-count rule is why the history is squashed on each round).

This round fixes the class rather than the third instance of it. The subtree is now frozen for the cascade's duration. api_chat_folder_delete computes the set it empties once, under the folder-store lock, and records it in a frozen set that the store's own callbacks consult under the same lock (_deleting_folder_ids). While frozen: creating a child under a frozen folder is refused (400 folder_parent_deleting); renaming/reparenting a frozen folder, reparenting into one, reordering one or deleting one again is refused (409 folder_deleting); and the filing paths that consult the store — _unhide_folder (slot-folder PATCH, slot create with folder_id, resume, session-control create/fork) and arrival_folder_exists — report a frozen folder absent, so a filing gets the existing 400 folder_not_found and a resume lands the session at the top level. The archive pass therefore walks exactly the set _remove deletes; the freeze is released in a finally, whichever way the request ends.

GPT 5.6 F1 — chat_folders.py:2090 reparenting a child out still archives its sessions. Right on ac9fbe305. Now the reparent is refused while the child is frozen (test_reparenting_a_child_out_of_the_frozen_subtree_is_refused: 409 folder_deleting, the child goes with the cascade, its session archived and unfiled), so target_ids cannot go stale with respect to folder moves and the pre-pop check never sees a session under a surviving folder.

GPT 5.6 F2 — :2246 concurrent filing can persist a deleted folder id. Right on ac9fbe305. The slot-folder PATCH's existence check is _unhide_folder, under the store lock; it now reports a frozen folder absent, so the filing is refused before its save rather than racing the commit (test_filing_a_session_into_the_frozen_subtree_is_refused_and_nothing_dangles: 400 mid-cascade, the session stays live and unfiled, nothing persisted names the deleted folder, filing into the deleted id afterwards is the plain 400). Paths that file without consulting the store (a fork inheriting its parent's folder, channel/cron placement) can still land a session in a frozen folder; the unfile loop catches those live and unfiled, as before.

Opus 5 finding — :2054 target_ids read unlocked while _remove narrows it under the lock. Right; resolved by construction: the set is computed under the lock, frozen, and _remove deletes exactly it (no intersection, no narrowing), so the cascade cannot archive or unfile sessions out of a folder it then declines to delete. Also covered: a child created under the frozen subtree (test_a_child_created_under_the_frozen_subtree_is_refused), a reparent into it, a second delete of it, and release of the freeze after a refused close (test_the_freeze_is_released_when_a_refused_close_aborts_the_cascade).

First Principles. Item 1 (zero consumers) stands as declared: the sidebar's second confirm step is the follow-up and this route is its contract.

Backend Lint & Type Check (3.12). Green on ac9fbe305 (job 108227036644, 21 min). The reds on the earlier heads 371bfa275 / 4040b3c37 were the black step killed with exit 143 (SIGTERM) before it printed a result (jobs 108179717935, 108208094143 — the same kill hit e.g. job 108210651501 on feat/cron-project-dir in the same hour), not a formatting result. Locally on this head: black ratchet, isort, flake8 and mypy pass; 2185 tests across the folder, arrival-folder, channel-folder, session-control, session-transfer, slot-close and dashboard-chat files pass.

@ash663
ash663 force-pushed the folder-delete-contents branch from ebde372 to f7c29d7 Compare September 25, 2026 21:29
@ash663

ash663 commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Round 4 reply, applied in f7c29d7a1 on this branch (one squashed commit replacing ebde372d2, for PR Hygiene's commit-count rule).

GPT 5.6 F1 — chat_folders.py:2258 final slot snapshot misses late folder assignments. Right, with one precision: the slot snapshots (archive pass and unfile loop) are already taken after the freeze — the gap was that session_control's three folder existence checks (create_session's and the spawn path's _exists, and the fork's _folder_exists_now) test id presence only and assign in the same synchronous window, so a session-control create/fork could still file into a frozen folder and land between the unfile snapshot and _remove. Those three checks now read a frozen folder as absent (folder_is_deleting), so such a create/fork is refused folder_not_found and allocates nothing — the same rule _unhide_folder and arrival_folder_exists already applied. Tests: test_session_control.py::test_create_refuses_a_folder_frozen_by_a_running_delete (refused while frozen, nothing allocated; accepted once thawed) and test_session_control_fork.py::test_a_folder_frozen_by_a_running_delete_refuses_the_whole_fork. The paths that file without consulting the store at all (a fork inheriting its parent's folder, channel/cron placement) remain the residual session_control.py:2291-2301 documents: caught live and unfiled by the unfile loop, or rendered unfiled and dropped on resume.

Opus 5 advisory from ac9fbe305 (:2054, sessions archived/unfiled out of a folder the cascade then declines to delete). Not reachable with the freeze: _remove deletes exactly the frozen set, and while frozen no folder in it can be reparented out, removed by another request, or given a child, so every folder the archive pass emptied is present at commit and removed. The one write another request may make to a frozen folder is the safe-path delete of its PARENT re-parenting it to the top level; the cascade then deletes it by id regardless.

Backend Tests (3.12, 7) on ebde372d2 — ours, fixed. One failure: test/test_forced_save_history_key_pin.py::TestRefusalDispositionPerSite::test_restore_unfiled_refusal_marks_dirty_and_keeps_restored_field (job 108245073982). Its store double failed EVERY mutate_folders call; the delete now freezes through that method first (no-write callback), so the request failed before the unfile it was testing. The test now fails only the _remove commit. While there, the freeze itself became leak-proof: the callback records what it took and the thaw runs synchronously in finally without awaiting the store, so a store failure inside the freeze call cannot leave the tree frozen. Locally 2384 tests across 31 files pass, gates green.

First Principles. Item 1 (zero consumers) stands as declared.

@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 Sep 25, 2026
@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 30, 2026
@ash663
ash663 force-pushed the folder-delete-contents branch from 0346b43 to 3129e29 Compare September 30, 2026 14:22
@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 Sep 30, 2026
@ash663
ash663 force-pushed the folder-delete-contents branch from 3129e29 to 016b711 Compare September 30, 2026 15:28
@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 Sep 30, 2026
@ash663
ash663 force-pushed the folder-delete-contents branch from 016b711 to 53f981e Compare September 30, 2026 16:41
@github-actions github-actions Bot added readiness: checking Automated validation is still running merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: action required A blocking check or review needs attention labels Sep 30, 2026
…n one step

`DELETE /api/chat/folders/{id}` only ever removed the one row: its `_remove`
callback re-parented direct children to the top level and the unfile loop
moved the folder's live sessions there. A shift folder holding a hundred
per-ticket subfolders therefore could not be removed in one step -- deleting
it spilled every ticket folder onto the top level.

Add `?delete_contents=true`, mirroring the artifact-library folder delete
(same flag, same truthy spellings, same safe default). Off, the route
answers `{ok}` exactly as it does today. On, the subtree goes: every folder
in it is deleted; every live session filed anywhere in it is ARCHIVED
through `chat_handlers.close_slot`, the same function the tab close uses --
saved to history as closed, resumable, never a hard delete; and archived
sessions still filed under the subtree have `folder_id` cleared by a
compare-and-set `update_metadata_if` run off the loop, after the folder
commit succeeded. A close that refuses stops the cascade with that close's
own code and the tree untouched; a folder-store write that fails after the
archive pass is audited with the archive count and leaves that same
retryable state. The response carries the counts: deleted_folder_ids,
unfiled_sessions, archived_sessions, unfiled_history_sessions.

The sessions live in a different store from the folders, so no reading of
"what is in this folder" can be atomic with its removal. Instead the tree is
held still: the set a delete empties (the one row, or the whole subtree) is
computed once under the folder-store lock and FROZEN for the request's
duration. A frozen folder refuses a child create (400
`folder_parent_deleting`), any update or reparent, a reparent into it, a
reorder naming it and a second delete (409 `folder_deleting`), and every
filing path that consults the store -- `_unhide_folder`,
`arrival_folder_exists`, the session-control create/fork existence checks --
reports it absent to a NEW filing, so no session is filed into it (the two
callers holding a STORED filing -- the resume, the import repair -- ask with
`frozen_is_present=True` and keep it: frozen is not gone, and the delete's
commit decides) -- and the removal callback
itself sweeps the live slot table under the store lock, unfiling any slot a
path that consults neither (a cron placement, an inherited fork folder) filed
into a removed folder since the unfile snapshot, so the commit can never
leave a dangling assignment. The archive pass therefore walks exactly the set
`_remove` deletes. A session moved OUT of the subtree
while its close awaited is a rescue the delete honours: `close_slot`'s
synchronous `pre_pop_check` re-reads registration and membership at the
point of no return and unwinds that close. The unfile loop walks a list
snapshot of the slot table with a per-entry registration re-check, so a
close popping the table while a save awaits cannot raise outside the
rollback. The freeze is released synchronously in `finally`, whichever way
the request ends, including a store failure inside the freeze itself.

The unknown-folder 404 and the app-caller 403s run before the flag is
read, so an app gains no second door. No MCP tool exposes folder deletion
(tree/create/move/move_session/file_self), so none is added. The module
spec's route line describes both modes. The sidebar's second confirm step
is left for a follow-up: it needs a new destructive-confirm string across
every catalog.
…ete verb

Four parts, each also recorded as its own commit on the author's local
record branch; folded into one here because the commit-count gate caps a
PR at two commits.

1. Thaw the committed ids the moment the removal lands. The freeze's
"frozen is present" reading keeps a resume's or an import's stored
filing for the commit-time sweep to decide. That sweep runs inside the
removal callback, so once mutate_folders(_remove) has returned it cannot
see a slot published later -- yet the ids stayed frozen across the
post-commit tidy (the swept saves, the history scan), and a resume
landing there kept a filing into a folder that was already gone, which
the sidebar renders in no lane. The route now hands _delete_frozen a
thaw callback and the committed ids leave the freeze right after the
commit, before the tidy awaits; a frozen id the commit did not remove is
still released by the route's finally.

2. Close the late-assignment window at the publish; make dangling ids
inert; frozen is not gone. A folder verdict earned before an await --
the resume's stored filing, the channel reconcile's filing write --
could be published after a delete committed inside that await: the
commit-time sweep walks the live slot table, and the slot did not exist
yet. The design stays as it is (frozen subtree, commit-time sweep,
call-site checks); the window is closed at the assignment itself.
folder_is_gone is the synchronous last word -- not in the committed tree
AND not frozen -- asked with nothing between the answer and the
assignment: the resume asks it right before the build and again before
the hook path's re-publish, and the channel surface asks it for both the
stored and the just-filed folder. Gone, the session publishes unfiled.
Frozen is not gone: a stored filing into a frozen folder is kept and
published (so the commit-time sweep decides it), nothing is written, the
hydrate never clears a frozen folder's id, and serialize_slot projects
the filing as unfiled only while the folder is frozen -- an abort's thaw
re-publishes the slot table and the filing renders again, in memory, on
disk and in the payload. The commit sweeps the live table once more,
synchronously, right before the thaw, for a slot published while the
store's disk write was in flight. A dangling folder_id is made harmless
at the one read chokepoint: DashboardState.serialize_slot projects an id
no folder record carries as unfiled (full list, slot_patch frame,
single-slot answers) -- and a stored value that is not a string, since
the record comes back from a file an agent's tools can edit -- writes
nothing, and the slot's next folder write replaces the stored id. The
same shape rule holds everywhere a stored folder_id is hashed or asked
about: is_folder_id gates folder_is_deleting, folder_is_gone and
_unhide_folder (a list or a dict is not frozen, is gone, reads absent,
so the resume's own drop clears it instead of a TypeError failing the
resume every time), the delete route's membership tests go through
_filed_in (such a slot is filed nowhere, so no folder delete fails on
it), and the removal callback re-parents only a string parent_id. And a
session moved INTO the subtree is never provisionally there: every
writer that files a LIVE slot after an awaited verdict -- the
slot-folder PATCH, the chat-turn filing by name, the revive's filing --
awaits its destination's verdict (_unhide_folder, under the store
lock) before assigning slot.folder_id, so no folder_id the route may
yet reject is live for the cascade's membership pass or close_slot's
point of no return to read; a refusal leaves nothing to roll back.
And a slot an active close owns is left to that close by the two
pre-commit passes (the unfile loop and the commit callback's sweep
skip is_closing, as the archive pass does): every save the route could
make for it is refused by the close fence and only marks it dirty,
while the close's own archival save is unguarded -- an in-memory
unfile would be persisted by that save and, the commit then failing,
could not be restored. Its closing save carries the folder it sat in;
the post-commit pass clears that row on a committed cascade. The
arrival resolver refuses a frozen adopted group or sender folder under
the store lock, the way create_folder_record refuses a frozen parent, so
a sender folder cannot be appended under a group a delete is removing
and outlive it re-parented to the top level.

3. chat_folder_delete, the agent-facing consumer of delete_contents. It
sits beside chat_folder_create on the dashboard MCP server: `folder` (id
or human path) and `delete_contents` (default false). The default is the
route's safe delete; delete_contents=true removes the whole subtree and
archives every session in it through the tab-close path, and the
description tells the agent to echo the affected count to the user
first, as artifact_folder_delete's does. A thin wrapper: the endpoint
owns every rule. The verified caller key rides on the DELETE
(mcp_core._delete gains the session_key and timeout keywords _patch
already has), the resolved id is quoted as one path segment, so an app agent's call gets the route's own
folder_delete_forbidden and a crew member's is refused by the member
gate; the person's own sessions delete. The set-grant ratchet records
the decision and why the verb's blast radius stays bounded by the route.
The sidebar dialog is a separate frontend follow-up.

4. The channel filing writers re-ask the folder at their commit
boundary. reconcile_channel_slots and backfill_channel_folder write a
filing with update_metadata_if under the transcript's lock; the folder
verdict they held was earned before that write queued, and a delete can
freeze and commit in between. _filing_write_guard wraps both writes:
evaluated under the record's lock right before the write, it refuses a
folder that is frozen or gone, so a write stalled across a delete lands
no deleted id. The guard resolves the frozen set on the loop when it is
built and the worker thread only reads it. And because the folder store
has its own lock and the write itself is a transcript rewrite off the
loop, _filing_stands_after_the_write asks the folder once more on the
loop the moment the write is known to have landed: gone, the filing is
withdrawn with a compare-and-set on the value the pass wrote (folder
cleared, marker taken back) so the conversation stays unfiled and
eligible; frozen, the pass waits for the running delete's verdict --
the route thaws in a finally, so the wait is bounded by the delete --
and a commit withdraws while an abort keeps the filing. The
withdrawal's verdict is read back from the row, never from the
conditional write's boolean: a row another writer settled stands, a row
still naming the folder is retried once, and an unconfirmed withdrawal
is returned as such -- the reconcile surfaces the conversation unfiled,
the backfill reports a failed write, never a move.

Also: cron_inject names the import cycle on its function-local
chat_folders import; the delete verb's description stops short of
per-folder archived counts, which the folder tree does not carry, and
its result names the counts as filings cleared -- from live sessions
during the deletion, and from stored sessions -- not as sessions.

Tests: the thaw (frozen set empty and the resume reading absent during a
swept slot's post-commit save, both modes); the window (a resume whose
folder is deleted between the verdict and the build publishes unfiled,
the revive hook path likewise, a channel restore into a gone folder
surfaces unfiled, a dangling id or one of the wrong shape projects
unfiled in every view and is replaced by the next slot-folder write);
frozen is not gone (a cascade that aborts retains a filing resumed while
it ran -- memory, disk, payload after the thaw -- and one that commits
unfiles it; a slot published during the commit's disk write is swept
before the thaw; the hydrate never clears a frozen id; a frozen filing
projects unfiled only while frozen; a frozen adopted group or sender
folder takes no arrival, and a frozen hidden group owes no un-hide; a
stored folder_id that is not a string resumes to an unfiled slot with
the value cleared, and a folder delete survives a live slot carrying
one; a cascade run inside a move's verdict await never archives the
moving session, a confirmed move lands, and the revive and chat-turn
filings hold no provisional folder_id while their verdict is pending;
a failed commit leaves a mid-close session's folder on its transcript
and a committed cascade clears that row); the channel writers'
commit boundary (a
stalled write lands no deleted id, is skipped while frozen; a filing
that landed as its folder was deleted is withdrawn, by compare-and-set
on this pass's value, waited for while frozen, and neither mirrored nor
counted by the backfill; an unconfirmed withdrawal is a failed write in
the report; the guard reads the freeze the loop owns); the verb (both
modes' call shape and counts, the verified key on the write, root and
unknown-folder refusals, the endpoint's app and member refusals surfaced
verbatim, the unverifiable-caller refusal, schema validation, the
description contract; the registration and advertised-set ratchets and
the doc tool count carry the verb). Fixtures that filed into ids with no
folder record now create the folder.
@ash663
ash663 force-pushed the folder-delete-contents branch from 53f981e to d7c564f Compare September 30, 2026 18:03
@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: checking Automated validation is still running labels Sep 30, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

Hi @ash663 — thank you very much for this work and for seeing it through, including choosing option (c) and fixing the fenced BLOCKs yourself. We really appreciate the care you put into it.

After review, the maintainers have decided not to take this feature. An opt-in delete_contents subtree delete isn't something we need right now, and the change is larger and riskier than the value it adds: roughly +3.4k lines across 16 source files, touching session transfer, cron inject, channel slots, and resume paths, with a GPT security review block still open on the delete cascade.

This is no reflection on the quality of your contribution — thank you again for the time and effort. I'm closing this PR with that decision.

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 needs-author-decision PR blocked on author input

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants