Skip to content

Instantly share code, notes, and snippets.

@stevesolun
Last active July 2, 2026 13:29
Show Gist options
  • Select an option

  • Save stevesolun/51be298459636969392cfc5a228cb5bd to your computer and use it in GitHub Desktop.

Select an option

Save stevesolun/51be298459636969392cfc5a228cb5bd to your computer and use it in GitHub Desktop.
Goal Contract Loop: Codex skill for verified autonomous coding goals

Goal Contract Loop

Codex skill for turning loose coding intent into a verified work loop:

intent -> contract -> SPEC/Plan/tracker/prompt -> execution evidence

It captures the outcome, evidence, edit boundaries, tools, iteration policy, budgets, pause conditions, and task acceptance criteria before the agent starts work.

Install

curl -fsSL https://gist.githubusercontent.com/stevesolun/51be298459636969392cfc5a228cb5bd/raw/1a366a014b82ba2ea768b00d26eb899f6ff159b4/install-goal-contract-loop.sh | bash

With the gated micro-pipeline variant:

curl -fsSL https://gist.githubusercontent.com/stevesolun/51be298459636969392cfc5a228cb5bd/raw/1a366a014b82ba2ea768b00d26eb899f6ff159b4/install-goal-contract-loop.sh | bash -s -- --with-micro

Then open a new Codex thread.

Use

Use $goal-contract-loop to turn this into a goal contract:
I want to audit this repo for latency regressions and fix the highest-severity issue.

The skill generates:

  • SPEC.md
  • Plan.md
  • goal_tracker.csv
  • goal_prompt.md
  • goal_contract.normalized.json

Files

  • install-goal-contract-loop.sh
  • goal-contract-loop.SKILL.md
  • generate_goal_package.py
  • contract-schema.md
  • interview-questions.md
  • openai.yaml
  • micro-pipeline.SKILL.md
  • micro-01-scope.md through micro-05-deliver.md
  • check-gates.md
  • failure-log.md

Domain Gate Questions -- Goal Contract Loop

Answer each YES or NO. Any NO = fix before proceeding.

  1. Is the user's desired outcome captured in one concrete sentence? YES/NO
  2. Are success criteria observable rather than subjective? YES/NO
  3. Is there at least one verification surface: command, benchmark, manual check, or artifact review? YES/NO
  4. Are editable paths and protected areas explicit? YES/NO
  5. Are public API, schema, data, and external-service risks considered? YES/NO
  6. Is the iteration policy clear about priority, test cadence, attempts, commits, and subagents? YES/NO
  7. Are budgets and pause conditions explicit? YES/NO
  8. Does every task have an ID, name, expected behavior, severity, and verification method? YES/NO
  9. Does the tracker include status and attempt fields? YES/NO
  10. Does the launch prompt tell the agent when to stop instead of continuing? YES/NO
  11. Are assumptions separated from verified facts? YES/NO
  12. Is user approval requested before launching autonomous execution unless explicitly waived? YES/NO

Goal Contract Schema

Use this schema for goal_contract.json. The helper script accepts missing optional fields and normalizes them into planning artifacts.

JSON Shape

{
  "objective": "Add payment processing without changing the existing user schema.",
  "done_when": [
    "Users can complete checkout in the happy path.",
    "Existing account creation still passes regression tests."
  ],
  "evidence": {
    "commands": ["npm test", "npm run lint"],
    "benchmarks": [],
    "manual_checks": ["Complete a sandbox checkout in the browser."],
    "artifacts": ["SPEC.md", "Plan.md", "goal_tracker.csv"]
  },
  "constraints": {
    "editable_paths": ["src/payments", "tests/payments"],
    "read_only_paths": ["db/schema.sql"],
    "do_not_change": ["Public user API", "Existing account schema"],
    "external_limits": ["Use sandbox provider only"],
    "required_tools": ["React", "Stripe sandbox"]
  },
  "iteration_policy": {
    "priority_order": "highest severity first, then feature order",
    "commit_policy": "small coherent commits after passing task tests",
    "test_cadence": "run task tests after each change and full suite before final",
    "subagents": "allowed only for independent test and audit tasks",
    "max_attempts_per_task": 3
  },
  "budgets": {
    "time": "2 hours",
    "tokens": "unspecified",
    "cost": "no paid API calls",
    "branch": "scratch branch"
  },
  "pause_conditions": [
    "Need production credentials",
    "Need schema migration approval",
    "A task fails 3 times"
  ],
  "tasks": [
    {
      "id": "F001",
      "name": "Checkout happy path",
      "user_story": "As a customer, I can pay for my cart with the sandbox provider.",
      "expected_behavior": "Checkout completes and records a sandbox payment.",
      "acceptance_criteria": [
        "Payment form validates required fields.",
        "Successful sandbox response creates an order."
      ],
      "test_command": "npm test -- payments",
      "severity": "P0",
      "status": "Not Started",
      "notes": ""
    }
  ],
  "assumptions": [
    "Sandbox credentials are available in the existing environment."
  ],
  "open_questions": [
    "Should refunds be included in this goal?"
  ]
}

Tracker Columns

Use these columns exactly for CSV trackers:

  • Feature ID
  • Name
  • User Story
  • Expected Behaviour
  • Test Command
  • Status
  • Severity
  • Attempts
  • Last Checked
  • Notes

Status Values

  • Not Started: no implementation or verification work yet.
  • Implementing: code or test changes are in progress.
  • Testing: verification is running or being analyzed.
  • Pass: acceptance criteria and evidence are satisfied.
  • Fail: current attempt failed but more attempts remain.
  • Blocked: attempt limit, external dependency, missing approval, or boundary conflict prevents progress.

Severity Values

  • P0: required for the goal to count as successful.
  • P1: important but not the central success gate.
  • P2: useful improvement, cleanup, or non-critical follow-up.
  • P3: optional polish or deferred work.

Goal Prompt Template

/goal <objective> verified by <evidence> while preserving <constraints>.
Use <allowed tools and resources>. Between iterations, <iteration policy>.
If blocked after <max attempts/time/budget>, report the blocker, update the tracker, and stop.

Failure Log -- Goal Contract Loop

Patterns caught by Check get appended here.

  • Avoid launching execution before approval.
  • Avoid vague evidence like "works well" or "looks good."
  • Avoid hidden edit boundaries.
#!/usr/bin/env python3
"""Generate goal-loop planning artifacts from a structured contract JSON."""
from __future__ import annotations
import argparse
import csv
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
TRACKER_COLUMNS = [
"Feature ID",
"Name",
"User Story",
"Expected Behaviour",
"Test Command",
"Status",
"Severity",
"Attempts",
"Last Checked",
"Notes",
]
STATUS_VALUES = {"Not Started", "Implementing", "Testing", "Pass", "Fail", "Blocked"}
SEVERITY_VALUES = {"P0", "P1", "P2", "P3"}
def as_list(value: Any) -> list[str]:
if value is None or value == "":
return []
if isinstance(value, list):
return [str(item) for item in value if str(item).strip()]
return [str(value)]
def as_dict(value: Any) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
def bullet(items: list[str], empty: str = "None specified.") -> str:
if not items:
return f"- {empty}"
return "\n".join(f"- {item}" for item in items)
def value_list(mapping: dict[str, Any], keys: list[str]) -> list[str]:
values: list[str] = []
for key in keys:
for item in as_list(mapping.get(key)):
values.append(item)
return values
def normalize_task(raw: dict[str, Any], index: int) -> dict[str, Any]:
task_id = str(raw.get("id") or raw.get("feature_id") or f"F{index:03d}")
status = str(raw.get("status") or "Not Started")
severity = str(raw.get("severity") or "P1")
if status not in STATUS_VALUES:
status = "Not Started"
if severity not in SEVERITY_VALUES:
severity = "P1"
return {
"id": task_id,
"name": str(raw.get("name") or f"Task {index}"),
"user_story": str(raw.get("user_story") or raw.get("story") or ""),
"expected_behavior": str(raw.get("expected_behavior") or raw.get("expected_behaviour") or ""),
"acceptance_criteria": as_list(raw.get("acceptance_criteria")),
"test_command": str(raw.get("test_command") or ""),
"severity": severity,
"status": status,
"attempts": int(raw.get("attempts") or 0),
"last_checked": str(raw.get("last_checked") or ""),
"notes": str(raw.get("notes") or ""),
}
def normalize_contract(raw: dict[str, Any]) -> dict[str, Any]:
evidence = as_dict(raw.get("evidence"))
constraints = as_dict(raw.get("constraints"))
iteration_policy = as_dict(raw.get("iteration_policy"))
budgets = as_dict(raw.get("budgets"))
tasks_raw = raw.get("tasks") if isinstance(raw.get("tasks"), list) else []
objective = str(raw.get("objective") or raw.get("outcome") or "Complete the requested coding goal.")
tasks = [normalize_task(task if isinstance(task, dict) else {}, i) for i, task in enumerate(tasks_raw, 1)]
if not tasks:
tasks = [
normalize_task(
{
"id": "F001",
"name": "Implement goal",
"user_story": objective,
"expected_behavior": "The requested outcome is implemented and verified.",
"test_command": ", ".join(as_list(evidence.get("commands"))),
"severity": "P0",
},
1,
)
]
return {
"objective": objective,
"done_when": as_list(raw.get("done_when") or raw.get("success_criteria")),
"evidence": {
"commands": as_list(evidence.get("commands")),
"benchmarks": as_list(evidence.get("benchmarks")),
"manual_checks": as_list(evidence.get("manual_checks")),
"artifacts": as_list(evidence.get("artifacts")),
},
"constraints": {
"editable_paths": as_list(constraints.get("editable_paths")),
"read_only_paths": as_list(constraints.get("read_only_paths")),
"do_not_change": as_list(constraints.get("do_not_change")),
"external_limits": as_list(constraints.get("external_limits")),
"required_tools": as_list(constraints.get("required_tools") or constraints.get("tools")),
},
"iteration_policy": {
"priority_order": str(iteration_policy.get("priority_order") or "highest severity first, then plan order"),
"commit_policy": str(iteration_policy.get("commit_policy") or "commit small coherent diffs when permitted"),
"test_cadence": str(iteration_policy.get("test_cadence") or "run task tests after each change and broader checks before final"),
"subagents": str(iteration_policy.get("subagents") or "do not use subagents unless explicitly allowed"),
"max_attempts_per_task": int(iteration_policy.get("max_attempts_per_task") or 3),
},
"budgets": {
"time": str(budgets.get("time") or "unspecified"),
"tokens": str(budgets.get("tokens") or "unspecified"),
"cost": str(budgets.get("cost") or "unspecified"),
"branch": str(budgets.get("branch") or "use existing branch unless user requests scratch branch"),
},
"pause_conditions": as_list(raw.get("pause_conditions")),
"tasks": tasks,
"assumptions": as_list(raw.get("assumptions")),
"open_questions": as_list(raw.get("open_questions")),
}
def render_spec(contract: dict[str, Any]) -> str:
constraints = contract["constraints"]
evidence = contract["evidence"]
budgets = contract["budgets"]
policy = contract["iteration_policy"]
created = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
lines = [
"# SPEC",
"",
f"Generated: {created}",
"",
"## Objective",
"",
contract["objective"],
"",
"## Done When",
"",
bullet(contract["done_when"]),
"",
"## Evidence",
"",
"### Commands",
bullet(evidence["commands"]),
"",
"### Benchmarks",
bullet(evidence["benchmarks"]),
"",
"### Manual Checks",
bullet(evidence["manual_checks"]),
"",
"### Required Artifacts",
bullet(evidence["artifacts"]),
"",
"## Constraints",
"",
"### Editable Paths",
bullet(constraints["editable_paths"]),
"",
"### Read-only Paths",
bullet(constraints["read_only_paths"]),
"",
"### Do Not Change",
bullet(constraints["do_not_change"]),
"",
"### External Limits",
bullet(constraints["external_limits"]),
"",
"### Required Tools",
bullet(constraints["required_tools"]),
"",
"## Iteration Policy",
"",
f"- Priority order: {policy['priority_order']}",
f"- Commit policy: {policy['commit_policy']}",
f"- Test cadence: {policy['test_cadence']}",
f"- Subagents: {policy['subagents']}",
f"- Max attempts per task: {policy['max_attempts_per_task']}",
"",
"## Budgets",
"",
f"- Time: {budgets['time']}",
f"- Tokens: {budgets['tokens']}",
f"- Cost: {budgets['cost']}",
f"- Branch: {budgets['branch']}",
"",
"## Pause Conditions",
"",
bullet(contract["pause_conditions"]),
"",
"## Assumptions",
"",
bullet(contract["assumptions"]),
"",
"## Open Questions",
"",
bullet(contract["open_questions"]),
"",
]
return "\n".join(lines)
def render_plan(contract: dict[str, Any]) -> str:
lines = [
"# Plan",
"",
f"Objective: {contract['objective']}",
"",
"## Task List",
"",
]
for task in contract["tasks"]:
criteria = bullet(task["acceptance_criteria"], "No separate acceptance criteria specified.")
lines.extend(
[
f"### {task['id']}: {task['name']}",
"",
f"- Severity: {task['severity']}",
f"- Status: {task['status']}",
f"- User story: {task['user_story'] or 'Not specified.'}",
f"- Expected behavior: {task['expected_behavior'] or 'Not specified.'}",
f"- Test command: `{task['test_command'] or 'Not specified.'}`",
"",
"Acceptance criteria:",
criteria,
"",
]
)
return "\n".join(lines)
def render_goal_prompt(contract: dict[str, Any]) -> str:
evidence = value_list(contract["evidence"], ["commands", "benchmarks", "manual_checks", "artifacts"])
constraints = value_list(
contract["constraints"],
["editable_paths", "read_only_paths", "do_not_change", "external_limits", "required_tools"],
)
policy = contract["iteration_policy"]
limits = [
f"{policy['max_attempts_per_task']} attempts per task",
f"time budget: {contract['budgets']['time']}",
f"token budget: {contract['budgets']['tokens']}",
f"cost budget: {contract['budgets']['cost']}",
]
return (
f"/goal {contract['objective']} verified by {', '.join(evidence) or 'the agreed evidence'} "
f"while preserving {', '.join(constraints) or 'the agreed constraints'}. "
f"Use the required tools and resources from SPEC.md. Between iterations, prioritize {policy['priority_order']}; "
f"{policy['test_cadence']}; {policy['commit_policy']}; subagents: {policy['subagents']}. "
f"If blocked after {', '.join(limits)}, report the blocker, update goal_tracker.csv, and stop.\n"
)
def write_tracker(path: Path, contract: dict[str, Any]) -> None:
with path.open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=TRACKER_COLUMNS)
writer.writeheader()
for task in contract["tasks"]:
writer.writerow(
{
"Feature ID": task["id"],
"Name": task["name"],
"User Story": task["user_story"],
"Expected Behaviour": task["expected_behavior"],
"Test Command": task["test_command"],
"Status": task["status"],
"Severity": task["severity"],
"Attempts": task["attempts"],
"Last Checked": task["last_checked"],
"Notes": task["notes"],
}
)
def write_text(path: Path, content: str) -> None:
path.write_text(content, encoding="utf-8")
def ensure_writable(paths: list[Path], force: bool) -> None:
existing = [str(path) for path in paths if path.exists()]
if existing and not force:
joined = "\n".join(f"- {item}" for item in existing)
raise SystemExit(f"Refusing to overwrite existing files. Use --force to replace:\n{joined}")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--contract", required=True, type=Path, help="Path to goal_contract.json")
parser.add_argument("--out", default=Path("."), type=Path, help="Output directory")
parser.add_argument("--force", action="store_true", help="Overwrite generated files if they exist")
args = parser.parse_args()
raw = json.loads(args.contract.read_text(encoding="utf-8"))
if not isinstance(raw, dict):
raise SystemExit("Contract JSON must be an object.")
contract = normalize_contract(raw)
out_dir = args.out
out_dir.mkdir(parents=True, exist_ok=True)
outputs = {
"SPEC.md": render_spec(contract),
"Plan.md": render_plan(contract),
"goal_prompt.md": render_goal_prompt(contract),
"goal_contract.normalized.json": json.dumps(contract, indent=2, sort_keys=True) + "\n",
}
output_paths = [out_dir / name for name in outputs]
output_paths.append(out_dir / "goal_tracker.csv")
ensure_writable(output_paths, args.force)
for name, content in outputs.items():
write_text(out_dir / name, content)
write_tracker(out_dir / "goal_tracker.csv", contract)
print(f"Generated {len(output_paths)} files in {out_dir}")
for path in output_paths:
print(path)
return 0
if __name__ == "__main__":
raise SystemExit(main())
name goal-contract-loop
description Turn a user's high-level coding intent into a clarified Codex goal contract, SPEC.md, Plan.md, tracker, launch prompt, and evidence-driven execution loop. Use when the user asks to convert an idea into a /goal, autonomous Codex loop, implementation plan, repo audit loop, migration loop, performance goal, feature delivery workflow, or reusable service/skill for verified coding work with constraints, budgets, and stop conditions.

Goal Contract Loop

Overview

Use this skill to transform vague coding intent into a concrete, reviewable contract before launching autonomous work. Keep the loop grounded in explicit outcomes, verification surfaces, editable boundaries, budgets, and pause conditions.

Do not start or create a goal loop until the user has approved the contract, unless the user explicitly asks you to proceed autonomously and the missing details are low risk.

Workflow

  1. Capture the raw intent in the user's words.
  2. Interview only for missing decision-critical details.
  3. Produce a structured goal contract.
  4. Generate planning artifacts: SPEC.md, Plan.md, goal_tracker.csv, and goal_prompt.md.
  5. Review the artifacts with the user.
  6. Launch or hand off the goal loop only after approval.
  7. During execution, update the tracker after every meaningful test or blocker.
  8. Finish with a report listing passed tasks, blocked tasks, evidence, changed files, and remaining risks.

Interview Gate

Ask concise questions across these required fields:

  • Objective and outcome: what result should exist when done, and how success is recognized.
  • Evidence: test commands, benchmarks, builds, lint checks, manual QA, acceptance criteria, or artifacts.
  • Boundaries: editable paths, forbidden files, public API/schema compatibility, data safety, and external systems.
  • Tools and resources: required frameworks, package managers, plugins, internet access, credentials, and allowed subagents.
  • Iteration policy: task priority, fix style, commit cadence, whether parallel worktrees are acceptable, and when to run full checks.
  • Stop conditions: success criteria, maximum failed attempts per task, time/token budget, approval gates, and external blockers.

Read references/interview-questions.md when the user intent is broad, risky, or missing verification/boundary details.

Goal Contract

Represent the result as a compact JSON-compatible structure with these keys:

  • objective: one sentence describing the target outcome.
  • done_when: list of observable success criteria.
  • evidence: commands, benchmarks, manual checks, and required artifacts.
  • constraints: editable paths, protected behavior, off-limits systems, and required tools.
  • iteration_policy: prioritization, commit policy, test cadence, subagent policy, and maximum attempts.
  • budgets: time, token, cost, branch, or scope limits.
  • pause_conditions: reasons to stop and ask the user.
  • tasks: implementation or audit items with IDs, acceptance criteria, severity, and test commands.
  • assumptions: explicit assumptions used to avoid over-questioning.
  • open_questions: unresolved items that need user approval or validation.

Read references/contract-schema.md for the full schema, status values, severity values, and examples.

Planning Artifacts

Create artifacts in the repository root or in a clearly named planning folder if the repo has one. Use the helper script when a contract JSON exists:

python3 path/to/goal-contract-loop/scripts/generate_goal_package.py --contract goal_contract.json --out .

The script writes:

  • SPEC.md: requirements, assumptions, constraints, and open questions.
  • Plan.md: task list with acceptance criteria and verification commands.
  • goal_tracker.csv: tracker with feature status, attempts, last checked time, and notes.
  • goal_prompt.md: a launchable goal prompt derived from the contract.
  • goal_contract.normalized.json: normalized contract used to generate the artifacts.

If no contract JSON exists, write the artifacts manually using references/contract-schema.md and then optionally backfill goal_contract.json.

Execution Loop

Use this loop after approval:

  1. Select the next Not Started, Fail, or unblocked task according to the priority policy.
  2. Inspect the relevant code and tests before editing.
  3. Set tracker status to Implementing or Testing.
  4. Make a focused change inside the allowed boundaries.
  5. Run the task's test command, then the broader suite according to the test cadence.
  6. Record pass/fail evidence, command output summary, attempt count, last checked time, and notes.
  7. Mark a task Pass only when its acceptance criteria and evidence are satisfied.
  8. Mark a task Blocked after the configured attempt limit or when a pause condition is hit.
  9. Commit small coherent diffs when the user's workflow permits commits.

Use subagents only when tasks are independent, boundaries are clear, and the user has allowed parallel work. Each subagent should receive only the relevant task, constraints, and verification commands.

Completion

When all tasks are Pass or Blocked, produce a final report with:

  • Outcome summary.
  • Tracker summary by status and severity.
  • Evidence commands and results.
  • Changed files or diff statistics.
  • Blockers and required external decisions.
  • Recommended next goal, if the blocked work should continue later.

Do not describe partial preflight or planning work as complete execution. Keep verified facts separate from assumptions.

#!/usr/bin/env bash
set -euo pipefail
GIST_URL="https://gist.github.com/stevesolun/51be298459636969392cfc5a228cb5bd.git"
DEST_ROOT="${CODEX_HOME:-$HOME/.codex}/skills"
WITH_MICRO=0
for arg in "$@"; do
case "$arg" in
--with-micro) WITH_MICRO=1 ;;
-h|--help)
echo "Usage: install-goal-contract-loop.sh [--with-micro]"
exit 0
;;
*)
echo "Unknown option: $arg" >&2
exit 1
;;
esac
done
command -v git >/dev/null 2>&1 || {
echo "git is required to install from the Goal Contract Loop gist." >&2
exit 1
}
backup_if_exists() {
local dest="$1"
if [[ -e "$dest" ]]; then
local backup="${dest}.backup.$(date +%Y%m%d%H%M%S)"
mv "$dest" "$backup"
echo "Existing install moved to $backup"
fi
}
install_main() {
local src="$1"
local dest="$DEST_ROOT/goal-contract-loop"
backup_if_exists "$dest"
mkdir -p "$dest/references" "$dest/scripts" "$dest/agents"
cp "$src/goal-contract-loop.SKILL.md" "$dest/SKILL.md"
cp "$src/contract-schema.md" "$dest/references/contract-schema.md"
cp "$src/interview-questions.md" "$dest/references/interview-questions.md"
cp "$src/generate_goal_package.py" "$dest/scripts/generate_goal_package.py"
cp "$src/openai.yaml" "$dest/agents/openai.yaml"
chmod +x "$dest/scripts/generate_goal_package.py"
echo "Installed goal-contract-loop to $dest"
}
install_micro() {
local src="$1"
local dest="$DEST_ROOT/goal-contract-loop-micro"
backup_if_exists "$dest"
mkdir -p "$dest/references"
sed 's/^name: goal-contract-loop$/name: goal-contract-loop-micro/' \
"$src/micro-pipeline.SKILL.md" > "$dest/SKILL.md"
for file in "$src"/micro-0*.md; do
cp "$file" "$dest/references/${file##*/micro-}"
done
cp "$src/check-gates.md" "$dest/check-gates.md"
cp "$src/failure-log.md" "$dest/failure-log.md"
echo "Installed goal-contract-loop-micro to $dest"
}
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
git clone --quiet --depth 1 "$GIST_URL" "$tmp/gist"
mkdir -p "$DEST_ROOT"
install_main "$tmp/gist"
[[ "$WITH_MICRO" -eq 1 ]] && install_micro "$tmp/gist"
echo
echo "Done. Open a new Codex thread, then try:"
echo " Use \$goal-contract-loop to turn this into a goal contract: audit this repo for latency regressions."
[[ "$WITH_MICRO" -eq 1 ]] && echo " Use \$goal-contract-loop-micro for the gated micro-pipeline version."

Interview Questions

Use this reference when the raw intent is underspecified. Ask the smallest useful batch of questions; do not turn the interview into a questionnaire if the answer can be safely inferred from repository context.

Minimum Viable Interview

  1. What specific outcome should exist when this is done?
  2. What commands, tests, benchmarks, or manual checks prove it worked?
  3. Which files, directories, APIs, schemas, or behaviors must not change?
  4. Are there tools, services, credentials, plugins, or internet access rules I should follow?
  5. What should make me pause instead of continuing autonomously?

Objective And Outcome

  • Is the work a new feature, bug fix, refactor, migration, audit, performance target, documentation pass, or release task?
  • What should the user be able to do after the work is finished?
  • What is out of scope even if it looks related?
  • Should the result be a local diff, committed branch, pull request, report, benchmark result, or deployed artifact?
  • How should acceptance be phrased from the end user's point of view?

Verification Surfaces

  • Which test command is authoritative?
  • Is there a build, lint, typecheck, formatter, integration test, snapshot test, or browser check?
  • Are there benchmarks, profiling scripts, load tests, or target thresholds?
  • Are manual QA steps required?
  • If tests are missing, should the first task be to add a failing test or a lightweight harness?
  • Which evidence should be preserved in the final report?

Constraints And Boundaries

  • Which paths may be edited?
  • Which paths are read-only?
  • Must public APIs, schemas, generated files, lockfiles, migrations, or snapshots remain unchanged?
  • Are there data privacy, production safety, or credential handling rules?
  • Are external APIs, paid services, network calls, or package installs allowed?
  • Should changes be minimal, compatibility-preserving, or allowed to reshape architecture?

Tools And Resources

  • Which language, framework, package manager, runtime, database, or deployment target matters?
  • Are browser automation, GitHub, Vercel, Gmail, Linear, Hugging Face, or other connectors allowed?
  • Is internet research allowed or required?
  • Are subagents allowed? If yes, may they use separate worktrees and create separate commits or PRs?
  • Are there existing docs, issue links, tickets, specs, logs, screenshots, or traces to use?

Iteration Policy

  • Should work proceed feature-by-feature, highest severity first, simplest first, or risk-first?
  • How often should commits be made?
  • When should the full suite run?
  • How many failed attempts should be allowed per task before marking it blocked?
  • Should blocked tasks be skipped so independent tasks can continue?
  • Should the agent preserve a tracker, status updates, or changelog during work?

Budgets And Stop Conditions

  • Is there a time, token, cost, CI, or API-call budget?
  • Should the agent pause before destructive commands, dependency upgrades, schema migrations, large rewrites, or production-touching operations?
  • What external approvals are required?
  • What counts as a blocker?
  • Should scratch branches, temporary worktrees, or draft PRs be used for safety?

Step 1: Scope

Capture the user's raw intent and convert it into missing contract fields.

Actions

  1. State the desired outcome in one sentence.
  2. Identify the request type: feature, bug fix, audit, migration, performance, refactor, docs, release, or mixed.
  3. Ask only for missing decision-critical details:
    • success criteria
    • verification commands or manual checks
    • editable and read-only paths
    • public APIs, schemas, data, or behavior that must not change
    • allowed tools, network, credentials, and subagents
    • budgets and pause conditions
  4. If tests are missing, propose adding a verification harness before implementation.

Gate

  • Can I state the deliverable in one sentence? YES/NO
  • Do I know what evidence proves success? YES/NO
  • Do I know the boundaries and stop conditions? YES/NO

All YES = proceed. Any NO = ask one concise question.

Step 2: Plan

Turn the scoped contract into a task plan before execution.

Actions

  1. Draft the goal contract:
    • objective
    • done_when
    • evidence
    • constraints
    • iteration_policy
    • budgets
    • pause_conditions
    • assumptions and open questions
  2. Break the work into tasks with IDs, user stories, expected behavior, acceptance criteria, test commands, and severity.
  3. Map every constraint to at least one task, check, or pause condition.
  4. Check failure-log.md for patterns that apply.

Gate

  • Does every success criterion have evidence? YES/NO
  • Does every constraint map to a task, check, or pause condition? YES/NO
  • Are tasks small enough to verify independently? YES/NO
  • Have I checked the failure log? YES/NO

All YES = proceed. Any NO = revise.

Step 3: Build

Generate the planning artifacts and launch prompt.

Actions

  1. Create or update:
    • SPEC.md
    • Plan.md
    • goal_tracker.csv
    • goal_prompt.md
    • optional goal_contract.json
  2. Use the generator script if a contract JSON exists: python3 scripts/generate_goal_package.py --contract goal_contract.json --out .
  3. Ensure tracker columns are: Feature ID, Name, User Story, Expected Behaviour, Test Command, Status, Severity, Attempts, Last Checked, Notes
  4. Keep generated artifacts in the repo root or agreed planning folder.

Gate

  • Are all required artifacts present? YES/NO
  • Does the tracker contain every planned task? YES/NO
  • Does the goal prompt include outcome, evidence, constraints, iteration policy, and stop conditions? YES/NO

All YES = proceed. Any NO = fix.

Step 4: Check

Hard gate. Answer every question YES or NO. "Mostly yes" = NO.

Universal Checks

  1. Does the package match the deliverable from Scope? YES/NO
  2. Are all user constraints represented in the contract? YES/NO
  3. Does every task have acceptance criteria? YES/NO
  4. Does every task have a test command or manual check? YES/NO
  5. Are pause conditions explicit? YES/NO
  6. Is the output usable without hidden assumptions? YES/NO

Domain Checks

Load check-gates.md and answer every question.

Failure Log

Re-read failure-log.md. Does the output violate any logged pattern? YES/NO

On Failure

For each NO, state the issue in one sentence, fix it, and rerun this full checklist.

Step 5: Deliver

Finalize and present the result.

Actions

  1. Remove scratch files from the shipped output.
  2. Verify all user-facing files are in their final locations.
  3. Present:
    • where the skill package lives
    • how to install it
    • how to invoke it
    • whether the micro-pipeline path is recommended
    • any validation limits or unresolved questions
  4. Keep the final summary concise and evidence-based.

Gate

  • Is every deliverable in the final folder? YES/NO
  • Are install and usage instructions included? YES/NO
  • Is the recommendation clear about normal skill vs micro-pipeline? YES/NO
  • Are validation gaps disclosed? YES/NO

All YES = done.

name goal-contract-loop
description Convert vague coding intent into a verified goal contract using a gated Scope-Plan-Build-Check-Deliver pipeline. Use for repo audits, features, migrations, performance work, refactors, or autonomous coding loops that need evidence, constraints, budgets, trackers, and stop conditions.

Goal Contract Loop

Execute this gated pipeline one step at a time. Do not skip ahead.

Pipeline

  1. Scope -- Read references/01-scope.md. Capture user intent and missing contract fields.
  2. Plan -- Read references/02-plan.md. Turn the contract into tasks and acceptance criteria.
  3. Build -- Read references/03-build.md. Generate artifacts and prepare the goal prompt.
  4. Check -- Read references/04-check.md. Answer every gate question YES or NO. Any NO = fix.
  5. Deliver -- Read references/05-deliver.md. Present the package and next action.

Failure Log

Read failure-log.md before starting. Every listed pattern is a mandatory constraint.

Rules

  • Keep the skill agnostic: ask for the user's outcome, evidence, constraints, and stop conditions.
  • Do not launch a goal loop until the contract is approved or the user explicitly asks for autonomous execution.
  • "Mostly yes" counts as NO in the Check step.
  • On Check failure: fix, rerun the checklist, then append a short pattern to failure-log.md.
interface:
display_name: "Goal Contract Loop"
short_description: "Turn coding intent into verified goal loops"
default_prompt: "Use $goal-contract-loop to turn this coding intent into a clarified goal contract, plan, tracker, and execution loop."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment