fix: exclude lifecycle turns from task activity (#3142)

This commit is contained in:
Carlos Florêncio
2026-08-29 10:00:07 +00:00
committed by GitHub
parent 4e732c7989
commit 21e7d5be23
12 changed files with 302 additions and 15 deletions
@@ -79,6 +79,7 @@ func (r *Repository) LoadTaskLastActivity(ctx context.Context, taskIDs []string)
for _, chunk := range chunkIDs(taskIDs, sqliteMaxHostParams/6) {
placeholders, ids := buildInPlaceholders(chunk)
lifecycleOnlyPredicate := turnLifecycleOnlyPredicate(r.ro.DriverName(), "task_session_turns")
query := `
WITH activity AS (
SELECT id AS task_id, created_at AS activity_at
@@ -103,11 +104,13 @@ func (r *Repository) LoadTaskLastActivity(ctx context.Context, taskIDs []string)
FROM task_session_turns
WHERE task_id IN (` + placeholders + `)
AND started_at IS NOT NULL
AND NOT (` + lifecycleOnlyPredicate + `)
UNION ALL
SELECT task_id, completed_at AS activity_at
FROM task_session_turns
WHERE task_id IN (` + placeholders + `)
AND completed_at IS NOT NULL
AND NOT (` + lifecycleOnlyPredicate + `)
)
SELECT task_id, MAX(activity_at) AS activity_at
FROM activity
@@ -119,6 +119,17 @@ func TestPostgresTaskLastActivityBatch(t *testing.T) {
}, 10); err != nil {
t.Fatalf("insert postgres queued agent prompt: %v", err)
}
lifecycleCompletedAt := base.Add(8 * time.Hour)
if err := repo.CreateTurn(ctx, &models.Turn{
ID: "turn-activity-postgres-lifecycle",
TaskSessionID: "session-activity-postgres",
TaskID: "task-activity-postgres",
StartedAt: base.Add(7 * time.Hour),
CompletedAt: &lifecycleCompletedAt,
Metadata: map[string]interface{}{models.TurnMetaKeyLifecycleOnly: true},
}); err != nil {
t.Fatalf("create postgres lifecycle turn: %v", err)
}
got, err := repo.LoadTaskLastActivity(ctx, []string{"task-activity-postgres"})
if err != nil {
@@ -245,6 +245,17 @@ func TestTaskLastActivityBatch(t *testing.T) {
}); err != nil {
t.Fatalf("create agent message: %v", err)
}
lifecycleCompletedAt := base.Add(14 * time.Hour)
if err := repo.CreateTurn(ctx, &models.Turn{
ID: "turn-activity-lifecycle",
TaskSessionID: "session-activity-turn",
TaskID: "task-activity-turn",
StartedAt: base.Add(13 * time.Hour),
CompletedAt: &lifecycleCompletedAt,
Metadata: map[string]interface{}{models.TurnMetaKeyLifecycleOnly: true},
}); err != nil {
t.Fatalf("create lifecycle turn: %v", err)
}
if err := repo.CreateTurn(ctx, &models.Turn{
ID: "turn-activity-active",
TaskSessionID: "session-activity-active",
@@ -7,6 +7,7 @@ import (
"time"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/task/models"
)
func (p *Projector) applySourceEventLocked(state *projectionState, eventType string, data map[string]interface{}) bool {
@@ -85,8 +86,14 @@ func applyTaskActivityEventLocked(state *projectionState, eventType string, data
}
candidate = timeValue(data["queued_at"])
case events.TurnStarted:
if isLifecycleOnlyTurn(data) {
return false
}
candidate = timeValue(data["started_at"])
case events.TurnCompleted:
if isLifecycleOnlyTurn(data) {
return false
}
candidate = timeValue(data["completed_at"])
default:
return false
@@ -94,6 +101,11 @@ func applyTaskActivityEventLocked(state *projectionState, eventType string, data
return advanceTaskActivity(state, candidate)
}
func isLifecycleOnlyTurn(data map[string]interface{}) bool {
metadata, _ := data["metadata"].(map[string]interface{})
return boolValue(metadata[models.TurnMetaKeyLifecycleOnly])
}
func isUserQueuedPrompt(data map[string]interface{}) bool {
queuedBy := stringField(data, "queued_by")
return queuedBy != "" && queuedBy != "agent" && queuedBy != "workflow" && queuedBy != "server"
@@ -15,6 +15,7 @@ import (
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/events/bus"
"github.com/kandev/kandev/internal/task/models"
)
type projectorTestStore struct {
@@ -448,6 +449,48 @@ func TestProjectorLastActivityTracksBoundedSourcesMonotonically(t *testing.T) {
assertProjectedLastActivity(t, store.summary(taskID), "2026-08-01T18:10:00Z")
}
// @covers AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.10
func TestProjectorLastActivityIgnoresLifecycleTurns(t *testing.T) {
_, store, eventBus, _, _ := newProjectorTest(t)
const taskID = "task-last-activity-lifecycle"
const sessionID = "session-last-activity-lifecycle"
publishProjectorEvent(t, eventBus, events.TaskCreated, events.TaskCreated, map[string]interface{}{
"task_id": taskID,
"workspace_id": "workspace-1",
"created_at": "2026-08-01T18:00:00Z",
"updated_at": "2026-08-01T18:00:00Z",
})
publishProjectorEvent(t, eventBus, events.TurnStarted, events.TurnStarted, map[string]interface{}{
"task_id": taskID,
"session_id": sessionID,
"started_at": "2026-08-01T18:01:00Z",
"metadata": map[string]interface{}{models.TurnMetaKeyLifecycleOnly: true},
})
publishProjectorEvent(t, eventBus, events.TurnCompleted, events.TurnCompleted, map[string]interface{}{
"task_id": taskID,
"session_id": sessionID,
"completed_at": "2026-08-01T18:02:00Z",
"metadata": map[string]interface{}{models.TurnMetaKeyLifecycleOnly: true},
})
assertProjectedLastActivity(t, store.summary(taskID), "2026-08-01T18:00:00Z")
publishProjectorEvent(t, eventBus, events.TurnStarted, events.TurnStarted, map[string]interface{}{
"task_id": taskID,
"session_id": sessionID,
"started_at": "2026-08-01T18:03:00Z",
})
assertProjectedLastActivity(t, store.summary(taskID), "2026-08-01T18:03:00Z")
publishProjectorEvent(t, eventBus, events.TurnCompleted, events.TurnCompleted, map[string]interface{}{
"task_id": taskID,
"session_id": sessionID,
"completed_at": "2026-08-01T18:04:00Z",
})
assertProjectedLastActivity(t, store.summary(taskID), "2026-08-01T18:04:00Z")
}
func TestProjectorLastActivityRehydratesFromDurableLoader(t *testing.T) {
const taskID = "task-last-activity-rehydrate"
want := time.Date(2026, 8, 1, 18, 11, 0, 0, time.UTC)
@@ -1,6 +1,6 @@
# ADR-2026-08-17-separate-task-activity-from-summary-freshness: Separate Task Activity From Summary Freshness
**Status:** accepted
**Status:** accepted (amended 2026-08-29)
**Date:** 2026-08-17
**Area:** backend, frontend, protocol
@@ -24,7 +24,10 @@ rebuildable summary.
- task creation or a persisted task mutation
- a user-authored prompt, including a prompt that enters the queue
- an agent turn start or completion
- a conversational agent turn start or completion
A turn with `metadata.lifecycle_only=true` is not conversational. The
synthetic turn named `agent_boot` on resume does not advance task activity.
The timestamp does not advance for task focus, session subscription, Git or
pull-request polling, queue bookkeeping, status-summary repair, or session
@@ -47,9 +50,10 @@ Idle tasks stay stable when background provider status changes. Desktop and
mobile saved views can sort by meaningful work without opening task sessions.
The backend needs a batched activity query and more bounded projector inputs.
Turn milestones prevent per-chunk agent output from producing task-list update
traffic. A running turn becomes recent when it starts and advances again when
it completes.
Both paths must exclude lifecycle-only turns. Conversational-turn milestones
prevent per-chunk agent output from producing task-list update traffic. A
running conversational turn becomes recent when it starts and advances again
when it completes.
Older summaries need a one-time semantic repair. During partial rollout, the
frontend falls back to the task update or creation time when
@@ -65,3 +69,5 @@ frontend falls back to the task update or creation time when
history is not loaded and task switchers must not subscribe to it.
- **Write every activity to the task row.** Rejected because message and turn
domains gain extra task writes and mix activity with task edits.
- **Count every persisted turn.** Rejected because lifecycle turns record
runtime maintenance, not user or agent work.
+1 -1
View File
@@ -183,7 +183,7 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-08-15-office-mode-follows-active-workspace | [Office Mode Follows the Active Workspace](2026-08-15-office-mode-follows-active-workspace.md) | accepted | frontend, backend | 2026-08-15 |
| 2026-08-16-session-mcp-tool-catalog | [Keep MCP Tool Catalogs Session Owned](2026-08-16-session-mcp-tool-catalog.md) | superseded by 2026-08-18-session-mcp-tool-definition-details | backend, agentctl, frontend, protocol, security | 2026-08-16 |
| 2026-08-18-session-mcp-tool-definition-details | [Bound MCP Tool Definition Details to Current Sessions](2026-08-18-session-mcp-tool-definition-details.md) | accepted | backend, agentctl, frontend, protocol, security | 2026-08-18 |
| 2026-08-17-separate-task-activity-from-summary-freshness | [Separate Task Activity From Summary Freshness](2026-08-17-separate-task-activity-from-summary-freshness.md) | accepted | backend, frontend, protocol | 2026-08-17 |
| 2026-08-17-separate-task-activity-from-summary-freshness | [Separate Task Activity From Summary Freshness](2026-08-17-separate-task-activity-from-summary-freshness.md) | accepted (amended 2026-08-29) | backend, frontend, protocol | 2026-08-17 |
| 2026-08-17-release-pr-ruleset-bypass | [Give Stable Release PRs an Administrator Token Bypass](2026-08-17-release-pr-ruleset-bypass.md) | accepted | infra, workflow, security | 2026-08-17 |
| 2026-08-18-never-started-agent-stall-terminal | [Treat Never-Started Agent Stalls as Terminal](2026-08-18-never-started-agent-stall-terminal.md) | accepted | backend, frontend, protocol | 2026-08-18 |
| 2026-08-18-plugin-task-row-metadata | [Keep Task Row Plugin Metadata Generic](2026-08-18-plugin-task-row-metadata.md) | accepted | frontend | 2026-08-18 |
@@ -0,0 +1,92 @@
---
created: 2026-08-29
status: done
requirements:
- REQ-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001
system_design:
- ../../specs/platform/system-design/bounded-task-status-delivery.md
legacy_specs: []
---
# Implementation Plan: Preserve Last Activity During Passive Resume
## Overview
Exclude synthetic lifecycle turns from task activity. Apply the same rule to
live projection and restart reconstruction so both paths stay equivalent.
## Scope
### In scope
- Preserve `last_activity_at` when task opening resumes an idle agent.
- Exclude turns marked `lifecycle_only` from live activity projection.
- Exclude the same turns from SQLite and PostgreSQL activity reconstruction.
- Add focused regression tests for both activity paths.
### Out of scope
- Change agent resume, task focus, or session subscription behavior.
- Remove `agent_boot` messages or their synthetic parent turns.
- Change activity for task mutations, user prompts, or conversational turns.
- Change sidebar sorting, labels, or saved-view settings.
## Technical approach
### Live projection
Update `applyTaskActivityEventLocked` in
`apps/backend/internal/task/statussummary/projector_events.go`. Ignore
`turn.started` and `turn.completed` events whose metadata sets
`lifecycle_only`.
Use the existing marker from `models.TurnMetaKeyLifecycleOnly`. Add projector
tests that compare lifecycle turns with conversational turns.
### Durable reconstruction
Update `LoadTaskLastActivity` in
`apps/backend/internal/task/repository/sqlite/task_status_summary.go`. Filter
both turn branches with the existing dialect-aware lifecycle predicate.
Use `turnLifecycleOnlyPredicate` so SQLite and PostgreSQL use the same marker
semantics. Extend both activity-batch tests with a newer lifecycle turn. The
expected result must remain the latest qualifying activity.
## Tests
- `AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.10`: the projector test proves
that lifecycle-turn events do not change `last_activity_at`.
- `AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.10`: the SQLite test proves
that restart reconstruction ignores a newer lifecycle turn.
- The PostgreSQL test uses the same scenario when its test database exists.
## Work orders
- [x] [Task 01: Exclude lifecycle turns from activity](task-01-exclude-lifecycle-turns.md)
## Verification results
- RED: `cd apps/backend && go test ./internal/task/statussummary -run
TestProjectorLastActivityIgnoresLifecycleTurns -count=1` failed because a
lifecycle-only completion advanced projected activity.
- RED: `cd apps/backend && go test ./internal/task/repository/sqlite -run
'TestTaskLastActivityBatch|TestPostgresTaskLastActivityBatch' -count=1`
failed because the SQLite batch included the newer lifecycle turn.
- GREEN: `cd apps/backend && go test ./internal/task/statussummary -run
'LastActivity.*Lifecycle|Lifecycle.*LastActivity'` passed.
- GREEN: `cd apps/backend && go test ./internal/task/repository/sqlite -run
'TaskLastActivity'` passed.
- GREEN race checks passed for both targeted commands.
- Full affected packages passed: `statussummary` (80 tests) and `sqlite` (814
tests).
- `gofmt -l` reported no changed Go files, and `git diff --check` passed.
## Risks
- Live and reconstructed activity can diverge if only one path applies the
lifecycle marker.
- SQLite and PostgreSQL decode JSON booleans differently. The shared predicate
must retain the existing tolerant marker semantics.
- Conversational turns without the marker must keep their current activity
behavior.
@@ -0,0 +1,97 @@
---
id: "01-exclude-lifecycle-turns"
title: "Exclude lifecycle turns from activity"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001
acceptance_criteria:
- AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.10
system_design:
- ../../specs/platform/system-design/bounded-task-status-delivery.md
---
# Task 01: Exclude Lifecycle Turns From Activity
## Summary
Make lifecycle-only turns invisible to `last_activity_at`. Keep live projection
and restart reconstruction on one marker contract.
## In scope
- Add failing live-projector and repository regression tests.
- Ignore lifecycle-only turn events in the task-status projector.
- Filter lifecycle-only rows from the activity reconstruction query.
- Cover SQLite and the environment-gated PostgreSQL path.
## Out of scope
- Change lifecycle-turn creation or message history.
- Change agent resume or task-state transitions.
- Change frontend code or saved-view behavior.
## Acceptance
- A newer lifecycle-only turn does not change live or rebuilt task activity.
- A newer conversational turn still advances task activity.
- SQLite and PostgreSQL use the existing shared marker predicate.
## Verification
```bash
cd apps/backend && go test ./internal/task/statussummary -run 'LastActivity.*Lifecycle|Lifecycle.*LastActivity'
cd apps/backend && go test ./internal/task/repository/sqlite -run 'TaskLastActivity'
```
## Files likely touched
- `apps/backend/internal/task/statussummary/projector_events.go`
- `apps/backend/internal/task/statussummary/projector_test.go`
- `apps/backend/internal/task/repository/sqlite/task_status_summary.go`
- `apps/backend/internal/task/repository/sqlite/task_status_summary_test.go`
- `apps/backend/internal/task/repository/sqlite/task_status_summary_postgres_test.go`
## Dependencies
None.
## Risks
- A hand-written JSON expression can drift between database dialects.
- An over-broad filter can remove real conversational turns.
## Parallelism
`sequential`
## Inputs
- `AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.10`
- The activity derivation section in the bounded task-status design.
- `ADR-2026-08-17-separate-task-activity-from-summary-freshness`
- `models.TurnMetaKeyLifecycleOnly` and `turnLifecycleOnlyPredicate`.
## Results
- RED: `cd apps/backend && go test ./internal/task/statussummary -run
TestProjectorLastActivityIgnoresLifecycleTurns -count=1` failed because the
lifecycle-only completion timestamp advanced live activity.
- RED: `cd apps/backend && go test ./internal/task/repository/sqlite -run
'TestTaskLastActivityBatch|TestPostgresTaskLastActivityBatch' -count=1`
failed because the SQLite batch included the newer lifecycle turn.
- GREEN: `cd apps/backend && go test ./internal/task/statussummary -run
'LastActivity.*Lifecycle|Lifecycle.*LastActivity'` passed.
- GREEN: `cd apps/backend && go test ./internal/task/repository/sqlite -run
'TaskLastActivity'` passed.
- GREEN race checks passed for both targeted commands.
- Full affected packages passed: `statussummary` (80 tests) and `sqlite` (814
tests).
- `gofmt -l` reported no changed Go files, and `git diff --check` passed.
- Changed files: `projector_events.go`, `projector_test.go`,
`task_status_summary.go`, `task_status_summary_test.go`, and
`task_status_summary_postgres_test.go`.
- The live projector and durable activity loader now share the existing
`lifecycle_only` marker contract. No known implementation blockers remain.
@@ -2,7 +2,7 @@
status: active
system: platform
created: 2026-08-01
updated: 2026-08-27
updated: 2026-08-29
owners:
- kandev
---
@@ -33,6 +33,10 @@ Task rows currently obtain compact status indicators by observing large, session
flush shall apply all accepted `session.message.updated` replacements in one
store transaction while preserving semantic barriers and final transcript
content.
- **AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.10:** When task opening resumes
an idle agent after a restart, `status_summary.last_activity_at` shall remain
unchanged. A later task mutation, user prompt, or conversational agent turn
can advance it.
## System design
@@ -4,7 +4,7 @@ system: platform
requirements:
- REQ-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001
created: 2026-08-01
updated: 2026-08-28
updated: 2026-08-29
owners:
- kandev
---
@@ -68,7 +68,7 @@ The initial contract is:
| Field | Meaning | Bound |
| ---------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------- |
| `revision`, `updated_at` | Monotonic task-local version and projection time | Constant |
| `last_activity_at` | Latest durable task, user-prompt, or turn milestone | Constant |
| `last_activity_at` | Latest durable task, user-prompt, or conversational-turn milestone | Constant |
| `primary_session` | Primary session ID and lifecycle state | One session |
| `foreground_activity`, `active_subagent_count` | Existing task-level busy aggregate | Constant |
| `pending_action` | `permission`, `clarification`, or absent | Constant |
@@ -145,9 +145,13 @@ remain during migration, but switchers use the summary when present.
- Clients ignore a summary delta whose revision is not newer than the stored
revision.
- `last_activity_at` is separate from projection freshness. Task creation,
persisted task mutations, user-authored prompts, and turn start or completion
advance it by source time. Focus, subscriptions, Git or pull-request polling,
queue bookkeeping, summary repair, and streamed chunks do not advance it.
persisted task mutations, user-authored prompts, and conversational-turn
start or completion advance it by source time. Focus, subscriptions, Git or
pull-request polling, queue bookkeeping, summary repair, and streamed chunks
do not advance it.
- A turn with `metadata.lifecycle_only=true` is not conversational. The live
projector and the durable batch loader exclude these turns. This rule covers
the synthetic `agent_boot` turn that records an agent resume.
- Missing and older summaries rebuild `last_activity_at` in one batch from
task, user-message, and turn records. Live and rebuilt values use a monotonic
maximum, so replay and repair cannot move activity backward. See
@@ -306,6 +310,9 @@ intermediate replacement.
- **GIVEN** an idle task receives Git or pull-request summary changes, **WHEN**
its replacement summary arrives, **THEN** `updated_at` can advance while
`last_activity_at` remains unchanged.
- **GIVEN** an idle task after a backend restart, **WHEN** opening the task
resumes its agent and creates only a lifecycle turn, **THEN**
`last_activity_at` remains unchanged.
- **GIVEN** a recoverable error is dismissed or followed by a newer agent
response, **WHEN** the projector processes that occurrence, **THEN** the
independent error indicator clears on both task switchers.
@@ -2,7 +2,7 @@
status: draft
system: ui
created: 2026-08-17
updated: 2026-08-17
updated: 2026-08-29
owners:
- kandev
---
@@ -70,8 +70,8 @@ Decision:
| Task creation | `tasks.created_at` |
| Persisted task mutation | `tasks.updated_at` |
| User-authored prompt, including a queued prompt | message `created_at` |
| Agent turn starts | turn `started_at` |
| Agent turn completes | turn `completed_at` |
| Conversational agent turn starts | turn `started_at` |
| Conversational agent turn completes | turn `completed_at` |
The following events do not advance activity:
@@ -80,6 +80,7 @@ The following events do not advance activity:
- queued-prompt count changes and other queue bookkeeping
- status-summary rebuilds or transport delivery
- session metadata maintenance without a user prompt or agent turn
- synthetic lifecycle turns, including the `agent_boot` turn on resume
- streamed agent chunks inside an already-started turn
A task-state or workflow-placement change counts because it is a persisted task