Work Packages: CLI Event Emission + Sync

Inputs: Design documents from /kitty-specs/028-cli-event-emission-sync/ Prerequisites: plan.md (required), spec.md (user stories), research.md, data-model.md, contracts/events.schema.json, quickstart.md

Tests: WP07 contains explicit testing work as required by spec (SC-001 through SC-010).

Organization: Fine-grained subtasks (Txxx) roll up into work packages (WPxx). Each work package must be independently deliverable and testable.

Prompt Files: Each work package references a matching prompt file in /tasks/ generated by /spec-kitty.tasks. Treat this file as the high-level checklist; keep deep implementation detail inside the prompt files.

Subtask Format: [Txxx] [P?] Description

  • [P] indicates the subtask can proceed in parallel (different files/components).
  • Include precise file paths or modules.

Path Conventions

  • Single project: src/specify_cli/, tests/
  • Adjust paths to match the implementation plan.

Work Package WP01: Event Factory Module (Priority: P0)

Goal: Create the singleton EventEmitter with all 8 event builder methods, Lamport clock management, and queue/sync routing. Independent Test: Unit tests pass for event creation, clock persistence, and validation against schema. Prompt: /tasks/WP01-event-factory.md

Included Subtasks

  • ✅ T001 Create src/specify_cli/sync/clock.py with LamportClock class and JSON persistence
  • ✅ T002 Create src/specify_cli/sync/emitter.py with EventEmitter class (singleton pattern)
  • ✅ T003 [P] Create src/specify_cli/sync/events.py with get_emitter() accessor and convenience emit functions
  • ✅ T004 [P] Implement node_id generation (hostname + username hash)
  • ✅ T005 Implement event builders for all 8 event types (WPStatusChanged, WPCreated, WPAssigned, FeatureCreated, FeatureCompleted, HistoryAdded, ErrorLogged, DependencyResolved)
  • ✅ T006 Implement emit_event() routing logic (WebSocket vs queue decision)
  • ✅ T007 Add schema validation using spec-kitty-events library

Implementation Notes

  • Use ~/.spec-kitty/clock.json for Lamport clock persistence (atomic writes via temp file + rename)
  • Use ULID for event_id generation via python-ulid library
  • AuthClient integration for team_slug and authentication status check
  • Non-blocking design: event emission failures must not halt calling code

Parallel Opportunities

  • T003 and T004 can proceed in parallel after T001/T002 foundation exists
  • Event builders (T005) can be implemented in parallel once emitter structure is in place

Dependencies

  • None (foundation package)

Risks & Mitigations

  • spec-kitty-events API changes: Pin to specific commit per ADR-11
  • Lamport clock corruption: Use atomic writes with temp file

Work Package WP02: Workflow Command Integration (Priority: P0)

Goal: Wire event emission into implement, merge, and accept commands. Independent Test: Running each command emits correct event to queue (verifiable via queue inspection). Prompt: /tasks/WP02-workflow-commands.md

Included Subtasks

  • ✅ T008 Modify src/specify_cli/cli/commands/implement.py to emit WPStatusChanged(planned->doing)
  • ✅ T009 [P] Modify src/specify_cli/cli/commands/merge.py to emit WPStatusChanged(doing->for_review)
  • ✅ T010 [P] Modify src/specify_cli/cli/commands/accept.py to emit WPStatusChanged(for_review->done)
  • ✅ T011 Add try/except wrappers to ensure non-blocking event emission
  • ✅ T012 Add console warnings (via Rich) when event emission fails

Implementation Notes

  • Import from specify_cli.sync.events module
  • Emit events AFTER the core action succeeds (workspace creation, merge, acceptance)
  • Use feature_slug from context when available
  • changed_by field should be "user" for CLI-initiated commands

Parallel Opportunities

  • T009 and T010 can proceed in parallel once T008 establishes the pattern

Dependencies

  • Depends on WP01 (Event Factory must exist)

Risks & Mitigations

  • Import errors: Verify sync module exports during implementation
  • Silent failures: Ensure warnings are visible to users

Work Package WP03: Task Command Integration (Priority: P1)

Goal: Wire event emission into move-task, mark-status, and add-history agent commands. Independent Test: Running task commands emits correct events to queue. Prompt: /tasks/WP03-task-commands.md

Included Subtasks

  • ✅ T013 Modify src/specify_cli/cli/commands/agent/tasks.py move-task to emit WPStatusChanged
  • ✅ T014 [P] Modify src/specify_cli/cli/commands/agent/tasks.py mark-status to emit WPStatusChanged
  • ✅ T015 [P] Modify src/specify_cli/cli/commands/agent/tasks.py add-history to emit HistoryAdded
  • ✅ T016 Add error logging: emit ErrorLogged event when command encounters errors
  • ✅ T017 Ensure Lamport clock increments correctly for sequential commands

Implementation Notes

  • Task commands update frontmatter AND emit events
  • changed_by field should identify the agent when agent context is available
  • ErrorLogged events should capture error_type (validation, runtime, etc.)

Parallel Opportunities

  • T014 and T015 can proceed in parallel once T013 establishes the pattern

Dependencies

  • Depends on WP01 (Event Factory must exist)

Risks & Mitigations

  • Agent context not available: Default to "user" for changed_by

Work Package WP04: Finalize-Tasks Integration (Priority: P1)

Goal: Wire event emission into finalize-tasks for batch FeatureCreated + WPCreated events. Independent Test: Running finalize-tasks with N work packages emits 1 FeatureCreated + N WPCreated events. Prompt: /tasks/WP04-finalize-tasks.md

Included Subtasks

  • ✅ T018 Modify src/specify_cli/cli/commands/agent/feature.py finalize-tasks to emit FeatureCreated
  • ✅ T019 Emit WPCreated event for each work package in tasks.md
  • ✅ T020 Generate shared causation_id for batch events (linking all events to single finalize-tasks action)
  • ✅ T021 Include dependency information in WPCreated payload
  • ✅ T022 Extract metadata from meta.json for FeatureCreated payload

Implementation Notes

  • Use get_emitter().generate_causation_id() for batch correlation
  • Parse tasks.md to get WP list and dependencies
  • FeatureCreated payload: feature_slug, feature_number, target_branch, wp_count
  • WPCreated payload: wp_id, title, dependencies[], feature_slug

Parallel Opportunities

  • Limited parallelization within this WP (sequential event emission)

Dependencies

  • Depends on WP01 (Event Factory must exist)

Risks & Mitigations

  • tasks.md parsing errors: Reuse existing parsing logic from finalize-tasks

Work Package WP05: Orchestrate Integration (Priority: P1)

Goal: Wire event emission into orchestrate for WPAssigned and lifecycle events. Independent Test: Running orchestrate emits WPAssigned events when agents are assigned. Prompt: /tasks/WP05-orchestrate.md

Included Subtasks

  • ✅ T023 Modify src/specify_cli/cli/commands/orchestrate.py to emit WPAssigned on agent assignment
  • ✅ T024 Emit WPAssigned with phase=implementation when implementation agent starts
  • ✅ T025 [P] Emit WPAssigned with phase=review when review agent starts
  • ✅ T026 Track retry_count in WPAssigned when fallback agents are used
  • ✅ T027 Emit FeatureCompleted when all WPs reach done status
  • ✅ T028 [P] Emit DependencyResolved when WP completes and unblocks dependents

Implementation Notes

  • Orchestrator manages multiple agents, so events track which agent is assigned
  • retry_count increments when primary agent fails and fallback is used
  • FeatureCompleted should include total_duration if start time is tracked

Parallel Opportunities

  • T025 and T028 can proceed in parallel once T023/T024 establish patterns

Dependencies

  • Depends on WP01 (Event Factory must exist)

Risks & Mitigations

  • Orchestrate complexity: Instrument carefully to avoid affecting core logic

Work Package WP06: Background Sync Service (Priority: P2)

Goal: Implement background sync service that auto-flushes queue periodically. Independent Test: Background service syncs queued events within configured interval. Prompt: /tasks/WP06-background-sync.md

Included Subtasks

  • ✅ T029 Create src/specify_cli/sync/background.py with BackgroundSyncService class
  • ✅ T030 Implement periodic sync timer (default 5 minutes, configurable)
  • ✅ T031 Implement exponential backoff on repeated failures (500ms -> 30s)
  • ✅ T032 Add graceful shutdown handling (cleanup on CLI session end)
  • ✅ T033 Integrate with existing batch_sync() function
  • ✅ T034 Add spec-kitty sync now command for manual immediate sync
  • ✅ T035 Add spec-kitty sync status command showing queue size, connection state, last sync

Implementation Notes

  • Use threading or asyncio for background operation (match existing CLI patterns)
  • Respect rate limits: max 1000 events/batch, max 1 batch/5 seconds
  • Handle 401 errors by logging warning (user must re-authenticate)
  • Sync should be optional (CLI works fine without background service)

Parallel Opportunities

  • T034 and T035 can proceed in parallel once T029-T033 establish service

Dependencies

  • Depends on WP05 (orchestrate patterns inform background service design)

Risks & Mitigations

  • Thread safety: Use locks for queue access
  • Resource leaks: Ensure proper cleanup on shutdown

Work Package WP07: Test Suite (Priority: P1)

Goal: Comprehensive tests for event emission and sync integration. Independent Test: All tests pass with 90%+ coverage on new code. Prompt: /tasks/WP07-tests.md

Included Subtasks

  • ✅ T036 Create tests/sync/test_events.py - unit tests for EventEmitter
  • ✅ T037 [P] Create tests/sync/test_clock.py - unit tests for LamportClock persistence
  • ✅ T038 [P] Create tests/sync/test_background.py - unit tests for BackgroundSyncService
  • ✅ T039 Create tests/sync/test_integration.py - integration tests with mock server
  • ✅ T040 [P] Create tests/cli/commands/test_event_emission.py - command integration tests
  • ✅ T041 Add test fixtures for event validation, mock AuthClient, mock queue
  • ✅ T042 Verify all success criteria (SC-001 through SC-010) via tests
  • ✅ T043 Add edge case tests: offline queue, schema validation errors, clock desync

Implementation Notes

  • Use pytest with 90%+ coverage requirement
  • Mock AuthClient for isolated testing
  • Mock WebSocket/HTTP for sync tests
  • Test all 8 event types have valid schemas

Parallel Opportunities

  • T037, T038, T040 can proceed in parallel with different test files

Dependencies

  • Depends on WP06 (all implementation must be complete before final tests)

Risks & Mitigations

  • Flaky tests: Use deterministic mocks, avoid real network calls

Dependency & Execution Summary

  • Sequence: WP01 -> (WP02, WP03, WP04, WP05 in parallel) -> WP06 -> WP07
  • Parallelization: After WP01 completes, WP02-WP05 can run with 4 agents simultaneously
  • MVP Scope: WP01, WP02, WP03 constitute minimum viable release (events emit and queue)
                    WP01 (Event Factory)
                           |
           +---------------+---------------+---------------+
           |               |               |               |
        WP02           WP03            WP04            WP05
    (impl/merge/    (task cmds)    (finalize)     (orchestrate)
      accept)                                          |
           |               |               |           |
           +---------------+---------------+-----------+
                                                       |
                                                    WP06
                                              (Background Sync)
                                                       |
                                                    WP07
                                                   (Tests)

Subtask Index (Reference)

Subtask IDSummaryWork PackagePriorityParallel?
T001LamportClock class + persistenceWP01P0No
T002EventEmitter singleton classWP01P0No
T003get_emitter() and convenience functionsWP01P0Yes
T004node_id generationWP01P0Yes
T005Event builders (8 types)WP01P0No
T006emit_event() routing logicWP01P0No
T007Schema validationWP01P0No
T008implement.py event emissionWP02P0No
T009merge.py event emissionWP02P0Yes
T010accept.py event emissionWP02P0Yes
T011Non-blocking try/except wrappersWP02P0No
T012Console warnings for failuresWP02P0No
T013move-task event emissionWP03P1No
T014mark-status event emissionWP03P1Yes
T015add-history event emissionWP03P1Yes
T016ErrorLogged event emissionWP03P1No
T017Lamport clock verificationWP03P1No
T018FeatureCreated emissionWP04P1No
T019WPCreated batch emissionWP04P1No
T020Shared causation_idWP04P1No
T021Dependency info in WPCreatedWP04P1No
T022meta.json extractionWP04P1No
T023WPAssigned on agent assignmentWP05P1No
T024phase=implementation trackingWP05P1No
T025phase=review trackingWP05P1Yes
T026retry_count trackingWP05P1No
T027FeatureCompleted emissionWP05P1No
T028DependencyResolved emissionWP05P1Yes
T029BackgroundSyncService classWP06P2No
T030Periodic sync timerWP06P2No
T031Exponential backoffWP06P2No
T032Graceful shutdownWP06P2No
T033batch_sync integrationWP06P2No
T034spec-kitty sync now commandWP06P2Yes
T035spec-kitty sync status commandWP06P2Yes
T036test_events.pyWP07P1No
T037test_clock.pyWP07P1Yes
T038test_background.pyWP07P1Yes
T039test_integration.pyWP07P1No
T040test_event_emission.pyWP07P1Yes
T041Test fixturesWP07P1No
T042Success criteria verificationWP07P1No
T043Edge case testsWP07P1No

> All placeholder text has been replaced with feature-specific content based on spec.md, plan.md, data-model.md, and contracts/events.schema.json.

<!-- status-model:start -->

Canonical Status (Generated)

<!-- status-model:end -->

  • WP01: done
  • WP02: done
  • WP03: done
  • WP04: done
  • WP05: done
  • WP06: done
  • WP07: done