Loop System Architect
Turn a repeated task into an observable control system that can execute, prove its result,
recover after interruption, and improve without rewriting its own purpose.
Choose the mode
- Audit: inspect an existing workflow and report missing or open-loop parts. Do not edit unless asked.
- Design: produce the contract, state schema, role graph, evals, and runtime design.
- Operationalize: implement the controller, adapters, persistence, evidence, and one-command run path.
- Evolve: analyze completed runs, validate a proposed loop/knowledge/skill improvement, and promote or reject it.
When the user asks to “build” or “get it working,” include Operationalize. A Markdown plan alone
is not an operational loop.
Start from live reality
- Read repository instructions and the artifacts the user placed in scope.
- Inspect the actual tools, entry points, state files, tests, schedulers, agent CLIs, and dirty worktree.
- Separate current authoritative input from reference material. Do not use model memory to fill gaps.
- Classify the loop:
- Terminal: one goal with a demonstrable finish line.
- Recurring: every run terminates, while the monitor/service continues until retired.
- State what exists, what is missing, and what is only claimed before changing anything.
For a full audit, read audit-rubric.md.
Require a closed control loop
Identify and connect all of these:
- objective and owner;
- completion condition or per-run success condition;
- authoritative source boundary and provenance;
- trigger and cheap preflight;
- sensor and collected signal;
- comparator, window, and threshold/rule;
- controller and finite decision space;
- actuator and the path that returns the new result to the sensor;
- persistent state, cursor, event log, and evidence store;
- orchestrator, executor, and independent verifier responsibilities;
- open capability/skill discovery and candidate-skill creation;
- authority boundaries and protected fields;
- acceptance evals and required evidence;
- retries, timeouts, backoff, failure classification, and rollback;
- idempotency, deduplication, concurrency lock, and side-effect choke point;
- token, cost, turn, and wall-time budgets;
- observability, alerts, and a no-op success state;
- direct replacement of superseded active truth;
- experience distillation and controlled promotion;
- stop, pause, kill, and retirement conditions.
Missing sensor-to-actuator feedback means open loop. Missing persistent state means a repeated
prompt. Missing verifier evidence means self-asserted completion. Missing a controller/trigger
means a procedure humans must operate.
Minimal profile
Not every loop needs all twenty elements. For a single-operator, cron-grade loop — one user, one
machine, low blast radius, no shared side effects — a contract is sufficient with eight:
- objective and owner;
- success condition (completion or per-run);
- trigger and cheap preflight;
- actuator and its side-effect path;
- persistent state and cursor;
- idempotency/dedupe on the side-effect path;
- observability: where to see the last result and next action;
- retirement condition.
Declare the omissions explicitly instead of leaving them blank: set learning.enabled: false,
and set capabilities.discovery: "none" with a reason field. The linter accepts both. See
loop.contract.minimal-example.json for a passing
minimal contract. Upgrade to the full contract when the loop gains shared side effects, a second
operator, external tenants, or any form of self-modification.
Produce a loop package
Adapt names to the repository, but keep one canonical machine-readable contract and one state
record. Loop packages, state, and evidence live in the user's project, never inside this skill
package. The default package is:
loop/
├── LOOP-CONTRACT.md human-readable operating contract
├── loop.contract.json machine-readable canonical contract
├── RUN-STATE.json current run, cursor, attempts, next machine action
├── events/ append-only run events or an equivalent event store
├── evidence/ verifier-readable receipts
├── evals/ deterministic and semantic acceptance checks
├── knowledge/ typed promoted knowledge, not raw logs
├── candidates/ unpromoted lessons and skill changes
└── scripts/run-loop one-command controller or project-native equivalent
Use loop-contract.md for the field contract. Copy
loop.contract.template.json, fill every placeholder,
then run:
python3 "<installed-skill-dir>/scripts/loop_lint.py" /path/to/loop.contract.json
Resolve <installed-skill-dir> to this skill's actual installation directory;
do not resolve scripts/ against an unrelated project. A lint PASS checks contract
structure, not actual scheduling, locks, freshness, or recovery. A preflight may
skip only when all inputs relevant to its sensor are still fresh; unchanged local
docs cannot prove external links are still reachable. If nothing can be
written to disk, output the contract and controller as copyable text and say what remains to be
placed on disk before the loop is operational.
Build the controller, not only the instructions
The controller must make one invocation advance the loop without asking the user to copy and
paste between agents:
- acquire a concurrency lock and derive an idempotency key;
- load and lint the contract and state;
- verify frozen-source hashes or current source authority;
- run the cheap trigger/preflight and record a no-op success when no work exists;
- resolve required capabilities;
- create a minimal context packet for the orchestrator/executor;
- execute in an isolated workspace when changes are possible;
- capture outputs, costs, tool calls, diffs, and evidence;
- run an independent verifier that cannot certify its own writes;
- on failure, classify and route a bounded repair, retry, rollback, or stop;
- on pass, atomically promote the result and update current state;
- append an immutable event/receipt;
- invoke distillation only when its trigger is satisfied;
- release the lock and expose the next machine-executable action.
Minimal verifier independence, by engine:
- Claude Code (or any runtime with subagents): run the verifier as a fresh-context subagent
that receives only the contract, the acceptance checks, and the evidence paths — not the
executor's conversation.
- No subagent mechanism: run the verifier as a separate process or separate invocation that
re-reads the evidence from disk and returns a verdict against the acceptance checks.
- Neither available: the same context checking its own work is self-review — performance,
not verification. Say so in the audit instead of labeling it a verifier.
Prefer deterministic code for triggers, state transitions, schema checks, permissions, retries,
hashes, and promotion. Use LLMs for judgment, planning, diagnosis, and content that cannot be
decided mechanically.
Discover or create skills without a static allowlist
Use open discovery with controlled execution:
- Derive a capability contract from the task: input, output, side effects, evidence, risk.
- Search installed skills and project capabilities by metadata and contract fit.
- Inspect provenance and dependencies; do not import embedded project identity as truth.
- Sandbox a candidate skill and run capability-specific evals.
- If none fits, create a candidate skill in isolation with its own examples and evals.
- Promote a version only after it passes security, privacy, functional, and regression checks.
- Register locally by default. External publication follows the owning environment's separate policy.
Open discovery does not grant open authority. Mandates, data scope, side-effect policy, and runtime
permissions still constrain every skill.
Distill experience into usable knowledge
Never feed an ever-growing log to every agent. Keep raw evidence, episodic summaries, candidate
lessons, canonical knowledge, procedural skills, and evals separate.
Run the promotion path:
trace + outcome
→ normalized episode
→ candidate lesson
→ deduplicate and conflict-check
→ replay against prior runs and counterexamples
→ shadow or canary
→ promote a version
→ monitor the next runs
→ keep or rollback
Trigger distillation on repeated failure, repeated manual work, drift, cost regression, meaningful
outcome evidence, or a configured sample size—not merely because time passed. Read
distillation.md before designing or changing the learning layer.
If a dedicated distillation skill (such as experience-pack) is installed, let it own the
distillation workflow itself; this skill designs the loop that invokes it.
The evolution process may improve SOPs, triggers, context packing, scripts, skills, retrieval, and
operational thresholds within delegated authority. It may not silently rewrite the objective,
source boundary, tenant/privacy boundary, authority model, or the eval that defines success.
Replace active truth cleanly
For any accepted update:
- compute the impact graph across contract, state schema, code, tests, docs, views, and skills;
- declare
REPLACES, REMOVES, and KEEPS;
- update all dependents;
- remove superseded wording and values from active retrieval;
- run contradiction/stale-value scans;
- run affected happy and failure-path evals;
- run a zero-context probe that must recover exactly one current answer;
- promote atomically; retain prior versions only in version control/event history, not active context.
Calibrate autonomy
- Auto-run reversible, bounded actions when deterministic and independent verification passes.
- Use canary, shadow, dual verification, and rollback for higher-risk automated actions.
- Stop for the user only when authority is missing, a required decision changes the objective,
or the action is materially irreversible and not already authorized.
- Never make routine human approval a hidden actuator in a loop advertised as autonomous.
Verify completion
Do not call the loop operational until all are true:
- one command or configured event can advance it without prompt ferrying;
- interruption recovery resumes from persisted state without redoing accepted work;
- duplicate triggers cannot duplicate side effects;
- verifier failure causes bounded repair or a clean stop;
- both success and fail-closed paths have evidence;
- a no-work run terminates successfully and cheaply;
- the current status, last result, cost, open failure, and next action are observable;
- one evolution candidate has been replayed and either promoted or correctly rejected
(waived under the minimal profile with
learning.enabled: false);
- a zero-context agent can explain the current contract and next action from active files alone.
Report separately: what is implemented, what was exercised, what remains dormant for lack of a
live sensor, and what still requires the user's authority.
1---2name: loop-system-architect3description: Design, audit, repair, and operationalize reliable agent loops with explicit goals, triggers, persistent state, orchestration, independent verification, failure recovery, open skill discovery or creation, controlled self-improvement, and retirement conditions. Use to build a loop, an autonomous or recurring agent workflow, a multi-agent operating system, a self-improving process, a zero-context recovery flow, a permanent update/replacement loop, or to turn a prose plan or repeated prompt into a genuinely executable loop. Trigger on natural phrasings such as "I keep running this prompt by hand — automate it", "make this agent run on its own and check its own work", "why does my automation silently fail", and Chinese phrasings such as "把这个流程变成自动循环", "帮我设计一个自动跑的 agent 工作流". For a plain scheduled reminder or interval re-run without state or verification, use the host scheduler (cron/schedule tools) instead. For static product architecture and responsibility contracts, use map-product-system.4---56# Loop System Architect78Turn a repeated task into an observable control system that can execute, prove its result,9recover after interruption, and improve without rewriting its own purpose.1011## Choose the mode1213- **Audit**: inspect an existing workflow and report missing or open-loop parts. Do not edit unless asked.14- **Design**: produce the contract, state schema, role graph, evals, and runtime design.15- **Operationalize**: implement the controller, adapters, persistence, evidence, and one-command run path.16- **Evolve**: analyze completed runs, validate a proposed loop/knowledge/skill improvement, and promote or reject it.1718When the user asks to “build” or “get it working,” include Operationalize. A Markdown plan alone19is not an operational loop.2021## Start from live reality22231. Read repository instructions and the artifacts the user placed in scope.242. Inspect the actual tools, entry points, state files, tests, schedulers, agent CLIs, and dirty worktree.253. Separate current authoritative input from reference material. Do not use model memory to fill gaps.264. Classify the loop:27 - **Terminal**: one goal with a demonstrable finish line.28 - **Recurring**: every run terminates, while the monitor/service continues until retired.295. State what exists, what is missing, and what is only claimed before changing anything.3031For a full audit, read [audit-rubric.md](references/audit-rubric.md).3233## Require a closed control loop3435Identify and connect all of these:36371. objective and owner;382. completion condition or per-run success condition;393. authoritative source boundary and provenance;404. trigger and cheap preflight;415. sensor and collected signal;426. comparator, window, and threshold/rule;437. controller and finite decision space;448. actuator and the path that returns the new result to the sensor;459. persistent state, cursor, event log, and evidence store;4610. orchestrator, executor, and independent verifier responsibilities;4711. open capability/skill discovery and candidate-skill creation;4812. authority boundaries and protected fields;4913. acceptance evals and required evidence;5014. retries, timeouts, backoff, failure classification, and rollback;5115. idempotency, deduplication, concurrency lock, and side-effect choke point;5216. token, cost, turn, and wall-time budgets;5317. observability, alerts, and a no-op success state;5418. direct replacement of superseded active truth;5519. experience distillation and controlled promotion;5620. stop, pause, kill, and retirement conditions.5758Missing sensor-to-actuator feedback means open loop. Missing persistent state means a repeated59prompt. Missing verifier evidence means self-asserted completion. Missing a controller/trigger60means a procedure humans must operate.6162## Minimal profile6364Not every loop needs all twenty elements. For a single-operator, cron-grade loop — one user, one65machine, low blast radius, no shared side effects — a contract is sufficient with eight:66671. objective and owner;682. success condition (completion or per-run);693. trigger and cheap preflight;704. actuator and its side-effect path;715. persistent state and cursor;726. idempotency/dedupe on the side-effect path;737. observability: where to see the last result and next action;748. retirement condition.7576Declare the omissions explicitly instead of leaving them blank: set `learning.enabled: false`,77and set `capabilities.discovery: "none"` with a `reason` field. The linter accepts both. See78[loop.contract.minimal-example.json](assets/loop.contract.minimal-example.json) for a passing79minimal contract. Upgrade to the full contract when the loop gains shared side effects, a second80operator, external tenants, or any form of self-modification.8182## Produce a loop package8384Adapt names to the repository, but keep one canonical machine-readable contract and one state85record. Loop packages, state, and evidence live in the user's project, never inside this skill86package. The default package is:8788```text89loop/90├── LOOP-CONTRACT.md human-readable operating contract91├── loop.contract.json machine-readable canonical contract92├── RUN-STATE.json current run, cursor, attempts, next machine action93├── events/ append-only run events or an equivalent event store94├── evidence/ verifier-readable receipts95├── evals/ deterministic and semantic acceptance checks96├── knowledge/ typed promoted knowledge, not raw logs97├── candidates/ unpromoted lessons and skill changes98└── scripts/run-loop one-command controller or project-native equivalent99```100101Use [loop-contract.md](references/loop-contract.md) for the field contract. Copy102[loop.contract.template.json](assets/loop.contract.template.json), fill every placeholder,103then run:104105```bash106python3 "<installed-skill-dir>/scripts/loop_lint.py" /path/to/loop.contract.json107```108109Resolve `<installed-skill-dir>` to this skill's actual installation directory;110do not resolve `scripts/` against an unrelated project. A lint PASS checks contract111structure, not actual scheduling, locks, freshness, or recovery. A preflight may112skip only when all inputs relevant to its sensor are still fresh; unchanged local113docs cannot prove external links are still reachable. If nothing can be114written to disk, output the contract and controller as copyable text and say what remains to be115placed on disk before the loop is operational.116117## Build the controller, not only the instructions118119The controller must make one invocation advance the loop without asking the user to copy and120paste between agents:1211221. acquire a concurrency lock and derive an idempotency key;1232. load and lint the contract and state;1243. verify frozen-source hashes or current source authority;1254. run the cheap trigger/preflight and record a no-op success when no work exists;1265. resolve required capabilities;1276. create a minimal context packet for the orchestrator/executor;1287. execute in an isolated workspace when changes are possible;1298. capture outputs, costs, tool calls, diffs, and evidence;1309. run an independent verifier that cannot certify its own writes;13110. on failure, classify and route a bounded repair, retry, rollback, or stop;13211. on pass, atomically promote the result and update current state;13312. append an immutable event/receipt;13413. invoke distillation only when its trigger is satisfied;13514. release the lock and expose the next machine-executable action.136137Minimal verifier independence, by engine:138139- **Claude Code (or any runtime with subagents)**: run the verifier as a fresh-context subagent140 that receives only the contract, the acceptance checks, and the evidence paths — not the141 executor's conversation.142- **No subagent mechanism**: run the verifier as a separate process or separate invocation that143 re-reads the evidence from disk and returns a verdict against the acceptance checks.144- **Neither available**: the same context checking its own work is self-review — performance,145 not verification. Say so in the audit instead of labeling it a verifier.146147Prefer deterministic code for triggers, state transitions, schema checks, permissions, retries,148hashes, and promotion. Use LLMs for judgment, planning, diagnosis, and content that cannot be149decided mechanically.150151## Discover or create skills without a static allowlist152153Use open discovery with controlled execution:1541551. Derive a capability contract from the task: input, output, side effects, evidence, risk.1562. Search installed skills and project capabilities by metadata and contract fit.1573. Inspect provenance and dependencies; do not import embedded project identity as truth.1584. Sandbox a candidate skill and run capability-specific evals.1595. If none fits, create a candidate skill in isolation with its own examples and evals.1606. Promote a version only after it passes security, privacy, functional, and regression checks.1617. Register locally by default. External publication follows the owning environment's separate policy.162163Open discovery does not grant open authority. Mandates, data scope, side-effect policy, and runtime164permissions still constrain every skill.165166## Distill experience into usable knowledge167168Never feed an ever-growing log to every agent. Keep raw evidence, episodic summaries, candidate169lessons, canonical knowledge, procedural skills, and evals separate.170171Run the promotion path:172173```text174trace + outcome175→ normalized episode176→ candidate lesson177→ deduplicate and conflict-check178→ replay against prior runs and counterexamples179→ shadow or canary180→ promote a version181→ monitor the next runs182→ keep or rollback183```184185Trigger distillation on repeated failure, repeated manual work, drift, cost regression, meaningful186outcome evidence, or a configured sample size—not merely because time passed. Read187[distillation.md](references/distillation.md) before designing or changing the learning layer.188If a dedicated distillation skill (such as experience-pack) is installed, let it own the189distillation workflow itself; this skill designs the loop that invokes it.190191The evolution process may improve SOPs, triggers, context packing, scripts, skills, retrieval, and192operational thresholds within delegated authority. It may not silently rewrite the objective,193source boundary, tenant/privacy boundary, authority model, or the eval that defines success.194195## Replace active truth cleanly196197For any accepted update:1981991. compute the impact graph across contract, state schema, code, tests, docs, views, and skills;2002. declare `REPLACES`, `REMOVES`, and `KEEPS`;2013. update all dependents;2024. remove superseded wording and values from active retrieval;2035. run contradiction/stale-value scans;2046. run affected happy and failure-path evals;2057. run a zero-context probe that must recover exactly one current answer;2068. promote atomically; retain prior versions only in version control/event history, not active context.207208## Calibrate autonomy209210- Auto-run reversible, bounded actions when deterministic and independent verification passes.211- Use canary, shadow, dual verification, and rollback for higher-risk automated actions.212- Stop for the user only when authority is missing, a required decision changes the objective,213 or the action is materially irreversible and not already authorized.214- Never make routine human approval a hidden actuator in a loop advertised as autonomous.215216## Verify completion217218Do not call the loop operational until all are true:219220- one command or configured event can advance it without prompt ferrying;221- interruption recovery resumes from persisted state without redoing accepted work;222- duplicate triggers cannot duplicate side effects;223- verifier failure causes bounded repair or a clean stop;224- both success and fail-closed paths have evidence;225- a no-work run terminates successfully and cheaply;226- the current status, last result, cost, open failure, and next action are observable;227- one evolution candidate has been replayed and either promoted or correctly rejected228 (waived under the minimal profile with `learning.enabled: false`);229- a zero-context agent can explain the current contract and next action from active files alone.230231Report separately: what is implemented, what was exercised, what remains dormant for lack of a232live sensor, and what still requires the user's authority.