Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,48 +1,13 @@
# This migration comes from coplan (originally 20261120230000)
# Comments deleted before Comments::SoftDelete blanked them still hold their
# text in three places: the comment row, the comment_deleted history event's
# body_preview, and agent events queued for the comment. Each step is one
# idempotent UPDATE per row with no model code, so a rerun is harmless and no
# row's content can fail it.
# The historical migration name is retained for hosts that already installed it.
# Deleted comment content must remain in the database until an admin explicitly
# deletes it permanently. This migration only installs the comment lookup index.
class ScrubDeletedCommentBodies < ActiveRecord::Migration[8.1]
DELETED_BODY = "_This comment was deleted._".freeze

class Comment < ActiveRecord::Base
self.table_name = "coplan_comments"
end

class PlanEvent < ActiveRecord::Base
self.table_name = "coplan_plan_events"
end

class AgentEvent < ActiveRecord::Base
self.table_name = "coplan_agent_events"
end

def up
# Deleting a comment now looks up its agent events.
add_index :coplan_agent_events, :comment_id unless index_exists?(:coplan_agent_events, :comment_id)

deleted = Comment.where.not(deleted_at: nil)
deleted.where.not(body_markdown: DELETED_BODY).update_all(body_markdown: DELETED_BODY)

PlanEvent.where(event_type: "comment_deleted").find_each do |event|
metadata = event.metadata
next unless metadata.is_a?(Hash) && metadata.key?("body_preview")

event.update_columns(metadata: metadata.except("body_preview"))
end

AgentEvent.where(comment_id: deleted.select(:id)).find_each do |event|
payload = event.payload
next unless payload.is_a?(Hash) && payload.key?("comment_body") && payload["comment_body"] != DELETED_BODY

event.update_columns(payload: payload.merge("comment_body" => DELETED_BODY))
end
end

def down
# The deleted text is gone on purpose; only the index comes back out.
remove_index :coplan_agent_events, :comment_id if index_exists?(:coplan_agent_events, :comment_id)
end
end
1 change: 1 addition & 0 deletions docs/DEMO_LIBRARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ look up this key rather than copying generated UUIDs.
| pending-review | Two approvers, neither approved |
| review-reassignment | Alex Pending after reassignment; earlier approval and removal remain in activity, Noura stays Approved |
| approved-review | Two approvers, both approved |
| deleted-comments | A retained soft-deleted comment, a visible reply, and an explicit admin-only permanent deletion form |
| collab-showcase | Agent edit, human and agent comments, open/resolved and overlapping anchors, general thread, citations and references |
| api-gateway | Architecture proposal with a wide flowchart, trust-boundary table, rollout, external links |
| launch-deck | Presentation with speaker notes |
Expand Down
8 changes: 8 additions & 0 deletions docs/HOST_APP_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -422,3 +422,11 @@ redact both connection codes, and approval/token responses disable caching.
The helper stores the credential with mode 0600 without printing it. A second
host needs its own credentials file; the helper never overwrites another host's
configuration.

## Deleted comment retention

Ordinary comment deletion sets `deleted_at` and preserves the stored body. Public pages, notification previews, API responses, and queued agent event responses hide the text. Admins can inspect retained content under Plan Comments. The separate permanent deletion form requires a soft-deleted comment and explicit confirmation; it removes the comment and its associated copies. A metadata-only history entry records the admin who performed permanent deletion.

The historical `ScrubDeletedCommentBodies` migration now only adds the agent-event comment lookup index. Keep its historical migration version when updating an installed host copy, so Rails does not run the same migration twice. Replace any pending copy of the old destructive implementation before deploying this revision. Text erased by an earlier release cannot be recovered by migrating down.

Review notes also belong to immutable review receipts. Deleting the linked discussion comment does not change its receipt. The admin comment purge refuses these notes and leaves the receipt intact.
48 changes: 36 additions & 12 deletions engine/app/admin/comments.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
ActiveAdmin.register Coplan::Comment, as: "PlanComment" do
# No destroy and no batch delete: a hard delete leaves no trace, and
# nothing in Coplan can restore it. Authors soft-delete their own comments.
actions :all, except: [ :destroy ]
# Inspect retained content here; permanent deletion is a separate action.
actions :index, :show
config.batch_actions = false
permit_params :body_markdown

filter :comment_thread_id
filter :author_type
filter :created_at
filter :deleted_at

member_action :permanently_delete, method: :delete do
unless params[:confirmation] == "DELETE"
return render json: { error: "Type DELETE to confirm permanent deletion." }, status: :unprocessable_content
end

Coplan::Comments::PermanentlyDelete.call(comment: resource, actor: current_coplan_admin_user)
render json: { html: render_to_string(partial: "coplan/admin/comment_permanently_deleted", formats: [ :html ]) }
rescue Coplan::Comments::PermanentlyDelete::NotAllowed => error
render json: { error: error.message }, status: :unprocessable_content
end

index do
id_column
Expand All @@ -16,18 +26,32 @@
column :author_id
column(:body_markdown) { |c| truncate(c.body_markdown, length: 80) }
column :created_at
column :deleted_at
actions
end

show do
attributes_table do
row :id
row :comment_thread
row :author_type
row :author_id
row :body_markdown
row :created_at
row :updated_at
text_node javascript_import_module_tag("coplan/admin_comments")
div data: { controller: "coplan--admin-comment-deletion" } do
attributes_table do
row :id
row :comment_thread
row :author_type
row :author_id
row :body_markdown
row :created_at
row :updated_at
row :deleted_at
end
if resource.review_note?
para "This comment belongs to an immutable review receipt. Permanent deletion is unavailable here."
elsif resource.deleted?
panel "Permanently delete comment" do
render "coplan/admin/comment_deletion", comment: resource
end
else
para "This comment is active. Its author must soft-delete it before an admin can permanently delete it."
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def long_poll_events
events = fetch_events
if events.any? || Time.current >= deadline
render json: {
events: events.map(&:as_api_json),
events: AgentEvent.as_api_json_batch(events),
cursor: events.last&.id || params[:cursor],
**(granted ? {} : { throttled: true })
}
Expand Down Expand Up @@ -113,8 +113,8 @@ def write_event_stream

while Time.current < deadline
events = fetch_events(cursor: cursor)
events.each do |event|
response.stream.write("id: #{event.id}\nevent: #{event.event_type}\ndata: #{event.as_api_json.to_json}\n\n")
events.zip(AgentEvent.as_api_json_batch(events)).each do |event, serialized|
response.stream.write("id: #{event.id}\nevent: #{event.event_type}\ndata: #{serialized.to_json}\n\n")
cursor = event.id
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ def thread_json(thread)
author_type: c.author_type,
author_id: c.author_id,
agent_name: c.agent_name,
body_markdown: c.body_markdown,
body_markdown: c.public_body_markdown,
deleted: c.deleted?,
created_at: c.created_at,
reactions: CommentReaction.as_api_json(c)
Expand Down
2 changes: 1 addition & 1 deletion engine/app/controllers/coplan/api/v1/plans_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ def thread_json(thread)
author_type: c.author_type,
author_id: c.author_id,
agent_name: c.agent_name,
body_markdown: c.body_markdown,
body_markdown: c.public_body_markdown,
deleted: c.deleted?,
created_at: c.created_at,
reactions: CommentReaction.as_api_json(c)
Expand Down
2 changes: 1 addition & 1 deletion engine/app/controllers/coplan/dictations_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def reject_prompt_echo(transcript)
end

def recent_comments
# kept: a deleted comment's text was removed on purpose, and this
# kept: deleted comments are hidden from normal readers, and this
# context leaves the building — it must not resurface there.
Comment.kept.joins(:comment_thread)
.where(comment_thread: { plan_id: @plan.id })
Expand Down
2 changes: 2 additions & 0 deletions engine/app/helpers/coplan/plan_events_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ def render_event_summary(event)
safe_join([ "Withdrew the review request for ", content_tag(:strong, event.metadata["reviewer_name"]) ])
when "comment_deleted"
"Deleted comment"
when "comment_permanently_deleted"
"Permanently deleted comment"
else
"#{event.event_type}: #{event.before_value || "—"} → #{event.after_value || "—"}"
end
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
static targets = ["form", "button", "error"]

connect() {
this.buttonTarget.disabled = false
}

async submit(event) {
event.preventDefault()
if (this.buttonTarget.disabled) return

this.buttonTarget.disabled = true
this.buttonTarget.textContent = "Permanently deleting…"
this.errorTarget.textContent = ""
this.element.setAttribute("aria-busy", "true")

try {
const response = await fetch(this.formTarget.action, {
method: "DELETE",
body: new FormData(this.formTarget),
headers: {
"Accept": "application/json"
}
})
const result = await response.json()
if (!response.ok) throw new Error(result.error || "Permanent deletion failed. Try again.")

this.element.innerHTML = result.html
} catch (error) {
this.errorTarget.textContent = error.message
this.buttonTarget.disabled = false
this.buttonTarget.textContent = "Permanently delete comment"
} finally {
this.element.removeAttribute("aria-busy")
}
}
}
5 changes: 5 additions & 0 deletions engine/app/javascript/coplan/admin_comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Application } from "@hotwired/stimulus"
import AdminCommentDeletionController from "controllers/coplan/admin_comment_deletion_controller"

const application = Application.start()
application.register("coplan--admin-comment-deletion", AdminCommentDeletionController)
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module Coplan
class BroadcastPermanentCommentDeletionJob < ApplicationJob
queue_as :default
self.enqueue_after_transaction_commit = false

retry_on StandardError, wait: :polynomially_longer, attempts: 5
retry_on ActiveRecord::RecordNotFound, wait: 1.second, attempts: 5 do |_job, _error|
Rails.logger.info("Permanent comment deletion broadcast has no audit event; the producer rolled back or the plan was removed.")
end

def perform(event_id:, user_ids:)
event = PlanEvent.find(event_id)
event.broadcast_history_update
thread = CommentThread.find_by(id: event.metadata.fetch("thread_id"))
if thread
comment = Comment.new(id: event.metadata.fetch("comment_id"))
target = thread.empty? ? thread : comment
Broadcaster.remove_to(thread.plan, target: ActionView::RecordIdentifier.dom_id(target))
Comments::RefreshPreviews.call(thread: thread)
end
Notifications::BroadcastBadges.call(user_ids: user_ids)
end
end
end
6 changes: 4 additions & 2 deletions engine/app/jobs/coplan/create_notifications_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ class CreateNotificationsJob < ApplicationJob
queue_as :default

def perform(comment_thread_id:, actor_id:, comment_id: nil, reason:, actor_api_token_id: nil, excluded_user_ids: [])
thread = CommentThread.find(comment_thread_id)
comment = comment_id ? Comment.find(comment_id) : nil
thread = CommentThread.find_by(id: comment_thread_id)
return unless thread
comment = comment_id ? thread.comments.find_by(id: comment_id) : nil
return if comment_id && (comment.nil? || comment.deleted?)
Notifications::Create.call(
comment_thread: thread,
actor_id: actor_id,
Expand Down
22 changes: 20 additions & 2 deletions engine/app/models/coplan/agent_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,34 @@ def self.ransackable_associations(_auth_object = nil)
%w[api_token plan]
end

def as_api_json
def self.as_api_json_batch(events)
comment_ids = events.filter_map do |event|
event.comment_id if event.payload.is_a?(Hash) && event.payload.key?("comment_body")
end
visible_ids = Comment.kept.where(id: comment_ids).pluck(:id).to_set
events.map { |event| event.as_api_json(comment_visible: visible_ids.include?(event.comment_id)) }
end

def as_api_json(comment_visible: nil)
{
id: id,
type: event_type,
plan_id: plan_id,
comment_thread_id: comment_thread_id,
comment_id: comment_id,
payload: payload,
payload: public_payload(comment_visible: comment_visible),
created_at: created_at
}
end

private

def public_payload(comment_visible:)
return payload unless comment_id.present? && payload.is_a?(Hash) && payload.key?("comment_body")
visible = comment_visible.nil? ? Comment.kept.exists?(id: comment_id) : comment_visible
return payload if visible

payload.merge("comment_body" => Comment::DELETED_BODY)
end
end
end
19 changes: 13 additions & 6 deletions engine/app/models/coplan/comment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,20 @@ class Comment < ApplicationRecord
# Attribution labels sit inline next to the body, so they stay short.
AGENT_NAME_LIMIT = 20

# What a deleted comment's body becomes. Deleting a comment retracts its
# words, so none of the readers that copy the body (the API, the inbox,
# web push, Slack DMs, agent events) can serve them afterwards.
# Public readers see a tombstone; the stored body remains available to admins.
DELETED_BODY = "_This comment was deleted._".freeze

belongs_to :comment_thread
# Notifications reference the comment, so deleting one used to fail on
# a foreign key. They're delivery records for a comment that no longer
# exists — they go with it.
has_many :notifications, class_name: "Coplan::Notification", dependent: :delete_all
has_many :notifications, class_name: "Coplan::Notification", dependent: :destroy
has_many :reactions, class_name: "Coplan::CommentReaction", dependent: :delete_all
belongs_to :api_token, class_name: "Coplan::ApiToken", optional: true
belongs_to :agent_harness, class_name: "Coplan::AgentHarness", optional: true

def self.ransackable_attributes(_auth_object = nil)
%w[id comment_thread_id author_type author_id created_at]
%w[id comment_thread_id author_type author_id created_at deleted_at]
end

def self.ransackable_associations(_auth_object = nil)
Expand Down Expand Up @@ -51,7 +49,16 @@ def deleted?
end

def soft_delete!
update!(deleted_at: Time.current, body_markdown: DELETED_BODY)
update!(deleted_at: Time.current)
end

def public_body_markdown
deleted? ? DELETED_BODY : body_markdown
end

def review_note?
ReviewResponse.exists?(comment_thread_id: comment_thread_id) &&
comment_thread.comments.order(:created_at, :id).pick(:id) == id
end

# Call in the same transaction that changes this comment's reactions.
Expand Down
5 changes: 2 additions & 3 deletions engine/app/models/coplan/plan_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class PlanEvent < ApplicationRecord
attachment_added
attachment_removed
comment_deleted
comment_permanently_deleted
review_requested
review_withdrawn
review_removed
Expand Down Expand Up @@ -66,9 +67,7 @@ def history_kind
:event
end

after_create_commit :broadcast_history_update

private
after_create_commit :broadcast_history_update, unless: -> { event_type == "comment_permanently_deleted" }

# Prepend the new event into the open history tab and bump the count
# badge so anyone watching the plan sees metadata changes appear live
Expand Down
2 changes: 1 addition & 1 deletion engine/app/services/coplan/agent_events/publish.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def call

# The job that publishes may have loaded the comment before it was
# deleted. Lock and re-read it: a delete either finished first (skip,
# nothing to retract) or waits for these rows and then scrubs them.
# nothing to publish) or later readers redact the queued payload.
Comment.transaction do
@comment = Comment.lock.find_by(id: @comment.id)
publish if @comment && !@comment.deleted?
Expand Down
Loading
Loading