Core Modules

This section documents the core modules that power ToDoWrite Models.

todowrite.core

Models Module

The models module contains all ToDoWrite Models:

ToDoWrite Core Models Package.

This package provides access to all ToDoWrite SQLAlchemy models. You can import models in two ways:

# Import the entire package (backward compatible) from todowrite.core.models import Goal, Task, Command

# Or import specific models from todowrite.core.models import Goal from todowrite.core.models import Task from todowrite.core.models import Command

Models Available: - Base: SQLAlchemy declarative base - Goal: High-level project objectives - Concept: Abstract ideas and requirements - Context: Background information and constraints - Constraint: Technical and business constraints - Requirement: Specific functional requirements - AcceptanceCriteria: Definition of done criteria - InterfaceContract: API and interface contracts - Phase: Project phases and milestones - Step: Individual steps within phases - Task: Specific tasks with owners and status - SubTask: Breakdown of tasks into smaller units - Command: Executable commands and scripts - Label: Tags and categorization system - Metadata: Extensible metadata for ToDoWrite nodes

class AcceptanceCriteria(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite AcceptanceCriteria model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

assignee
created_at
description
ended_on
extra_data
id
interface_contracts
labels
owner
progress
requirements
severity
started_on
status
title
updated_at
work_type
class Base(**kwargs)[source]

Bases: DeclarativeBase

Base class for all ToDoWrite models.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

metadata = MetaData()

Refers to the _schema.MetaData collection that will be used for new _schema.Table objects.

registry = <sqlalchemy.orm.decl_api.registry object>

Refers to the _orm.registry in use where new _orm.Mapper objects will be associated.

class Command(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Command model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

acceptance_criteria_id
artifacts
property artifacts_list

Get artifacts as list.

assignee
cmd
cmd_params
created_at
description
ended_on
id
labels
mark_completed()[source]

Mark command as completed with current timestamp.

Return type:

None

mark_started()[source]

Mark command as started with current timestamp.

Return type:

None

output
owner
progress
runtime_env
property runtime_env_dict

Get runtime environment as dictionary.

severity
started_on
status
sub_tasks
title
updated_at
work_type
class Concept(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Concept model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

assignee
contexts
created_at
description
ended_on
extra_data
goals
id
labels
owner
progress
requirements
severity
started_on
status
title
updated_at
work_type
class Constraint(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Constraint model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

assignee
created_at
description
ended_on
extra_data
goals
id
labels
owner
progress
requirements
severity
started_on
status
title
updated_at
work_type
class Context(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Context model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

assignee
concepts
created_at
description
ended_on
extra_data
goals
id
labels
owner
progress
requirements
severity
started_on
status
title
updated_at
work_type
class Goal(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Goal model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

add_label(label)[source]

Add a label to this goal.

Return type:

None

add_phase(phase)[source]

Add a phase to this goal.

Return type:

None

add_task(task)[source]

Add a task to this goal.

Return type:

None

classmethod all(session)[source]

Get all goals.

Return type:

list[Goal]

assignee
complete_work()[source]

Mark goal as completed by setting ended_on to current timestamp.

Return type:

None

concepts
constraints
contexts
classmethod create(title, description='', owner='', severity='', work_type='', assignee='')[source]

Create a new Goal instance with default values.

Return type:

Goal

created_at
delete(session)[source]

Delete this goal from the database.

Return type:

None

description
ended_on
extra_data
classmethod find_active(session)[source]

Get all active (not completed) goals.

Return type:

list[Goal]

classmethod find_by_id(session, goal_id)[source]

Find a goal by ID.

Return type:

Goal | None

classmethod find_by_title(session, title)[source]

Find a goal by title.

Return type:

Goal | None

classmethod find_completed(session)[source]

Get all completed goals.

Return type:

list[Goal]

classmethod from_dict(data)[source]

Create Goal instance from dictionary.

Return type:

Goal

get_summary()[source]

Get a brief summary of the goal.

Return type:

str

get_work_duration()[source]

Get the duration between start and completion in ISO format.

Return type:

str | None

id
is_completed()[source]

Check if goal is marked as completed.

Return type:

bool

is_started()[source]

Check if goal is marked as started.

Return type:

bool

is_valid()[source]

Check if goal data is valid.

Return type:

bool

labels
owner
phases
progress
remove_label(label)[source]

Remove a label from this goal.

Return type:

None

remove_phase(phase)[source]

Remove a phase from this goal.

Return type:

None

remove_task(task)[source]

Remove a task from this goal.

Return type:

None

save(session)[source]

Save this goal to the database.

Return type:

None

set_progress(progress)[source]

Set progress percentage (0-100).

Return type:

None

severity
start_work()[source]

Mark goal as started by setting started_on to current timestamp.

Return type:

None

started_on
status
tasks
title
to_dict()[source]

Convert goal to dictionary representation.

Return type:

dict[str, object]

updated_at
validate()[source]

Validate goal data and return list of errors.

Return type:

list[str]

work_type
class InterfaceContract(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite InterfaceContract model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

acceptance_criteria
assignee
created_at
description
ended_on
extra_data
id
labels
owner
phases
progress
severity
started_on
status
title
updated_at
work_type
class Label(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Label model for categorizing and tagging other models.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

acceptance_criteria
commands
concepts
constraints
contexts
created_at
goals
id
interface_contracts
name
phases
requirements
steps
sub_tasks
tasks
updated_at
class Metadata(owner='', labels=None, severity='', work_type='', assignee='', extra=None)[source]

Bases: object

Extensible metadata for ToDoWrite nodes.

__init__(owner='', labels=None, severity='', work_type='', assignee='', extra=None)[source]
to_dict()[source]

Convert metadata to dictionary.

Return type:

dict[str, str | list[str] | int | bool]

class Phase(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Phase model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

assignee
created_at
description
ended_on
extra_data
goals
id
interface_contracts
labels
owner
progress
severity
started_on
status
steps
title
updated_at
work_type
class Requirement(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Requirement model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

acceptance_criteria
assignee
concepts
constraints
contexts
created_at
description
ended_on
extra_data
id
labels
owner
progress
severity
started_on
status
title
updated_at
work_type
class Step(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Step model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

assignee
created_at
description
ended_on
extra_data
id
labels
owner
phases
progress
severity
started_on
status
tasks
title
updated_at
work_type
class SubTask(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite SubTask model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

assignee
commands
created_at
description
ended_on
extra_data
id
labels
owner
progress
severity
started_on
status
tasks
title
updated_at
work_type
class Task(**kwargs)[source]

Bases: Base, TimestampMixin

ToDoWrite Task model for hierarchical task management.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

assignee
property commands

Get all commands from all subtasks for this task.

Provides complete execution plan visibility by aggregating all commands across all subtasks belonging to this task.

Returns:

List of all Command objects from all subtasks in execution order.

property completed_commands_count

Get count of completed commands across all subtasks.

created_at
description
ended_on
property execution_progress_percentage

Calculate execution progress as percentage based on completed commands.

extra_data
goals
id
labels
owner
progress
severity
started_on
status
steps
sub_tasks
title
property total_commands_count

Get total number of commands across all subtasks.

updated_at
work_type

Schema Validator Module

Schema validation and database initialization:

ToDoWrite Model Schema Validator and Database Initializer.

This module provides programmatic access to the ToDoWrite model schemas, allowing the library to validate data, initialize databases from schemas, and ensure consistency between models and database structure.

class FieldSchema[source]

Bases: TypedDict

Schema definition for a model field.

type
nullable
default
max_length
primary_key
unique
class ModelSchema[source]

Bases: TypedDict

Schema definition for a model.

table_name
fields
required_fields
relationships
class AssociationTableSchema[source]

Bases: TypedDict

Schema definition for an association table.

table_name
columns
source_model
target_model
class ToDoWriteCompleteSchema[source]

Bases: TypedDict

Complete ToDoWrite schema structure.

models
association_tables
generated_at
description
exception SchemaValidationError[source]

Bases: ToDoWriteError

Raised when schema validation fails.

exception DatabaseInitializationError[source]

Bases: ToDoWriteError

Raised when database initialization from schema fails.

class ToDoWriteSchemaValidator(schema_path=None)[source]

Bases: object

ToDoWrite Model Schema Validator and Database Manager.

Provides programmatic access to: 1. Validate data against schemas 2. Initialize databases from schema definitions 3. Ensure model-schema consistency 4. Import schemas into properly typed database tables

__init__(schema_path=None)[source]

Initialize schema validator with schema file path.

get_model_schema(model_name)[source]

Get the schema definition for a specific model.

Return type:

ModelSchema

get_association_table_schema(table_name)[source]

Get the schema definition for an association table.

Return type:

AssociationTableSchema

validate_model_data(model_name, data)[source]

Validate data against a specific model schema.

Return type:

bool

initialize_database_from_schema(engine, drop_existing=False)[source]

Initialize database with all tables defined in the schema.

Parameters:
  • engine (Engine) – SQLAlchemy engine to use for database operations

  • drop_existing (bool) – Whether to drop existing tables first

Return type:

None

get_all_model_schemas()[source]

Get all model schemas.

Return type:

dict[str, ModelSchema]

get_all_association_table_schemas()[source]

Get all association table schemas.

Return type:

dict[str, AssociationTableSchema]

get_model_relationships(model_name)[source]

Get relationship information for a model.

Return type:

dict[str, object]

get_associated_models(model_name)[source]

Get list of models that this model has relationships with.

Return type:

list[str]

get_schema_summary()[source]

Get a summary of the schema structure.

Return type:

dict[str, object]

class DatabaseSchemaInitializer(validator=None)[source]

Bases: object

Helper class for database initialization using schema definitions.

Provides methods to create, drop, and verify database structure based on the ToDoWrite model schema.

__init__(validator=None)[source]

Initialize with schema validator.

create_database(database_url, drop_existing=False)[source]

Create a new database initialized with the ToDoWrite model schema.

Parameters:
  • database_url (str) – SQLAlchemy database URL

  • drop_existing (bool) – Whether to drop existing database first

Return type:

Engine

Returns:

SQLAlchemy engine for the created database

verify_database_structure(database_url)[source]

Verify that database matches the schema structure.

Return type:

bool

get_database_status(database_url)[source]

Get status information about the database.

Return type:

dict[str, object]

get_schema_validator()[source]

Get the default schema validator instance.

Return type:

ToDoWriteSchemaValidator

validate_model_data(model_name, data)[source]

Validate data against model schema using default validator.

Return type:

bool

initialize_database(database_url, drop_existing=False)[source]

Initialize database with schema using default validator.

Return type:

Engine

Exceptions Module

Core exception classes:

Custom exceptions for ToDoWrite

This module defines custom exception classes for consistent error handling throughout the ToDoWrite codebase.

exception ToDoWriteError[source]

Bases: Exception

Base exception class for all ToDoWrite errors.

exception ModelError[source]

Bases: ToDoWriteError

Base exception for ToDoWrite Models-related errors.

exception ModelNotFoundError(model_name, record_id)[source]

Bases: ModelError

Raised when a model record is not found.

__init__(model_name, record_id)[source]
exception InvalidModelError(message, details=None)[source]

Bases: ModelError

Raised when model data is invalid.

__init__(message, details=None)[source]
exception StorageError[source]

Bases: ToDoWriteError

Base exception for storage-related errors.

exception DatabaseError(message, original_exception=None)[source]

Bases: StorageError

Raised for database-related errors.

__init__(message, original_exception=None)[source]
exception YAMLError(message, file_path=None)[source]

Bases: StorageError

Raised for YAML-related errors.

__init__(message, file_path=None)[source]
exception SchemaError(message, validation_errors=None)[source]

Bases: ToDoWriteError

Raised for schema validation errors.

__init__(message, validation_errors=None)[source]
exception ConfigurationError[source]

Bases: ToDoWriteError

Raised for configuration-related errors.

exception CLIError[source]

Bases: ToDoWriteError

Raised for CLI-related errors.

exception TokenOptimizationError[source]

Bases: ToDoWriteError

Raised for token optimization errors.

Schema Module

JSON schema definitions and validation:

Types Module

Type definitions and collections:

ToDoWrite Core Type Definitions.

This module contains shared type definitions and utility classes used throughout the ToDoWrite package.

Key Concepts: - LayerType: The 12 hierarchical layers from Goal to Command - StatusType: Workflow states for task tracking - Metadata: Extensible metadata system - Command: Executable command definitions

Example

>>> from todowrite.core.models import Goal
>>> from todowrite.core.types import LayerType, Metadata
>>>
>>> goal = Goal(
...     title="Launch Product",
...     description="Successfully launch the new product",
...     owner="product-team",
...     severity="high"
... )
class AcceptanceCriteriaCollection(items=None)[source]

Bases: ToDoWriteCollection

Collection for AcceptanceCriteria items.

class CommandCollection(items=None)[source]

Bases: ToDoWriteCollection

Collection for Command items.

class Metadata(owner='', labels=None, severity='', work_type='', assignee='', extra=None)[source]

Bases: object

Extensible metadata for ToDoWrite nodes.

__init__(owner='', labels=None, severity='', work_type='', assignee='', extra=None)[source]
to_dict()[source]

Convert metadata to dictionary.

Return type:

dict[str, str | list[str] | int | bool]

class PhaseCollection(items=None)[source]

Bases: ToDoWriteCollection

Collection for Phase items.

class StepCollection(items=None)[source]

Bases: ToDoWriteCollection

Collection for Step items.

class SubTaskCollection(items=None)[source]

Bases: ToDoWriteCollection

Collection for SubTask items.

class TaskCollection(items=None)[source]

Bases: ToDoWriteCollection

Collection for Task items.

class ToDoWriteCollection(items=None)[source]

Bases: object

Base collection class for ToDoWrite models.

__init__(items=None)[source]
all()[source]

Get all items in the collection.

Return type:

list[str]

size()[source]

Get the size of the collection.

Return type:

int

empty()[source]

Check if the collection is empty.

Return type:

bool

exists()[source]

Check if any items exist in the collection.

Return type:

bool

Utils Module

Utility functions and helpers:

Utility functions for ToDoWrite

This module contains utility functions that are used across the codebase to avoid code duplication and provide consistent behavior.

generate_node_id(prefix='')[source]

Generate a unique node ID with optional prefix.

Parameters:

prefix (str) – Optional prefix for the node ID (e.g., “GOAL”, “TASK”)

Return type:

str

Returns:

A unique node ID as “PREFIX-UUID” or just “UUID” if no prefix

safe_get_nested(data, *keys, default=None)[source]

Safely get a nested value from a dictionary using dot notation.

Parameters:
  • data (dict[str, object]) – The dictionary to search

  • *keys (str) – Keys to traverse in order

  • default (Optional[TypeVar(T)]) – Default value if any key is not found

Return type:

Optional[TypeVar(T)]

Returns:

The nested value or default value if not found (generic type)

truncate_string(text, max_length=100, suffix='...')[source]

Truncate a string to maximum length with suffix.

Parameters:
  • text (str) – The string to truncate

  • max_length (int) – Maximum length of the result

  • suffix (str) – Suffix to add if truncation occurs

Return type:

str

Returns:

The truncated string or original string if short enough

Project Manager Module

Project management utilities:

class OptimizationParams[source]

Bases: TypedDict

Parameters for token optimization functions

text
context
model
max_tokens
class OptimizationResult[source]

Bases: TypedDict

Result from token optimization

optimized
error
tokens_saved
original_tokens
optimized_tokens
optimization_ratio
strategies_used
class ProjectManager[source]

Bases: object

Centralized project management and utility methods.

__init__()[source]
check_deprecated_schema()[source]

Check that the deprecated schema doesn’t have unintended changes. Returns True if check passes, False if there are issues.

Return type:

bool

check_schema_changes()[source]

Check if schema changes are in the correct location. Returns True if check passes, False if there are issues.

Return type:

bool

setup_integration(project_path, db_type='postgres')[source]

Set up ToDoWrite integration in a project.

Parameters:
  • project_path (str | Path) – Path to the project directory

  • db_type (str) – Database type (‘postgres’, ‘sqlite’)

Return type:

bool

Returns:

True if setup was successful, False otherwise

init_database_sql()[source]

Return PostgreSQL initialization SQL as string. This provides the SQL content that would be in the init script.

Return type:

str

create_project_structure(project_path)[source]

Create a basic ToDoWrite project structure.

Parameters:

project_path (str | Path) – Path where to create the structure

Return type:

bool

Returns:

True if structure was created successfully

validate_project_setup(project_path)[source]

Validate that a project is properly set up for ToDoWrite.

Return type:

dict[str, object]

Returns:

Dictionary with validation results

check_deprecated_schema()[source]

Check that deprecated schema hasn’t been modified.

Return type:

bool

check_schema_changes()[source]

Check if schema changes are in the correct location.

Return type:

bool

setup_integration(project_path, db_type='postgres')[source]

Set up ToDoWrite integration in a project.

Return type:

bool

create_project_structure(project_path)[source]

Create a basic ToDoWrite project structure.

Return type:

bool

validate_project_setup(project_path)[source]

Validate that a project is properly set up for ToDoWrite.

Return type:

dict[str, object]

init_database_sql()[source]

Return PostgreSQL initialization SQL as string.

Return type:

str

optimize_token_usage(goal, **kwargs)[source]

Public function for token optimization. Returns None if AI dependencies are not available.

Return type:

OptimizationResult | None

ensure_token_sage()[source]

Public function to check if token-sage functionality is available. Returns True if AI dependencies are available.

Return type:

bool

Constants Module

Application constants and configuration:

Shared constants for ToDoWrite

todowrite.storage

Storage backend implementations and utilities:

class DatabaseSchemaInitializer(validator=None)[source]

Bases: object

Helper class for database initialization using schema definitions.

Provides methods to create, drop, and verify database structure based on the ToDoWrite model schema.

__init__(validator=None)[source]

Initialize with schema validator.

create_database(database_url, drop_existing=False)[source]

Create a new database initialized with the ToDoWrite model schema.

Parameters:
  • database_url (str) – SQLAlchemy database URL

  • drop_existing (bool) – Whether to drop existing database first

Return type:

Engine

Returns:

SQLAlchemy engine for the created database

get_database_status(database_url)[source]

Get status information about the database.

Return type:

dict[str, object]

verify_database_structure(database_url)[source]

Verify that database matches the schema structure.

Return type:

bool

exception SchemaValidationError[source]

Bases: ToDoWriteError

Raised when schema validation fails.

exception StorageConnectionError[source]

Bases: StorageError

Database connection error.

exception StorageError[source]

Bases: Exception

Base storage exception.

exception StorageQueryError[source]

Bases: StorageError

Database query error.

class ToDoWriteSchemaValidator(schema_path=None)[source]

Bases: object

ToDoWrite Model Schema Validator and Database Manager.

Provides programmatic access to: 1. Validate data against schemas 2. Initialize databases from schema definitions 3. Ensure model-schema consistency 4. Import schemas into properly typed database tables

__init__(schema_path=None)[source]

Initialize schema validator with schema file path.

get_all_association_table_schemas()[source]

Get all association table schemas.

Return type:

dict[str, AssociationTableSchema]

get_all_model_schemas()[source]

Get all model schemas.

Return type:

dict[str, ModelSchema]

get_associated_models(model_name)[source]

Get list of models that this model has relationships with.

Return type:

list[str]

get_association_table_schema(table_name)[source]

Get the schema definition for an association table.

Return type:

AssociationTableSchema

get_model_relationships(model_name)[source]

Get relationship information for a model.

Return type:

dict[str, object]

get_model_schema(model_name)[source]

Get the schema definition for a specific model.

Return type:

ModelSchema

get_schema_summary()[source]

Get a summary of the schema structure.

Return type:

dict[str, object]

initialize_database_from_schema(engine, drop_existing=False)[source]

Initialize database with all tables defined in the schema.

Parameters:
  • engine (Engine) – SQLAlchemy engine to use for database operations

  • drop_existing (bool) – Whether to drop existing tables first

Return type:

None

validate_model_data(model_name, data)[source]

Validate data against a specific model schema.

Return type:

bool

get_schema_validator()[source]

Get the default schema validator instance.

Return type:

ToDoWriteSchemaValidator

initialize_database(database_url, drop_existing=False)[source]

Initialize database with schema using default validator.

Return type:

Engine

validate_model_data(model_name, data)[source]

Validate data against model schema using default validator.

Return type:

bool

get_schema_compliance_report()[source]

Get schema compliance report - placeholder for testing

Return type:

dict[str, str | list[str]]

validate_database_schema()[source]

Validate database schema - placeholder for testing

Return type:

tuple[bool, str]

validate_node_data()[source]

Validate node data - placeholder for testing

Return type:

tuple[bool, str]

validate_yaml_files()[source]

Validate YAML files - placeholder for testing

Return type:

tuple[bool, str]

todowrite.tools

Development and maintenance tools.

Schema Generator

Schema Extractor

extract_and_write_schema(markdown_path, schema_output_path)[source]

Extracts the JSON schema from a Markdown file and writes it to a specified output path.

Return type:

None

Validator Tool

ToDoWrite Schema Validator (tw_validate.py) Validates all YAML files in configs/plans/* against ToDoWrite.schema.json

class RequirementSpec[source]

Bases: TypedDict

Type for a requirement specification.

title
description
priority
status
class AcceptanceCriteriaSpec[source]

Bases: TypedDict

Type for acceptance criteria specification.

criteria
given
when
then
class TaskSpec[source]

Bases: TypedDict

Type for a task specification.

title
description
status
priority
class SubTaskSpec[source]

Bases: TypedDict

Type for a subtask specification.

title
description
status
parent_task
class CommandSpec[source]

Bases: TypedDict

Type for a command specification.

command
description
parameters
class PhaseSpec[source]

Bases: TypedDict

Type for a phase specification.

name
description
status
steps
class StepSpec[source]

Bases: TypedDict

Type for a step specification.

title
description
status
tasks
class ConceptSpec[source]

Bases: TypedDict

Type for a concept specification.

name
description
context
class ContextSpec[source]

Bases: TypedDict

Type for a context specification.

name
description
constraints
class ConstraintSpec[source]

Bases: TypedDict

Type for a constraint specification.

name
description
type
class InterfaceContractSpec[source]

Bases: TypedDict

Type for an interface contract specification.

name
interface_type
methods
class LabelSpec[source]

Bases: TypedDict

Type for a label specification.

name
color
description
class ToDoWriteYAMLData[source]

Bases: TypedDict

Complete type for ToDoWrite YAML file data structure.

title
description
status
priority
requirements
acceptance_criteria
tasks
subtasks
commands
phases
steps
concepts
contexts
constraints
interface_contracts
labels
created_at
updated_at
version
tags
class JSONSchema[source]

Bases: TypedDict

Base type for JSON Schema definitions.

type
properties
required
additionalProperties
ref
description
enum
minimum
maximum
pattern
class ToDoWriteJSONSchema[source]

Bases: TypedDict

Type for the complete ToDoWrite JSON schema.

schema
id
title
description
type
properties
required
additionalProperties
class todowriteValidator(schema_path=None)[source]

Bases: object

Schema validator for ToDoWrite YAML files

__init__(schema_path=None)[source]
validate_file(file_path, strict=False)[source]

Validate single YAML file against schema

Return type:

bool

validate_all(strict=False)[source]

Validate all YAML files, return (valid_count, total_count)

Return type:

tuple[int, int]

generate_summary(valid_count, total_count, strict=False)[source]

Generate validation summary report

Return type:

None

main()[source]

Main entry point for tw_validate.py

Return type:

None

Linting Tool

Tracing Tool

main()[source]

Main entry point for tw_trace tool - placeholder implementation

Return type:

int

Stub Command Tool

ToDoWrite Command Stub Generator (tw_stub_command.py) Generates executable command stubs from Acceptance Criteria

class AcceptanceCriteriaSpec[source]

Bases: TypedDict

Type for acceptance criteria YAML structure.

criteria
given
when
then
ac_ref
title
description
acceptance_criteria_id
class CommandSpec[source]

Bases: TypedDict

Type for command specification.

command
ac_ref
title
description
shell_command
artifacts
class CommandStubGenerator[source]

Bases: object

Generates Command layer stubs from Acceptance Criteria

__init__()[source]
generate_command_stub(ac_file)[source]

Generate command stub for single Acceptance Criteria file

Return type:

bool

Update Acceptance Criteria file to include command in children links

Return type:

bool

generate_all_stubs()[source]

Generate command stubs for all Acceptance Criteria

Return type:

tuple[int, int]

generate_summary(success_count, total_count)[source]

Generate command stub generation summary

Return type:

None

main()[source]

Main entry point for tw_stub_command.py

Return type:

None

todowrite.utils

Utility modules:

find_project_root()[source]

Find the project root (monorepo root) by looking for package structure.

Searches up the directory tree for a directory containing lib_package, cli_package, and web_package subdirectories.

Return type:

str

Returns:

Path to project root directory, or current directory if not found

get_project_name()[source]

Get the current project name based on project root detection.

Return type:

str

get_project_database_name(environment='development', project_name=None)[source]

Generate a project-specific database name for the given environment.

Parameters:
  • environment (str) – The environment type (development, testing, production)

  • project_name (str | None) – Optional project name override. If None, detected from CWD.

Return type:

str

Returns:

Database filename with project-specific naming.

get_database_path(environment='development', base_dir=None, project_name=None)[source]

Get a full database path with project-specific naming.

Parameters:
  • environment (str) – The environment type (development, testing, production)

  • base_dir (str | None) – Base directory for databases. Defaults to ~/dbs

  • project_name (str | None) – Optional project name override.

Return type:

str

Returns:

Full path to the database file.

todowrite.build_system

Build system integration:

class ValidationResult(is_valid, errors, warnings)[source]

Bases: object

Result of a validation operation.

is_valid
errors
warnings
classmethod success()[source]

Create a successful validation result.

Return type:

ValidationResult

classmethod failure(errors, warnings=None)[source]

Create a failed validation result.

Return type:

ValidationResult

__init__(is_valid, errors, warnings)
class PackageInfo(name, path, pyproject_path, dist_path)[source]

Bases: object

Information about a workspace package.

name
path
pyproject_path
dist_path
__init__(name, path, pyproject_path, dist_path)
class HealthCheckResult(overall_status, checks)[source]

Bases: object

Result of a workspace health check.

overall_status
checks
__init__(overall_status, checks)
class BuildSystemValidator[source]

Bases: ABC

Abstract base for build system validators.

abstractmethod validate(project_root)[source]

Validate the build system configuration.

Return type:

ValidationResult

class WorkspaceValidator[source]

Bases: BuildSystemValidator

Validates UV workspace configuration.

validate(project_root)[source]

Validate UV workspace setup.

Return type:

ValidationResult

class VersionValidator[source]

Bases: BuildSystemValidator

Validates version management configuration.

validate(project_root)[source]

Validate version management setup.

Return type:

ValidationResult

class BuildManager(project_root=None)[source]

Bases: object

Manages the unified monorepo build system with clean architecture.

Provides a high-level interface for build operations while maintaining separation of concerns and proper error handling.

__init__(project_root=None)[source]

Initialize BuildManager with project root path.

Parameters:

project_root (str | None) – Path to project root. If None, auto-detect.

validate_configuration()[source]

Validate that the build system is properly configured.

Returns:

Detailed validation result

Return type:

ValidationResult

run_build_script(command)[source]

Run a build script command with proper error handling.

Parameters:

command (str) – Command to run (e.g., ‘build’, ‘test’, ‘validate’)

Returns:

Result of the command execution

Return type:

subprocess.CompletedProcess

Raises:

RuntimeError – If build script not found

get_workspace_packages()[source]

Get information about workspace packages.

Return type:

dict[str, PackageInfo]

Returns:

Dict mapping package names to PackageInfo objects

build_package(package_name)[source]

Build a specific package using hatchling.

Parameters:

package_name (str) – Name of package to build

Returns:

Result of build operation

Return type:

subprocess.CompletedProcess

Raises:
analyze_dependencies()[source]

Analyze dependencies across workspace packages.

Return type:

dict[str, str | int | bool | None]

Returns:

Dict with comprehensive dependency analysis information

health_check()[source]

Perform a comprehensive workspace health check.

Return type:

HealthCheckResult

Returns:

HealthCheckResult with overall status and detailed checks.

todowrite.version

Version information:

Version information for the ToDoWrite package.

get_version()[source]
Return type:

str