agora.plan.builder

Mutable in-memory plan state for tool-driven plan authoring.

An LLM-facing plan-authoring flow mutates a PlanDraft via typed inner tools (plan_add_task, plan_attach_postcondition etc). The framework owns YAML serialization — the model never authors YAML. At plan_finalize the draft converts to a frozen Flow which is saved via agora.core.flow.save_flow() and round-tripped through agora.plan.loader.load_plan() + instantiate_plan to prove the emitted YAML is executable.

Design notes

  • Task insertion order is preserved via an OrderedDict so the emitted YAML is deterministic and diff-friendly.

  • Validation happens at the tool boundary. Each add_* / attach_* method raises AgoraError with a human-readable message the tool executor surfaces back to the LLM. The LLM can then correct on its next turn — standard feedback loop.

  • Stages are stored as plain dicts (shape mirrors StageTemplate). They convert to real StageTemplate objects only at to_flow() time.

Classes

PlanDraft

Mutable plan being authored by an LLM agent via typed tool calls.

class agora.plan.builder.PlanDraft[source]

Bases: object

Mutable plan being authored by an LLM agent via typed tool calls.

name: str = ''
description: str = ''
agents: list[dict[str, Any]]
tasks: OrderedDict[str, dict[str, Any]]
brief: str = ''
api_spec: str = ''
set_metadata(name, description='')[source]
set_agents(agents)[source]

Replace the agent roster in one shot. agents is a list of {name, role, instructions, model?} dicts. Validates roles and deduplicates by name.

upsert_agent(name, role, instructions, model='')[source]

Add OR replace one agent by name. Idempotent on the name key.

Returns True if a new agent was appended, False if an existing entry was updated. This is the surface the per-agent author stages call — each stage’s narrow scope is “define one agent”, and upsert lets a stage retry correct a prior mistake without clobbering the rest of the roster.

reset_agents()[source]

Clear the agents roster. Returns the prior count so callers can log it. Mirrors _autofill_missing_postconditions() / the plan_reset_tasks pattern — framework-only, no validation.

validate_agent(name, *, expected_role='')[source]

Per-agent compile check. Returns the list of problems (empty = valid). Used both by the plan_validate_agent framework stage and by the plan_draft_all_agents_valid postcondition.

Checks:
  • an agent with name exists in the draft

  • role is a known AgentRole value

  • if expected_role is given, actual role matches

  • instructions is at least _MIN_AGENT_INSTRUCTIONS_CHARS chars long (catches “” / template defaults)

validate_roster(*, min_agents=2)[source]

Roster-level checks. Returns a list of problems.

  • minimum count

  • at least one agent with a “builder” role (architect or implementer) so the plan actually has someone to produce deliverables

  • no duplicate (name, role) pairs (name uniqueness is enforced on upsert, but a rogue direct-mutation could still produce dupes)

Re-balance task assignments so every agent has ≥1 task when possible. Returns a dict of {action: [task_ids]} for logging.

Phase 1 — Fill gaps: any task with empty assigned_to gets a role-based suggestion matched against the roster. If no agent with that role exists, the first builder-role agent is used.

Phase 2 — Rebalance orphans: for each agent that still has no task assigned, steal the first task from an agent who has ≥2 tasks AND whose role matches the orphan’s role (or, failing that, any multi-task agent).

Never overwrites an explicit assigned_to when the named agent exists in the roster.

validate_agents_vs_tasks()[source]

Coverage cross-check between agents and tasks.

  • every agent has ≥ 1 task assigned (else why declare?)

  • every task’s assigned_to is a known agent

  • every task has a non-empty assigned_to

Returns the problems list; empty → OK. Called by the plan_validate_agents_vs_tasks framework stage that runs after author_tasks but before finalize_plan.

snapshot_markdown()[source]

Human-readable snapshot of the current draft for cross-stage context injection. Each author stage’s next-stage reads this via context_files so the LLM can see what task_ids exist when choosing depends_on values, etc.

add_task(task_id, description, assigned_to, depends_on=None, output_path='')[source]
add_task_spec(task_id, description, assigned_to, depends_on=None, output_path='', postconditions=None, api_spec_modules=None)[source]

Atomic: add a task AND attach its postconditions in one call.

The compound operation is the tool surface that weak models can actually use reliably — per-task stages invoke this once instead of looping plan_add_task then plan_attach_postcondition N times. If any postcondition is malformed, the whole task is rolled back so the draft never ends up in a half-authored state.

v2.8 (Approach C — C4a): if api_spec_modules is non-empty, any src/*.py path referenced by output_path or by a postcondition rel must appear in the set. Surfaces the architect’s “I’m targeting a module that was never declared” mistake at authoring time rather than silently at finalize-time remapping/dropping. Non-src paths (tests/*, requirements.txt, etc.) are never gated.

Also auto-fills the rel arg for any postcondition whose factory requires it (file_exists, py_compiles, file_contains, no_code_after_main_block, max_line_length, python_imports) when the caller didn’t pass one and the task has an output_path. Lets weak models pass a minimal [{"name": "file_exists"}] list instead of [{"name": "file_exists", "args": {"rel": <path>}}].

Returns the number of postconditions attached.

attach_postcondition(task_id, name, args=None)[source]
add_llm_stage(task_id, name, instruction, context_files=None, max_iterations=5)[source]
add_decision_stage(task_id, name, decision_id, question, options, output_path)[source]
validate_ready()[source]

Return a list of structural problems that would prevent finalize.

Empty list → ready. Non-empty → plan_finalize should surface the issues as an error string and let the LLM retry.

Checks: ≥ 1 agent, ≥ 1 task, every task has ≥ 1 postcondition, DAG is acyclic. The compound plan_add_task_spec tool makes it easy for weak models to satisfy the postcondition rule — each per-task stage authors one complete task (spec + postconditions) via a single call.

to_flow()[source]

Convert the draft to a frozen Flow ready for save_flow.

Does NOT re-validate readiness — callers should call validate_ready() first and handle any problems.

summary()[source]

Short human-readable summary for tool-result strings.

__init__(name='', description='', agents=<factory>, tasks=<factory>, brief='', api_spec='', _ROLE_HEURISTICS=(('tester', ('test_', 'tests/', '/tests/', 'pytest', 'unittest', '_test')), ('architect', ('setup', 'scaffold', 'skeleton', 'requirements.txt', 'pyproject', '__init__.py', 'config', 'manifest', 'architecture', 'outline'))))