AI Wiki中文/EN

HTN planning: choose a decomposition, then check every action

层次任务网络规划

Build a bounded, totally ordered task decomposer with method guards, primitive validation and auditable plans; distinguish exhaustion from budget interruption.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A checklist can be in the wrong order

A small instrument needs calibration, a fresh label and a final inspection. Calibrating it removes the old label. The suggested routine “label, calibrate, inspect” therefore fails at inspection, even though all three actions appear on the checklist. “Calibrate, label, inspect” works.

Hierarchical task network planning represents both the actions and the ways a larger task may be decomposed. Here prepare is a compound task. A method replaces it with an ordered list of subtasks; primitive tasks such as calibrate have state-changing operators. Choosing a method is a search decision, not a promise that its entire body will succeed.

SHOP’s 1999 paper develops ordered task decomposition: planning follows execution order, so the state preceding the next task is known. Its semantics distinguishes primitive tasks from methods and permits backtracking between decompositions. The program below uses a much smaller, finite vocabulary and an explicit decomposition bound. Nau and colleagues, §§2.1–2.3.

A method changes the pending work, not the world

The model is deterministic, fully known and sequential. Its atoms and task names are finite strings, with no variables or parameter substitution. A state lists exactly the declared atoms that are true; omitted atoms are false. Each primitive task has one operator with positive/negative preconditions and disjoint add/delete effects. Compound names are disjoint from primitive names. Different methods may share a compound head.

Write a search configuration as the current state s, an ordered pending list and a remaining method allowance f. The symbol ∥ denotes list concatenation. A primitive first task changes the state and disappears from the list:

⟨s,(a)∥R,f⟩→a⟨(s∖Ea−)∪Ea+,R,f⟩if Pa+⊆s and Pa−∩s=∅.\langle s,(a)\mathbin{\|}R,f\rangle\xrightarrow{a}\langle(s\setminus E_a^-)\cup E_a^+,R,f\rangle\quad\text{if }P_a^+\subseteq s\text{ and }P_a^-\cap s=\varnothing.

A method m for the first compound task c has a required-true guard G⁺, required-false guard G⁻ and an ordered body B. Applying it consumes one method allowance and replaces that occurrence of c:

⟨s,(c)∥R,f⟩→m⟨s,Bm∥R,f−1⟩if f>0, Gm+⊆s, Gm−∩s=∅.\langle s,(c)\mathbin{\|}R,f\rangle\xrightarrow{m}\langle s,B_m\mathbin{\|}R,f-1\rangle\quad\text{if }f>0,\ G_m^+\subseteq s,\ G_m^-\cap s=\varnothing.

The guard is checked when that compound task reaches the front. It need not remain true throughout the body. Later compound guards see changes made by earlier primitive actions. Primitive preconditions are still checked at their own execution points. Method applicability alone cannot certify a plan.

Success means the pending list is empty after licensed reductions and applicable primitive steps. There is no additional final-state goal in this interface. If prepare must imply certified, that intention needs a sound method library or an extra checked postcondition. A method with an empty body is legal and consumes one allowance; it does not automatically make any atom true.

The network here is totally ordered, including every method body. A body must finish before the old remainder continues. No interleaving of sibling subtasks, binding constraints or protected intervals is implemented. Erol, Hendler and Nau distinguish these features in their general task-network formalism; their complexity results depend on the restrictions used. In particular, an undecidability result involving a partially ordered initial network must not be applied to this fully ordered interface. 1994 paper, printed pp1125–1126.

Backtrack over complete alternatives

This complete Python 3.10+ program uses an explicit depth-first stack. The first declared applicable method is explored first. It returns the first successful decomposition, which need not use the fewest actions. An action can be executable in the current state yet unavailable as a solution if no allowed decomposition produces it.

max_methods bounds the total method applications on each candidate derivation, not the number of attempts across the search and not the nesting depth. Failed alternatives do not consume their siblings’ allowance. max_nodes separately bounds the number of nonempty configurations examined across the whole run; one such examination may test several method guards. Neither bound includes validation time.

found includes the primitive plan, final state and a certificate of method/action events. bounded-failure means all alternatives within the method bound were exhausted. It does not prove that a larger bound has no solution. unknown means the node budget stopped the search while an unexamined nonempty configuration remained. An empty task list succeeds before the node-budget check, including at budget zero. cutoffs counts examined compound configurations with zero allowance, even when that head has no applicable method; it is not a count of lost solutions.

All declarations are validated before searching, including unused methods. Inputs must be lists or tuples with nonempty string names. Atom and compound declarations, primitive task names and method IDs must be unique in their respective namespaces. Method heads must be declared compound tasks; every body occurrence must name a declared task. Repeated facts are collapsed, but repeated tasks are preserved. Contradictory guards or effects, unknown names, negative bounds, Booleans and noninteger bounds are rejected.

def seq(value):
    if type(value) not in (list, tuple):
        raise ValueError('expected list or tuple')
    return tuple(value)


def named(value):
    if type(value) is not str or not value:
        raise ValueError('expected nonempty name')
    return value


def bound(value):
    if type(value) is not int or value < 0:
        raise ValueError('expected nonnegative integer')
    return value


def solve(atoms, actions, compounds, methods, initial, tasks,
          max_methods=4, max_nodes=None):
    atoms = tuple(named(a) for a in seq(atoms))
    compounds = tuple(named(t) for t in seq(compounds))
    if len(set(atoms)) != len(atoms) or len(set(compounds)) != len(compounds):
        raise ValueError('duplicate declaration')
    universe = frozenset(atoms)
    compound_set = frozenset(compounds)

    def facts(values):
        values = frozenset(named(v) for v in seq(values))
        if not values <= universe:
            raise ValueError('undeclared atom')
        return values

    operators = {}
    for raw in seq(actions):
        row = seq(raw)
        if len(row) != 5:
            raise ValueError('action needs id, positive, negative, add, delete')
        aid = named(row[0])
        if aid in operators or aid in compound_set:
            raise ValueError('duplicate or ambiguous task name')
        positive, negative, add, delete = map(facts, row[1:])
        if positive & negative or add & delete:
            raise ValueError('contradictory action fields')
        operators[aid] = (positive, negative, add, delete)
    declared = compound_set | operators.keys()

    def task_list(values):
        values = tuple(named(t) for t in seq(values))
        if any(t not in declared for t in values):
            raise ValueError('undeclared task')
        return values

    choices = {t: [] for t in compounds}
    method_ids = set()
    for raw in seq(methods):
        row = seq(raw)
        if len(row) != 5:
            raise ValueError('method needs id, head, positive, negative, body')
        mid, head = named(row[0]), named(row[1])
        if mid in method_ids or head not in choices:
            raise ValueError('duplicate method or noncompound head')
        method_ids.add(mid)
        positive, negative = facts(row[2]), facts(row[3])
        if positive & negative:
            raise ValueError('contradictory method guard')
        choices[head].append((mid, positive, negative, task_list(row[4])))
    initial, tasks = facts(initial), task_list(tasks)
    max_methods = bound(max_methods)
    if max_nodes is not None:
        max_nodes = bound(max_nodes)
    # Each alternative owns immutable state, pending tasks and certificate.
    stack = [(initial, tasks, max_methods, (), ())]
    nodes = action_checks = method_checks = cutoffs = 0

    def answer(status, state=None, moves=None, proof=None):
        return dict(status=status, plan=moves, proof=proof,
                    final=None if state is None else tuple(a for a in atoms if a in state),
                    nodes=nodes, action_checks=action_checks,
                    method_checks=method_checks, cutoffs=cutoffs)

    while stack:
        state, pending, fuel, moves, proof = stack[-1]
        if not pending:
            return answer('found', state, moves, proof)
        if max_nodes is not None and nodes >= max_nodes:
            return answer('unknown')
        stack.pop()
        nodes += 1
        task, tail = pending[0], pending[1:]
        if task in operators:
            action_checks += 1
            positive, negative, add, delete = operators[task]
            if positive <= state and negative.isdisjoint(state):
                successor = (state - delete) | add
                stack.append((successor, tail, fuel, moves + (task,),
                              proof + (('action', task),)))
        elif fuel == 0:
            cutoffs += 1
        else:
            # Reverse the pushes so the first declared method is tried first.
            for mid, positive, negative, body in reversed(choices[task]):
                method_checks += 1
                if positive <= state and negative.isdisjoint(state):
                    stack.append((state, body + tail, fuel - 1, moves,
                                  proof + (('method', mid),)))
    return answer('bounded-failure')


ATOMS = ('powered', 'calibrated', 'labelled', 'certified')
ACTIONS = (
    ('calibrate', ('powered',), (), ('calibrated',), ('labelled',)),
    ('label', ('powered',), (), ('labelled',), ()),
    ('certify', ('calibrated', 'labelled'), (), ('certified',), ()),
)
METHODS = (
    ('label-first', 'prepare', ('powered',), (), ('label', 'calibrate', 'certify')),
    ('calibrate-first', 'prepare', ('powered',), (), ('calibrate', 'label', 'certify')),
)


if __name__ == '__main__':
    args = (ATOMS, ACTIONS, ('prepare',), METHODS, ('powered',), ('prepare',))
    answer = solve(*args, max_methods=1)
    print('plan:', answer['plan'])
    print('proof:', answer['proof'])
    print('final:', answer['final'])
    print('work:', tuple(answer[k] for k in ('nodes', 'action_checks', 'method_checks', 'cutoffs')))
    print('node cap 6:', solve(*args, max_methods=1, max_nodes=6)['status'])
    print('method cap 0:', solve(*args, max_methods=0)['status'])
    recursive = (('again', 'loop', (), (), ('loop',)), ('stop', 'loop', (), (), ()))
    r = solve((), (), ('loop',), recursive, (), ('loop',), max_methods=2)
    print('recursive:', r['status'], r['proof'], r['nodes'], r['cutoffs'])

The actual output is:

plan: ('calibrate', 'label', 'certify')
proof: (('method', 'calibrate-first'), ('action', 'calibrate'), ('action', 'label'), ('action', 'certify'))
final: ('powered', 'calibrated', 'labelled', 'certified')
work: (7, 6, 2, 0)
node cap 6: unknown
method cap 0: bounded-failure
recursive: found (('method', 'again'), ('method', 'stop')) 3 1

The first method fails after calibrate removes labelled. Its failed state and plan do not leak into the next alternative: each stack entry contains immutable branch data. The successful certificate records only its own derivation; the six action checks include both branches. With node cap 6, the successful branch’s final inspection has not yet been examined. Cap 7 permits it and returns success immediately afterward.

Why the bound guarantees termination

Let r be the initial task count, q the method bound, and b the largest body length, taking b = 0 if there are no methods. Each method introduces at most b tasks. Along any branch, at most r + qb primitive occurrences can therefore be executed, alongside at most q reductions. Both the pending list and the certificate are bounded by:

H=r+q(b+1).H=r+q(b+1).

Let M be the largest number of methods sharing any head, or zero, and B = max(1,M). The number N of examined nonempty configurations has the conservative bound:

N≤∑i=0HBi.N\le\sum_{i=0}^{H}B^i.

Every branch is finite and each node has finitely many alternatives, so the unbudgeted search terminates. Induction over a returned certificate establishes that every reduction was allowed and every primitive action applicable. Conversely, every successful derivation using at most q methods appears in this finite search tree. Exhausting it is complete for that bounded question. There is no state-only visited set: identical world states with different pending tasks have different obligations.

For raw input size D including one constant unit, n atoms and the values above, conservative costs for this implementation are:

T=O ⁣(D+(N+1)(M+1)(n+H+1)),S=O ⁣(D+(1+MH)(n+H+1)).T=O\!\left(D+(N+1)(M+1)(n+H+1)\right),\qquad S=O\!\left(D+(1+MH)(n+H+1)\right).

Time includes guard scans and copied lists/certificates. The stack keeps at most a linear number of sibling alternatives per branch level; its entries retain states and task/certificate tuples. These bounds use expected hashing and unit-cost names/counters. Large strings and integer bit lengths add costs. Increasing q can expand the search enormously even when the physical state space is small.

A hierarchy also restricts which plans count

The method library carries domain knowledge and can omit useful solutions. That omission is not repaired by finding an executable action sequence outside the hierarchy. Conversely, an empty or careless method can make a named task “complete” without accomplishing what its name suggests. Validate the primitive model, the decomposition rules and their intended outcomes separately.

Without the method bound, loop → loop can keep a naive depth-first planner on one branch forever, even if a later empty method would solve the task. SHOP’s paper explicitly distinguishes finite-search completeness from this infinite-branch failure. §2.3, PDF pages 2–3 Here a recursive method is allowed, but it must consume allowance. Raising the bound eventually includes any fixed finite derivation; this is not a promise that an arbitrary fixed node budget will reach it.

The implementation has no grounding, unification, partial ordering, costs, simultaneous actions, uncertain observations or execution monitoring. It is not a complete implementation of SHOP or general HTN semantics. A language model’s list of subtasks is also not an HTN certificate unless its task declarations, method choices, guards and primitive effects have actually been checked.

Check what the decomposition licenses

  1. Why does the first prepare method fail? Give the successful primitive plan and explain the work counts.

    Answer: Its first label is erased by calibration, so inspection lacks labelled. The second method yields calibrate, label, certify. The root tests two method guards; three primitive configurations from each branch give six action checks and seven examined nonempty configurations in total. The returned proof contains only the successful branch.

  2. Compare a method allowance of zero, a node budget of zero and an initially empty task list. Does any failure prove unrestricted impossibility?

    Answer: For prepare, zero method allowance gives bounded-failure after examining and cutting off the compound task. With positive allowance but zero node budget, it gives unknown. Empty initial tasks give found with plan () even when both bounds are zero. Bounded exhaustion concerns only the chosen allowance; budget interruption proves no impossibility at all.

  3. A method guarded by p has body off, child. off deletes p; the only child method requires p false and then restores it. Is this legal? What changes if the guard were meant to hold throughout?

    Answer: It is legal under entry-time guards: the parent sees p true, while the child sees p false after off. A maintenance requirement would reject that interval and needs additional constraints; the current guard is not such a requirement.

  4. With methods loop → loop then loop → (), why does allowance 2 return a proof containing again and stop? Does that make the result shortest or the unbounded DFS terminating?

    Answer: DFS first reduces recursively twice, reaches a zero-allowance compound and cuts that branch. The saved empty-method sibling at the second level then succeeds. Its selected proof is again, stop, with an empty primitive plan. A root-level stop would need fewer reductions, but input order controls the result. Removing the bound lets the first recursive branch continue forever. The test with wait, finish before finish separately shows that the first plan need not minimize primitive action count either.

Read the task semantics before comparing planners

The 1999 SHOP source is an author-hosted six-page technical-report version, labeled CS-TR-3981 / UMIACS-TR-99-04 and “to appear” in IJCAI-99. Its simplified operators and richer implementation features differ from this explicitly guarded, ground teaching language. No original Lisp code, transportation example or benchmark result is reused.

The 1994 analysis gives reductions and completions a formal role and separates propositional, totally ordered and other restrictions. Our allowance proof concerns a finite teaching search tree; it is not a new classification of unrestricted HTN planning. Both papers are useful for seeing exactly which problem a planner solves.

For follow-up reading, classical planning compares state-goal search, while partial-order planning addresses ordering freedom. The tests here independently generate complete decomposition forests at exact method counts, then evaluate their entry guards and primitive effects. That separates allowable task structure from executability and catches failures that checking only the final state would miss.

Make a prediction, then check

A prepare method labels before calibration, which removes the label; final inspection requires it. Does a satisfied method-entry guard establish completion?

Choose one answer

Learning objectives

  • Distinguish world-changing primitive actions from task-reducing methods, and check entry guards, ordering and derivation certificates.
  • Run a bounded totally ordered HTN search and separate per-derivation method allowance from global node budget.
  • Prove bounded soundness, completeness and termination, and explain recursion, absent methods, empty bodies and method-library restrictions.

Prerequisites & connections

Explore related knowledge →

References

  1. SHOP: Simple Hierarchical Ordered Planner — CS-TR-3981 / UMIACS-TR-99-04
    Dana Nau; Yue Cao; Amnon Lotem; Héctor Muñoz-Avila · 1999
  2. HTN Planning: Complexity and Expressivity
    Kutluhan Erol; James Hendler; Dana S. Nau · 1994

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent finite-state oracles, bilingual review and second-agent cross-checks; not independent human peer review.

  • Original calibration/label/inspection fixture; six anchors, five identical displays, identical complete Python, seven actual output lines and four answered exercises. Method guards are checked at entry and primitive guards at execution; total body order and success as task-list completion are explicit.
  • All nine tests passed. The independent reference first generates complete decomposition forests at exact method-node counts, without the pending-list stack rewrite, then checks guards/effects by Boolean event execution. Across 2,858 models, 605 complete forests, 214 executable derivations and 198 returned certificates agree. Includes 49 body pairs times nine guard pairs times two initial states times three allowances, plus two allowances on 100 seeded models and dedicated boundaries.
  • Actually checked main counts 7 nodes/6 action checks/2 method checks/0 cutoffs and its certificate; node caps 0–6 are unknown and 7 succeeds. Recursive again/stop at allowance 2 gives three nodes, one cutoff and the again/stop proof. Empty tasks succeed at both zero bounds; missing methods or pure self-recursion give bounded failure. Failed branches preserve sibling state/allowance, parent guards are not maintenance constraints, and method order can change primitive plan length.
  • All declarations are validated before search, including invalid methods hidden behind empty initial tasks. Repeated facts collapse while task occurrences remain; primitive/compound names are disjoint; contradictory effects/guards, unknown names and Boolean/float bounds are rejected. General bounded completeness is separately proved through a finite branching tree, with H=r+q(b+1). Costs include alternatives, state/task/certificate copying and empty-input constants. No full-HTN or shortest-plan claim.
  • Strict MDX/KaTeX and actual React HTML pass with five displays, six headings and four strong answers per locale. Five math annotations agree byte for byte, with complete costs and no emphasis residue. Reread under the pinned neutral technical Humanizer guidance rather than treating a scan as editorial review. Actual source reading and failed curl attempts are distinguished. Only /tmp, review written and AI author checks, awaiting independent AI cross-review; no repository edits, browser/whole-site build or human review.
  • Read both full MDX articles, complete Python, nine tests and final metadata. Method guards apply at entry, primitives at execution; methods preserve state, allow empty bodies and replace only the leading task occurrence. Completion means an empty pending list, not an unstated goal.
  • Independent FIFO reachability over (bit-encoded state, task word, used method count), rather than author decomposition-forest enumeration: 340 bounded instances and 555 reachable configurations agree on existence. Instances comprise 80 new-seed small models plus five targeted models, each at allowances 0–3.
  • Replayed 153 returned certificates using Boolean vectors and raw declarations; checked ordered task obligations, guards, effects, method count, plan and final state. Removing the last event was rejected in all 45 nonempty proofs. Ran 1,000 node-cap cases around zero and exact exhaustion/success boundaries, checking unknown versus found/bounded-failure and unchanged inputs.
  • Verified main result and counts, sibling-state/allowance isolation, total method applications rather than nesting depth, recursive cutoff, entry versus maintenance guards, and lack of shortest-plan claims. Checked finite branching termination with H=r+q(b+1), the conservative node bound and the stated copying/hash cost model including empty inputs. No defects found.
  • All nine author tests passed once. Independently rendered final English and Chinese MDX with strict KaTeX and React HTML: five display equations, six anchors and four answers each; five complete math annotations match. Final five file hashes match sha256.json. This is an AI technical check, not human peer review or a proof assistant verification.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation check: completed topics link to formal chapters with obsolete planned labels removed; temporal planning remains a catalogue topic in progress. Reversible replacements are recorded. Other prose, equations, programs, exercises and previous evidence are preserved, with final bilingual hashes rebound.

Source locations checked:

  • SHOP: Simple Hierarchical Ordered Planner — CS-TR-3981 / UMIACS-TR-99-04 · Actually opened the author-hosted six-page PDF via web. Read section 2.1, PDF page 2, lines 97–144, distinguishing ground states, primitive/compound tasks, operator syntax and method guards/bodies; section 2.2 lines 145–182 on current-state reduction, ordered execution and empty tasks; section 2.3, PDF pages 2–3, lines 183–213, including explicit incompleteness of plain DFS on an infinite leftmost branch and the iterative-deepening option. Read section 3 lines 232–257 and 318–334 to distinguish richer Lisp/axiom/conditional-method features from this interface. The header labels CS-TR-3981 / UMIACS-TR-99-04 and to appear in IJCAI-99; the author publications page also identifies 1999. Text extraction has spaced letters but the definitions were actually read. A local curl attempt failed DNS resolution; no local PDF download/hash or visual inspection is claimed.
  • HTN Planning: Complexity and Expressivity · Actually opened the original author-hosted six-page PDF through web. Read printed page 1125, lines 154–225: primitive/compound/goal tasks, task constraints, method heads/bodies, ground/propositional and totally ordered restrictions. Read printed page 1126, lines 235–318: completions/reductions and finite-step solution family; Theorem 1 retains an exception for the initial task network, Theorem 2 uses a decreasing finite level mapping, and Theorem 3 treats wholly totally ordered networks separately. Do not claim the paper’s richer formalism or complexity classification for the bounded program. Local curl failed DNS; no local PDF copy/hash, full-paper proof audit or visual scan claimed.
  • SHOP: Simple Hierarchical Ordered Planner — CS-TR-3981 / UMIACS-TR-99-04 · Actually opened original author-hosted six-page PDF through web. Read title/header, sections 2.1–2.2 on primitive/compound syntax, current-state method applicability, ordered reductions and empty task success; section 2.3 across PDF pages 2–3 distinguishes finite-search completeness from an infinite leftmost branch. Read the simplified operator syntax to confirm that the article explicitly introduces its own primitive preconditions. No local PDF, visual inspection or old benchmark reproduction claimed.
  • HTN Planning: Complexity and Expressivity · Actually read author-hosted PDF text, printed pages 1124–1126: primitive/compound tasks and constraints; positive and negative temporal truth constraints; methods, completions and reductions; Theorem 1 retains the partially ordered input-network exception, Theorem 2 uses a finite decreasing level map, and Theorem 3 treats wholly total-order cases separately. Checked the article does not transfer the richer formalism or unrestricted complexity classes to its bounded language.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.