Skip to content

Mother Workflow Tool Generation Subsystem Secondary Development

This document explains how to perform secondary development on the Tool generation subsystem of the Mother Workflow, specifically modifying tools/workflow_tool_generator/, its UCTool wrapper, mother configuration registration, and related regression tests, to enable future generated business workflows to obtain new tool templates, spec fields, write policies, or registration capabilities. It does not teach business Agents how to invoke a specific tool.

A Tool is a deterministic capability exposed by the Mother Workflow to the UCAgent, and it is also the type of artifact delivered by the Mother Workflow generation to the sub-workflow. Developers must understand both "the UCTool of the generator itself" and "the business Tool produced by the generator," but actual modifications should focus on the source code, spec contract, and templates of the former.

Secondary Development Goals

Tasks suitable for completion in this subsystem include: adding generic tool templates, extending the tool spec schema, modifying preserve/replace policies, enhancing path safety, adjusting config registration, adding tool test baselines, or fixing generation states. Business-specific algorithms that serve only a single generation workflow should be provided as inline source code or business templates via the central spec, rather than being hard-coded into all workflows shared by the Mother Generator.

Mother Workflow Modification Entry Points

  • tools/workflow_tool_generator/core.py: spec validation, generation state, write, and registration.
  • tools/workflow_tool_generator/templates.py: built-in tools and generic source code renderer.
  • tools/workflow_tool_generator/uc_tools.py: parameter model and UCTool for calls to the Mother Agent.
  • Root config.yaml: which mother stage calls the generator and which specs are passed.
  • Guide_Doc/stages/: instructs the Mother Agent on how to prepare specs and perform batch generation.
  • regression/: tool descriptions, delivery contracts, and stability verification.

DOCX tool cases mentioned later should be understood as "how to verify that a Mother Generator extension can support a business," not a requirement for developers to write DOCX logic into the WorkflowToolGenerator.

Real Generation Pipeline

The tool generation entry point is located in tools/workflow_tool_generator/. Tool specs in the central workflow_build.yaml first declare the name, purpose, parameters, output, errors, invocation stage, and tests, and then the generator writes them into the business workflow's tools/ directory and updates the registration. The core coordination logic of the Mother Builder is located in tools/workflow_builder/core.py; this file also generates the generic environment, README, and fixed skeleton.

When developers adjust the tool protocol, they should search simultaneously:

rg -n "tool_spec|GeneratedTools|tools\." workflow_builder workflow_tool_generator regression

Do not modify the generation result of a single workspace_x/workspace/workflow/tools/ instance, as that will not improve subsequent builds.

Interface Structure

A tool should have a stable name, a clear docstring, serializable parameters, and a structured return value. The recommended return format is:

1
2
3
4
5
6
7
{
    "ok": True,
    "data": {"output_path": "output/example/document.docx"},
    "errors": [],
    "warnings": [],
    "meta": {"tool": "BuildDocument", "version": 1},
}

When failing, ok must be False, and errors should contain stable error codes, actionable messages, and related fields or paths. Do not catch exceptions and still return success, nor print terminal text and let the Agent guess the result.

Key Business Code Analysis Requirements

The generated docs/04开发者文档-tools.md must reference real source code snippets for each tool, not pseudo-code. Each tool must analyze at least:

  1. How the tool entry function or class receives parameters and performs type, path, and business pre-condition validation.
  2. How the core algorithm or third-party library call converts input into a business product.
  3. How file writing restricts to allowed directories, uses temporary files, and handles partial failures.
  4. How exceptions are mapped to structured errors, and which errors allow retries.
  5. How registration code allows the UCAgent to find the tool, ensuring parameter configuration and Python signatures are consistent.
  6. Which branches are covered by normal, boundary, and failure tests.

Source code references must note relative paths and symbol names. After the snippet, key variables and control flow must be explained; do not simply paste the entire file. If a tool is generated by a template, also indicate the template source and the actual file differences after generation.

Write and Command Boundaries

Tools can only write to directories allowed by the business workflow. Temporary data from the build process enters the workspace tmp/ and should not be scattered in wfgen/ as debug scripts. When executing batch operations or external programs, use whitelists, parameter arrays, timeouts, and return codes; do not concatenate user input into arbitrary shells.

Path validation should occur after parsing and normalization to prevent .., symbolic links, and absolute path escapes. The existence of an output directory does not equal a valid product; tools must also verify size, format, or re-parsability.

Parallelism and Performance

Independent tools can be generated or tested in parallel by the Agent, but writes to shared registration files and central specs must be coordinated serially. The generation stage should not stipulate "only one tool can be called per response"; the real constraint is avoiding concurrent modifications to the same file and running a comprehensive check once after batch generation.

Modification Checklist

  • Update the central tool spec and requirements manifest.
  • Update generator templates or generic implementations, not just individual products.
  • Update registration, GuideDoc, and developer document generation rules.
  • Add positive, negative, boundary, and path escape tests.
  • Run tool generator regression and the total make regression.

Complete Data Flow from Tool Spec to Source Code

Business tools are not written directly to tools/ based on natural language. In the first phase, tool responsibilities are clarified in the requirements manifest and implementation plan. In the design phase, stable fields are written into the central tool spec. The generator reads the spec, validates paths and interfaces, renders source code, updates registration, and saves generation state. Finally, the business config is exposed to the UCAgent via a dynamic adapter.

A maintainable spec must include at least: name, description, entry file, class name, input schema, output schema, errors, invocation stage, implementation template or inline source code, tests, and existing file policies. The description must answer what problem the tool solves in the business process, not just repeat the class name. Input fields need type, requiredness, and meaning; output fields must allow subsequent Agents and Checkers to stably read the data.

Path Safety Code Analysis

Source location: tools/workflow_tool_generator/core.py, symbol _safe_resolve().

1
2
3
4
5
6
7
8
def _safe_resolve(root: Path, rel_path: str) -> Path:
    candidate = Path(rel_path)
    if candidate.is_absolute() or ".." in candidate.parts:
        raise ToolGenerationError(...)
    target = (root / candidate).resolve()
    if target != root and root not in target.parents:
        raise ToolGenerationError(...)
    return target

The first layer rejects absolute paths and explicit .., and the second layer checks the true parent directory after resolve(), so symbolic links or path normalization cannot escape the workflow root. All specs, generated files, configurations, and test paths should go through this entry point. When adding tools like "copy resources," do not re-use string prefix checks in your own branch, because /root/workflow-old might incorrectly match /root/workflow.

Path safety verification only proves that the generator's write location is safe; it does not guarantee runtime safety of the generated business tools. Runtime tools still need to re-normalize user-provided paths relative to the business workspace and restrict allowed read/write roots.

Generation State and Overwrite Strategy

Source location: tools/workflow_tool_generator/core.py, symbols _load_generation_state(), _write_generated_file(), and _normalize_existing_policy().

The generator saves file content hashes and test baselines to distinguish three scenarios: the file is still the content from the previous generation, the file has been modified by the user or an incremental process, and the file appears for the first time. The existing file policy cannot be expressed by a single boolean overwrite, because automatically overwriting manually maintained code may cause data loss, while skipping everything would make spec updates never take effect.

The following is pseudo-code omitting implementation details; the full implementation is in the source code above.

1
2
3
4
5
6
policy = _normalize_existing_policy(existing_policy, overwrite)
if target.exists() and policy == "preserve":
    report.skipped_files.append(relative)
    return
...
state["files"][relative] = {"sha256": _sha256_text(content), ...}

When developers add a policy, they must define how to handle: target does not exist, target matches the last hash, target has drifted, and forced overwrite; how the report records these; and whether failures leave a new state. The state file must be updated only after successful actual writes and must use secure persistence; do not record the new hash before writing the file.

Spec Validation Code Analysis

Source location: tools/workflow_tool_generator/core.py, symbol _validate_tool_spec().

This function checks the spec top-level mapping, tool name, description, entry file and class, input/output, implementation type, and tests. The validation order should be structural before semantic: if entry is not a mapping, do not continue to read entry.file. Tool descriptions, parameter explanations, and error contracts belong to maintainable interfaces, not optional decorations.

When declaring inline source code in the spec, Python AST or compilation checks should also be performed, and the existence of the entry class confirmed. Template tools are generated by render_tool_from_spec(), but must also pass the tool static checker and direct runner after writing to prevent template string syntax correctness while having incorrect runtime protocols.

Generic Template Rendering Code Analysis

Source location: tools/workflow_tool_generator/templates.py, symbols _schema_from_inputs(), _output_schema_from_spec(), and _render_generic_tool().

1
2
3
4
5
def render_tool_from_spec(spec):
    template = spec.get("template")
    if template in BUILTIN_RENDERERS:
        return BUILTIN_RENDERERS[template](spec)
    return _render_generic_tool(spec)

Input specs are first converted to fields required by Pydantic/JSON schema, then written into the generated class. The output schema is not the runtime result itself, but the contract that the Agent and tests understand the data structure. Generic tool templates must retain the ok/data/errors/warnings/meta structure; otherwise, the upper-layer Agent cannot uniformly determine failure.

If the business subject in the generated class is just a placeholder NotImplemented or unconditionally succeeds, the static syntax may pass, but the tool is unusable. Therefore, the central plan should prefer explicit templates or provide real implementation source code, and invoke them with positive and negative cases using the direct runner. When adding a new template, add the template name to the allowed set, implement the renderer, add fixtures, record requirements, and update developer documents.

Registration Process Code Analysis

Source location: tools/workflow_tool_generator/core.py, symbols _tool_record_from_spec() and _register_tool_records().

Registration records convert spec entry points into runtime loadable module class paths while preserving tool names, descriptions, parameter schemas, and source specs. The generator should batch collect records before a single update to the config to prevent multiple parallel tool generations from overwriting the registration file.

Registration must satisfy three-way consistency: the Python class name and entry file exist; the class path recorded in the config is importable; and the tool parameter model matches the spec input fields. If files are created in tools/ without registration, UCAgent will not call them; registering non-existent files will cause failures at startup or upon first use.

Batch registration must also handle tools with duplicate names. Duplicate names should typically update the same record or fail explicitly; they cannot silently generate two sequentially dependent records. When modifying the registration structure, simultaneously check tools/mcp_adapters.py, the tool spec checker, the static runner, and the evaluation tool registration review.

UCTool Wrapping Layer Code Analysis

Source location: tools/workflow_tool_generator/uc_tools.py, symbols WorkflowToolGeneratorArgs and WorkflowToolGenerator.

The parameter model is responsible for converting JSON passed by the Agent into stable Python types. The actual run() should only perform parameter normalization, invoke the core, catch ToolGenerationError, and return a structured result, without duplicating business generation logic in the wrapping layer. This allows CLI, regression, and UCTool to share the same core.

The wrapping layer docstring becomes the tool description visible to UCAgent and must specify the generation location, spec requirements, overwrite strategy, and return content. Parameter default values should be handled carefully: setting overwrite=True as the default may cause the Agent to overwrite user-maintained code without awareness.

Structured Error Design

Recommended failure result:

{
    "ok": False,
    "data": {},
    "errors": [{
        "code": "TOOL-GEN-SPEC-004",
        "message": "entry.file must be workflow-relative",
        "location": ".workflow/tool_specs/BuildDoc.yaml:entry.file",
    }],
    "warnings": [],
    "meta": {"generated": [], "skipped": []},
}

Error codes are used for stable association in FAQs, Checkers, and Agent fix prompts; the message explains the fact and fix direction; the location points to the spec field. Do not include full sensitive inputs or large stderr in errors. External command output should be truncated and saved in tmp/ logs; the returned structure should only provide summaries and paths.

Secondary Development Case: Enabling the Parent Generator to Support New Business Tools

Assume enabling the parent workflow to stably generate DocumentStructurePlanner required by business DOCX. The secondary developer first determines if the existing generic renderer is sufficient; if so, only enhance the parent stage's spec planning and validation without adding public templates. If multiple businesses reuse the structure planning algorithm, add a template renderer in templates.py and allow the template name in the core. The tool spec defines content_path, requirements_path, and assets_index_path, outputting plan_path, chapter count, and warnings.

After generation, verify: missing body content returns a stable error; unknown heading levels form warnings; resource references do not escape paths; identical inputs yield stable plans; registered classes are importable; positive fixtures include headings, lists, and images; negative fixtures lack only one required file. GuideDoc explains call order and failure recovery, and docs/04开发者文档-tools.md references the actual planning algorithm source code.

If later support for tables is added, do not just modify the Python implementation. Also update capability requirements, spec output schema, test samples, GuideDoc, user input descriptions, and developer code analysis. If output fields change, the Checker using them and subsequent DOCX renderers must also be synchronized.

Correct Boundaries for Parallel Generation

Different tool sources and independent fixtures can be prepared in parallel as they write to different files. Central tool specs, generation state, config registration, and comprehensive reports are shared resources that must be submitted by a single coordination step. The recommended process is parallel generation of candidate content, followed by serial calls to the generator to write and register, with the final run performing tool static/direct/MCP comprehensive checks.

Do not enforce a global rule of "only one tool call at a time," as it would force serial execution of dependency-free workflows. Also, do not allow unconstrained parallel calls to multiple generators that would overwrite the same config. Parallel strategy should be based on whether write sets intersect, not on the number of tools.

Extension Points, Modification Impact, and Regression Matrix

Modification Must Check
New spec field schema, validation, templates, console view, old spec default values
Path rule modification safe resolve, symbolic links, absolute paths, Windows/Posix expressions, write boundary regression
Return structure modification UCTool, Agent guidance, direct runner, evaluation tool availability check
Overwrite strategy modification generation state, hash, user drift, repeated runs and incremental compatibility
New template renderer, requirements, positive/negative fixtures, registration and developer documentation
Registration modification import test, MCP adapter, config generator, and eval_tools

After target tests pass, run total regression. During real business validation, let the sub-Agent call the generation tool to complete the stage; developers cannot manually place the final tool and pass the Checker as if the generator succeeded.

Parent Workflow UCTool Complete List

The following table lists classes that truly inherit UCTool in the current source code. "Registration Context" indicates which configuration exposes it to the Agent; it does not mean every configuration uses all tools. After modifying class names, parameter models, or return structures, search config.yaml, inc.yaml, and eval_*.yaml for ex_tools and synchronize GuideDoc and regression.

Tool Source Registration Context Core Responsibilities and Side Effects
WorkflowBuilder tools/workflow_builder/uc_tools.py Main config.yaml Reads central construction design, materializes sub-workflow skeletons, fixed supporting files, and reports; is the controlled entry point for the build core.
WorkflowCommandRunner tools/workflow_builder/uc_tools.py Main config.yaml Runs whitelist commands within the build workspace, restricting cwd, timeout, parameters, and output; should not evolve into arbitrary shell execution.
WorkflowArtifactInspector tools/workflow_builder/uc_tools.py Main config.yaml Structurally queries files, directory trees, summaries, and local content for evidence collection; read-only and size-limited.
WorkflowEnvironmentPreflight tools/workflow_builder/uc_tools.py Main config.yaml Checks Python, Make, UCAgent, paths, dependencies, and optional external commands, outputting a distinguishable environment report for "missing" vs "optional skip".
WorkflowPlanAppender tools/workflow_builder/uc_tools.py Main config.yaml Appends implementation plans with phase markers, preserving prior phase content; responsible for the living plan's non-overwrite constraint.
WorkflowToolGenerator tools/workflow_tool_generator/uc_tools.py Main process and inc.yaml Validates tool spec, generates business tool source, fixtures, tests, and registration, maintaining generation state and overwrite strategy.
WorkflowCheckerGenerator tools/workflow_checker_generator/uc_tools.py inc.yaml Generates or updates Checker, fixtures, and registration from checker spec; some Checkers in main builds can also be materialized directly by the Builder.
WorkflowConfigGenerator tools/workflow_config_generator/uc_tools.py Main process and inc.yaml Generates or updates config.yaml and inc.yaml based on workflow spec, injecting Tools, Checkers, GuideDoc, and phase contracts.
WorkflowGuideDocGenerator tools/workflow_guidedoc_generator/uc_tools.py Main process and inc.yaml Validates document spec, generates GuideDoc and user/developer documentation, registering only against guidance needed by the Agent.
ChildWorkflowSupervisor tools/workflow_child_supervisor/uc_tools.py Main process limited validation and eval_run.yaml Starts, queries, captures, or stops sub-workflows via independent tmux sessions, returning run id and observable state; should not be registered in static eval_tools/checkers/flow/env.
IncrementalContextInventory tools/workflow_evaluation_control/uc_tools.py inc.yaml Inventories sub-workflows, reports, approvals, and resources under controlled reading budgets, producing a round-trip cognitive index rather than copying full text.
StructuredJsonStore tools/workflow_evaluation_control/uc_tools.py All evaluation and inc.yaml Performs CRUD with schema, revision, and audit on allowed eval/*.json and res/*.json; is the sole conventional write channel for structured files.
EvaluationCommandRunner tools/workflow_evaluation_control/uc_tools.py All static evaluation and inc.yaml Runs evaluation/regression whitelist commands, saving return codes and truncated evidence; does not allow static evaluation to start sub-workflows via it.
StaticEvaluationAudit tools/workflow_evaluation_control/uc_tools.py All evaluation and inc.yaml Performs deterministic audit on Tools, Checkers, config, GuideDoc, environment, and write boundaries, outputting rule id and evidence.
EvaluationControl tools/workflow_evaluation_control/uc_tools.py Control API/compatibility entry Encapsulates aggregation, approval, suggestion, and incremental run control; not all YAML ex_tools register it currently; do not assume Agent visibility upon modification.
IncrementalCandidateStager tools/workflow_evaluation_control/uc_tools.py inc.yaml Safely copies approved targets from the formal workflow/ to the current run/batch/attempt candidate directory and records source hash.
IncrementalChangeDeployer tools/workflow_evaluation_control/uc_tools.py inc.yaml Validates candidate mapping against current approval, backs up old versions, atomically replaces formal files, and rolls back on failure while writing applied_changes.json.
ReadTextFileMCPTool tools/workflow_builder/core.py Generated sub-workflow MCP Reads text within the business workspace with path boundaries and chunk parameters; it is the generation source template, not a regular tool for the parent Agent build stage.
WriteTextFileMCPTool tools/workflow_builder/core.py Generated sub-workflow MCP Writes text within the business-allowed root, maintaining output and temporary file boundaries.
RunCommandMCPTool tools/workflow_builder/core.py Generated sub-workflow MCP Provides limited command execution for sub-workflows; the allowed set should be determined by business design and environment configuration.

Secondary Development of Control Tools

The parameter layer of WorkflowBuilder should only accept workspace-relative design paths, override strategies, and optional phase ranges; materialization must be delegated to tools/workflow_builder/core.py. When adding a fixed deliverable, updates must be applied simultaneously to BuildReport, the initial skeleton, requirements manifest overrides, the delivery contract, and the secondary development documentation for artifacts. A file not recorded by the core must never be temporarily written inside run().

WorkflowCommandRunner and EvaluationCommandRunner share similar names but distinct permissions. The former serves the generation and verification of the build workspace, while the latter serves the evaluation of evidence and incremental regression. Adding allowed commands requires adding precise parameter rules to the whitelist of the corresponding executor; allowing arbitrary make <target> simply because make check is needed in one place is incorrect. Regression tests must cover non-whitelisted targets, timeouts, out-of-bounds current working directories, non-zero return codes, and excessively long outputs.

WorkflowArtifactInspector is used to reduce the need for Agents to perform full-text scans to establish understanding. When adding a new query type, it should return file count, size, hash, matches, and a truncation marker, rather than expanding content without limits. The check items in WorkflowEnvironmentPreflight must declare required/optional status, confirm commands, and provide installation suggestions; missing optional Verilator and Python failure to start cannot be set as equivalent blocking conditions.

WorkflowPlanAppender must use stable begin/end markers to locate the current phase block and refuse to overwrite other phases. When extending plan fields, compatibility reading of old plans without new fields, idempotency of retries within the same phase, and corresponding rules from WorkflowLivingPlanChecker must be checked.

Secondary Development of Four Generator Tools

WorkflowToolGenerator, WorkflowCheckerGenerator, WorkflowConfigGenerator, and WorkflowGuideDocGenerator follow the same wrapping principle: Pydantic Args ensure basic types for Agent JSON, the core handles path normalization and business validation, and UCTool converts expected exceptions into structured failures. If new fields are added only to Args without passing them to the core, the Agent will mistakenly believe the parameters are active; if only the core is modified, the Agent cannot construct the parameter.

The deliverables differ among the four generators: the Tool generator maintains tool source code and generates hashes; the Checker generator also materializes positive and negative fixtures; the Config generator performs cross-file reference closure, placeholders, and phase connection audits; the GuideDoc generator distinguishes between Agent GuideDoc and human documents. A generic generator that merely "reads spec then writes file" should not be abstracted, as this would lose their respective semantic validations.

Secondary Development of Evaluation and Incremental Tools

The output of IncrementalContextInventory should be a "navigable cognitive list": configuration phases, tool/checker indices, target findings, direct dependencies, and a read-order based on demand. It should not embed docs/, all source code, and historical reports into a single large report. When extending inventory items, set per-file and total byte budgets, and retain truncated evidence to prevent evaluation/incremental Agents from repeatedly reading after continuous compression.

Public operations of StructuredJsonStore include list/get/create/update/upsert/delete and must select a fixed schema via relative document ID. Adding a structured file requires synchronizing json_store.py to allow list, initial documents, collection/id rules, CLI, review API, UI, and regression. Agents must not bypass revision to directly cover JSON via WriteTextFile.

Each rule returned by StaticEvaluationAudit must have a stable id, scope, passed status, severity, evidence, and remediation. New rules must belong to the correct evaluation domain and provide minimal positive and negative fixtures. If EvaluationControl is registered as a new Agent entry point, its permissions overlapping with CLI/review server must be explicitly defined to avoid three inconsistent implementations of the same approval operation.

IncrementalCandidateStager and IncrementalChangeDeployer must be separated. The Stager only copies formal files to the current candidate and records hashes; the Deployer can then verify approval, backup, and atomic replacement. Merging them would pollute formal files before candidates are checked. When modifying the mapping format, synchronize incremental reports, applied changes, historical indices, consoles, and rollback tests.

Operations start/status/capture/list/stop of ChildWorkflowSupervisor are implemented in tools/workflow_child_supervisor/core.py, allowing only explicit Make targets like run_tui, run, run_inc, and run_inc_tui. Adding a target requires first determining it will not bypass the evaluation cost gate, and adding regression tests for session naming, run metadata, startup failures, timeouts, stopping, and residual tmux cleanup. When modifying capture, continue limiting line count, avoiding returning the entire long TUI log to the Agent context.

Built-in MCP Tools for Generated Artifacts

ReadTextFileMCPTool, WriteTextFileMCPTool, and RunCommandMCPTool are defined in the generation source of tools/workflow_builder/core.py. Developers modifying them must simultaneously read the generated tools/mcp_adapters.py, config registration, security boundaries, and make test_tools. They represent the lowest-level capabilities of sub-workflows; arbitrary commands or out-of-bounds writes cannot be allowed simply because business tools are incomplete.

These classes appear in Builder source code but run within the generated sub-workflow. Therefore, after modification, not only must the parent code be compiled, but a brand new business workflow must be generated, importing the classes from the generation directory and executing out-of-bounds negative cases. Success of AST parsing in Builder source code alone does not prove the template string is runnable after generation.

Standard Steps for Adding or Modifying UCTool

  1. First, determine in the table above whether the tool belongs to parent build, generator, evaluation/incremental, or sub-artifact, clarifying its readable root, writable root, and caller.
  2. Add or modify the Args model and specific Tool in the corresponding uc_tools.py, maintaining consistent docstrings, defaults, core parameters, and structured returns.
  3. In the core implementation, perform path validation, business logic, and atomic writes, avoiding placing large logic blocks inside the UCTool run().
  4. Register only in the YAML ex_tools where truly needed, then update the parameter source, output, failure recovery, and Checker evidence in the GuideDoc for that phase.
  5. Add Args validation, direct invocation, out-of-bounds paths, repeated execution, partial failures, and configuration registration regression, then run component regression and total regression for related components.

Continue Reading

To understand how tool outputs are judged by phases, please continue reading Checker Introduction. To modify tools in the generated sub-workflow, also combine with Generated Workflow Development Guide to judge whether modifications should flow back to the parent generator or be retained as a single business extension.