# goal-prompt

Drafts copy-paste-ready /goal commands for goal mode in Claude Code and Codex. Use when the user asks to create, write, rewrite, improve, compress, clean up, or prepare a goal prompt, goal condition, /goal command, goal-mode objective, or copy-ready long-running task objective.

- **Kind:** skill
- **Source:** https://github.com/trailofbits/skills
- **Page:** https://forefy.com/skills/ccfeb1ba-0a98-427d-918c-0b642ae38438
- **API (JSON + files):** https://forefy.com/api/skills/ccfeb1ba-0a98-427d-918c-0b642ae38438

---

## SKILL.md

---
name: goal-prompt
description: "Drafts copy-paste-ready /goal commands for goal mode in Claude Code and Codex. Use when the user asks to create, write, rewrite, improve, compress, clean up, or prepare a goal prompt, goal condition, /goal command, goal-mode objective, or copy-ready long-running task objective."
allowed-tools: Bash Read Write
---

# Goal Prompt

`/goal` keeps the agent working until a completion condition is met. Both Claude Code and Codex take it as one line, max 4,000 characters. In Claude Code a small model re-judges the condition after each turn from the transcript alone — it cannot run commands.

Draft a condition that can terminate, then format it. A goal fits work bigger than one turn with a checkable finish line; chain small goals with review between them rather than writing one giant goal.

## Draft

Include, joined with AND — never "or", the loop takes the cheaper branch:

1. **End state, not activity** — "all `legacyAuth()` call sites use `auth.verify()`", not "migrate the auth code". An activity can be claimed; an end state is true or false.
2. **Scope to read first** — the files, issue, logs, or plan to read before acting.
3. **Stated check** — the exact command and its observable result ("`npm test` exits 0"), plus an instruction to run it and show the output; a result that never lands in the transcript does not exist to the evaluator.
4. **Invariants** — what must not change ("without modifying vendor/"), always including "do not weaken, skip, or edit the checks themselves".
5. **Stop bound or blocked clause** — "or stop after 20 turns", "if blocked, stop and report the blocker". Without one, a mis-stated condition loops forever; the formatter warns when it is missing. (Claude Code resets the turn counter on session resume, so a turn bound silently extends across resumes.)

**Keep it small.** Every constraint narrows the state space the model can explore. Collapse to one terminating criterion when possible, move scope and definitions into a referenced file, and drop non-goals — a constraint earns its place only by closing a real easy-out.

For long goals, also name the final evidence (diff, report, artifact) and require a progress log file — durable state across compaction and resume. If the brief exceeds 4,000 characters, put the details in a `GOAL.md` and reference that file from the objective.

**Never invent missing elements.** Ground every element in the user's request, the conversation, or the repository — look things up rather than guessing. If an element cannot be filled from available information, still optimize and format what the user provided, leave the element out, and flag it as missing (see Format). A goal with an invented success condition terminates on the wrong contract.

## Close the easy-outs

Before formatting, reread the drafted condition as a lazy model would: what is the cheapest way to make every check pass without doing the intended work? Close the cheapest ones — prefer pairing checks you already have over adding constraints, and do not enumerate every conceivable out into a non-goal list. The recurring outs:

- **Delete or stub instead of fix** — "search prints nothing" also holds when the callers are gone; pair such checks with one that proves the feature still works.
- **Pass on a subset** — running one test file, narrowing the search path, excluding directories from the check.
- **Game the gate** — skipping/xfail-ing tests, hardcoding expected outputs, special-casing the test inputs, editing the check (the invariants rule).
- **Claim without running** — declaring done or blocked with no check output in the transcript (the show-the-output rule).

Same discipline as above: an out you cannot close from available information goes in the `Missing:` list as a warning — an invented or absurd constraint is worse than a flagged gap.

## Security research goals

Collapse audit goals to one terminating criterion, such as identifying, triggering, and validating one high-severity vulnerability valid under a referenced threat-model file. That file, not the goal, carries scope, attacker powers, severity baseline, and known findings to skip. Use neutral wording ("trigger and validate", not "prove this is exploitable"), require demonstrated preconditions — assumed attacker access is the most common false positive — and stop for human review after each finding rather than piling up untriaged reports. Validate findings with a second pass by a fresh agent, never the finder alone.

## Format

Run `uv run --no-project {baseDir}/scripts/format_goal_prompt.py --fenced` on the draft (file or stdin). It collapses whitespace to one line, strips `/goal` prefixes, quotes, and fences, warns on a missing stop clause, and rejects output over 4,000 characters — shorten or move detail to a file and rerun.

Return exactly one fenced `text` block, one line:

```text
/goal <single normalized objective>
```

Add no prose around it — except when checklist elements could not be grounded: then follow the block with a `Missing:` list, one line per gap, telling the user what to supply.

## Example

Draft:

```
/goal Migrate the auth module:
  - replace legacyAuth() with auth.verify()
  - make sure the tests still work
```

Redrafted and formatted:

```text
/goal All legacyAuth() call sites use auth.verify(): `rg "legacyAuth\(" -t ts` prints nothing AND `npm test` exits 0 (run both, show the output), without modifying vendor/ or weakening any test. If blocked, stop and report attempted paths and the blocker, or stop after 20 turns.
```

Here `npm test` came from the repo's package.json — not a guess — and pairing it with the zero-matches check closes the cheapest out: deleting the call sites instead of migrating them. When nothing grounds an element, format what exists and flag the gaps:

Draft: `make checkout faster`, with no metric or benchmark anywhere in context:

```text
/goal Make checkout faster
```

Missing:
- measurable end state — which metric and threshold count as "faster"
- verification — the benchmark or command that proves it
- stop bound — e.g. "or stop after 20 turns"

## agents

```

```

## agents/openai.yaml

```yaml
interface:
  display_name: "Goal Prompt"
  short_description: "Format copy-ready /goal commands"
  default_prompt: "Use $goal-prompt to turn this task into a copy-ready /goal command."
```

## scripts

```

```

## scripts/format_goal_prompt.py

```python
#!/usr/bin/env python3
"""Format a /goal command with deterministic whitespace normalization."""

from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path

DEFAULT_MAX_PROMPT_CHARS = 4000

# A numeric turn/time bound ("or stop after 20 turns") or a blocked clause
# ("if blocked, stop and report..."). Without one, a mis-stated condition
# keeps the goal loop running indefinitely.
STOP_CLAUSE_PATTERN = re.compile(
    r"\bafter\s+\d+\s+(?:turns?|iterations?|attempts?|rounds?|hours?|minutes?)\b"
    r"|\bblocked\b",
    re.IGNORECASE,
)


def has_stop_clause(objective: str) -> bool:
    return bool(STOP_CLAUSE_PATTERN.search(objective))


def read_text(path: str | None) -> str:
    if path in (None, "-"):
        return sys.stdin.read()
    return Path(path).read_text(encoding="utf-8")


def strip_surrounding_fence(text: str) -> str:
    stripped = text.strip()
    match = re.fullmatch(r"```[A-Za-z0-9_-]*\n(.*)\n```", stripped, flags=re.DOTALL)
    if match:
        return match.group(1)
    return text


def normalize_objective(text: str) -> str:
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    text = strip_surrounding_fence(text)
    text = text.strip()
    text = re.sub(r"^/goal(?:\s+|$)", "", text, count=1)
    text = text.strip().strip('"').strip("'").strip()
    return re.sub(r"\s+", " ", text).strip()


def format_goal_command(
    text: str,
    *,
    objective_only: bool = False,
    max_chars: int = DEFAULT_MAX_PROMPT_CHARS,
) -> str:
    objective = normalize_objective(text)
    if not objective:
        raise ValueError("goal objective is empty after normalization")
    output = objective if objective_only else f"/goal {objective}"
    if max_chars > 0 and len(output) > max_chars:
        raise ValueError(f"formatted goal prompt is {len(output)} characters; limit is {max_chars}")
    return output


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Normalize text into a copy-ready /goal command.")
    parser.add_argument(
        "path",
        nargs="?",
        default="-",
        help="Draft objective file path, or '-' / omitted for stdin.",
    )
    parser.add_argument(
        "--fenced",
        action="store_true",
        help="Wrap output in a fenced text block for a final response.",
    )
    parser.add_argument(
        "--objective-only",
        action="store_true",
        help="Print only the normalized objective, without the /goal prefix.",
    )
    parser.add_argument(
        "--max-chars",
        type=int,
        default=DEFAULT_MAX_PROMPT_CHARS,
        help="Maximum formatted output length. Use 0 to disable the length check.",
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        output = format_goal_command(
            read_text(args.path),
            objective_only=args.objective_only,
            max_chars=args.max_chars,
        )
    except (OSError, ValueError) as exc:
        print(f"format_goal_prompt.py: error: {exc}", file=sys.stderr)
        return 1

    if not has_stop_clause(output):
        print(
            "format_goal_prompt.py: warning: no stop bound or blocked clause found; "
            'consider adding "or stop after 20 turns" or '
            '"if blocked, stop and report the blocker"',
            file=sys.stderr,
        )

    if args.fenced:
        print("```text")
        print(output)
        print("```")
    else:
        print(output)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
```

## scripts/test_format_goal_prompt.py

```python
"""Unit tests for format_goal_prompt.py.

The formatter must produce a single-line /goal command from any messy draft,
and must FAIL (non-zero / ValueError) on empty input and on output past the
length cap — a formatter that emits nothing or an oversized command must
never exit 0.
"""

from __future__ import annotations

import pytest
from format_goal_prompt import (
    DEFAULT_MAX_PROMPT_CHARS,
    format_goal_command,
    has_stop_clause,
    main,
    normalize_objective,
)


def test_collapses_multiline_draft_to_single_line() -> None:
    draft = "Refactor the auth module:\n  - replace MD5\n\t- add tests\n"
    assert format_goal_command(draft) == (
        "/goal Refactor the auth module: - replace MD5 - add tests"
    )


def test_strips_existing_goal_prefix_without_doubling() -> None:
    assert format_goal_command("/goal do the thing") == "/goal do the thing"


def test_strips_surrounding_code_fence_and_quotes() -> None:
    draft = '```text\n"do the thing"\n```'
    assert format_goal_command(draft) == "/goal do the thing"


def test_normalizes_crlf_and_unicode_whitespace() -> None:
    assert normalize_objective("a\r\nb\rc d") == "a b c d"


def test_objective_only_omits_prefix() -> None:
    assert format_goal_command("do it", objective_only=True) == "do it"


def test_empty_input_raises() -> None:
    with pytest.raises(ValueError, match="empty"):
        format_goal_command("/goal \n  \n")


def test_output_over_limit_raises() -> None:
    with pytest.raises(ValueError, match="limit"):
        format_goal_command("x" * DEFAULT_MAX_PROMPT_CHARS)


def test_max_chars_zero_disables_limit() -> None:
    long = "x" * (DEFAULT_MAX_PROMPT_CHARS + 1)
    assert format_goal_command(long, max_chars=0) == f"/goal {long}"


def test_main_fenced_output(tmp_path, capsys) -> None:
    draft = tmp_path / "draft.txt"
    draft.write_text("do\nthe   thing\n", encoding="utf-8")
    assert main([str(draft), "--fenced"]) == 0
    assert capsys.readouterr().out == "```text\n/goal do the thing\n```\n"


def test_main_returns_nonzero_on_empty_draft(tmp_path, capsys) -> None:
    draft = tmp_path / "draft.txt"
    draft.write_text("   \n", encoding="utf-8")
    assert main([str(draft)]) == 1
    assert "empty" in capsys.readouterr().err


def test_stop_clause_detects_turn_bound() -> None:
    assert has_stop_clause("fix the tests, or stop after 20 turns")
    assert has_stop_clause("iterate; pause after 3 attempts")


def test_stop_clause_detects_blocked_clause() -> None:
    assert has_stop_clause("if blocked, stop and report the blocker")


def test_stop_clause_rejects_end_state_only() -> None:
    assert not has_stop_clause("all tests pass and the queue is empty")
    assert not has_stop_clause("keep each file under a 300-line budget")


def test_main_warns_without_stop_clause(tmp_path, capsys) -> None:
    draft = tmp_path / "draft.txt"
    draft.write_text("make npm test exit 0\n", encoding="utf-8")
    assert main([str(draft)]) == 0
    assert "no stop bound or blocked clause" in capsys.readouterr().err


def test_main_does_not_warn_with_stop_clause(tmp_path, capsys) -> None:
    draft = tmp_path / "draft.txt"
    draft.write_text("make npm test exit 0, or stop after 20 turns\n", encoding="utf-8")
    assert main([str(draft)]) == 0
    assert capsys.readouterr().err == ""
```

