cy0307 commited on
Commit
1e54930
·
verified ·
1 Parent(s): 409cbb4

Sync GitHub commit 62cbb0b

Browse files

Mirror the docs-drift runnable implementation, regression checks, memory lifecycle reference, and maintenance documentation from GitHub main.

.github/workflows/quality.yml CHANGED
@@ -37,6 +37,11 @@ jobs:
37
  - name: Install brand asset dependency
38
  run: python -m pip install "Pillow>=10.4,<13"
39
 
 
 
 
 
 
40
  - name: Check Markdown formatting
41
  uses: DavidAnson/markdownlint-cli2-action@v17
42
  with:
 
37
  - name: Install brand asset dependency
38
  run: python -m pip install "Pillow>=10.4,<13"
39
 
40
+ - name: Check runnable loop examples
41
+ run: |
42
+ python scripts/check_runnable_examples.py
43
+ python scripts/check_url_checker.py
44
+
45
  - name: Check Markdown formatting
46
  uses: DavidAnson/markdownlint-cli2-action@v17
47
  with:
.gitignore CHANGED
@@ -1,4 +1,5 @@
1
  __pycache__/
2
  *.py[cod]
 
3
  output/
4
  .playwright-cli/
 
1
  __pycache__/
2
  *.py[cod]
3
+ .loop-state/
4
  output/
5
  .playwright-cli/
README.zh-CN.md CHANGED
@@ -28,7 +28,7 @@
28
 
29
  Prompt engineering 改进你对模型说什么。Context engineering 改进模型能看到什么。Harness engineering 改进单次 agent 运行周围的工具、权限、沙箱和检查。**Loop Engineering 位于三者之上**:人不再逐轮手动提示 agent,而是设计一个循环系统,让它负责提示、监督、验证、更新状态并再次触发 agents。
30
 
31
- 一个 loop 会发现工作、分派给一个或多个 agents、检查结果、记录状态决定下一步,并节奏或满足可验证目标持续运行
32
 
33
  Loop Engineering 专指具备明确触发、外部验证和持久状态的可重复 AI-agent 与 coding-agent 系统,不包括软件事件循环、控制论、增长循环、通用 workflow automation 或非 AI feedback loop。
34
 
@@ -56,7 +56,7 @@ Prompt、context 和 harness engineering 让单次 agent 运行更好。Loop Eng
56
  | Context | 哪些知识应该长期存在? | `AGENTS.md`、`CLAUDE.md`、`SKILL.md`、docs |
57
  | Delegation | 哪个 agent 负责什么? | explorer、implementer、reviewer、judge |
58
  | Verification | 什么机制判断通过或失败? | tests、typecheck、lint、evals、trace graders |
59
- | State | 下一轮需要保留什么? | progress file、checkpoint、trace、issue comment |
60
  | Budget | 何时停止消耗? | max turns、max retries、token budget、time box |
61
  | Escalation | 何时交给人? | PR、issue、Slack alert、triage inbox |
62
  | Exit | loop 如何知道完成? | acceptance criteria、passing checks、no work found |
 
28
 
29
  Prompt engineering 改进你对模型说什么。Context engineering 改进模型能看到什么。Harness engineering 改进单次 agent 运行周围的工具、权限、沙箱和检查。**Loop Engineering 位于三者之上**:人不再逐轮手动提示 agent,而是设计一个循环系统,让它负责提示、监督、验证、更新状态并再次触发 agents。
30
 
31
+ 一个 loop 会发现工作、分派给一个或多个 agents、检查结果、留下可审查的运行凭证(receipts)、更新状态决定下一步;它既定节奏重复运行,在达到可验证目标后停止。
32
 
33
  Loop Engineering 专指具备明确触发、外部验证和持久状态的可重复 AI-agent 与 coding-agent 系统,不包括软件事件循环、控制论、增长循环、通用 workflow automation 或非 AI feedback loop。
34
 
 
56
  | Context | 哪些知识应该长期存在? | `AGENTS.md`、`CLAUDE.md`、`SKILL.md`、docs |
57
  | Delegation | 哪个 agent 负责什么? | explorer、implementer、reviewer、judge |
58
  | Verification | 什么机制判断通过或失败? | tests、typecheck、lint、evals、trace graders |
59
+ | State | 下一轮需要保留什么? | progress file、checkpoint、trace、运行凭证(receipt) |
60
  | Budget | 何时停止消耗? | max turns、max retries、token budget、time box |
61
  | Escalation | 何时交给人? | PR、issue、Slack alert、triage inbox |
62
  | Exit | loop 如何知道完成? | acceptance criteria、passing checks、no work found |
examples/runnable/README.md CHANGED
@@ -1,6 +1,6 @@
1
  # Runnable Loop Starters
2
 
3
- Eight implementation starters connect a loop contract to a runtime. Three are dependency-light executables; five are copy/paste runtime templates with concrete prompts, schedules, permissions, state, and stop conditions.
4
 
5
  Each starter keeps the control loop visible: permissions, verification, state, and budgets remain explicit instead of disappearing inside a framework.
6
 
@@ -116,6 +116,49 @@ A timed-out agent or verifier consumes one attempt and leaves a receipt before t
116
  - **Evidence stops waste.** Repeated failures and threshold breaches stop or escalate instead of consuming an open-ended budget.
117
  - **Permissions remain visible.** The starters expect a branch, worktree, sandbox, or read-only boundary rather than pretending isolation is automatic.
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  ## Smoke Checks
120
 
121
  Run these without an agent account:
@@ -123,6 +166,7 @@ Run these without an agent account:
123
  ```bash
124
  bash -n test-repair-loop.sh threshold-monitor-loop.sh
125
  python3 -m py_compile queue-worker-loop.py
 
126
  printf '%s\n' '{"id":"demo","objective":"Validate the queue"}' > /tmp/loop-queue.jsonl
127
  python3 queue-worker-loop.py --queue /tmp/loop-queue.jsonl --dry-run
128
  PROBE_CMD="printf '42\\n'" THRESHOLD=100 MAX_SAMPLES=1 ./threshold-monitor-loop.sh
 
1
  # Runnable Loop Starters
2
 
3
+ Eight general-purpose starters connect a loop contract to a runtime. Three are dependency-light executables; five are copy/paste runtime templates with concrete prompts, schedules, permissions, state, and stop conditions. A nested worked implementation shows how to specialize these primitives without pretending every use case is a new runtime.
4
 
5
  Each starter keeps the control loop visible: permissions, verification, state, and budgets remain explicit instead of disappearing inside a framework.
6
 
 
116
  - **Evidence stops waste.** Repeated failures and threshold breaches stop or escalate instead of consuming an open-ended budget.
117
  - **Permissions remain visible.** The starters expect a branch, worktree, sandbox, or read-only boundary rather than pretending isolation is automatic.
118
 
119
+ ## Worked Implementation: Scheduled Docs Drift
120
+
121
+ [`docs-drift/docs-drift-loop.py`](docs-drift/docs-drift-loop.py) specializes the [shell / cron starter](shell-cron-loop.md) for the [docs-drift pattern](../../patterns/docs-drift-collector.md) and [validated contract](../docs-drift-loop.json). The detector, acting agent, and verifier remain separate:
122
+
123
+ - the detector exits `0` when docs are current, `1` with evidence when drift is confirmed, and any other code on detector failure;
124
+ - report-only mode stores an evidence receipt and exits `2` for human triage;
125
+ - patch mode gives the evidence to an agent, enforces allowed and generated paths plus a file-count budget, then lets an independent command decide success;
126
+ - every outcome is appended to `.loop-state/docs-drift.jsonl`, which is ignored by Git but survives model calls;
127
+ - the script never commits, pushes, merges, changes a verifier, or reverts an unsafe edit behind the operator's back.
128
+
129
+ Run the detector without invoking an agent or writing state:
130
+
131
+ ```bash
132
+ python3 examples/runnable/docs-drift/docs-drift-loop.py \
133
+ --discover-command "python3 scripts/check_project_consistency.py" \
134
+ --dry-run
135
+ ```
136
+
137
+ Produce a scheduled evidence-backed report:
138
+
139
+ ```bash
140
+ python3 examples/runnable/docs-drift/docs-drift-loop.py \
141
+ --discover-command "python3 scripts/check_project_consistency.py" \
142
+ --report-only
143
+ ```
144
+
145
+ Patch confirmed drift inside a clean branch or worktree:
146
+
147
+ ```bash
148
+ python3 examples/runnable/docs-drift/docs-drift-loop.py \
149
+ --discover-command "python3 scripts/check_project_consistency.py" \
150
+ --agent-command "codex exec" \
151
+ --verify-command "python3 scripts/check_project_consistency.py" \
152
+ --allowed-path README.md \
153
+ --allowed-path docs \
154
+ --allowed-path meta \
155
+ --max-attempts 2 \
156
+ --max-changed-files 8 \
157
+ --command-timeout 900
158
+ ```
159
+
160
+ Copy [`docs-drift/github-actions.yml`](docs-drift/github-actions.yml) into `.github/workflows/` for a read-only Monday schedule that uploads the JSONL receipt. For cron, run the report-only command from the repository root and send exit code `2` to the docs owner. Add `--generated-path <path>` for files that must be regenerated or reviewed rather than edited directly.
161
+
162
  ## Smoke Checks
163
 
164
  Run these without an agent account:
 
166
  ```bash
167
  bash -n test-repair-loop.sh threshold-monitor-loop.sh
168
  python3 -m py_compile queue-worker-loop.py
169
+ python3 ../../scripts/check_runnable_examples.py
170
  printf '%s\n' '{"id":"demo","objective":"Validate the queue"}' > /tmp/loop-queue.jsonl
171
  python3 queue-worker-loop.py --queue /tmp/loop-queue.jsonl --dry-run
172
  PROBE_CMD="printf '42\\n'" THRESHOLD=100 MAX_SAMPLES=1 ./threshold-monitor-loop.sh
examples/runnable/docs-drift/docs-drift-loop.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run a bounded documentation-drift loop with external verification.
3
+
4
+ The discovery command owns the drift decision: exit 0 means no confirmed drift,
5
+ exit 1 means confirmed drift and its output is evidence, and any other exit code
6
+ is a detector error. The script can write a report only or delegate a patch to
7
+ an agent CLI, enforce a path and file-count boundary, run an independent
8
+ verifier, and persist every outcome as JSONL outside the model context.
9
+
10
+ Run this only in a clean branch or worktree. The script never commits, pushes,
11
+ merges, edits generated files itself, or weakens a verifier.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import datetime as dt
18
+ import fnmatch
19
+ import hashlib
20
+ import json
21
+ import shlex
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+
28
+ EXIT_OK = 0
29
+ EXIT_ESCALATED = 2
30
+ EXIT_ERROR = 3
31
+
32
+
33
+ def utc_now() -> str:
34
+ return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
35
+
36
+
37
+ def command_argv(command: str) -> list[str]:
38
+ argv = shlex.split(command)
39
+ if not argv:
40
+ raise ValueError("command cannot be empty")
41
+ return argv
42
+
43
+
44
+ def run_command(
45
+ command: str,
46
+ *,
47
+ workdir: Path,
48
+ timeout: int,
49
+ final_argument: str | None = None,
50
+ ) -> subprocess.CompletedProcess[str]:
51
+ argv = command_argv(command)
52
+ if final_argument is not None:
53
+ argv.append(final_argument)
54
+ return subprocess.run(
55
+ argv,
56
+ cwd=workdir,
57
+ text=True,
58
+ capture_output=True,
59
+ check=False,
60
+ timeout=timeout,
61
+ )
62
+
63
+
64
+ def combined_output(result: subprocess.CompletedProcess[str], *, max_lines: int) -> str:
65
+ output = "\n".join(part.strip() for part in (result.stdout, result.stderr) if part.strip())
66
+ return "\n".join(output.splitlines()[-max_lines:])
67
+
68
+
69
+ def append_receipt(path: Path, receipt: dict[str, Any]) -> None:
70
+ path.parent.mkdir(parents=True, exist_ok=True)
71
+ with path.open("a", encoding="utf-8") as handle:
72
+ handle.write(json.dumps(receipt, ensure_ascii=True, sort_keys=True) + "\n")
73
+
74
+
75
+ def evidence_digest(evidence: str) -> str:
76
+ return hashlib.sha256(evidence.encode("utf-8")).hexdigest()[:16]
77
+
78
+
79
+ def git_paths(workdir: Path) -> set[str]:
80
+ commands = (
81
+ ["git", "diff", "--name-only", "--relative"],
82
+ ["git", "diff", "--cached", "--name-only", "--relative"],
83
+ ["git", "ls-files", "--others", "--exclude-standard"],
84
+ )
85
+ paths: set[str] = set()
86
+ for argv in commands:
87
+ result = subprocess.run(argv, cwd=workdir, text=True, capture_output=True, check=False)
88
+ if result.returncode != 0:
89
+ raise RuntimeError(result.stderr.strip() or "workdir is not a Git repository")
90
+ paths.update(line.strip() for line in result.stdout.splitlines() if line.strip())
91
+ return paths
92
+
93
+
94
+ def path_matches(path: str, boundary: str) -> bool:
95
+ normalized_path = Path(path).as_posix().removeprefix("./")
96
+ normalized_boundary = Path(boundary).as_posix().removeprefix("./").rstrip("/")
97
+ if any(character in normalized_boundary for character in "*?["):
98
+ return fnmatch.fnmatch(normalized_path, normalized_boundary)
99
+ return normalized_path == normalized_boundary or normalized_path.startswith(normalized_boundary + "/")
100
+
101
+
102
+ def receipt_base(run_id: str, status: str, evidence: str) -> dict[str, Any]:
103
+ return {
104
+ "run_id": run_id,
105
+ "status": status,
106
+ "timestamp": utc_now(),
107
+ "evidence_digest": evidence_digest(evidence),
108
+ }
109
+
110
+
111
+ def main() -> int:
112
+ parser = argparse.ArgumentParser(description=__doc__)
113
+ parser.add_argument("--discover-command", required=True, help="exit 0 for no drift, 1 for confirmed drift")
114
+ parser.add_argument("--agent-command", help="agent CLI; the bounded patch prompt is appended as one argument")
115
+ parser.add_argument("--verify-command", help="deterministic command that must pass after an agent edit")
116
+ parser.add_argument("--workdir", type=Path, default=Path.cwd(), help="clean Git branch or worktree")
117
+ parser.add_argument(
118
+ "--state",
119
+ type=Path,
120
+ default=Path(".loop-state/docs-drift.jsonl"),
121
+ help="durable JSONL receipt log",
122
+ )
123
+ parser.add_argument("--allowed-path", action="append", default=[], help="allowed file or directory; repeat as needed")
124
+ parser.add_argument(
125
+ "--generated-path",
126
+ action="append",
127
+ default=[],
128
+ help="generated path requiring owner review; repeat as needed",
129
+ )
130
+ parser.add_argument("--max-attempts", type=int, default=2, help="maximum agent attempts")
131
+ parser.add_argument("--max-changed-files", type=int, default=8, help="hard file-count boundary")
132
+ parser.add_argument("--command-timeout", type=int, default=900, help="seconds allowed per command")
133
+ parser.add_argument("--evidence-lines", type=int, default=120, help="maximum detector/verifier lines in a prompt")
134
+ parser.add_argument("--report-only", action="store_true", help="persist drift evidence and escalate without an agent")
135
+ parser.add_argument("--dry-run", action="store_true", help="run discovery and print the decision without writing state")
136
+ args = parser.parse_args()
137
+
138
+ if min(args.max_attempts, args.max_changed_files, args.command_timeout, args.evidence_lines) < 1:
139
+ parser.error("budgets and evidence-lines must be positive")
140
+
141
+ workdir = args.workdir.resolve()
142
+ state = args.state if args.state.is_absolute() else workdir / args.state
143
+ run_id = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
144
+
145
+ try:
146
+ discovery = run_command(args.discover_command, workdir=workdir, timeout=args.command_timeout)
147
+ except (OSError, ValueError, subprocess.TimeoutExpired) as error:
148
+ evidence = f"discovery could not complete: {error}"
149
+ if not args.dry_run:
150
+ append_receipt(state, {**receipt_base(run_id, "escalated", evidence), "reason": evidence})
151
+ print(f"[docs-drift] {evidence}", file=sys.stderr)
152
+ return EXIT_ERROR
153
+
154
+ evidence = combined_output(discovery, max_lines=args.evidence_lines)
155
+ if discovery.returncode == 0:
156
+ decision = {"run_id": run_id, "status": "no_drift", "detector_exit": 0}
157
+ if args.dry_run:
158
+ print(json.dumps(decision, indent=2))
159
+ else:
160
+ append_receipt(state, {**receipt_base(run_id, "no_drift", evidence), "detector_exit": 0})
161
+ print("[docs-drift] no confirmed drift")
162
+ return EXIT_OK
163
+
164
+ if discovery.returncode != 1 or not evidence:
165
+ reason = (
166
+ f"detector exited {discovery.returncode}; expected 0 (clean) or 1 (drift)"
167
+ if discovery.returncode != 1
168
+ else "detector reported drift without evidence"
169
+ )
170
+ if not args.dry_run:
171
+ append_receipt(
172
+ state,
173
+ {
174
+ **receipt_base(run_id, "escalated", evidence or reason),
175
+ "detector_exit": discovery.returncode,
176
+ "reason": reason,
177
+ },
178
+ )
179
+ print(f"[docs-drift] {reason}", file=sys.stderr)
180
+ return EXIT_ERROR
181
+
182
+ if args.dry_run:
183
+ print(
184
+ json.dumps(
185
+ {
186
+ "run_id": run_id,
187
+ "status": "drift_detected",
188
+ "detector_exit": discovery.returncode,
189
+ "evidence": evidence,
190
+ },
191
+ indent=2,
192
+ )
193
+ )
194
+ return EXIT_OK
195
+
196
+ if args.report_only:
197
+ append_receipt(
198
+ state,
199
+ {
200
+ **receipt_base(run_id, "reported", evidence),
201
+ "detector_exit": discovery.returncode,
202
+ "evidence": evidence,
203
+ "reason": "confirmed drift requires a patch or owner decision",
204
+ },
205
+ )
206
+ print(evidence)
207
+ print("[docs-drift] report persisted; escalating", file=sys.stderr)
208
+ return EXIT_ESCALATED
209
+
210
+ if not args.agent_command or not args.verify_command or not args.allowed_path:
211
+ parser.error("patch mode requires --agent-command, --verify-command, and at least one --allowed-path")
212
+
213
+ try:
214
+ dirty_before = git_paths(workdir)
215
+ except RuntimeError as error:
216
+ append_receipt(state, {**receipt_base(run_id, "escalated", evidence), "reason": str(error)})
217
+ print(f"[docs-drift] {error}", file=sys.stderr)
218
+ return EXIT_ERROR
219
+
220
+ if dirty_before:
221
+ reason = "workdir must be clean before patch mode: " + ", ".join(sorted(dirty_before))
222
+ append_receipt(state, {**receipt_base(run_id, "escalated", evidence), "reason": reason})
223
+ print(f"[docs-drift] {reason}", file=sys.stderr)
224
+ return EXIT_ESCALATED
225
+
226
+ try:
227
+ state_relative = state.resolve().relative_to(workdir)
228
+ except ValueError:
229
+ state_relative = None
230
+ if state_relative is not None:
231
+ ignored = subprocess.run(
232
+ ["git", "check-ignore", "--quiet", state_relative.as_posix()],
233
+ cwd=workdir,
234
+ check=False,
235
+ )
236
+ if ignored.returncode != 0:
237
+ reason = "state path must be outside the worktree or ignored by Git: " + state_relative.as_posix()
238
+ print(f"[docs-drift] {reason}", file=sys.stderr)
239
+ return EXIT_ERROR
240
+
241
+ previous_verify_digest = ""
242
+ for attempt in range(1, args.max_attempts + 1):
243
+ prompt = "\n".join(
244
+ [
245
+ "You are the implementer inside a bounded documentation-drift loop.",
246
+ "",
247
+ "Confirmed detector evidence:",
248
+ "---",
249
+ evidence,
250
+ "---",
251
+ "",
252
+ f"Attempt: {attempt} of {args.max_attempts}",
253
+ "Allowed paths: " + ", ".join(args.allowed_path),
254
+ "Generated or owner-controlled paths: " + (", ".join(args.generated_path) or "none declared"),
255
+ "",
256
+ "Rules:",
257
+ "- Confirm the mismatch against code, tests, schema, or runtime output before editing.",
258
+ "- Make the smallest source-document change that resolves the confirmed mismatch.",
259
+ "- Do not edit generated or owner-controlled paths; report the source that must be regenerated.",
260
+ "- Do not change product behavior, public APIs, tests, policies, or verification commands.",
261
+ "- Do not commit, push, merge, expose credentials, or expand permissions.",
262
+ "- Do not decide completion; the loop runs an independent verifier.",
263
+ ]
264
+ )
265
+
266
+ try:
267
+ agent = run_command(
268
+ args.agent_command,
269
+ workdir=workdir,
270
+ timeout=args.command_timeout,
271
+ final_argument=prompt,
272
+ )
273
+ except (OSError, ValueError, subprocess.TimeoutExpired) as error:
274
+ append_receipt(
275
+ state,
276
+ {
277
+ **receipt_base(run_id, "retry", evidence),
278
+ "attempt": attempt,
279
+ "reason": f"agent could not complete: {error}",
280
+ },
281
+ )
282
+ continue
283
+
284
+ try:
285
+ changed = sorted(git_paths(workdir))
286
+ except RuntimeError as error:
287
+ append_receipt(state, {**receipt_base(run_id, "escalated", evidence), "reason": str(error)})
288
+ return EXIT_ERROR
289
+
290
+ outside = [path for path in changed if not any(path_matches(path, item) for item in args.allowed_path)]
291
+ generated = [path for path in changed if any(path_matches(path, item) for item in args.generated_path)]
292
+ if len(changed) > args.max_changed_files or outside or generated:
293
+ reasons: list[str] = []
294
+ if len(changed) > args.max_changed_files:
295
+ reasons.append(f"{len(changed)} files exceed the {args.max_changed_files}-file budget")
296
+ if outside:
297
+ reasons.append("out-of-scope paths: " + ", ".join(outside))
298
+ if generated:
299
+ reasons.append("generated or owner-controlled paths: " + ", ".join(generated))
300
+ reason = "; ".join(reasons)
301
+ append_receipt(
302
+ state,
303
+ {
304
+ **receipt_base(run_id, "escalated", evidence),
305
+ "attempt": attempt,
306
+ "changed_paths": changed,
307
+ "reason": reason,
308
+ },
309
+ )
310
+ print(f"[docs-drift] {reason}; inspect the worktree", file=sys.stderr)
311
+ return EXIT_ESCALATED
312
+
313
+ if agent.returncode != 0:
314
+ agent_evidence = combined_output(agent, max_lines=args.evidence_lines)
315
+ append_receipt(
316
+ state,
317
+ {
318
+ **receipt_base(run_id, "retry", agent_evidence or evidence),
319
+ "attempt": attempt,
320
+ "agent_exit": agent.returncode,
321
+ "changed_paths": changed,
322
+ "reason": "agent command failed",
323
+ },
324
+ )
325
+ evidence = agent_evidence or evidence
326
+ continue
327
+
328
+ if not changed:
329
+ append_receipt(
330
+ state,
331
+ {
332
+ **receipt_base(run_id, "retry", evidence),
333
+ "attempt": attempt,
334
+ "agent_exit": agent.returncode,
335
+ "changed_paths": [],
336
+ "reason": "agent produced no file change",
337
+ },
338
+ )
339
+ continue
340
+
341
+ try:
342
+ verification = run_command(args.verify_command, workdir=workdir, timeout=args.command_timeout)
343
+ except (OSError, ValueError, subprocess.TimeoutExpired) as error:
344
+ verify_evidence = f"verifier could not complete: {error}"
345
+ verify_exit = None
346
+ else:
347
+ verify_evidence = combined_output(verification, max_lines=args.evidence_lines)
348
+ verify_exit = verification.returncode
349
+
350
+ receipt = {
351
+ **receipt_base(run_id, "verified" if verify_exit == 0 else "retry", verify_evidence or evidence),
352
+ "attempt": attempt,
353
+ "agent_exit": agent.returncode,
354
+ "verify_exit": verify_exit,
355
+ "changed_paths": changed,
356
+ "verification": verify_evidence,
357
+ }
358
+ append_receipt(state, receipt)
359
+
360
+ if verify_exit == 0:
361
+ print("[docs-drift] patch passed the external verifier")
362
+ return EXIT_OK
363
+
364
+ current_digest = evidence_digest(verify_evidence)
365
+ if current_digest == previous_verify_digest:
366
+ evidence = verify_evidence or evidence
367
+ break
368
+ previous_verify_digest = current_digest
369
+ evidence = verify_evidence or evidence
370
+
371
+ reason = "retry budget exhausted or verifier evidence repeated"
372
+ append_receipt(state, {**receipt_base(run_id, "escalated", evidence), "reason": reason})
373
+ print(f"[docs-drift] {reason}; inspect the worktree", file=sys.stderr)
374
+ return EXIT_ESCALATED
375
+
376
+
377
+ if __name__ == "__main__":
378
+ raise SystemExit(main())
examples/runnable/docs-drift/github-actions.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Scheduled docs drift report
2
+
3
+ on:
4
+ schedule:
5
+ - cron: "17 3 * * 1"
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ detect:
13
+ runs-on: ubuntu-latest
14
+ timeout-minutes: 30
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.x"
20
+ - name: Detect confirmed metadata drift
21
+ run: >-
22
+ python3 examples/runnable/docs-drift/docs-drift-loop.py
23
+ --discover-command "python3 scripts/check_project_consistency.py"
24
+ --report-only
25
+ - name: Upload the evidence receipt
26
+ if: always()
27
+ uses: actions/upload-artifact@v4
28
+ with:
29
+ name: docs-drift-receipt
30
+ path: .loop-state/docs-drift.jsonl
31
+ if-no-files-found: ignore
gallery/README.md CHANGED
@@ -19,6 +19,7 @@ These entries are reference examples, not claimed production deployments. They s
19
  - [PR babysitter reference loop](pr-babysitter-reference.md)
20
  - [CI repair reference loop](ci-repair-reference.md)
21
  - [Docs drift reference loop](docs-drift-reference.md)
 
22
 
23
  ## Quality Bar
24
 
 
19
  - [PR babysitter reference loop](pr-babysitter-reference.md)
20
  - [CI repair reference loop](ci-repair-reference.md)
21
  - [Docs drift reference loop](docs-drift-reference.md)
22
+ - [Agent memory lifecycle reference loop](agent-memory-lifecycle-reference.md) - Community-proposed design with explicit provenance and no deployment claim.
23
 
24
  ## Quality Bar
25
 
gallery/agent-memory-lifecycle-reference.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Agent Memory Lifecycle Reference Loop
2
+
3
+ ## Summary
4
+
5
+ A reference design for carrying useful state across recurring agent runs without turning raw transcripts into permanent, ungoverned memory. The loop admits explicit records, recalls only task-relevant state, audits contradictions and retention rules, consolidates duplicates, and forgets or redacts records when policy requires it.
6
+
7
+ This is a design reference, not a claimed production deployment. It was adapted from [TerminallyLazy's public pattern proposal](https://github.com/ChaoYue0307/awesome-loop-engineering/issues/7); the linked Tree Ring Memory project is an illustrative implementation, not an adoption or reliability claim.
8
+
9
+ ## Runtime Or Tooling
10
+
11
+ - Runtime: any scheduled, event-driven, or manually bootstrapped agent runtime with a durable local or service-backed store.
12
+ - Agent system: operator, bounded worker, memory curator, independent verifier, and human owner.
13
+ - Illustrative tooling: [Tree Ring Memory](https://github.com/TerminallyLazy/Tree-Ring-Memory), SQLite/FTS, a project ledger, or another inspectable memory store with deletion support.
14
+ - Repository or environment: recurring coding, documentation, release, outreach, or operations work where cold starts cause repeated discovery.
15
+
16
+ ## Loop Contract
17
+
18
+ - Objective: preserve useful, attributable lessons between runs while preventing stale, sensitive, contradictory, or irrelevant state from silently steering future work.
19
+ - Trigger: before and after a bounded agent run, plus a scheduled audit and consolidation pass.
20
+ - Discover / intake: the current task, project instructions, approved prior records, public receipts, and explicit operator corrections; never silent terminal or transcript capture.
21
+ - Workspace: a scoped project store separate from model context, with retention and access rules reviewed before unattended use.
22
+ - Context: task identity, source links, timestamps, confidence, access class, expiry, contradiction links, and the last audit decision.
23
+ - Delegation: the operator selects relevant records, the worker acts, the curator proposes writes or consolidation, the verifier checks receipts and policy, and the human owns sensitive or ambiguous decisions.
24
+ - Verification: schema and provenance checks, duplicate and contradiction search, retention-policy checks, deterministic project tests, and public or local receipts for consequential actions.
25
+ - State: append-only memory records plus indexes, tombstones, consolidation links, audit decisions, and the next review time.
26
+ - Budget: cap recalled records, new writes, consolidation operations, and retries per run; stop when the same contradiction or policy failure repeats.
27
+ - Escalation: credentials, private data, legal or license questions, conflicting operator decisions, deletion uncertainty, or any memory that would authorize a higher-impact action.
28
+ - Exit: the task is externally verified and the memory delta is accepted, or the run stops with an evidence-backed report and named human owner.
29
+
30
+ ## Loop Instruction Or Automation
31
+
32
+ ```text
33
+ Before acting, recall only approved records relevant to the current task and cite their IDs.
34
+ After acting, propose explicit memory writes with source, timestamp, confidence, retention,
35
+ and contradiction links. Run project verification and memory-policy checks independently.
36
+ Persist accepted receipts and tombstones outside the model. Never store secrets or raw
37
+ transcripts by default. Escalate ambiguous, sensitive, stale, or conflicting state.
38
+ ```
39
+
40
+ ## Receipts
41
+
42
+ - Pattern proposal: [issue #7](https://github.com/ChaoYue0307/awesome-loop-engineering/issues/7).
43
+ - Inspectable implementation: [Tree Ring Memory source](https://github.com/TerminallyLazy/Tree-Ring-Memory).
44
+ - Implementation snapshot: [Tree Ring Memory v0.11.0](https://github.com/TerminallyLazy/Tree-Ring-Memory/releases/tag/v0.11.0).
45
+ - A real deployment should additionally retain task IDs, recalled record IDs, accepted and rejected writes, verifier commands, tombstones, and the human escalation decision.
46
+
47
+ No production run receipt was supplied with the proposal, so this entry does not claim measured reliability, adoption, or deployed outcomes.
48
+
49
+ ## Worked Scenario
50
+
51
+ A weekly PR-maintenance loop repeatedly rediscovers that generated API files must be updated through a source schema and that one flaky integration test needs a fixed seed. Before each run, it recalls only those two source-linked records. After a verified patch, it records the PR URL and passing command but rejects a proposed transcript summary that contains an access token. When the schema workflow changes, the curator links the old instruction to a tombstone and writes a replacement instead of leaving both active.
52
+
53
+ ## Lessons Learned
54
+
55
+ - Useful memory is a governed state transition, not a transcript dump.
56
+ - Recall needs a relevance and access boundary; more context can preserve stale or conflicting instructions.
57
+ - Writes need provenance, retention, and deletion semantics before an unattended loop can trust them.
58
+ - Public receipts and deterministic checks should validate consequential memories; the memory tool must not certify its own downstream result.
59
+
60
+ ## Safety Notes
61
+
62
+ - Sensitive actions: storing credentials, private conversations, customer data, identity-bound decisions, or records that expand permissions.
63
+ - Human approvals: required for sensitive retention, ambiguous contradictions, destructive forgetting, and any memory used to authorize a high-impact action.
64
+ - Data or privacy constraints: default to explicit writes, least retention, scoped recall, inspectable exports, and tested redaction or deletion.
meta/MAINTENANCE.md CHANGED
@@ -75,6 +75,8 @@ python3 scripts/check_project_consistency.py
75
  python3 scripts/build_hf_card.py --check
76
  python3 scripts/check_publication_metadata.py
77
  python3 scripts/check_loop_contract_examples.py
 
 
78
  python3 scripts/check_pages_metadata.py
79
  python3 scripts/check_internal_links.py
80
  python3 scripts/check_commit_identity.py
 
75
  python3 scripts/build_hf_card.py --check
76
  python3 scripts/check_publication_metadata.py
77
  python3 scripts/check_loop_contract_examples.py
78
+ python3 scripts/check_runnable_examples.py
79
+ python3 scripts/check_url_checker.py
80
  python3 scripts/check_pages_metadata.py
81
  python3 scripts/check_internal_links.py
82
  python3 scripts/check_commit_identity.py
posts/launch.zh-CN.md CHANGED
@@ -35,6 +35,8 @@ v0.8.0 将这些层级连接起来:
35
  1. 当工作需要跨事件、会话或时间重复时,使用 operational pattern 与 Loop Contract。
36
  1. 用外部证据、持久状态、硬预算与 human escalation 管理真实世界中的重复执行。
37
 
 
 
38
  目标仍然不是无限自治,而是有边界、可审阅、由证据驱动的重复运行。
39
 
40
  ## 浏览与复用
 
35
  1. 当工作需要跨事件、会话或时间重复时,使用 operational pattern 与 Loop Contract。
36
  1. 用外部证据、持久状态、硬预算与 human escalation 管理真实世界中的重复执行。
37
 
38
+ 每次运行都应留下可审查的凭证(receipts),让下一轮和 human owner 能判断发生了什么、哪些 gate 已通过,以及为什么继续、升级或停止。
39
+
40
  目标仍然不是无限自治,而是有边界、可审阅、由证据驱动的重复运行。
41
 
42
  ## 浏览与复用
scripts/check_commit_identity.py CHANGED
@@ -11,25 +11,29 @@ OWNER_NAME = "ChaoYue0307"
11
  OWNER_EMAIL = "hechaoyue0307@gmail.com"
12
 
13
 
14
- def git(*args: str) -> str:
15
- return subprocess.check_output(["git", *args], text=True).strip()
 
 
 
 
 
 
 
 
 
 
16
 
17
 
18
  def main() -> int:
19
  try:
20
- commits = git("rev-list", "HEAD").splitlines()
21
- except subprocess.CalledProcessError as error:
22
  print(f"Could not inspect git history: {error}", file=sys.stderr)
23
  return 1
24
 
25
  failures: list[str] = []
26
- for commit in commits:
27
- author_name = git("show", "-s", "--format=%an", commit)
28
- author_email = git("show", "-s", "--format=%ae", commit)
29
- committer_name = git("show", "-s", "--format=%cn", commit)
30
- committer_email = git("show", "-s", "--format=%ce", commit)
31
- message = git("show", "-s", "--format=%B", commit)
32
-
33
  if (author_name, author_email) != (OWNER_NAME, OWNER_EMAIL):
34
  failures.append(f"{commit}: unexpected author {author_name} <{author_email}>")
35
  if (committer_name, committer_email) != (OWNER_NAME, OWNER_EMAIL):
 
11
  OWNER_EMAIL = "hechaoyue0307@gmail.com"
12
 
13
 
14
+ def commit_records() -> list[tuple[str, str, str, str, str, str]]:
15
+ record_format = "%H%x00%an%x00%ae%x00%cn%x00%ce%x00%B%x00"
16
+ raw = subprocess.check_output(["git", "log", "-z", f"--format={record_format}"])
17
+ records: list[tuple[str, str, str, str, str, str]] = []
18
+ for raw_record in raw.split(b"\x00\x00"):
19
+ if not raw_record:
20
+ continue
21
+ fields = raw_record.decode("utf-8").split("\x00", 5)
22
+ if len(fields) != 6:
23
+ raise ValueError("could not parse a commit identity record")
24
+ records.append((fields[0], fields[1], fields[2], fields[3], fields[4], fields[5]))
25
+ return records
26
 
27
 
28
  def main() -> int:
29
  try:
30
+ commits = commit_records()
31
+ except (subprocess.CalledProcessError, UnicodeDecodeError, ValueError) as error:
32
  print(f"Could not inspect git history: {error}", file=sys.stderr)
33
  return 1
34
 
35
  failures: list[str] = []
36
+ for commit, author_name, author_email, committer_name, committer_email, message in commits:
 
 
 
 
 
 
37
  if (author_name, author_email) != (OWNER_NAME, OWNER_EMAIL):
38
  failures.append(f"{commit}: unexpected author {author_name} <{author_email}>")
39
  if (committer_name, committer_email) != (OWNER_NAME, OWNER_EMAIL):
scripts/check_runnable_examples.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Smoke-test the dependency-light runnable loop examples."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import shlex
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ from pathlib import Path
13
+
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ RUNNABLE = ROOT / "examples" / "runnable"
17
+ DOCS_DRIFT = RUNNABLE / "docs-drift" / "docs-drift-loop.py"
18
+
19
+
20
+ def run(
21
+ argv: list[str],
22
+ *,
23
+ cwd: Path = ROOT,
24
+ env: dict[str, str] | None = None,
25
+ expected: tuple[int, ...] = (0,),
26
+ ) -> subprocess.CompletedProcess[str]:
27
+ result = subprocess.run(argv, cwd=cwd, env=env, text=True, capture_output=True, check=False, timeout=30)
28
+ if result.returncode not in expected:
29
+ raise RuntimeError(
30
+ f"command failed ({result.returncode}): {shlex.join(argv)}\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}"
31
+ )
32
+ return result
33
+
34
+
35
+ def write(path: Path, text: str) -> None:
36
+ path.write_text(text, encoding="utf-8")
37
+
38
+
39
+ def main() -> int:
40
+ run(["bash", "-n", str(RUNNABLE / "test-repair-loop.sh"), str(RUNNABLE / "threshold-monitor-loop.sh")])
41
+ run([sys.executable, "-m", "py_compile", str(RUNNABLE / "queue-worker-loop.py"), str(DOCS_DRIFT)])
42
+
43
+ with tempfile.TemporaryDirectory(prefix="ale-runnable-") as temporary:
44
+ temp = Path(temporary)
45
+ queue = temp / "queue.jsonl"
46
+ write(queue, '{"id":"docs-1","objective":"Check the docs"}\n')
47
+ run([sys.executable, str(RUNNABLE / "queue-worker-loop.py"), "--queue", str(queue), "--dry-run"])
48
+
49
+ monitor_state = temp / "monitor.md"
50
+ monitor_env = {
51
+ **os.environ,
52
+ "PROBE_CMD": "printf '42\\n'",
53
+ "THRESHOLD": "100",
54
+ "MAX_SAMPLES": "1",
55
+ "PROGRESS_FILE": str(monitor_state),
56
+ }
57
+ run(["bash", str(RUNNABLE / "threshold-monitor-loop.sh")], env=monitor_env)
58
+
59
+ detector_clean = temp / "detector-clean.py"
60
+ write(detector_clean, "raise SystemExit(0)\n")
61
+ state = temp / "docs-drift.jsonl"
62
+ run(
63
+ [
64
+ sys.executable,
65
+ str(DOCS_DRIFT),
66
+ "--discover-command",
67
+ shlex.join([sys.executable, str(detector_clean)]),
68
+ "--state",
69
+ str(state),
70
+ ]
71
+ )
72
+ receipt = json.loads(state.read_text(encoding="utf-8").splitlines()[-1])
73
+ if receipt["status"] != "no_drift":
74
+ raise RuntimeError("docs-drift no-work exit did not persist a no_drift receipt")
75
+
76
+ detector_drift = temp / "detector-drift.py"
77
+ write(detector_drift, "print('README output differs from current CLI help')\nraise SystemExit(1)\n")
78
+ dry_run = run(
79
+ [
80
+ sys.executable,
81
+ str(DOCS_DRIFT),
82
+ "--discover-command",
83
+ shlex.join([sys.executable, str(detector_drift)]),
84
+ "--dry-run",
85
+ ]
86
+ )
87
+ if json.loads(dry_run.stdout)["status"] != "drift_detected":
88
+ raise RuntimeError("docs-drift dry run did not expose confirmed evidence")
89
+
90
+ report_state = temp / "report-state.jsonl"
91
+ run(
92
+ [
93
+ sys.executable,
94
+ str(DOCS_DRIFT),
95
+ "--discover-command",
96
+ shlex.join([sys.executable, str(detector_drift)]),
97
+ "--report-only",
98
+ "--state",
99
+ str(report_state),
100
+ ],
101
+ expected=(2,),
102
+ )
103
+ report_receipt = json.loads(report_state.read_text(encoding="utf-8").splitlines()[-1])
104
+ if report_receipt["status"] != "reported":
105
+ raise RuntimeError("docs-drift report-only mode did not persist an escalation receipt")
106
+
107
+ repository = temp / "repo"
108
+ repository.mkdir()
109
+ write(repository / "README.md", "old command\n")
110
+ run(["git", "init", "-q"], cwd=repository)
111
+ run(["git", "add", "README.md"], cwd=repository)
112
+ run(
113
+ [
114
+ "git",
115
+ "-c",
116
+ "user.name=Loop Smoke Test",
117
+ "-c",
118
+ "user.email=loop-smoke@example.com",
119
+ "commit",
120
+ "-qm",
121
+ "fixture",
122
+ ],
123
+ cwd=repository,
124
+ )
125
+
126
+ agent = temp / "agent.py"
127
+ verifier = temp / "verifier.py"
128
+ write(agent, "from pathlib import Path\nPath('README.md').write_text('current command\\n', encoding='utf-8')\n")
129
+ write(
130
+ verifier,
131
+ "from pathlib import Path\nraise SystemExit(0 if Path('README.md').read_text(encoding='utf-8') == 'current command\\n' else 1)\n",
132
+ )
133
+ patch_state = temp / "patch-state.jsonl"
134
+ run(
135
+ [
136
+ sys.executable,
137
+ str(DOCS_DRIFT),
138
+ "--discover-command",
139
+ shlex.join([sys.executable, str(detector_drift)]),
140
+ "--agent-command",
141
+ shlex.join([sys.executable, str(agent)]),
142
+ "--verify-command",
143
+ shlex.join([sys.executable, str(verifier)]),
144
+ "--allowed-path",
145
+ "README.md",
146
+ "--workdir",
147
+ str(repository),
148
+ "--state",
149
+ str(patch_state),
150
+ ]
151
+ )
152
+ patch_receipt = json.loads(patch_state.read_text(encoding="utf-8").splitlines()[-1])
153
+ if patch_receipt["status"] != "verified" or patch_receipt["changed_paths"] != ["README.md"]:
154
+ raise RuntimeError("docs-drift patch mode did not persist a verified scoped change")
155
+
156
+ run(["git", "restore", "README.md"], cwd=repository)
157
+ unsafe_agent = temp / "unsafe-agent.py"
158
+ write(unsafe_agent, "from pathlib import Path\nPath('outside.txt').write_text('unsafe\\n')\nraise SystemExit(1)\n")
159
+ unsafe_state = temp / "unsafe-state.jsonl"
160
+ run(
161
+ [
162
+ sys.executable,
163
+ str(DOCS_DRIFT),
164
+ "--discover-command",
165
+ shlex.join([sys.executable, str(detector_drift)]),
166
+ "--agent-command",
167
+ shlex.join([sys.executable, str(unsafe_agent)]),
168
+ "--verify-command",
169
+ shlex.join([sys.executable, str(verifier)]),
170
+ "--allowed-path",
171
+ "README.md",
172
+ "--workdir",
173
+ str(repository),
174
+ "--state",
175
+ str(unsafe_state),
176
+ ],
177
+ expected=(2,),
178
+ )
179
+ unsafe_receipt = json.loads(unsafe_state.read_text(encoding="utf-8").splitlines()[-1])
180
+ if unsafe_receipt["status"] != "escalated" or "out-of-scope paths" not in unsafe_receipt["reason"]:
181
+ raise RuntimeError("docs-drift did not stop an out-of-scope edit from a failed agent command")
182
+
183
+ print("Runnable loop smoke checks passed.")
184
+ return 0
185
+
186
+
187
+ if __name__ == "__main__":
188
+ raise SystemExit(main())
scripts/check_url_checker.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Regression checks for transient and permanent URL-checker failures."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import io
7
+ import urllib.error
8
+ import urllib.request
9
+ from unittest import mock
10
+
11
+ from verify_urls import check_url
12
+
13
+
14
+ class FakeResponse:
15
+ def __init__(self, url: str, status: int) -> None:
16
+ self.url = url
17
+ self.status = status
18
+
19
+ def geturl(self) -> str:
20
+ return self.url
21
+
22
+ def __enter__(self) -> "FakeResponse":
23
+ return self
24
+
25
+ def __exit__(self, *args: object) -> None:
26
+ return None
27
+
28
+
29
+ class FixtureOpener:
30
+ def __init__(self) -> None:
31
+ self.transient_gets = 0
32
+
33
+ def open(self, request: urllib.request.Request, timeout: float) -> FakeResponse:
34
+ url = request.full_url
35
+ if request.get_method() == "HEAD":
36
+ raise urllib.error.HTTPError(url, 500, "fixture HEAD failure", {}, io.BytesIO())
37
+ if url.endswith("/transient"):
38
+ self.transient_gets += 1
39
+ if self.transient_gets == 1:
40
+ raise urllib.error.HTTPError(url, 500, "fixture transient failure", {}, io.BytesIO())
41
+ return FakeResponse(url, 200)
42
+ raise urllib.error.HTTPError(url, 404, "fixture missing", {}, io.BytesIO())
43
+
44
+
45
+ def main() -> int:
46
+ opener = FixtureOpener()
47
+ with mock.patch("verify_urls.urllib.request.build_opener", return_value=opener), mock.patch(
48
+ "verify_urls.time.sleep"
49
+ ):
50
+ ok, detail = check_url("https://fixture.invalid/transient", timeout=2, attempts=2)
51
+ if not ok or detail != "200 GET" or opener.transient_gets != 2:
52
+ raise RuntimeError(f"transient 500 was not retried successfully: {ok=}, {detail=}")
53
+
54
+ ok, detail = check_url("https://fixture.invalid/missing", timeout=2, attempts=3)
55
+ if ok or detail != "404 GET":
56
+ raise RuntimeError(f"permanent 404 was not reported: {ok=}, {detail=}")
57
+
58
+ print("URL checker regression checks passed.")
59
+ return 0
60
+
61
+
62
+ if __name__ == "__main__":
63
+ raise SystemExit(main())
scripts/verify_urls.py CHANGED
@@ -21,6 +21,7 @@ from urllib.parse import urlparse
21
 
22
  URL_RE = re.compile(r'https?://[^\s)\]}>"]+')
23
  CLAUDE_DOC_HOSTS = {"code.claude.com", "docs.anthropic.com"}
 
24
 
25
 
26
  class RedirectHandler(urllib.request.HTTPRedirectHandler):
@@ -81,7 +82,10 @@ def check_url(url: str, timeout: float, attempts: int) -> tuple[bool, str]:
81
  return True, f"{error.code} restricted"
82
  if method == "HEAD":
83
  continue
84
- return False, f"{error.code} {method}"
 
 
 
85
  except Exception as error: # noqa: BLE001 - report URL checker failures plainly.
86
  last_error = error.__class__.__name__
87
  if method == "HEAD":
 
21
 
22
  URL_RE = re.compile(r'https?://[^\s)\]}>"]+')
23
  CLAUDE_DOC_HOSTS = {"code.claude.com", "docs.anthropic.com"}
24
+ RETRYABLE_HTTP_CODES = {408, 425, 500, 502, 503, 504}
25
 
26
 
27
  class RedirectHandler(urllib.request.HTTPRedirectHandler):
 
82
  return True, f"{error.code} restricted"
83
  if method == "HEAD":
84
  continue
85
+ last_error = f"{error.code} {method}"
86
+ if error.code in RETRYABLE_HTTP_CODES:
87
+ break
88
+ return False, last_error
89
  except Exception as error: # noqa: BLE001 - report URL checker failures plainly.
90
  last_error = error.__class__.__name__
91
  if method == "HEAD":