AC Optimal Power Flow Analysis
When to Use
- Find least-cost AC-feasible operating point for power systems
- Analyze voltage profiles and power flows
- Verify day-ahead market schedule feasibility
- Generate power system reports in JSON format
- Do not use this skill for heuristic or approximate dispatch-only outputs when the task requires AC-feasible results
Execution Focus
- Treat the task as an instance-solving job, not a software development project.
- Produce the required report for the provided inputs in the current session.
- Do not stop at a plan, architecture proposal, or request to "proceed"; complete the computation and write the report.
Runtime Protocol Is Mandatory
- Start by inspecting the workspace and referenced files to infer input paths, output path, solver options, and runtime constraints; ask clarifying questions only after confirming the needed information is genuinely unavailable.
- Before the first tool use or file operation, identify any task-specific requirements for tool-call syntax, allowed directories, file-access limits, message schema, per-turn waiting rules, and exact completion token.
- If the runtime specifies an exact
Thought/Actionformat, JSON action payload, one-tool-per-turn rule, or single allowed tool interface, use that literal format on every step; do not substitute default tool wrappers, prose-only substitutes, or habitual syntax. - If the runtime exposes only one tool/interface, use only that interface for reads, writes, and execution; do not invent alternate tool names or wrappers.
- Before the first action, extract the runtime interaction contract into a mini-checklist: exact wrapper/tags if any, required field names and JSON shape, allowed tool/interface names, one-action-per-turn waiting behavior, allowed paths, and exact completion token.
- Before emitting any tool call, copy the required interaction pattern literally from the runtime instructions and match it field-for-field: exact wrapper/prefix, exact JSON keys, exact tool/interface name, one-action-per-turn rule if any, allowed paths, and exact completion token. Keep that syntax unchanged for the rest of the run.
- On the first executable turn, make exactly one valid action using the required runtime wrapper to inspect the workspace or open the task files; do not spend the first turn on planning, todo updates, approval-seeking, or clarification questions when the environment can answer them.
- If the runtime requires a literal pattern such as
Thought:followed byAction:plus a JSON object, mirror that exact capitalization, labels, and payload shape on every action; do not substitute XML/tool tags, markdown fences, pseudo-function calls, renamed tools, alternate capitalization, or prose in place of that structure. - If the runtime mandates a literal action format, use that exact wrapper on every tool step; do not switch to XML-style tags, markdown/code-fence wrappers, prose-plus-tool hybrids, placeholder pseudo-commands, or default tool-call syntax.
- Treat action payloads as executable artifacts, not summaries of intent: shell actions must contain the exact command text to run, and file-write/edit actions must contain exact paths and literal old/new text or full file contents.
- Do not use underspecified actions like
list directory contents,install dependencies,validate report, orfix the script; issue the concrete command, path, pattern, replacement, or full content instead.
- Every action argument must be directly executable or directly applicable as written. Use literal commands, paths, offsets, limits, JSON fields, and exact old/new text or full file contents; do not send placeholders such as
..., pseudo-calls, or natural-language intent likeinspect inputs,run the solver, orreplace previous block. - Before creating scripts, virtual environments, logs, or outputs, identify the explicitly allowed or workspace-confirmed directories and anchor every file operation to those paths; do not assume habitual locations are permitted.
- Reuse the same confirmed path consistently for any environment or artifact you create; do not drift between similar locations later in the run.
- If the runtime exposes a special sub-workflow such as plan mode, approval prompts, or question/answer mode, enter it only when explicitly required by the interface and exit it cleanly with the exact required call before resuming normal actions. If such a mode-switch returns an unexpected prompt, malformed-response error, or ambiguous intermediate state, correct that interaction immediately instead of continuing in free-form prose.
- Treat protocol compliance as a hard gate: an otherwise correct OPF result is still incomplete if tool calls, path usage, or the final completion signal violate the runtime instructions.
- Treat any plan mode as temporary at most: inspect inputs, run or patch the solve, generate the report, and exit only after the required artifact exists and has been validated.
- If a mode switch, tool call, or protocol step fails, correct the invocation immediately and continue execution; do not end with a request for permission to proceed.
- If the task requires an exact final completion string, end with exactly that string and no extra prose.
- Do not ask for file names, file locations, output path, solver choice, or format details until you have first inspected the workspace and task files using the permitted interface and confirmed the information is genuinely unavailable there.
- Treat protocol mismatch as task failure even if the OPF work itself is correct.
- Before the final response, compare your intended closing message against the runtime's exact completion instruction. If a literal token is required, output exactly that token and nothing else.
- Before finalizing, run a last protocol gate: confirm the required artifact was actually generated and validated from the latest completed run, then compare your closing message against the runtime's exact completion token character-for-character.
- If the runtime requires an exclusive completion string such as
ACTION: TASK_COMPLETE, reserve it for the final turn and output exactly that string alone with no added prose, markdown, prefix, suffix, or punctuation. - Treat the exact completion signal as exclusive and non-substitutable: do not replace it with marker files, a prose summary, explanatory wrap-up text, or a near-match.
Input Files
network.json: MATPOWER format power system snapshotmath-model.md: Mathematical model description
- Derive the solver equations from
math-model.mdbefore coding; do not substitute an ad hoc AC-OPF formulation without checking each objective and constraint against the provided model.
- Do not proceed from a skimmed or truncated model read when implementing equations. Confirm the exact objective, sign conventions, indexing, bounds, and branch-flow expressions from
math-model.mdbefore trusting solver results.
Execution Checklist
- Before coding or patching the solver, finish reading any truncated
math-model.md,network.json, or task instructions until the needed objective terms, constraints, indexing, limits, report schema, and input structure are explicitly confirmed. - On any interpreter, virtualenv, or dependency repair step, immediately run a proof command that shows the intended Python executable works and that required imports succeed before relying on that environment.
- If a dependency is missing or installation is blocked, switch to an available interpreter/toolchain or an allowed isolated environment rather than repeating the failing approach.
- When a run fails, diagnose the first concrete blocker from the latest traceback or error line before changing solver formulation, tolerances, initialization, or model logic.
- If a traceback points to a specific file and line, read that exact on-disk code region before editing and base the patch on the observed failing expression rather than a guessed root cause.
- If a solver build/run fails and the traceback or log is truncated, stop speculative editing and first rerun with full stdout/stderr capture or otherwise extract the complete error from the same failing step before making additional changes.
- Do not chain
solve && view-reportand then treat truncated combined output as evidence of success; first confirm the solve command finished, then inspect the saved report in a separate explicit validation step. - If solver construction or execution fails repeatedly, capture the full exception from that exact failing call before changing variable types, formulation, or solver options.
- When a nonlinear solver fails, stalls, or returns an infeasible/suboptimal point, debug the formulation before solver tuning: re-check bus/gen/branch indexing, sign conventions, per-unit-to-MW/MVAr conversions, admittance/flow equations, objective terms, and limit mapping against
math-model.mdandnetwork.json.
- Use the first invalid metric to drive the next check: negative losses or generation below load -> audit balance/sign/unit conversions; extreme branch overloads -> audit branch admittance, thermal-limit mapping, and flow formulas; voltage-limit violations with odd angles -> audit voltage-variable bounds and indexing before changing solver options.
- Use small targeted checks before a full rerun: verify network assembly on a few buses/branches, confirm that computed balances/flows have the expected sign and units, and only then adjust tolerances, initialization, or solver options.
- In symbolic or optimization code, reserve distinct names for core decision variables and never reuse them for local parameters from buses, generators, or branches.
- Treat names like
x,g,f,Vm,Va,Pg, andQgas reserved once they represent symbolic decision variables or expressions; use distinct loop names such asbr_x,tap,rateA, orbus_ifor numeric fields so a later reassignment cannot overwrite the model. - After assembling the optimization model but before solver creation, print or inspect quick sanity checks for decision-vector type/shape and bounds/constraint dimensions so name collisions, scalar-overwrite bugs, or malformed formulations are caught immediately.
- If using CasADi or another symbolic library, explicitly confirm the decision vector is still symbolic immediately before solver creation; if a debug print shows a plain float or array where a symbolic object is expected, stop and fix the overwrite before changing solver settings.
- If the requested
math-model.mdformulation is not fully implemented or verified, do not present a heuristic, DC-style, sequential, or otherwise simplified fallback as task completion.
- If you temporarily use a reduced diagnostic model to debug environment or formulation issues, label it explicitly as a debugging aid only, keep it separate from the main deliverable, and return to the full
math-model.mdformulation before claiming completion. - Do not replace the primary solver/report path with a simplified fallback script and then hand off that fallback as if it satisfied the requested AC-OPF model.
- After any code or model edit, treat prior solve conclusions as stale until the updated run completes and you inspect outputs from that new run.
- Before executing a script, verify the command names the same path you most recently created or edited; do not switch to a similarly named file unless you have explicitly inspected it and confirmed it is the intended artifact.
- If you created a scratch or repro script during debugging, keep it separate from the production run and make sure the final solve/report command uses the intended main script.
- After any solver run that exits successfully, inspect the expected output artifact immediately before concluding the solve failed or switching approaches.
- If the solver completed but report creation, serialization, or post-processing failed, treat that first as a reporting/integration bug. Patch the output-generation path with minimal edits, then rerun the solve -> report pipeline instead of changing the mathematical model without evidence.
- After you obtain a run that produces a valid report and passes feasibility checks, freeze the working path unless a task requirement or a verified report defect still requires a change.
- Keep debugging experiments isolated from the main deliverable: use separate scratch/test scripts instead of overwriting the primary solver file with reduced repro code, then intentionally copy validated fixes back and rerun the full solve -> report pipeline end to end.
- Preserve created scripts, reports, and intermediate artifacts until final validation and handoff are complete; do not delete generated files unless cleanup is explicitly requested.
- Triage failures in order: (1) runtime/protocol violation, (2) Python/type/format/path/reporting exception from the latest traceback, (3) only then solver feasibility or formulation issues. Do not describe a run as infeasible or retune the model when the latest visible failure is a concrete runtime, typing, formatting, path, or reporting exception.
- If a file read returns truncated content and the environment offers offsets, ranges, pagination, or follow-up reads, immediately continue reading until the specific needed sections are visible; do not start implementing AC equations, report logic, or schema mapping from a partial file view.
- Before implementing the model, inspect
network.jsonstructurally: confirm the dimensions ofbus,gen,branch, andgencost, identify bus-type codes and the slack/reference bus, and verify the column layout you will use for limits, setpoints, costs, and branch ratings. If the file is array-based MATPOWER data, map columns explicitly before writing equations. - If you need a concrete pattern for inspecting MATPOWER-style arrays and column mapping before modeling, read references/network-input-inspection.md.
- Probe the environment before committing to a stack: verify which interpreter names exist, check whether key libraries are importable, and detect managed-package restrictions before attempting installation. Treat environment recovery as incomplete until an observed proof step succeeds by printing the chosen Python executable/version and importing the exact packages needed for this run.
- After writing or overwriting any solver/report script, reopen the saved file and inspect enough content to confirm it contains concrete executable code, not a prose summary or placeholder description, before running it.
- Do not delete solver scripts, helper scripts, scratch diagnostics, generated reports, environments, or other artifacts during the task just because a run appears complete; preserve them until the final artifact has been re-opened, validated, and the exact required completion signal has been emitted.
Execution Checklist
- Read
math-model.mdand inspectnetwork.jsonfar enough to identify the exact objective, constraints, variable definitions, limits, required report fields, and relevant MATPOWER tables (bus,gen,branch,gencost) before implementing or solving; if any read is truncated, continue reading until the needed details are confirmed. - Follow any task- or runtime-specific interaction rules exactly; use the required tool/action syntax, path conventions, and exact completion signal verbatim when provided.
- If the environment requires waiting for an observation after each action, issue exactly one tool call per turn and wait before continuing.
- Use absolute file paths whenever the task or environment provides or requires them.
- Check available tools, Python version, and required libraries before choosing an implementation; do not assume OPF frameworks or numerical packages are installed.
- Choose a solver approach that matches the confirmed environment, and prefer established OPF tooling over a from-scratch nonlinear program when available.
- Do not commit immediately to
scipy.optimize.minimize/SLSQP for large AC-OPF instances; if no dedicated OPF solver is available, first do a small diagnostic/prototype run to verify the formulation and method are numerically viable. - Implement with minimal edits. If a script or report is already working, patch the specific issue instead of deleting and recreating the artifact.
- After any code change, rerun the full flow and re-check that the final report is still produced and remains valid.
- Do not delete helper scripts, temporary files, environments, or dependencies before final handoff unless cleanup is explicitly requested.
Key Outputs
Report at the task-required absolute output path (often /root/report.json, but follow the task's path constraints if they differ) with structure:
{
"summary": {
"total_cost_per_hour": 1234567.89,
"total_load_MW": 144839.06,
"total_generation_MW": 145200.00,
"solver_status": "optimal"
},
"generators": [{"id": 1, "bus": 316, "pg_MW": 245.5, ...}],
"buses": [{"id": 1, "vm_pu": 1.02, "va_deg": -5.3, ...}],
"most_loaded_branches": [{"from_bus": 123, "to_bus": 456, "loading_pct": 95.2, ...}],
"feasibility_check": {"max_p_mismatch_MW": 0.001, ...}
}
Validation requirements for the final report:
- Match the requested report schema exactly and confirm the file parses as complete, valid JSON.
- Confirm the required top-level keys are present:
summary,generators,buses,most_loaded_branches, andfeasibility_check. - Populate every numeric report field from the computed solution; do not use placeholder or hard-coded feasibility values.
- Normalize solver/library-specific termination strings to the report vocabulary before writing JSON (for example, map a successful raw status such as
Solve_Succeededto"optimal"). - Map raw solver termination text to report status only after capturing explicit final solver evidence programmatically or from complete logs; never infer
optimalfrom startup banners, iteration headers, or partial console output. - Never copy raw solver return strings directly into user-facing schema fields when the report defines its own vocabulary; translate them first, then reopen the written JSON to confirm the normalized value is what was saved.
- If solver metadata is missing, malformed, or raises an exception, keep
solver_statusaligned to the verified outcome from explicit post-solve checks; do not default it tooptimal. - After solving, reopen the generated report and verify that derived summary semantics are correct, especially that losses are computed as
total_generation_MW - total_load_MWand that normalized status labels still match the actual solve outcome. - Populate
summary.solver_statusandfeasibility_checkvalues from actual solver results or explicit post-solve validation; do not hard-code placeholders or infer success from partial logs. - Gate report writing and presentation on explicit solver success plus basic feasibility checks. If the solver reports infeasible, failed convergence, invalid numbers, or the solved point has impossible balances or large violations, do not write or present it as a valid solved report.
- Treat statuses such as
Invalid_Number_Detected, NaN residuals/Jacobians,infeasible, failed convergence, or missing final termination evidence as hard blocks on final report generation. - Do not let a script write the required report path directly from intermediate iterate data. First verify explicit successful termination and basic physical consistency, then serialize the final report from that validated solved state.
- Treat any preexisting report at the target path as stale by default. Trust it only after a later run clearly finishes successfully and you confirm the artifact was regenerated from that run.
- For large or truncated report reads, use the targeted parser-based verification pattern in references/report-verification.md before making final claims.
- Set
solver_statustooptimalonly if an actual AC-OPF or AC power-flow-consistent solve succeeded under the provided model. - Treat the output as complete only if it reflects an AC-feasible operating point, not merely the correct JSON shape.
- Verify power mismatch, voltage-limit violations, generator-limit violations, branch overloads, and consistency of generation, load, and losses before declaring success.
- Treat any positive reported overload or other explicit feasibility violation from your own checks as unfinished work, even if numerically small; do not declare success while a nonzero violation remains unless the task explicitly provides a tolerance that deems it acceptable.
- Do not use
debug, failed-solve, infeasible,acceptable, orsuboptimaliterates as final AC-OPF results unless you separately compute and confirm all required feasibility checks from that point; otherwise report failure rather than labeling it solved.- If major violations, impossible balances, missing final solver status, or solver failure remain, do not report success; continue remediation or report the failure clearly.
- If you suspect a schema mismatch, first locate the exact required schema in the task instructions or referenced files and compare the saved report against that requirement before editing code or rewriting the report.
- Do not patch report structure or
summary.solver_statusbased on a truncated preview, missing tail section, or a desire to make the output look successful. Change report fields only when explicit solver termination evidence or explicit post-solve validation from the latest run shows the mapped status or structure should differ.
Units
- Power: MW (real), MVAr (reactive)
- Angles: degrees
- Voltages: per-unit
Required Validation Before Declaring Success
- Treat feasibility as a hard completion gate: a valid JSON file or correct schema is not completion by itself.
- Apply a hard-stop physical consistency check before any success claim: if
solver_statusis not explicitly successful,total_generation_MW < total_load_MWbeyond tolerance, implied losses are materially negative, any voltage/branch/generator violation is positive, or your own feasibility metrics show unresolved nonzero violations, do not finalize as solved. - Treat solver statuses such as
Infeasible_Problem_Detected,infeasible, failed convergence, or physically contradictory totals as hard blocks on completion. Do not emit the final completion signal, and do not describe the case as solved, until you have either fixed the formulation/run and regenerated a feasible report or explicitly reported failure to obtain an AC-feasible solution. - If a report is schema-correct but fails any physical consistency check, shows contradictory evidence such as
optimalplus negative losses or explicit overloads, or comes from a run that never reached final termination evidence, treat it as debugging evidence only; continue remediation or clearly report failure to obtain an AC-feasible point. - When the saved report is too large for a single view or any read shows truncation, use the parser-based pattern in references/report-verification.md to inspect
summary, fullfeasibility_check, and samples fromgenerators,buses, andmost_loaded_branchesfrom the regenerated file. - Use validation checks as hard completion gates. If any required feasibility quantity cannot be computed from the current solution, or if mismatches, limit violations, negative-loss contradictions, or clearly nonphysical branch loadings remain beyond tolerance, do not mark the case
optimalor AC-feasible. - Do not infer success from a cost-minimizing dispatch alone. Accept the result only if bus-level AC balance, voltage variables, reactive power behavior, and branch/network constraints have been solved or explicitly validated against the required model.
- Cross-check reported aggregates and percentages against their underlying numbers before finalizing, especially branch
loading_pct = flow / limit * 100and summary totals versus the generated report contents. - If validation finds a nonzero branch overload, mismatch, or limit violation, continue remediation: tighten solver tolerances, rerun from the latest model, or refine post-processing/limit handling, then recompute feasibility metrics before finalizing.
- Do not let a "diagnosed but tiny" violation bypass the completion gate; either eliminate it, show that it is within an explicitly stated task tolerance, or report that strict AC-feasible completion was not achieved.
- Treat any of the following as a hard stop against success: negative implied losses beyond tolerance, total generation materially below total load, large mismatch residuals, or major voltage/branch/generator limit violations.
- Treat obvious red-flag numerics as formulation or reporting bugs until disproven: zero or near-zero generation with substantial load, negative losses beyond tolerance, branch loading in the hundreds or thousands of percent, or any result that is clearly unrealistic or nonphysical.
- If any such red flag appears, do not describe the case as feasible, solved, or constraint-satisfying; debug the model or report calculations first and rerun before making success claims.
- If the solver says infeasible but simple adequacy checks such as total
Pmaxversus load suggest the case should be solvable, assume formulation risk first and continue debugging rather than concluding the dataset is bad. - Do not replace missing validation with placeholders or "best found" values. Compute
feasibility_checkfields from the final solved state, or clearly report failure/unsupported status instead of claiming success. - Validate that all table-indexing, sign conventions, and unit conversions used in the solve and post-processing match the inspected input schema; if balances or flows look wrong, audit schema mapping and per-unit conversion before concluding the model is infeasible.
- After every root-cause fix, rerun the full solve -> report pipeline and re-open the regenerated report; treat pre-fix outputs as stale.
- Do not write or preserve
summary.solver_status: "optimal"unless explicit solver evidence and post-solve feasibility checks both support that label.
- Treat solver outcomes such as
acceptable, high residuals, nontrivial constraint violation, or failed convergence as unfinished work, not successful completion, unless the task explicitly allows that status and your post-solve checks confirm all required feasibility conditions. - If the latest visible problem is a runtime, type, formatting, or reporting exception, fix that exception first; do not pivot to model retuning until a rerun shows a genuine solver-stage issue.
- Do not accept a report as successful merely because the JSON exists or the pipeline ran end-to-end; a structurally correct artifact with impossible balances, negative losses beyond tolerance, explicit overloads, voltage violations, or contradictory status evidence is a failed result, not a completed solve.
- If the report or logs contain contradictory evidence such as
optimalstatus plus infeasibility metrics, large residuals, overloads, or nonphysical totals, fix the formulation, post-processing, or status mapping before finalizing. - After editing code late in the task, never stop at the patch itself: verify there is a subsequent completed run, a regenerated report from that run, and final inspection of the saved artifact before handoff.
Required Validation Before Declaring Success
- Compute feasibility metrics from the final solved state; never leave placeholder values in
feasibility_check. - Verify system accounting is physically consistent:
total_generation_MW >= total_load_MWand implied lossestotal_generation_MW - total_load_MWare nonnegative within a small numerical tolerance. - Compute and report actual
max_p_mismatch_MWandmax_q_mismatch_MVArfrom the network equations at the solution. - Compute actual branch loading percentages and any overload amount from the solved flows and limits.
- If summary values show contradictions, such as negative losses, suspicious angles, or violated voltage/flow limits, do not state AC-feasible; flag the result as invalid and investigate.
Tips
- Use an optimization solver suited to AC-OPF scale and numerics; prefer established OPF tooling when available.
- Check power balance by computing residuals from the solved state.
- Verify voltage limits [vmin, vmax] from reported bus voltages before concluding success.
- Monitor branch loading percentages and compute overloads from solved flows and ratings.
- Treat solver convergence as insufficient until the above validation checks pass.
- Start from the required deliverable: solve the provided network instance, then populate the final report at the required path.
- Prefer direct execution with available tools/libraries over designing new modules or reusable frameworks unless explicitly requested.
- Do not ask for input paths, output paths, or solver choice before checking the workspace and task files.
- Enforce the mathematical model in
math-model.md; do not replace AC network equations, voltages, angles, or reactive power with ad hoc heuristics and still claim AC feasibility. - Ground decisions in observed command/program output; do not infer file discovery, solver state, or saved-file completion without evidence.
- Verify solve completion from explicit termination evidence before writing
solver_statusin the report. - Do not claim
optimalbased on solver startup banners, iteration headers, Jacobian counts, or truncated console output. - Do not invent convergence details such as iteration counts, final objective values, or solver-success messages unless they are explicitly visible in the current run's output or confirmed by directly inspecting the produced report/log artifact.
- If solver stdout is truncated, rerun with capturable logging or inspect the solver-produced files/report before stating that the solve succeeded.
- If solver metadata is ambiguous, compute feasibility metrics directly from the solved point and report the true status.
- If optimization fails or is too slow, prefer an explicit failure or unsupported result over a simplified method mislabeled as AC-feasible.
- If OPF appears infeasible, first audit formulation details: bus/generator/branch indexing, per-unit vs MW/MVAr conversions, sign conventions, bounds, and power-balance/flow constraints.
- Treat physical sanity checks as completion gates: if generation/load totals are inconsistent, losses have impossible signs or magnitudes, or branch loading/voltages are clearly nonphysical, do not finalize the report as successful.
- Do not claim adherence to
math-model.mdfrom a partial read; finish reading truncated model text first. - Do not assume the beginning of
network.jsonshows all relevant structures; continue reading truncated input as needed. - Do not declare completion from a partial read of the final report; confirm the full JSON structure and feasibility details.
- If you launch a solver asynchronously or in the background, wait for completion, inspect stdout/stderr, and verify the final report exists before finishing.
- Prefer a two-step validation pattern near the end: (1) run the solver and confirm the process completed, then (2) separately parse and print the saved report fields you will cite. Do not rely on one chained command when output may truncate.
- Never stop at a waiting state after starting an async or background solve; fetch its completion, verify outputs, and then perform the exact required completion step.
- Confirm available tools/commands before depending on them; if a utility is missing, switch to a supported fallback such as the Python standard library.
- Prefer robust parsing and report generation with Python over optional shell tools that may not be installed.
- If an attempted workflow step fails, correct the concrete issue, verify the changed lines are present, rerun the full OPF pipeline, and revalidate the regenerated report.
- Immediately after writing or patching a
.pyfile, read back the saved contents or run a lightweight syntax/import smoke check before treating it as the script you intended to execute. - If a write tool accepts free-form content, assume semantic write failure is possible: inspect the saved file itself before execution rather than trusting the write acknowledgement.
- Do not assume a rerun changed the report; reopen the final JSON and verify the specific fields you intended to change.
- Do not stop when a report-shaped JSON exists; stop only after the solved point passes feasibility checks and the final artifact has been fully inspected.
Tips
Execution Protocol and Final Checks
- Follow the task/runtime interface exactly as given in the prompt or system instructions. If the environment specifies a strict action/tool syntax, JSON schema, message format, file-access restriction, or exact completion token, use that literal format with no substitutions.
- Make the first substantive move quickly: after reading the instructions, use the allowed interface to inspect the workspace or open the relevant files rather than replying with a plan or clarification request.
- Keep planning private and brief; visible progress should be an allowed action that advances the deliverable.
- Never finish without the runtime's exact completion mechanism.
- Treat finalization as its own last checkpoint: verify the required artifact exists and was validated from disk, verify the latest run status supports the claim, then send exactly the mandated completion token if the runtime requires one.
- Do not place any explanatory prose after the required final token; if exclusivity is required, emit only that token.
- Treat protocol compliance as a completion requirement, not a formatting preference: use the exact required per-turn action syntax and finish only with the mandated completion signal.
- If the runtime is turn-based, never send multiple actions in one assistant turn even if they seem independent.
- Use only explicitly permitted paths and interfaces for the current run.
- Maintain an auditable sequence: inspect -> edit -> rerun -> verify.
- For long-running or chained commands, do not infer that later stages ran just because early output appeared or an old report file exists. First confirm the command completed, then verify the target artifact was regenerated by that completed run, then inspect the saved report.
- Keep edits concrete and reviewable: write exact code or exact replacements, then reopen the saved file and inspect the changed lines before rerunning. Preserve create -> inspect -> run traceability: if you created or patched a solver/report script, validate by running that same file explicitly unless you first inspect and justify a different entrypoint.
- Keep the execution trail causal and observable: if you claim a script was fixed, there must be a visible edit step before the rerun that produced the new result.
- Make critical edits auditable. For any fix to equations, limits, indexing, or report logic, inspect the saved file and verify the exact changed lines or behavior are present; do not rely on vague edit descriptions, placeholder replacements, or file-exists evidence.
- Keep artifact provenance observable: do not state that
run_opf.py,report.json, or any other file was created/updated unless the session shows the concrete write action that produced it. - Treat file-write integrity as a validation step: after creating or overwriting a
.pyfile, inspect enough of the saved file to verify it contains Python source code rather than a natural-language placeholder or summary.
- For newly written solver/report scripts, do not trust the write action alone. Read back the file immediately and confirm it contains real code structure such as imports, function/class definitions, or executable Python statements, not a sentence describing intended behavior.
- If the read-back shows placeholder prose or a summary instead of executable code, repair the file contents before any execution or completion claim.
- Do not claim a solver script exists just because a write command succeeded; confirm the on-disk contents are executable-looking code and, when feasible, run it.
- If you wrote or patched a file in this session, name that same file explicitly in the execution command used for validation; avoid switching to a different similarly named script without first inspecting and justifying it.
- Do not claim a script, fix, or report exists unless it was explicitly created or updated and then checked.
- Validate the final report from the regenerated artifact itself, not from truncated logs, a header-only preview, or file existence.
- Ground every final success claim in the latest completed rerun of the exact file version now on disk. If you rewrote or restored a solver script, rerun that same script to completion and inspect the regenerated artifact before concluding.
- Do not report feasibility metrics, overload counts, limiting branches, mismatch values, or solver-success claims unless you directly re-read those exact fields from the regenerated artifact or explicit verification output of the latest completed run.
- Do not treat solver startup banners, iteration headers, or launch messages as solve completion; wait for explicit final termination evidence, process completion, or verified regenerated report contents from the latest run before claiming success.
- Treat any report/output file found before the current run as stale by default. Use it as evidence only after confirming the latest completed command regenerated or updated that exact file in this session.
- After creating or patching a critical code file, reopen it and inspect enough of the saved contents to confirm the actual code was written, not a placeholder summary or truncated fragment, before running it.
- If solver stdout/stderr or the report read is truncated before the needed fields are visible, continue reading or rerun with capturable output before making any claim about status, feasibility, totals, violations, or branch details.
- Keep all final statements evidence-bound. Only report solver status text, feasibility metrics, overload counts, limiting branches, or other numeric findings that you directly confirmed from the regenerated final JSON or explicit verification output of the latest completed run.
- Do not summarize unseen portions of the report; if a preview omitted
feasibility_checkfields, branch details, or claimed sections, open those sections before citing them. - For JSON deliverables, verify the whole artifact: open the final report from the required path, parse it as complete JSON, confirm the required top-level keys are present, and inspect enough of each section to ensure the report is complete rather than header-correct.
- Treat any truncation notice as incomplete verification. If a file view says it was truncated, continue reading the remainder or use another method to inspect the full artifact before declaring success.
- Do not rely on
head,tail, or smallgrepsnippets as sole evidence for report correctness when the file is larger than those views; use targeted parsing/reads to inspect the exact required fields. - For large JSON reports, prefer a parser-based check that prints the required fields and selected counts/entries from the saved file, then base final claims only on that observed output. If a file read reports truncation or shows only a preview, treat verification as incomplete and continue reading with offsets or use the targeted parsing pattern in references/report-verification.md before claiming the report is complete or valid.
- After each fix and rerun, re-open the regenerated artifact and directly inspect the specific affected fields before claiming the issue is resolved.
- If the report is large or a read is truncated, use targeted reads/queries to inspect the exact sections you changed or rely on for final claims; do not treat a file head/tail preview as full verification.
- Inspect enough of the saved JSON to confirm the reported claims, including
solver_status, total cost, total load/generation,generators,buses,most_loaded_branches, andfeasibility_check; if the read is truncated, continue reading the remainder before declaring success. - Sample multiple required sections of the written report before finishing: inspect
summary, at least one populated entry frombusesorgenerators,most_loaded_branches, and the fullfeasibility_checkblock. - Keep final statements evidence-bound: report only values, counts, statuses, and branch/bus findings that were directly read from the final JSON or explicit verification output from the latest completed run.
- Do not claim solver success or report correctness from startup banners, Jacobian/nonzero counts, early iteration logs, dependency-install logs, partial progress text, or other incomplete fragments. Confirm completion from explicit final status, exit code, completion log, or by directly inspecting the final report artifact.
- Before opening or summarizing the report file, first verify that the producing command finished and that the report was written or updated by that completed run; treat any pre-existing report at the target path as stale until then.
- If you start a solve asynchronously or in the background, you must fetch its final status/output, inspect stdout/stderr, confirm the required report file was regenerated, and only then proceed to completion.
- Before finishing, verify that the final report exists at the required path, parses as complete valid JSON, and contains the required top-level keys:
summary,generators,buses,most_loaded_branches, andfeasibility_check. - Do not treat structure-only checks as final validation. Cross-check that
total_generation_MWapproximately equalstotal_load_MWplus losses, branchloading_pctmatches the reported flow/limit ratio, and the report'ssolver_statusmatches the solver's actual termination result. - Separate artifact validation from solution validation before handoff: a complete schema-correct JSON file does not imply AC feasibility.
- Do not accept
solver_status: "optimal"plus correct top-level keys as sufficient evidence of success; explicit numerical consistency checks for balances, losses, residuals, and limits must also pass. - After each fix, verify the specific defect that motivated the change is gone in the new run. For example, if branch-flow logic was repaired, re-check branch loading and overload metrics from the regenerated report rather than only confirming that the file exists or parses.
- If output or file reads are truncated, incomplete, or ambiguous, fetch the needed remainder, rerun with full capture, or inspect the produced artifact before making claims.
- If you changed code or model inputs and reran the OPF, treat earlier outputs as stale until the new run clearly finishes and the report is confirmed to be from that latest run.
- If the latest run is infeasible or physically inconsistent, do not switch to a handoff that says the infrastructure works or the file is ready; continue remediation or explicitly report failure to obtain an AC-feasible solution.
- Separate artifact readiness from task completion: after all validations pass, perform the exact required closing action/token and nothing else when the runtime requires exclusivity.
- Keep the runtime environment and dependencies intact until final validation is complete.
- When editing solver code that uses symbolic math libraries (for example CasADi), do not introduce Python boolean tests on symbolic expressions inside
ifstatements; avoid patterns likeif mx_expr == 0unless the library explicitly returns a real boolean there. - If a run succeeds and the report passes feasibility checks, prefer final report verification and handoff over additional code churn.
- Do not claim solver success or report correctness from startup banners, dependency-install logs, early iteration text, partial progress output, or truncated stdout/stderr; require explicit final termination evidence, process exit evidence, or a regenerated artifact whose contents show the completed run's result.
- If output capture is incomplete or a chained command may still be running, fetch the remainder, rerun with capturable logging, or inspect the produced artifact before making any success claim.
- Treat exit code 0 or other process-success signals as a cue to check artifacts first: verify whether the required report was regenerated, parse it, and inspect solver/feasibility fields before rewriting the workflow.
- Do not replace a solver or start a new approach until you have checked whether the previous completed run already produced a valid deliverable.
- Ground the final handoff in the last completed observable run only: if the latest rerun output is truncated, interrupted, missing the expected report readback, or otherwise ambiguous, do not claim success yet.
- Do not end while a background or asynchronous solve is still running. Wait for final completion, inspect its outputs, verify the report, then emit the exact required completion token.
- Before final handoff, explicitly verify the target artifact from the filesystem produced by the latest completed run: confirm the file exists at the required path, parse it successfully, and inspect the saved contents rather than inferring success from startup text or a presumed chained command.
- If you used a scratch reproduction or temporary simplified script during debugging, confirm the final reported result came from the intended main solver/report path, not from an isolated test file unless the task explicitly allows that replacement.
- Keep final claims strictly evidence-bound: report only values, counts, statuses, and branch/bus findings that were directly read from the latest regenerated artifact or explicit verification output.
- Do not place explanatory prose where an action object or exact completion token is required.
- Once deliverables and validations are complete, stop acting immediately unless the task explicitly requests cleanup, teardown, or extra post-processing.
- Do not run cleanup commands such as deleting virtual environments, temporary folders, or helper artifacts after reporting readiness unless cleanup was explicitly requested.
- Finalization is a separate mandatory step: after the report is validated, emit the exact required completion signal and nothing else when the runtime requires exclusivity.
- Treat solver startup text, model dimensions, banners, dependency-install logs, and lines ending at
Solving...as nonterminal. Do not claim convergence, optimality, or completion until you observe explicit final termination text, process-completion evidence, or a regenerated validated artifact from that run. - Before the final response, perform one last gate in order: verify the latest completed run regenerated the target report, re-read every report section you intend to cite from the saved artifact (using targeted parsing if large or truncated), then emit the exact required completion token and stop acting unless cleanup was explicitly requested.
- Do not state that a solve succeeded, that a report is complete, or that specific totals, statuses, feasibility findings, branch results, or bus/generator details were obtained unless those exact facts were directly read from the latest completed run output or from the regenerated saved report.