Orchestrata Ultimate / Specs / 069-task-management-tools

069-task-management-tools: Task Management Tools - Stop & Output

Complete the task management suite by adding task stopping and output retrieval capabilities to the existing TaskCreate, TaskUpdate, TaskGet, TaskList tools. This specification defines the implementation requirements for TaskStopTool and TaskOutputTool to provide production-ready task lifecycle management.

At a glance

Item Value
Spec directory specs/069-task-management-tools/
Status line in the spec Complete
Requirement IDs defined 48
With a @traces citation in src/ 40 (83.3%)
With a @traces citation in tests/ 0 (0.0%)
Tracked files 3
RTM page 069-task-management-tools

Reading this spec

This spec completes the task management suite. The suite already has TaskCreate, TaskUpdate, TaskGet and TaskList; this spec adds TaskStopTool, which ends running tasks, and TaskOutputTool, which retrieves what a task wrote to stdout and stderr. Together they give production-ready task lifecycle management.

The goals are stopping long-running tasks (gracefully or by force), retrieving real-time and historical output, monitoring progress with performance metrics, debugging task execution through logging and error reporting, securing task operations with authorization, and staying reliable under races and faults. The scope is task termination, output retrieval in streaming and batch form, status monitoring with metrics, and security and governance integration. Four user stories illustrate it: stopping a stuck build process, debugging a failed deployment task, batch-stopping stale tasks and watching a build in real time.

The 48 requirement IDs (REQ-069-NNN) begin with security requirements: authenticating every task operation, sanitizing string inputs, logging every permission denial with a reason, and protecting against race conditions. Functional requirements follow: TaskStopTool supports a forced stop mode, and TaskOutputTool supports line-range retrieval with bounds checking. The last group lists error codes such as TERMINATION_FAILED. Several items carry explicit notes that they are not implemented in the current MVP, which keeps the task manager in-process: the Redis and persistent-storage requirements, the WebSocket streaming error, a full permission model beyond an owner-or-admin check, and a durable audit log.

The code is in the task tools module. The requirements traceability matrix lists each ID. The spec's own status line reads Complete and it tracks 3 files. Measured coverage is 40 of 48 requirements cited by at least one @traces in src/ (83.3%), spread over 1 module; the module citing the most of them is orchestrata_ultimate/tools/task_tools (40 requirements). In tests/, 0 requirements are cited by a test-side @traces. The 8 requirements with no citing symbol are mostly the not-implemented items above plus the line-range bounds rule REQ-069-009.

Requirements

Checkbox is the state recorded in the requirements checklist; Traced by is the count of src/ symbols whose @traces names the ID.

ID Done Requirement Traced by
REQ-069-001 yes (SEC-REQ-001) All task operations MUST authenticate the requesting agent 1
REQ-069-002 yes (SEC-REQ-002) Only task owners or admins MAY stop tasks 1
REQ-069-003 yes (SEC-REQ-003) Governance rules MUST be evaluated before any stop operation (in-process ownership/critical/protected gate — not the real Prolog may_stop_task/2 engine, which is a follow-up wiring task) 1
REQ-069-004 yes (SEC-REQ-004) Protected tasks MUST require admin role to terminate 1
REQ-069-005 yes (SEC-REQ-005) Critical infrastructure tasks MUST require elevated permissions 1
REQ-069-006 yes (SEC-REQ-006) Task IDs MUST match pattern ^task_[a-zA-Z0-9_-]+$ 1
REQ-069-007 yes (SEC-REQ-007) All string inputs MUST be sanitized before processing 2
REQ-069-008 yes (SEC-REQ-008) Numeric parameters MUST be validated for bounds 1
REQ-069-009 yes (SEC-REQ-009) Line range requests MUST NOT exceed output bounds none
REQ-069-010 no (SEC-REQ-010) Redis connections MUST use TLS 1.2 or higher — NOT IMPLEMENTED: this MVP has no Redis-backed storage (in-process TaskManager only) none
REQ-069-011 no (SEC-REQ-011) Sensitive task output MUST be encrypted at rest — NOT IMPLEMENTED: no persistent storage layer exists to encrypt none
REQ-069-012 yes (SEC-REQ-012) Output retention MUST NOT exceed configured limit (TaskManager.purge_expired_output, default 7 days; purge is explicit, not scheduler-driven) 1
REQ-069-013 no (SEC-REQ-013) Task access MUST follow principle of least privilege — NOT IMPLEMENTED: only an owner-or-admin boolean gate exists, not a full RBAC/ACL system none
REQ-069-014 yes (SEC-REQ-014) Task ID generation MUST use cryptographically secure random values (secrets.token_urlsafe) 2
REQ-069-015 yes (SEC-REQ-015) Task creation MUST use atomic operations to prevent collisions (lock-guarded retry loop) 1
REQ-069-016 yes (SEC-REQ-016) Concurrent stop operations MUST use optimistic locking (implemented as lock-serialized mutation + a per-record stopping flag rather than literal Redis WATCH/MULTI — no Redis in this MVP) 2
REQ-069-017 yes (SEC-REQ-017) Signal handling MUST be idempotent (a second concurrent/repeat stop call sees stopping=True or a terminal status and fails cleanly instead of double-signalling) 2
REQ-069-018 yes (SEC-REQ-018) All stop operations MUST be logged with agent ID 2
REQ-069-019 yes (SEC-REQ-019) All permission denials MUST be logged with reason 2
REQ-069-020 yes (SEC-REQ-020) Task state transitions MUST include timestamps 2
REQ-069-021 no (SEC-REQ-021) Audit logs MUST be immutable and retained per policy — PARTIAL only: the in-process audit log is append-only for the process lifetime but is not persisted across restarts and has no retention policy; needs an external audit store none
REQ-069-022 yes (FR-001) TaskStopTool MUST support stopping tasks by ID 4
REQ-069-023 yes (FR-002) TaskStopTool MUST support stopping tasks by name pattern 5
REQ-069-024 yes (FR-003) TaskStopTool MUST support graceful stop mode (default) 3
REQ-069-025 yes (FR-004) TaskStopTool MUST support forced stop mode 3
REQ-069-026 yes (FR-005) TaskStopTool MUST validate task existence before stop 1
REQ-069-027 yes (FR-006) TaskStopTool MUST support batch termination by pattern 2
REQ-069-028 yes (FR-007) TaskOutputTool MUST support full output retrieval 5
REQ-069-029 no (FR-008) TaskOutputTool MUST support output streaming — PARTIAL: mode="stream" implements the incremental-chunk polling primitive (a stream_position cursor); there is no WebSocket push transport (no gateway wiring was built for this spec) 1
REQ-069-030 yes (FR-009) TaskOutputTool MUST support tail mode (last N lines) 4
REQ-069-031 yes (FR-010) TaskOutputTool MUST support line range retrieval 4
REQ-069-032 yes (FR-011) TaskOutputTool MUST provide status metrics (memory/CPU/PID via psutil against a real attached process) 5
REQ-069-033 yes (FR-012) TaskOutputTool MUST support combined output mode 4
REQ-069-034 yes (ERR-001) TASK_NOT_FOUND 2
REQ-069-035 yes (ERR-002) TASK_NOT_RUNNING 2
REQ-069-036 yes (ERR-003) PERMISSION_DENIED 2
REQ-069-037 yes (ERR-004) TERMINATION_FAILED 4
REQ-069-038 yes (ERR-005) CRITICAL_TASK 2
REQ-069-039 yes (ERR-006) PROTECTED_TASK 2
REQ-069-040 yes (ERR-007) OUTPUT_NOT_AVAILABLE 2
REQ-069-041 yes (ERR-008) INVALID_LINE_RANGE 2
REQ-069-042 yes (ERR-009) OUTPUT_TOO_LARGE 2
REQ-069-043 no (ERR-010) STREAM_FAILED — NOT IMPLEMENTED: no WebSocket transport exists to fail none
REQ-069-044 yes (ERR-011) TASK_ID_COLLISION 2
REQ-069-045 no (ERR-012) STORAGE_CORRUPTION — NOT IMPLEMENTED / N/A: no persistent storage layer exists to corrupt none
REQ-069-046 yes (ERR-013) RATE_LIMIT_EXCEEDED (process-local sliding window, not distributed) 2
REQ-069-047 no (ERR-014) REDIS_ERROR — NOT IMPLEMENTED / N/A: this MVP has no Redis dependency none
REQ-069-048 yes (ERR-015) RACE_CONDITION — prevented outright (lock + stopping flag) rather than detected-and-retried 2

Code that traces this spec

Module Symbols Requirements
orchestrata_ultimate/tools/task_tools 29 40

Checklists

checklists/requirements.md

The requirement list above comes from this file; 40 of 48 checkbox items are ticked.

Other tracked files

Full spec text

Verbatim from specs/069-task-management-tools/spec.md; headings are pushed down two levels.

SPEC-069: Task Management Tools - Stop & Output

Version 1.0.0

Metadata

Overview

Purpose

Complete the task management suite by adding task stopping and output retrieval capabilities to the existing TaskCreate, TaskUpdate, TaskGet, TaskList tools. This specification defines the implementation requirements for TaskStopTool and TaskOutputTool to provide production-ready task lifecycle management.

Goals
Scope

Security Requirements

Authentication & Authorization
ID Requirement Priority
SEC-REQ-001 All task operations MUST authenticate the requesting agent Required
SEC-REQ-002 Only task owners or admins MAY stop tasks Required
SEC-REQ-003 Governance rules MUST be evaluated before any stop operation Required
SEC-REQ-004 Protected tasks MUST require admin role to terminate Required
SEC-REQ-005 Critical infrastructure tasks MUST require elevated permissions Required
Input Validation
ID Requirement Priority
SEC-REQ-006 Task IDs MUST match pattern ^task_[a-zA-Z0-9_-]+$ Required
SEC-REQ-007 All string inputs MUST be sanitized before processing Required
SEC-REQ-008 Numeric parameters MUST be validated for bounds Required
SEC-REQ-009 Line range requests MUST NOT exceed output bounds Required
Data Protection
ID Requirement Priority
SEC-REQ-010 Redis connections MUST use TLS 1.2 or higher Required
SEC-REQ-011 Sensitive task output MUST be encrypted at rest Required
SEC-REQ-012 Output retention MUST NOT exceed configured limit Required
SEC-REQ-013 Task access MUST follow principle of least privilege Required
Race Condition Protection
ID Requirement Priority
SEC-REQ-014 Task ID generation MUST use cryptographically secure random values Required
SEC-REQ-015 Task creation MUST use atomic operations to prevent collisions Required
SEC-REQ-016 Concurrent stop operations MUST use optimistic locking Required
SEC-REQ-017 Signal handling MUST be idempotent Required
Audit & Compliance
ID Requirement Priority
SEC-REQ-018 All stop operations MUST be logged with agent ID Required
SEC-REQ-019 All permission denials MUST be logged with reason Required
SEC-REQ-020 Task state transitions MUST include timestamps Required
SEC-REQ-021 Audit logs MUST be immutable and retained per policy Required

User Scenarios

US-001: Stop Stuck Build Process

As a Developer (Agent) I want to stop a long-running build task that has exceeded its expected duration So that I can prevent resource exhaustion and investigate the hang

Acceptance Criteria:

US-002: Debug Failed Deployment Task

As a DevOps Engineer (Agent) I want to retrieve and analyze the output from a failed deployment task So that I can identify the root cause of the failure

Acceptance Criteria:

US-003: Batch Stop Stale Tasks

As a System Administrator (Agent) I want to stop all tasks matching a naming pattern (e.g., stale overnight test runs) So that I can clean up zombie processes and free up system resources

Acceptance Criteria:

US-004: Real-Time Build Monitoring

As a Developer (Agent) I want to monitor task output in real-time via WebSocket streaming So that I can intervene immediately if errors occur

Acceptance Criteria:


Terminology

Task: A running or completed process managed by the orchestrata-ultimate system, identified by a unique task_id in format task_[a-zA-Z0-9_-]+.

TaskStopTool: Tool responsible for terminating task processes gracefully or by force, supporting both individual and batch operations.

TaskOutputTool: Tool responsible for retrieving and formatting task output (stdout/stderr) in full, tail, lines, and streaming modes.

Graceful Stop: Process termination that sends SIGTERM first, waits up to 10 seconds for clean shutdown, then escalates to SIGKILL if needed.

Forced Stop: Immediate process termination using SIGKILL without waiting for graceful shutdown.

Output Stream: Continuous flow of task output data delivered via WebSocket in real-time.

Task State: Current status of a task: pending, running, stopped, completed, failed, or timeout.

Output Retention: Time period (default 7 days) during which task output is preserved before automatic purging.


Data Models

JSON Schemas
TaskStatusResult Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "TaskStatusResult",
  "type": "object",
  "properties": {
    "task_id": {
      "type": "string",
      "pattern": "^task_[a-zA-Z0-9_-]+$",
      "description": "Unique task identifier"
    },
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 255,
      "description": "Human-readable task name"
    },
    "status": {
      "type": "string",
      "enum": ["pending", "running", "stopped", "completed", "failed", "timeout"],
      "description": "Current task status"
    },
    "started_at": {
      "type": "string",
      "format": "date-time",
      "description": "ISO 8601 timestamp when task started"
    },
    "stopped_at": {
      "type": ["string", "null"],
      "format": "date-time",
      "description": "ISO 8601 timestamp when task stopped (null if running)"
    },
    "progress": {
      "type": ["object", "null"],
      "properties": {
        "current": {
          "type": "integer",
          "minimum": 0,
          "description": "Current progress value"
        },
        "total": {
          "type": "integer",
          "minimum": 1,
          "description": "Total expected progress value"
        },
        "percent": {
          "type": ["number", "null"],
          "minimum": 0,
          "maximum": 100,
          "description": "Percentage completion (0-100)"
        },
        "message": {
          "type": ["string", "null"],
          "description": "Current progress message"
        }
      },
      "required": ["current", "total"]
    },
    "pid": {
      "type": ["integer", "null"],
      "minimum": 1,
      "description": "Process ID (null if not running)"
    },
    "exit_code": {
      "type": ["integer", "null"],
      "description": "Process exit code (null if running)"
    },
    "output_lines": {
      "type": "integer",
      "minimum": 0,
      "description": "Total number of output lines captured"
    },
    "memory_mb": {
      "type": ["number", "null"],
      "minimum": 0,
      "description": "Current memory usage in MB"
    },
    "cpu_percent": {
      "type": ["number", "null"],
      "minimum": 0,
      "maximum": 100,
      "description": "Current CPU usage percentage"
    },
    "agent_id": {
      "type": "string",
      "description": "ID of agent that owns the task"
    },
    "task_type": {
      "type": "string",
      "enum": ["build", "test", "deploy", "process", "custom"],
      "description": "Task category for governance"
    }
  },
  "required": ["task_id", "name", "status", "started_at", "output_lines"],
  "additionalProperties": false
}
TaskOutput Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "TaskOutput",
  "type": "object",
  "properties": {
    "task_id": {
      "type": "string",
      "pattern": "^task_[a-zA-Z0-9_-]+$",
      "description": "Associated task identifier"
    },
    "stdout": {
      "type": "string",
      "description": "Standard output content"
    },
    "stderr": {
      "type": "string",
      "description": "Standard error content"
    },
    "combined": {
      "type": "string",
      "description": "Combined stdout and stderr in chronological order"
    },
    "timestamp": {
      "type": "string",
      "format": "date-time",
      "description": "ISO 8601 timestamp when output was retrieved"
    },
    "line_count": {
      "type": "integer",
      "minimum": 0,
      "description": "Total lines in combined output"
    },
    "byte_count": {
      "type": "integer",
      "minimum": 0,
      "description": "Total bytes in combined output"
    },
    "tail_lines": {
      "type": "integer",
      "minimum": 1,
      "description": "Number of lines shown (for tail mode)"
    },
    "line_range": {
      "type": ["object", "null"],
      "properties": {
        "start": {
          "type": "integer",
          "minimum": 1
        },
        "end": {
          "type": "integer",
          "minimum": 1
        }
      },
      "required": ["start", "end"],
      "description": "Line range shown (for lines mode)"
    }
  },
  "required": ["task_id", "stdout", "stderr", "combined", "timestamp"],
  "additionalProperties": false
}
ToolResult Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "ToolResult",
  "type": "object",
  "properties": {
    "success": {
      "type": "boolean",
      "description": "Operation success status"
    },
    "message": {
      "type": "string",
      "description": "Human-readable result message"
    },
    "data": {
      "type": ["object", "null"],
      "description": "Additional operation-specific data"
    },
    "error": {
      "type": ["object", "null"],
      "properties": {
        "code": {
          "type": "string",
          "description": "Error code identifier"
        },
        "message": {
          "type": "string",
          "description": "Error description"
        },
        "details": {
          "type": "object",
          "description": "Additional error context"
        }
      },
      "required": ["code", "message"]
    },
    "timestamp": {
      "type": "string",
      "format": "date-time",
      "description": "ISO 8601 timestamp of operation"
    }
  },
  "required": ["success", "message", "timestamp"],
  "additionalProperties": false
}
Type Definitions
TaskStopMode
enum TaskStopMode {
  GRACEFUL = "graceful",
  FORCE = "force",
  CANCEL = "cancel"
}
OutputMode
enum OutputMode {
  FULL = "full",
  TAIL = "tail",
  LINES = "lines",
  STREAM = "stream"
}

Functional Requirements

TaskStopTool Requirements

FR-001: TaskStopTool MUST support stopping tasks by ID

FR-002: TaskStopTool MUST support stopping tasks by name pattern

FR-003: TaskStopTool MUST support graceful stop mode (default)

FR-004: TaskStopTool MUST support forced stop mode

FR-005: TaskStopTool MUST validate task existence before stop

FR-006: TaskStopTool MUST support batch termination by pattern

TaskOutputTool Requirements

FR-007: TaskOutputTool MUST support full output retrieval

FR-008: TaskOutputTool MUST support output streaming

FR-009: TaskOutputTool MUST support tail mode (last N lines)

FR-010: TaskOutputTool MUST support line range retrieval

FR-011: TaskOutputTool MUST provide status metrics

FR-012: TaskOutputTool MUST support combined output mode


Error Conditions

ID Condition Code HTTP Status Message Cause Recovery Severity
ERR-001 Task Not Found TASK_NOT_FOUND 404 Task task_xyz not found Task ID doesn't exist in system Verify task ID, check recent tasks list WARNING
ERR-002 Task Not Running TASK_NOT_RUNNING 409 Task task_xyz is not in running state Task already completed or stopped Check task status, no action needed INFO
ERR-003 Permission Denied PERMISSION_DENIED 403 Agent does not have permission to stop task task_xyz Agent lacks authorization per governance rules Request permission or use authorized agent ERROR
ERR-004 Process Termination Failed TERMINATION_FAILED 500 Failed to terminate process PID 12345 Process doesn't respond to signals Try force mode, check process state ERROR
ERR-005 Critical Task CRITICAL_TASK 423 Cannot stop critical task task_xyz Task marked as critical/infrastructure Use admin agent or change task classification ERROR
ERR-006 Protected Task PROTECTED_TASK 423 Task task_xyz is protected from termination Task has protection flag set Remove protection or use admin privileges ERROR
ERR-007 Output Not Available OUTPUT_NOT_AVAILABLE 404 Output not found for task task_xyz Task has no output captured or output purged Check if task has started, verify retention policy WARNING
ERR-008 Invalid Line Range INVALID_LINE_RANGE 400 Line range (50, 100) exceeds output length (75) Requested line numbers outside output bounds Adjust range to valid values WARNING
ERR-009 Output Too Large OUTPUT_TOO_LARGE 413 Output size 512MB exceeds limit 100MB Task output exceeds retrieval limit Use tail mode or line range WARNING
ERR-010 Stream Connection Failed STREAM_FAILED 500 WebSocket connection failed Network or server error Retry connection, check server status ERROR
ERR-011 Task ID Collision TASK_ID_COLLISION 409 Task ID collision detected Race condition in task creation/lookup Retry with exponential backoff ERROR
ERR-012 Storage Corruption STORAGE_CORRUPTION 500 Output storage corruption detected Data integrity issue in Redis/filesystem Rebuild from backup, notify admin CRITICAL
ERR-013 Rate Limit Exceeded RATE_LIMIT_EXCEEDED 429 Too many output requests (50/minute) Client exceeding rate limits Slow down requests, use exponential backoff WARNING
ERR-014 Redis Connection Error REDIS_ERROR 503 Unable to connect to Redis Redis server unavailable Wait for Redis recovery, retry operations ERROR
ERR-015 Race Condition Detected RACE_CONDITION 409 Concurrent operation conflict on task task_xyz Multiple operations on same task simultaneously Implement locking, retry after delay ERROR

API Contracts

TaskStopTool API
Stop by ID
interface TaskStopByIdRequest {
  task_id: string;
  force?: boolean;
  mode?: "graceful" | "force";
}

interface TaskStopByIdResponse {
  success: boolean;
  message: string;
  data?: {
    task_id: string;
    stop_mode: string;
    signal_sent?: string;
    wait_time_ms: number;
    exit_code?: number;
  };
  timestamp: string;
}

Request Example:

{
  "task_id": "task_build_123",
  "force": false
}

Response Example:

{
  "success": true,
  "message": "Task task_build_123 stopped gracefully",
  "data": {
    "task_id": "task_build_123",
    "stop_mode": "graceful",
    "signal_sent": "SIGTERM",
    "wait_time_ms": 5000,
    "exit_code": 0
  },
  "timestamp": "2026-04-08T10:30:00Z"
}
Stop by Name
interface TaskStopByNameRequest {
  name: string;
  force?: boolean;
  pattern?: "exact" | "regex" | "prefix" | "suffix";
}

interface TaskStopByNameResponse {
  success: boolean;
  message: string;
  data?: {
    name_pattern: string;
    tasks_found: number;
    tasks_stopped: number;
    failures: number;
    task_ids: string[];
  };
  timestamp: string;
}
TaskOutputTool API
Get Output
interface TaskOutputRequest {
  task_id: string;
  mode?: "full" | "tail" | "lines" | "stream";
  tail?: number;
  lines?: [number, number];
  stream?: boolean;
  include_metadata?: boolean;
}

interface TaskOutputResponse {
  success: boolean;
  message: string;
  data?: TaskOutput;
  timestamp: string;
}
Get Status
interface TaskStatusRequest {
  task_id: string;
  include_metrics?: boolean;
}

interface TaskStatusResponse {
  success: boolean;
  message: string;
  data?: TaskStatusResult;
  timestamp: string;
}
WebSocket API (for streaming)
Subscribe to Output
interface SubscribeToOutputMessage {
  type: "subscribe_output";
  task_id: string;
  buffer_size?: number;
}

interface OutputStreamMessage {
  type: "output_chunk";
  task_id: string;
  data: string;
  stream_position: number;
  timestamp: string;
}

Non-Functional Requirements

Performance Requirements
Metric Target Conditions
Task stop (graceful) < 1s p95 Under normal load
Task stop (forced) < 500ms p95 Under normal load
Output retrieval (full) < 500ms p95 For outputs < 100MB
Output retrieval (tail) < 100ms p95 Any output size
WebSocket latency < 100ms Network path
Concurrent stops 100 operations No degradation
Availability Requirements
Scalability Requirements

Technical Design

Architecture Layers

Layer 1: Tool Interface

Layer 2: Business Logic

Layer 3: Data Access

Layer 4: System Interface

Configuration
TASK_STOP_CONFIG = {
    "graceful_timeout": 10,
    "force": False,
    "max_concurrent_stops": 10,
    "retry_attempts": 3,
    "retry_delay": 1
}

TASK_OUTPUT_CONFIG = {
    "max_output_size": "100MB",
    "retention_days": 7,
    "tail_lines_default": 100,
    "stream_buffer_size": 4096,
    "rate_limit_per_minute": 50
}
Metrics

Examples

Example 1: Stop a Running Task

Request:

curl -X POST http://localhost:8000/tools/task_stop \
  -H "Content-Type: application/json" \
  -d '{
    "task_id": "task_build_456",
    "force": false
  }'

Response:

{
  "success": true,
  "message": "Task task_build_456 stopped gracefully",
  "data": {
    "task_id": "task_build_456",
    "stop_mode": "graceful",
    "signal_sent": "SIGTERM",
    "wait_time_ms": 5234,
    "exit_code": 143
  },
  "timestamp": "2026-04-09T08:15:00Z"
}
Example 2: Retrieve Task Output (Tail Mode)

Request:

curl "http://localhost:8000/tools/task_output?task_id=task_deploy_789&mode=tail&tail=50"

Response:

{
  "success": true,
  "message": "Retrieved last 50 lines",
  "data": {
    "task_id": "task_deploy_789",
    "stdout": "... (last 50 lines) ...",
    "stderr": "",
    "combined": "... (last 50 lines) ...",
    "timestamp": "2026-04-09T08:20:00Z",
    "line_count": 1523,
    "byte_count": 45678,
    "tail_lines": 50
  }
}
Example 3: Batch Stop by Pattern

Request:

curl -X POST http://localhost:8000/tools/task_stop \
  -H "Content-Type: application/json" \
  -d '{
    "name": "test_*",
    "pattern": "prefix"
  }'

Response:

{
  "success": true,
  "message": "Stopped 15 tasks",
  "data": {
    "name_pattern": "test_*",
    "tasks_found": 15,
    "tasks_stopped": 15,
    "failures": 0,
    "task_ids": ["task_test_001", "task_test_002", ...]
  },
  "timestamp": "2026-04-09T08:30:00Z"
}

Security

Task ID Collision Handling

SEC-001: Task IDs MUST be cryptographically random

SEC-002: Task ID validation MUST be atomic

SEC-003: Duplicate task ID detection MUST fail safely

SEC-004: Task ID patterns MUST be validated

Persistent Storage Security

SEC-005: Redis connections MUST use TLS

SEC-006: Sensitive task data MUST be encrypted

SEC-007: Output retention MUST have time limits

SEC-008: Access control MUST be enforced

Race Condition Protection

SEC-009: Optimistic locking MUST be implemented

SEC-010: Process state transitions MUST be atomic

SEC-011: Signal handling MUST be idempotent

SEC-012: Concurrent output reads MUST be safe

Authorization & Governance

SEC-013: Prolog governance MUST be enforced

SEC-014: Audit logging MUST be comprehensive

SEC-015: Input validation MUST be strict


Governance

Policy Enforcement
Access Control Matrix
Role Create Read Stop Delete Admin
Owner ✓ ✓ ✓ ✓ -
Admin ✓ ✓ ✓ ✓ ✓
Viewer - ✓ - - -
System ✓ ✓ ✓ ✓ -

Dependencies

Core Dependencies
Package Version Purpose License
redis-py ^5.0.0 Redis client MIT
psutil ^5.9.0 Process management BSD-3
websockets ^12.0 WebSocket streaming BSD-3
jsonschema ^4.20.0 Validation MIT
typing-extensions ^4.5.0 Type hints PSF
System Dependencies
Component Version Purpose Notes
Redis ^7.0.0 Persistent storage Require cluster mode
Linux ^5.15 Process signals Required for SIGTERM/SIGKILL
Python ^3.11 Runtime Async/await support
Development Dependencies
Package Version Purpose
pytest ^7.0.0 Testing framework
pytest-asyncio ^0.21.0 Async test support
pytest-cov ^4.0.0 Coverage reporting
mypy ^1.5.0 Type checking
black ^23.0.0 Code formatting
Infrastructure Dependencies

Testing Requirements

TR-001: Unit Test Coverage
ID Requirement Priority
TR-001-01 TaskStopTool MUST achieve 95%+ code coverage Required
TR-001-02 TaskOutputTool MUST achieve 95%+ code coverage Required
TR-001-03 All code paths MUST be tested including error conditions Required
TR-001-04 Data models MUST have validation tests Required
TR-002: Integration Test Coverage
ID Requirement Priority
TR-002-01 Redis integration MUST be fully tested Required
TR-002-02 End-to-end workflows MUST be verified Required
TR-002-03 WebSocket streaming MUST be tested for reliability Required
TR-002-04 Process signal handling MUST be verified Required
TR-003: Security Test Coverage
ID Requirement Priority
TR-003-01 Governance rule enforcement MUST be verified Required
TR-003-02 Race condition handling MUST be proven Required
TR-003-03 Input validation MUST be robust against attacks Required
TR-003-04 Permission denials MUST be logged correctly Required
TR-004: Performance Test Requirements
ID Requirement Priority
TR-004-01 Graceful stop MUST complete in <1s p95 Required
TR-004-02 Forced stop MUST complete in <500ms p95 Required
TR-004-03 Output retrieval MUST handle 100MB in <500ms p95 Required
TR-004-04 Tail mode MUST complete in <100ms p95 Required
TR-004-05 System MUST support 100 concurrent stop operations Required
TR-005: Test Environment Requirements
ID Requirement Priority
TR-005-01 Unit tests MUST run without external dependencies Required
TR-005-02 Integration tests MUST use test Redis instance Required
TR-005-03 Performance tests MUST use isolated environment Required
TR-005-04 Test data MUST be cleaned up after each test Required
TR-006: Test Automation
ID Requirement Priority
TR-006-01 All unit tests MUST run in CI pipeline Required
TR-006-02 Integration tests MUST run nightly Required
TR-006-03 Performance tests MUST run weekly Required
TR-006-04 Test results MUST be reported to dashboard Required

Testing

Unit Tests

TEST-001: TaskStopTool MUST have 95%+ code coverage

TEST-002: TaskOutputTool MUST have 95%+ code coverage

TEST-003: Data models MUST validate correctly

TEST-004: Process termination MUST work correctly

Integration Tests

TEST-005: Redis integration MUST be tested

TEST-006: End-to-end workflow MUST be verified

TEST-007: WebSocket streaming MUST be reliable

Security Tests

SEC-TEST-001: Permission enforcement MUST be verified

SEC-TEST-002: Race condition handling MUST be proven

SEC-TEST-003: Input validation MUST be robust

Performance Tests

PERF-001: Stop operation MUST complete in <1s

PERF-002: Output retrieval MUST handle large outputs

PERF-003: Concurrent operations MUST scale

Chaos Engineering Tests

CHAOS-001: Redis failover MUST be handled

CHAOS-002: Process kill MUST be recoverable


Integration Points

Internal Integrations
Component Integration Type Protocol
TaskCreate Task lifecycle Internal API
TaskUpdate State synchronization Redis pub/sub
TaskGet Data access Internal API
TaskList Query interface Internal API
Redis State storage redis-py
Logging Audit trail Structured JSON
External Integrations
Service Purpose Protocol
WebSocket Clients Output streaming WebSocket
Prometheus Metrics export HTTP
PagerDuty Alerting Webhook
Backup System Data persistence S3/API

Success Criteria

Functional Criteria
Performance Criteria
Security Criteria
Quality Criteria

Observability

Logging Requirements
  1. Component Logging
    • Log all major operations with appropriate log levels
    • Include correlation IDs for request tracing
    • Log performance metrics for critical operations
    • Log errors with full context for debugging
Metrics Requirements
  1. Performance Metrics
    • Operation duration histograms
    • Request/error rate counters
    • Resource utilization gauges
    • Business metrics relevant to domain
Tracing Requirements
  1. Distributed Tracing
    • Trace propagation across component boundaries
    • Span attributes for domain-specific context
    • Trace sampling based on operational needs
Alerting Requirements
  1. Critical Alerts
    • Error rate spikes
    • Performance degradation
    • Resource exhaustion
    • Business metric anomalies
Dashboard Requirements
  1. Operational Dashboard
    • Real-time system health
    • Performance trends
    • Error analysis
    • Resource monitoring

Revision History

Version Date Author Changes
1.0.0 2026-04-08 Mohamed Initial specification
1.0.1 2026-04-09 Mohamed Fixed spec standard compliance, added missing sections, converted to table format

End of SPEC-069