diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2ed27de..69626bd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,11 +22,14 @@ jobs: - name: Lint — every bash script parses run: | for f in bin/* setup/*.sh examples/*.sh tests/*.sh; do + [ -f "$f" ] || continue case "$f" in *.py) continue ;; esac bash -n "$f" done - name: Gate smoke tests run: bash tests/test_gates.sh + - name: Adversarial integrity and bounded-loop contracts + run: python tests/test_hardening.py - name: Worked example run: bash examples/demo.sh - name: Pre-publish gate (leaks / over-claim / worked example) @@ -75,3 +78,36 @@ jobs: # The import check above proves the module loads; it never reads the handshake. This # step launches the server and reads what it actually says on the wire. run: python mcp/tests/test_serverinfo_version.py + - name: Install compatible Mirror contract for integration tests + run: pip install "git+https://github.com/mirror-stack/mirror-stack-mcp@v0.2.14" + - name: CLI/MCP parity and real Mirror result contract + run: python mcp/tests/test_surface_contract.py + - name: Installed harness works away from the checkout + shell: bash + run: | + cd "$RUNNER_TEMP" + python - <<'PY' + import tempfile + from pathlib import Path + from yeoul_mcp import server + assert '_harness' in str(server.BIN), server.BIN + with tempfile.TemporaryDirectory() as tmp: + result = server.yeoul_new('installed-smoke', workspace=tmp, no_arc=True) + assert result['exit_code'] == 0, result + spec = Path(tmp)/'projects'/'installed-smoke'/'design'/'spec.md' + assert '**Goal**' in spec.read_text(encoding='utf-8') + PY + - name: Source archive builds a self-contained wheel too + shell: bash + run: | + python -m pip install build + python -m build ./mcp --sdist --outdir "$RUNNER_TEMP/yeoul-sdist" + python -m pip wheel "$RUNNER_TEMP"/yeoul-sdist/*.tar.gz --no-deps --wheel-dir "$RUNNER_TEMP/yeoul-wheel" + python - <<'PY' + import os, zipfile + from pathlib import Path + wheel = next((Path(os.environ['RUNNER_TEMP'])/'yeoul-wheel').glob('*.whl')) + with zipfile.ZipFile(wheel) as archive: + for path in ('bin/arc-close', 'bin/prereg_check.py', 'bin/ralph_core.py', 'templates/spec.md', 'LICENSE'): + assert 'yeoul_mcp/_harness/'+path in archive.namelist(), path + PY diff --git a/.gitignore b/.gitignore index dfd4bb1..8d6d7fe 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ projects/ graduated/ KNOWLEDGE_INDEX.md .venv/ +build/ +dist/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 74f49e8..be250ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,30 @@ All notable changes to this project are documented here. +## [0.3.0] — 2026-09-09 + +### Integrity contracts and compatibility changes + +- Verify every ledger hash/link and pin the first registration; reject unsealed, + tampered, malformed, duplicate-key, removed and changed bindings. Legacy links + require an explicit verified upgrade; existing archives/ledgers are untouched. +- Freeze original TODO criteria, reject command replacement/item deletion before + executing verification, and share CLI/MCP eligibility. Standalone verification + now requires a supervisor baseline; `--current-only` is a labelled manual diagnostic. +- Keep closure drafts pending until archival; reject deleted defense fields, + mismatched verdict metadata, concurrent closes and archive collisions. Record + archive-recording state separately, and show active arcs before historical verdicts. +- Bound Ralph rounds without an extra invocation; add timeouts and stop on unknown + token usage. Budgets remain between-round controls, not hard provider caps. +- Add an explicit `arc-result` bridge to Mirror's bound result contract. It records + the supplied status/evidence and reports a publication gate, but never publishes. +- Bundle harness/templates in wheels and sdists, isolate tests from production + ledgers/indexes, and test installation away from the checkout. +- Prefer Git Bash on Windows over the System32 WSL launcher. Keep per-run logs + without overwriting older evidence; require defense answers inside their checked section. +- Refresh active docs, command references, installation failure handling and migration + guidance. See [INTEGRITY.md](docs/INTEGRITY.md) for limitations and upgrade steps. + ## [0.2.0] — 2026-08-28 **The first tagged release.** `0.1.0` was never cut: the section below has sat marked *unreleased* diff --git a/README.md b/README.md index 1d2c48a..e4d9479 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,10 @@ **Yeoul is a file-based harness for running deliberation → pre-registration → autonomous work loops with integrity gates that resist self-deception and premature closure.** It is the *practice layer* on top of a measurement-discipline primitive (pre-registration + a tamper-evident ledger): the -primitive answers *"is this claim honest?"*; Yeoul answers *"how do I run a disciplined idea loop end to end?"* +primitive checks recorded evidence and integrity; Yeoul answers *"how do I run a disciplined idea loop end to end?"* -> ⚠️ **Work in progress — not yet released.** This README is a positioning draft, not a launch page. +> **v0.3.0: integrity-contract hardening.** See the [changelog](CHANGELOG.md) and +> [trust boundaries, installation and migration guide](docs/INTEGRITY.md). ## Install @@ -33,7 +34,7 @@ Register both MCP servers with your client (Claude Desktop/Code — merge `setup } } ``` -mirror-stack is optional — without it, sealing degrades to a no-op and everything else still runs +mirror-stack is optional — without a recorder, discussion closes are explicitly file-only (`setup/install.sh --no-mirror-stack`). ## Quickstart @@ -70,7 +71,8 @@ New to the method? Read [`docs/METHODOLOGY.md`](docs/METHODOLOGY.md), then paste - **Verify-gated dev loop** — each automated development round advances one TODO item and may only check it off after its own machine verification command exits 0, re-run by the harness rather than reported by the agent. Items without a verify command are refused — including checked ones, so deleting the clause is not - a way out. (A verify command that cannot fail is still a hole: that part is on the author.) + a way out. Original TODO criteria are pinned before work; changing commands or deleting items is refused. + (Test adequacy and protection of the test implementations remain the supervisor's responsibility.) ## Layers @@ -79,11 +81,12 @@ New to the method? Read [`docs/METHODOLOGY.md`](docs/METHODOLOGY.md), then paste | Primitive | pre-registration + tamper-evident ledger | *(optional dependency — the mirror-stack)* | | Practice | deliberation arcs, gates, dev handoff | **this repo** | -The mirror-stack dependency is optional: without it, sealing degrades to a no-op and everything else runs. +Mirror is optional for discussion. Linked claims must still pass offline hash verification. +Use `arc-result` only for an explicit, supervisor-judged measurement result; discussion closure is not publication. ## Status / honesty notes - The autonomous development loop ("Ralph"-style) is the **least-validated, most-commodity** part; its safety comes from the machine-verification gate, not the loop itself. Do not treat it as a proven technique. - No claim here is that Yeoul improves research *outcomes*. The claim is narrower: it makes honest - discipline the **default and hard-to-skip**, which is exactly what current autonomous-research systems lack. + discipline explicit and mechanically checked in the supported paths. It is not an OS security boundary. diff --git a/README_KO.md b/README_KO.md index 49e8e67..1776ccc 100644 --- a/README_KO.md +++ b/README_KO.md @@ -10,9 +10,10 @@ **Yeoul은 심의 → 사전등록 → 자율 작업 루프를 자기기만과 성급한 종결에 저항하는 무결성 게이트와 함께 돌리는 파일 기반 하네스입니다.** 측정 규율 프리미티브(사전등록 + 변조 감지 원장) 위에 얹힌 *실천 계층*이에요 — -프리미티브는 *"이 주장이 정직한가?"*에 답하고, Yeoul은 *"규율 있는 아이디어 루프를 처음부터 끝까지 어떻게 돌리나?"*에 답합니다. +프리미티브는 기록된 증거의 무결성을 확인하고, Yeoul은 *"규율 있는 아이디어 루프를 처음부터 끝까지 어떻게 돌리나?"*에 답합니다. -> ⚠️ **진행 중 — 아직 정식 릴리스 아님.** 이 문서는 포지셔닝 초안이지 출시 페이지가 아닙니다. +> **v0.3.0: 무결성 계약 보완.** [변경 기록](CHANGELOG.md)과 +> [검증 범위·설치·기존 아크 마이그레이션 안내](docs/INTEGRITY.md)를 확인하세요. ## 설치 @@ -32,7 +33,7 @@ setup/install.sh # mirror-stack(봉인 프리미티브) + yeoul- } } ``` -mirror-stack은 선택입니다 — 없으면 봉인이 no-op으로 완화되고 나머지는 그대로 돕니다 +mirror-stack은 선택입니다 — 기록기가 없으면 토론 종결은 파일 전용으로 명시됩니다 (`setup/install.sh --no-mirror-stack`). ## 빠른 시작 @@ -77,11 +78,16 @@ tests/test_gates.sh # 모든 게이트의 단언 기반 스모크 테스트 | 프리미티브 | 사전등록 + 변조 감지 원장 | *(선택 의존성 — mirror-stack)* | | 실천 | 심의 아크·게이트·개발 핸드오프 | **이 레포** | -mirror-stack 의존성은 선택입니다: 없으면 봉인이 no-op으로 완화되고 나머지는 그대로 돕니다. +토론에는 mirror-stack이 필수가 아닙니다. 다만 봉인을 연결하면 원장 전체 해시·체인과 최초 봉인을 검증합니다. +토론 종결은 측정 결과나 출판 승인이 아닙니다. 측정 결과는 감독자가 `arc-result`에 상태와 증거를 명시해 넘깁니다. + +개발 검증은 작업 전에 `verify-baseline`으로 기준을 고정한 뒤 `verify-gate`로 확인합니다. +Ralph는 최초 TODO를 부모 프로세스 메모리에 보관해 명령 변경·항목 삭제를 거부합니다. +기존 2줄 `.prereg`는 자동 인증하지 않으며, 같은 원장과 주장으로 명시적인 재연결이 필요합니다. ## 상태 / 정직 노트 - 자율 개발 루프("Ralph" 방식)는 **가장 덜 검증됐고 가장 commodity한** 부분입니다. 그 안전성은 루프 자체가 아니라 기계 검증 게이트에서 나와요. 검증된 기법으로 과신하지 마세요. -- Yeoul이 연구 *결과*를 개선한다는 주장은 하지 않습니다. 주장은 더 좁아요: 정직한 규율을 **기본값이자 건너뛰기 - 어렵게** 만든다는 것 — 현재 자율 연구 시스템에 정확히 빠져 있는 바로 그것. +- Yeoul이 연구 *결과*를 개선한다는 주장은 하지 않습니다. 지원하는 실행 경로에서 규율을 명시하고 + 기계적으로 검사한다는 뜻이며, 운영체제 수준의 보안 경계나 진실성 증명은 아닙니다. diff --git a/bin/arc-close b/bin/arc-close index 121401d..b0009d1 100755 --- a/bin/arc-close +++ b/bin/arc-close @@ -25,6 +25,9 @@ fi [ -d "$ARC_DIR" ] || { echo "arc dir not found: $ARC_DIR"; exit 1; } ARC_DIR="$(cd "$ARC_DIR" && pwd)" +LOCK_PATH="$ARC_DIR/.close.lock" +mkdir "$LOCK_PATH" 2>/dev/null || { echo 'close already in progress (or stale .close.lock; inspect before retry)'; exit 9; } +trap 'rmdir "$LOCK_PATH" 2>/dev/null || true' EXIT ARC="$(basename "$ARC_DIR")" ARCS_DIR="$(cd "$ARC_DIR/.." && pwd)" ARCHIVE_DIR="$ARCS_DIR/_archive" @@ -36,9 +39,8 @@ sed_inplace() { # sed_inplace sed "$1" "$2" > "$2.tmp" && mv "$2.tmp" "$2" } -# thread status In-Progress → Closed +# Do not mark a draft or refusal Closed. Commit status only after archiving. ARC_FILE="$ARC_DIR/ARC/${ARC}.md" -[ -f "$ARC_FILE" ] && sed_inplace 's/^status: "In-Progress"/status: "Closed"/' "$ARC_FILE" # is this a KILL-type close? (stop=falsified or verdict mentions KILL) IS_KILL="no" @@ -50,26 +52,15 @@ case "$VERDICT" in *KILL*|*kill*) IS_KILL="yes" ;; esac # the verbatim sealed kill-condition into the record instead of trusting an agent-typed field. The agent # is not the author of the condition, so it cannot be silently widened at close (post-hoc goalpost move). # NOTE: this fixes the *condition* by reference; whether the result triggers it remains a judgment. -extract_kill() { # extract_kill → verbatim kill_condition (whitespace-collapsed), else empty - [ -f "$1" ] || return 0 - $PY - "$1" "$2" 2>/dev/null <<'PY' -import json, sys -led, cid = sys.argv[1], sys.argv[2] -for line in open(led, encoding='utf-8', errors='ignore'): - line = line.strip() - if not line: continue - try: d = json.loads(line) - except Exception: continue - if d.get('claim_id') == cid and d.get('kill_condition'): - print(' '.join(str(d['kill_condition']).split())); break -PY -} PREREG="$ARC_DIR/.prereg" SEAL_CLAIM=""; SEAL_LEDGER=""; SEAL_KILL="" -if [ -f "$PREREG" ]; then - SEAL_CLAIM="$(sed -n '1p' "$PREREG")"; SEAL_LEDGER="$(sed -n '2p' "$PREREG")" - SEAL_KILL="$(extract_kill "$SEAL_LEDGER" "$SEAL_CLAIM")" -fi +CHECKER="$(dirname "${BASH_SOURCE[0]}")/prereg_check.py" +SEAL_BROKEN="no" +if RESOLVED="$($PY "$CHECKER" resolve "$ARC_DIR")"; then + SEAL_CLAIM="$(printf '%s' "$RESOLVED" | sed -n '1p')" + SEAL_LEDGER="$(printf '%s' "$RESOLVED" | sed -n '2p')" + SEAL_KILL="$(printf '%s' "$RESOLVED" | sed -n '3p')" +else SEAL_BROKEN="yes"; fi # ── An external anchor must not depend on a label the examinee writes ────────────────── # The defect: even when a sealed kill-condition existed, nothing was injected or checked @@ -86,7 +77,6 @@ fi # while missing the closes that mattered, which never use the word at all. SEAL_GATE="no"; [ -n "$SEAL_KILL" ] && SEAL_GATE="yes" # A .prereg that no longer resolves is a silent way around the gate. Never pass it in silence. -SEAL_BROKEN="no"; [ -f "$PREREG" ] && [ -z "$SEAL_KILL" ] && SEAL_BROKEN="yes" # ★2026-08-26 — the second key must be RECORDED, not only enforced. # Measured before this existed: a KILL close wrote "⚠️ UNSEALED …" into the _SUMMARY, but a GO @@ -98,7 +88,7 @@ SEAL_BROKEN="no"; [ -f "$PREREG" ] && [ -z "$SEAL_KILL" ] && SEAL_BROKEN="yes" # so "closed with one key" cannot be quietly edited into "closed with two". seal_state_line() { if [ -n "$SEAL_KILL" ]; then - printf -- '- **Second key (pre-registration)**: sealed — claim `%s` in %s\n' "$SEAL_CLAIM" "$SEAL_LEDGER" + printf -- '- **Second key (pre-registration)**: sealed — claim `%s` in %s (hash-verified, first seal pinned; identity/time/truth unverified)\n' "$SEAL_CLAIM" "$SEAL_LEDGER" elif [ "$SEAL_BROKEN" = "yes" ]; then printf -- '- **Second key (pre-registration)**: BROKEN — `.prereg` names claim `%s` but it could not be read from %s\n' "$SEAL_CLAIM" "$SEAL_LEDGER" else @@ -145,6 +135,7 @@ SUBSTANCE="$(dirname "${BASH_SOURCE[0]}")/substance_check.py" TAB="$(printf '\t')" # NOTE: ${v%%\t*} is a literal `t` in shell patterns — this must be a real tab check_answers() { # check_answers
+ "$PY" "$(dirname "${BASH_SOURCE[0]}")/closure_check.py" "$SUMMARY" "$IS_KILL" "$SEAL_GATE" || exit 5 # ★ The positive control runs at the HEAD OF THE GATE'S EXECUTION PATH, not in a test file. # If the checker cannot separate planted violations from planted genuine answers, we do NOT # interpret the real answers — we die. An instrument is not trusted because it is green; @@ -185,9 +176,9 @@ SUMMARY="$ARC_DIR/_SUMMARY_${ARC}.md" # ── 1st run: draft only, stop (no seal) ── if [ ! -f "$SUMMARY" ]; then cat > "$SUMMARY" << MDEOF -# 🏛️ Arc closed — ${ARC} +# 🏛️ Arc close draft — ${ARC} -- **Closed**: ${TODAY} (${TS_ISO}) +- **Drafted**: ${TODAY} (${TS_ISO}) - **stop_reason**: ${STOP} (falsified / no-progress / converged) - **Verdict**: ${VERDICT} $(seal_state_line) @@ -206,6 +197,7 @@ $(seal_state_line) MDEOF if [ "$IS_KILL" = "yes" ]; then emit_kill_defense >> "$SUMMARY" elif [ "$SEAL_GATE" = "yes" ]; then emit_seal_check >> "$SUMMARY"; fi + [ ! -f "$ARC_FILE" ] || sed_inplace 's/^status: .*/status: "Close-Pending"/' "$ARC_FILE" echo "📝 _SUMMARY drafted (not sealed): $SUMMARY" if [ "$SEAL_GATE" = "yes" ]; then echo " 🔒 sealed kill-condition injected from seal $SEAL_CLAIM (not agent-authored)." @@ -229,7 +221,7 @@ fi if [ "$SEAL_BROKEN" = "yes" ]; then echo "⛔ seal refused: .prereg is linked but its sealed kill-condition could not be read — anchor broken." echo " claim=$SEAL_CLAIM · ledger=$SEAL_LEDGER" - echo " Re-link with arc-prereg, or remove .prereg deliberately if there really is no seal (both are auditable acts)." + echo " Restore the bound files. For a legacy link, explicitly re-link the same verified claim with arc-prereg." exit 5 fi @@ -275,6 +267,7 @@ fi # keys were turned. Refuse and show both lines rather than sealing a summary that misreports it. # NB: `--` is load-bearing. The pattern starts with "- ", so without it grep parses the line as # options and exits non-zero — which this gate would have read as "the record is wrong". +"$PY" "$(dirname "${BASH_SOURCE[0]}")/closure_check.py" "$SUMMARY" --record "$VERDICT" "$STOP" || exit 8 if ! grep -qxF -- "$(seal_state_line)" "$SUMMARY"; then echo "⛔ seal refused: the second-key line in _SUMMARY does not match this arc's actual seal state." echo " in the file : $(grep -m1 -F -- '**Second key (pre-registration)**' "$SUMMARY" || echo '(the line is missing)')" @@ -283,11 +276,16 @@ if ! grep -qxF -- "$(seal_state_line)" "$SUMMARY"; then exit 8 fi -echo "ARC_CLOSED ${TODAY} stop=${STOP} — ${VERDICT}" >> "$ARC_DIR/STATE.md" - mkdir -p "$ARCHIVE_DIR" +[ ! -e "$ARCHIVE_DIR/$ARC" ] || { echo "archive destination already exists — refusing overwrite"; exit 9; } mv "$ARC_DIR" "$ARCHIVE_DIR/" +LOCK_PATH="$ARCHIVE_DIR/$ARC/.close.lock" SEALED="$ARCHIVE_DIR/$ARC/_SUMMARY_${ARC}.md" +ARC_FILE="$ARCHIVE_DIR/$ARC/ARC/${ARC}.md" +[ ! -f "$ARC_FILE" ] || sed_inplace 's/^status: .*/status: "Closed"/' "$ARC_FILE" +sed_inplace 's/Arc close draft/Arc closed/' "$SEALED" +printf '\n- **Closed**: %s (%s)\n' "$TODAY" "$TS_ISO" >> "$SEALED" +echo "ARC_CLOSED ${TODAY} stop=${STOP} — ${VERDICT}" >> "$ARCHIVE_DIR/$ARC/STATE.md" # ── optional: seal into append-only ledger (best-effort; skips if `am` absent) ── # 🔴 say what was actually tested. The condition below is "is the `am` CLI on PATH", @@ -297,15 +295,19 @@ SEALED="$ARCHIVE_DIR/$ARC/_SUMMARY_${ARC}.md" # NB: single-quoted on purpose — backticks inside double quotes are command substitution, # which ran `am` and leaked its exit status into the close (caught by tests/test_gates.sh). SEAL_MSG='not sealed — file only (`am` CLI not on PATH; mirror-stack may still be installed)' +RECORD_STATE="file-only" if command -v am >/dev/null 2>&1; then if am record --agent yeoul --action arc-close --target "$ARC" \ --payload "{\"stop_reason\":\"${STOP}\"}" \ --content-file "$SEALED" >/dev/null 2>&1; then SEAL_MSG="✅ sealed into ledger (content-hash = _SUMMARY → tamper-evident)" + RECORD_STATE="recorded" else SEAL_MSG="⚠️ am record failed (skipped)" + RECORD_STATE="record-failed" fi fi +printf 'ARCHIVE_RECORD %s\n' "$RECORD_STATE" >> "$ARCHIVE_DIR/$ARC/STATE.md" # ── auto-growing knowledge index (hands-off; appends on close) ── [ -x "$(dirname "${BASH_SOURCE[0]}")/index-append" ] && \ diff --git a/bin/arc-list b/bin/arc-list index fb23f33..90ecb53 100755 --- a/bin/arc-list +++ b/bin/arc-list @@ -31,7 +31,7 @@ for root in $ROOTS; do if [ "$archived" = "1" ]; then status="Archived"; fi title="$(field title "$arcfile")" roles="$(field roles "$arcfile")" - if [ "$OPEN_ONLY" = "1" ] && [ "$status" != "In-Progress" ]; then continue; fi + if [ "$OPEN_ONLY" = "1" ] && [ "$status" != "In-Progress" ] && [ "$status" != "Close-Pending" ]; then continue; fi printf '%s\t%s\t%s\t%s\n' "${status:-?}" "$arcdir" "${title:-?}" "${roles:-?}" done < <(find "$root" -type f -path '*/ARC/*.md' 2>/dev/null) done diff --git a/bin/arc-prereg b/bin/arc-prereg index 9533507..79abd98 100755 --- a/bin/arc-prereg +++ b/bin/arc-prereg @@ -30,18 +30,8 @@ fi [ -n "$LEDGER" ] || { echo "no ledger given (pass one or set \$YEOUL_LEDGER)"; exit 1; } [ -f "$LEDGER" ] || { echo "ledger not found: $LEDGER"; exit 1; } -KILL="$($PY - "$LEDGER" "$CLAIM" 2>/dev/null <<'PY' -import json, sys -led, cid = sys.argv[1], sys.argv[2] -for line in open(led, encoding='utf-8', errors='ignore'): - line = line.strip() - if not line: continue - try: d = json.loads(line) - except Exception: continue - if d.get('claim_id') == cid and d.get('kill_condition'): - print(' '.join(str(d['kill_condition']).split())); break -PY -)" +CHECKER="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/prereg_check.py" +KILL="$($PY "$CHECKER" claim "$LEDGER" "$CLAIM")" || exit 1 [ -n "$KILL" ] || { echo "❌ claim '$CLAIM' with a kill_condition not found in $LEDGER"; exit 1; } # ── second key: the arc's spec must carry a design before a seal may attach to it ── @@ -112,7 +102,8 @@ if [ -n "$MISSING" ]; then fi echo " ✅ spec carries a design: $CHECKED/$CHECKED fields hold substance." -printf '%s\n%s\n' "$CLAIM" "$LEDGER" > "$ARC_DIR/.prereg" +KILL="$($PY "$CHECKER" bind "$ARC_DIR" "$CLAIM" "$LEDGER")" || exit 1 echo "🔒 prereg linked: arc $(basename "$ARC_DIR") ← seal $CLAIM" echo " sealed kill-condition: ${KILL:0:100}$([ "${#KILL}" -gt 100 ] && echo '…')" -echo " arc-close will now inject this verbatim (agent cannot re-author it)." +echo " Hashes and links verified; first registration pinned. Identity/time/truth not verified." +echo " arc-close re-verifies the ledger and the pinned registration on every call." diff --git a/bin/arc-result b/bin/arc-result new file mode 100755 index 0000000..96e524e --- /dev/null +++ b/bin/arc-result @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +# Explicit supervisor action; never inferred from an arc verdict or run by Ralph. +. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/_pybin.sh" +PY="$(yeoul_pybin)" || yeoul_pybin_die +exec "$PY" "$(dirname "${BASH_SOURCE[0]}")/result_record.py" "$@" diff --git a/bin/build-handoff b/bin/build-handoff index ec55e76..cb48df1 100755 --- a/bin/build-handoff +++ b/bin/build-handoff @@ -53,7 +53,7 @@ cat > "$PLAN" << MDEOF - (copy the self-critique / blind-spots here) ## Graduation -- success condition met + GO gates passed → \`yeoul-graduate "${NAME}"\` +- success condition met + GO gates passed → \`graduate "${NAME}"\` (supervisor decision) MDEOF cat > "$DEV/TODO.md" << MDEOF diff --git a/bin/closure_check.py b/bin/closure_check.py new file mode 100644 index 0000000..297ab4b --- /dev/null +++ b/bin/closure_check.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Required closure fields, shared by the public and internal harness. + +Shape/substance checks are not evidence verification or independent reproduction. +""" +import re +import sys +from pathlib import Path + + +def check_fields(text, kill, linked): + marker = (r'KILL-defense check|KILL \ubc29\uc5b4 \uccb4\ud06c' if kill + else r'Sealed-condition cross-check|\ubd09\uc778 \ub300\uc870') + sections = re.findall(r'^## [^\n]*(?:'+marker+r')[^\n]*\n(.*?)(?=^## |\Z)', text, re.M | re.S) + if len(sections) != 1: + raise ValueError('required closure section must occur exactly once') + # Unicode escapes keep this shared source locale-neutral for publication. + groups = [('Result triggers', '\uacb0\uacfc\uac00') if linked + else ('Kill wording', 'kill \ubb38\uc5b8')] + if kill: + groups += [('Anchor', '\uc575\ucee4'), ('Independent', '\ub3c5\ub9bd'), + ('Implementation', '\uad6c\ud604'), ('Catalog', '\ub3c4\uac10')] + labels = re.findall(r'^- \*\*([^*]+)\*\*:', sections[0], re.M) + for alternatives in groups: + if sum(any(label.startswith(prefix) for prefix in alternatives) for label in labels) != 1: + raise ValueError('missing or duplicated required closure field: '+alternatives[0]) + + +def main(): + try: + text = Path(sys.argv[1]).read_text(encoding='utf-8') + if sys.argv[2] == '--record': + verdicts = re.findall(r'^- \*\*(?:Verdict|\ud310\uc815)\*\*:\s*(.*)$', text, re.M) + stops = re.findall(r'^- \*\*stop_reason\*\*:\s*(\S+)', text, re.M) + if verdicts != [sys.argv[3]] or stops != [sys.argv[4]]: + raise ValueError('verdict/stop must occur once and match the requested close') + for title in (r'What was closed|\ub2eb\uc740 \uac83', + r'What was NOT closed|\uc548 \ub2eb\uc740 \uac83'): + sections = re.findall(r'^## (?:'+title+r')[^\n]*\n(.*?)(?=^## |\Z)', text, re.M | re.S) + if len(sections) != 1 or not any(c.isalnum() for c in sections[0]): + raise ValueError('missing/empty/duplicated conclusion or out-of-scope section') + else: + check_fields(text, sys.argv[2] == 'yes', sys.argv[3] == 'yes') + except (OSError, ValueError, IndexError) as exc: + print(f'closure refused: {exc}', file=sys.stderr) + return 5 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/bin/index-append b/bin/index-append index 34a01f9..0d98827 100755 --- a/bin/index-append +++ b/bin/index-append @@ -2,8 +2,8 @@ set -uo pipefail # index-append # Hands-off, auto-growing arc-close knowledge index. arc-close calls this after archiving. -# Joins only sealed sources (the archived _SUMMARY + a linked mm claim) → appends to one file -# (never rots; not a new store). Index path = $YEOUL_INDEX, default /KNOWLEDGE_INDEX.md. +# Derived view of archived summaries and verified bindings, not a proof store. +# Index path = $YEOUL_INDEX, default ./KNOWLEDGE_INDEX.md in the caller's workspace. # Best-effort: a failure here never affects the close. # Resolve the interpreter by running one — `command -v python3` also finds the Windows Store stub. @@ -14,9 +14,12 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ARC_DIR="${1:-}"; [ -n "$ARC_DIR" ] && [ -d "$ARC_DIR" ] || exit 0 ARC="$(basename "$ARC_DIR")" SUM="$(ls "$ARC_DIR"/_SUMMARY_*.md 2>/dev/null | head -1)"; [ -f "$SUM" ] || exit 0 -INDEX="${YEOUL_INDEX:-$SCRIPT_DIR/../KNOWLEDGE_INDEX.md}" +INDEX="${YEOUL_INDEX:-./KNOWLEDGE_INDEX.md}" CLAIM="-"; [ -f "$ARC_DIR/.prereg" ] && CLAIM="$(sed -n '1p' "$ARC_DIR/.prereg")" +CLAIM_VERIFIED=0 +if [ "$CLAIM" != "-" ] && "$PY" "$SCRIPT_DIR/prereg_check.py" resolve "$ARC_DIR" >/dev/null 2>&1; then CLAIM_VERIFIED=1; fi +RECORD_STATE="$(sed -n 's/^ARCHIVE_RECORD //p' "$ARC_DIR/STATE.md" 2>/dev/null | tail -1)" read -r DATE STOP < <($PY - "$SUM" <<'PY' import re,sys @@ -53,7 +56,7 @@ PY [ -f "$INDEX" ] || cat > "$INDEX" <<'HDR' # 🌊 Yeoul arc-close knowledge index (auto-generated — do not hand-edit) -> arc-close appends here on close. Source = sealed _SUMMARY + any linked claim. New rows accrue below. +> arc-close appends here on archive. A summary is not necessarily sealed; see recording state. > Each entry: date · verdict · stop · arc · sealed claim · one-line conclusion. HDR @@ -65,8 +68,10 @@ REL="${ARC_DIR#"$SCRIPT_DIR"/../}" # 🔴 Always emit this row. It used to be printed only when a claim existed, so an unsealed close # produced an entry with the line simply absent — and the index header promises the column. # A reader could not tell "no seal" from "this row predates the field" or "the write failed". - if [ "$CLAIM" != "-" ]; then printf -- '- **Sealed claim**: `%s`\n' "$CLAIM" + if [ "$CLAIM_VERIFIED" = "1" ]; then printf -- '- **Sealed claim**: `%s` (hash-verified binding)\n' "$CLAIM" + elif [ "$CLAIM" != "-" ]; then printf -- '- **Linked claim (UNVERIFIED)**: `%s`\n' "$CLAIM" else printf -- '- **Sealed claim**: none (closed with one key only)\n'; fi + printf -- '- **Archive recording**: %s\n' "${RECORD_STATE:-unknown (historical or no state record)}" printf -- '- **Closed**: %s\n' "$CLOSED" printf -- '- source: %s\n\n' "$REL" } >> "$INDEX" diff --git a/bin/loop-guard b/bin/loop-guard index 08cf097..c31f370 100755 --- a/bin/loop-guard +++ b/bin/loop-guard @@ -20,8 +20,16 @@ for a in "${@:3}"; do case "$a" in --token-budget=*) BUDGET="${a#*=}" ;; --tokens=*) TOKENS="${a#*=}"; TOKENS_GIVEN=1 ;; --progress=*) PROGRESS="${a#*=}" ;; + *) echo "unknown option: $a" >&2; exit 2 ;; esac; done +number() { [[ "$1" =~ ^(0|[1-9][0-9]{0,11})$ ]]; } +for n in "$TOKENS" "${MAXR:-3}" "${BUDGET:-200000}"; do + number "$n" || { echo "invalid nonnegative integer: $n" >&2; exit 2; } +done +[ "${MAXR:-3}" -gt 0 ] && [ "${BUDGET:-200000}" -gt 0 ] || { echo 'limits must be positive'; exit 2; } +case "$PROGRESS" in yes|no) ;; *) echo 'progress must be yes or no'; exit 2 ;; esac + ROUND=0; MR=3; TB=200000; TU=0; NP=0; UM=0 load(){ if [ -f "$STATE" ]; then @@ -29,6 +37,9 @@ load(){ round) ROUND=$v ;; max_rounds) MR=$v ;; token_budget) TB=$v ;; tokens_used) TU=$v ;; no_progress) NP=$v ;; unmeasured) UM=$v ;; esac; done < "$STATE" + for n in "$ROUND" "$MR" "$TB" "$TU" "$NP" "$UM"; do + number "$n" || { echo 'invalid guard state' >&2; exit 2; } + done fi } save(){ printf 'round\t%s\nmax_rounds\t%s\ntoken_budget\t%s\ntokens_used\t%s\nno_progress\t%s\nunmeasured\t%s\n' \ @@ -47,8 +58,9 @@ case "$CMD" in if [ "$TOKENS_GIVEN" = "0" ]; then UM=$((UM+1)); fi if [ "$PROGRESS" = "no" ]; then NP=$((NP+1)); else NP=0; fi save - if [ "$ROUND" -gt "$MR" ]; then echo "STOP:max-rounds (round=$ROUND > max=$MR)" - elif [ "$TU" -gt "$TB" ]; then echo "STOP:budget (used=$TU > budget=$TB)" + if [ "$ROUND" -ge "$MR" ]; then echo "STOP:max-rounds (round=$ROUND >= max=$MR)" + elif [ "$TU" -ge "$TB" ]; then echo "STOP:budget (used=$TU >= budget=$TB)" + elif [ "$UM" -gt 0 ]; then echo "STOP:unmeasured (unmeasured=$UM/$ROUND-ticks)" elif [ "$NP" -ge 2 ]; then echo "STOP:no-progress (streak=$NP)" else echo "CONTINUE (round=$ROUND/$MR tokens=$TU/$TB noprog=$NP$(warn_unmeasured))" fi ;; diff --git a/bin/prereg_check.py b/bin/prereg_check.py new file mode 100644 index 0000000..14c56ed --- /dev/null +++ b/bin/prereg_check.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""MIRROR-SPEC hash verification and first-write arc binding (stdlib only). + +Hash integrity is not identity, external time, or content truth. Local bindings +detect drift; they are not a security boundary against an owner rewriting all files. +The wire algorithm matches mirror-stack-mcp.integrity; interoperability is tested. +""" +import argparse +import hashlib +import json +import sys +from pathlib import Path + + +def unique_object(pairs): + obj = {} + for key, value in pairs: + if key in obj: + raise ValueError(f'duplicate JSON key: {key}') + obj[key] = value + return obj + + +def read_verified(path): + entries = [json.loads(line, object_pairs_hook=unique_object) + for line in Path(path).read_text(encoding='utf-8').splitlines() if line.strip()] + if not entries: + raise ValueError('empty ledger') + previous = 'genesis' + for index, entry in enumerate(entries): + if not isinstance(entry, dict): + raise ValueError('ledger entry must be an object') + link, seal = entry.get('prev_seal'), entry.get('seal') + if not isinstance(link, str) or (link.lower() != 'genesis' if index == 0 else link != previous): + raise ValueError('ledger linkage broken') + if not isinstance(seal, str) or len(seal) not in (16, 64): + raise ValueError('missing or invalid seal') + body = {k: v for k, v in entry.items() if k not in ('seal', 'sig')} + digest = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False, + allow_nan=False).encode('utf-8')).hexdigest() + if seal != digest[:len(seal)]: + raise ValueError('seal mismatch: ledger content changed') + previous = seal + return entries + + +def claim(ledger, claim_id): + # Read and hash once; choose from exactly that verified snapshot. First write wins. + entries = read_verified(ledger) + entry = next((e for e in entries if e.get('claim_id') == claim_id + and e.get('_type') is None and e.get('metric') != 'protocol_amendment'), None) + if entry is None: + raise ValueError('no first registration for this claim') + condition = entry.get('kill_condition') + if not isinstance(condition, str) or not condition.strip(): + threshold = entry.get('kill_threshold') + if not isinstance(threshold, dict) or not threshold: + raise ValueError('first registration has no kill-condition') + condition = json.dumps(threshold, sort_keys=True, ensure_ascii=False, allow_nan=False) + return entry, ' '.join(condition.split()) + + +def anchors(arc): + state = arc / 'STATE.md' + if not state.exists(): + return [] + return [json.loads(line.removeprefix('PREREG_BOUND '), object_pairs_hook=unique_object) + for line in state.read_text(encoding='utf-8').splitlines() + if line.startswith('PREREG_BOUND ')] + + +def resolve(arc): + arc = Path(arc) + link = arc / '.prereg' + records = anchors(arc) + if not link.exists(): + if records: + raise ValueError('linked preregistration was removed; restore .prereg') + return None, None + lines = link.read_text(encoding='utf-8').splitlines() + if len(lines) != 3 or not records: + raise ValueError('legacy/unbound .prereg: explicitly re-link with arc-prereg after verification') + binding = dict(claim_id=lines[0], ledger=lines[1], seal=lines[2]) + if any(record != binding for record in records): + raise ValueError('preregistration binding changed from its first anchor') + entry, condition = claim(binding['ledger'], binding['claim_id']) + if entry['seal'] != binding['seal']: + raise ValueError('first registration no longer matches the pinned seal') + return binding, condition + + +def bind(arc, claim_id, ledger): + arc = Path(arc) + ledger = str(Path(ledger).resolve(strict=True)) + if any(c in claim_id + ledger for c in '\r\n'): + raise ValueError('claim and ledger must be single-line values') + entry, condition = claim(ledger, claim_id) + binding = dict(claim_id=claim_id, ledger=ledger, seal=entry['seal']) + records = anchors(arc) + if records and any(record != binding for record in records): + raise ValueError('refusing to replace the first bound registration; open a new arc') + link = arc / '.prereg' + if link.exists(): + old = link.read_text(encoding='utf-8').splitlines() + if len(old) not in (2, 3) or old[0] != claim_id or str(Path(old[1]).resolve()) != ledger: + raise ValueError('existing .prereg identifies another claim; open a new arc') + if len(old) == 3 and old[2] != entry['seal']: + raise ValueError('existing pinned seal changed') + # Anchor first: interruption fails closed instead of silently downgrading to unbound. + if not records: + with (arc / 'STATE.md').open('a', encoding='utf-8') as stream: + stream.write('\nPREREG_BOUND ' + json.dumps(binding, ensure_ascii=False) + '\n') + temp = arc / '.prereg.tmp' + temp.write_text(f'{claim_id}\n{ledger}\n{entry["seal"]}\n', encoding='utf-8') + temp.replace(link) + return condition + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('mode', choices=['claim', 'bind', 'resolve']) + parser.add_argument('args', nargs='+') + args = parser.parse_args() + try: + if args.mode == 'claim': + _, condition = claim(*args.args) + print(condition) + elif args.mode == 'bind': + print(bind(*args.args)) + else: + binding, condition = resolve(*args.args) + if binding: + print(binding['claim_id']) + print(binding['ledger']) + print(condition) + except (OSError, ValueError, TypeError, KeyError, IndexError, RecursionError) as exc: + print(f'preregistration verification refused: {exc}', file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/bin/ralph b/bin/ralph index d1373b7..6b73580 100755 --- a/bin/ralph +++ b/bin/ralph @@ -1,102 +1,5 @@ #!/usr/bin/env bash set -euo pipefail -# ralph [--max-rounds=N] [--token-budget=T] [--model=M] [--agent-cmd='claude -p ...'] -# Autonomous dev loop (external/unattended backend B): soak up dev/TODO.md items via a headless -# agent CLI. One round = one TODO item implemented + its `verify:` command run + checked off. -# Bounded by loop-guard. Projects root ./projects (override YEOUL_PROJECTS). -# -# ★ In-session backend A is preferred (the session drives rounds with subagents — no nesting). -# This script is for out-of-session unattended runs. It shells out to an agent CLI, so it CANNOT -# run from inside that same agent (nested-process guard) — launch it from a terminal. -# ⚠️ Loop-forbidden (belongs to the human/session): measurement runs, sealing, PASS/KILL judgment. -# Items without a `verify:` command are refused (exit 3). - -# Resolve the interpreter by running one — `command -v python3` also finds the Windows Store stub. . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/_pybin.sh" PY="$(yeoul_pybin)" || yeoul_pybin_die - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECTS_DIR="${YEOUL_PROJECTS:-./projects}" - -NAME="${1:-}"; [ -n "$NAME" ] || { echo "usage: ralph [--max-rounds=N --token-budget=T --model=M --agent-cmd='...']"; exit 1; } -PROJ="$PROJECTS_DIR/$NAME" -TODO="$PROJ/dev/TODO.md" -[ -f "$TODO" ] || { echo "no TODO: $TODO (run build-handoff first)"; exit 1; } - -MAXR=4; BUDGET=300000; MODEL=""; AGENT_CMD="${YEOUL_AGENT_CMD:-claude -p --output-format json --permission-mode acceptEdits}" -for a in "${@:2}"; do case "$a" in - --max-rounds=*) MAXR="${a#*=}" ;; - --token-budget=*) BUDGET="${a#*=}" ;; - --model=*) MODEL="${a#*=}" ;; - --agent-cmd=*) AGENT_CMD="${a#*=}" ;; -esac; done - -# Gate: any item without a `verify:` command → refuse the whole loop (form = eligibility). -# Checked items are included: the loop hands the file to an agent every round, and a checked item -# with no verify clause is exactly what the clause-deletion bypass produces. Requiring the clause on -# every item is what lets verify-gate run with --require-verify below (no exemption bookkeeping). -BAD="$(grep -E '^- \[( |x)\]' "$TODO" | grep -v 'verify:' || true)" -if [ -n "$BAD" ]; then - echo "⛔ items without a 'verify:' command — not loop-eligible (manual/session work):" - echo "$BAD" | sed 's/^/ /' - exit 3 -fi - -RALPH_DIR="$PROJ/dev/ralph_log"; mkdir -p "$RALPH_DIR" -"$SCRIPT_DIR/loop-guard" "$RALPH_DIR" init --max-rounds="$MAXR" --token-budget="$BUDGET" - -unchecked() { grep -c '^- \[ \]' "$TODO" 2>/dev/null || true; } - -ROUND=0 -while :; do - LEFT="$(unchecked)" - if [ "${LEFT:-0}" -eq 0 ]; then echo "RALPH_DONE: all TODO items checked"; break; fi - ROUND=$((ROUND+1)) - echo "── round $ROUND (unchecked $LEFT) ──" - - PROMPT="You are one round of an autonomous dev loop. Working dir: $(pwd). - -[backlog] $TODO -$(cat "$TODO") - -[rules — do not violate] -1. Work on ONLY the top unchecked (- [ ]) item this round. -2. Run the item's 'verify:' command and confirm exit 0 BEFORE checking it [x]. On failure, leave [ ] and note the cause in one line. - (The harness independently re-runs your verify command afterward and reverts the checkbox if it does not pass — checking off without a genuinely passing verify only wastes a round.) -3. Do NOT modify the verify commands or success criteria (no silent edits). No TODO changes except the checkbox. -4. Do NOT create/modify files outside this project's dev/ tree beyond what the item requires. -5. Forbidden: GPU/training runs, sealing tools, PASS/KILL or measurement claims, long-lived background processes. -6. Last output line: one-line summary of the completed item (or FAIL: cause)." - - ARGS=($AGENT_CMD) - [ -n "$MODEL" ] && ARGS+=(--model "$MODEL") - OUT="$RALPH_DIR/round_${ROUND}.json" - ( "${ARGS[@]}" "$PROMPT" > "$OUT" 2>"$RALPH_DIR/round_${ROUND}.err" ) || true - - # ★ harness enforces the gate: independently re-run verify for whatever got checked off; revert failures. - # The agent's claim that "verify passed" is not trusted — a checkbox survives only if the command - # actually exits 0 when the harness runs it. --require-verify additionally reverts a checked item - # whose verify clause went missing, so deleting the clause is not a way out either. - "$SCRIPT_DIR/verify-gate" "$TODO" --revert --require-verify || echo " ⚠ harness reverted a checked item (verify failed on re-run, or its verify clause was missing)" - - TOK=0 - if [ -n "$PY" ]; then - TOK=$($PY -c " -import json,sys -try: - d=json.load(open('$OUT')); u=d.get('usage',{}) - print(int(u.get('input_tokens',0))+int(u.get('output_tokens',0))) - print(str(d.get('result',''))[-300:], file=sys.stderr) -except Exception: print(0) -" 2>"$RALPH_DIR/round_${ROUND}.tail") || TOK=0 - tail -c 300 "$RALPH_DIR/round_${ROUND}.tail" 2>/dev/null || true; echo - fi - - NOW="$(unchecked)" - PROG="no"; [ "${NOW:-0}" -lt "${LEFT:-0}" ] && PROG="yes" - VERDICT="$("$SCRIPT_DIR/loop-guard" "$RALPH_DIR" tick --tokens="${TOK:-0}" --progress="$PROG")" - echo " progress=$PROG · $VERDICT" - case "$VERDICT" in STOP:*) echo "loop stopped: $VERDICT"; exit 2 ;; esac -done - -echo "── done: $(unchecked) unchecked · log $RALPH_DIR ──" +exec "$PY" "$(dirname "${BASH_SOURCE[0]}")/ralph_core.py" "$@" diff --git a/bin/ralph_core.py b/bin/ralph_core.py new file mode 100644 index 0000000..169b8d8 --- /dev/null +++ b/bin/ralph_core.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Bounded dev loop. No measurement, sealing or publication is performed here.""" +import argparse +import json +import math +import os +import shlex +import sys +import uuid +from pathlib import Path +from verify_core import canonical, eligible, execute, verify, atomic_write + + +def pending(text): + return sum(line.startswith('- [ ] ') for line in text.splitlines()) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('name') + p.add_argument('--check', action='store_true', help='read-only CLI/MCP eligibility check') + p.add_argument('--max-rounds', type=int, default=4) + p.add_argument('--token-budget', type=int, default=300000) + p.add_argument('--round-timeout', type=float, default=120) + p.add_argument('--verify-timeout', type=float, default=120) + p.add_argument('--model', default='') + p.add_argument('--agent-cmd', default=os.environ.get('YEOUL_AGENT_CMD', + 'claude -p --output-format json --permission-mode acceptEdits')) + a = p.parse_args() + try: + todo = Path(os.environ.get('YEOUL_PROJECTS', './projects')) / a.name / 'dev' / 'TODO.md' + baseline = todo.read_text(encoding='utf-8') + if not eligible(baseline): + print('not loop-eligible: require at least one item; ALL items need a nonempty verify command') + return 3 + if a.check: + print('loop-eligible: all items have verify commands (criteria not judged)') + return 0 + if any(not math.isfinite(n) or n <= 0 for n in + (a.max_rounds, a.token_budget, a.round_timeout, a.verify_timeout)): + raise ValueError('limits must be positive') + # Original criteria stay in parent memory, never reloaded from a worker-writable snapshot. + if verify(todo, baseline=baseline, revert=True, require=True, timeout=a.verify_timeout): + return 3 + if pending(todo.read_text(encoding='utf-8')) == 0: + print('RALPH_DONE: existing checked items re-verified') + return 0 + # Re-running a project must not overwrite previous round evidence. + log = todo.parent / 'ralph_log' / ('run-'+uuid.uuid4().hex) + log.mkdir(parents=True) + used = no_progress = 0 + for round_no in range(1, a.max_rounds + 1): + text = todo.read_text(encoding='utf-8') + if canonical(text) != canonical(baseline): + print('STOP: criteria changed between rounds') + return 3 + before = pending(text) + prompt = (f'Implement ONLY the first unchecked item in {todo.resolve()}.\n{text}\n' + 'Only change its checkbox in TODO; do not edit criteria or verify commands. ' + 'Run its verify command before checking it. No measurement/GPU runs, sealing, ' + 'PASS/KILL judgments, publishing or background processes. ' + 'Return JSON with usage.input_tokens and usage.output_tokens as nonnegative integers.') + args = shlex.split(a.agent_cmd) + if a.model: + args += ['--model', a.model] + args.append(prompt) + out = log / f'round_{round_no}.json' + with out.open('w', encoding='utf-8') as stdout, (log/f'round_{round_no}.err').open('w', encoding='utf-8') as stderr: + rc = execute(args, timeout=a.round_timeout, stdout=stdout, stderr=stderr) + if rc: + atomic_write(todo, text) + print(f'STOP: agent failed/timeout (exit {rc}); no completion accepted') + return 124 if rc == 124 else 2 + rc = verify(todo, baseline=baseline, revert=True, require=True, timeout=a.verify_timeout) + if rc == 3: + return 3 + try: + usage = json.loads(out.read_text(encoding='utf-8'))['usage'] + counts = [usage['input_tokens'], usage['output_tokens']] + if any(type(n) is not int or n < 0 for n in counts): + raise ValueError('invalid token count') + used += sum(counts) + except (ValueError, TypeError, KeyError): + print('STOP:unmeasured — missing/invalid usage is not zero tokens') + return 2 + remaining = pending(todo.read_text(encoding='utf-8')) + no_progress = no_progress + 1 if remaining >= before else 0 + print(f'round={round_no}/{a.max_rounds} tokens_used={used}/{a.token_budget} unchecked={remaining}') + print(f'log={log}') + if used > a.token_budget: + print('STOP:budget — reported usage exceeded budget in this round') + return 2 + if remaining == 0: + print('RALPH_DONE: all items verified against the original criteria') + return 0 + if used >= a.token_budget or no_progress >= 2: + print('STOP:budget' if used >= a.token_budget else 'STOP:no-progress') + return 2 + print('STOP:max-rounds — no extra round launched') + return 2 + except (OSError, ValueError, TypeError) as exc: + print(f'BLOCK: {exc}', file=sys.stderr) + return 3 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/bin/result_record.py b/bin/result_record.py new file mode 100644 index 0000000..83f0b61 --- /dev/null +++ b/bin/result_record.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Explicit, human-judged result adapter for mirror-stack-mcp >=0.2.14. + +Requires status, evidence summary file, and an explicit action ledger. Never +publishes anything or infers scientific success from a deliberation verdict. +""" +import argparse +import json +import sys +from pathlib import Path +from prereg_check import resolve, read_verified + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('arc', type=Path) + p.add_argument('--status', required=True, choices=['pass', 'fail', 'inconclusive']) + p.add_argument('--summary-file', required=True, type=Path) + p.add_argument('--am-ledger', required=True, type=Path) + a = p.parse_args() + try: + from actmirror import am + from mirror_stack_mcp.gate import decide + from mirror_stack_mcp.integrity import read_verified as mirror_read_verified + binding, _ = resolve(a.arc) + if not binding: + raise ValueError('a verified pinned preregistration is required') + summary = a.summary_file.read_text(encoding='utf-8').strip() + if not summary: + raise ValueError('empty result summary') + if a.am_ledger.resolve() == Path(binding['ledger']).resolve(): + raise ValueError('claims and actions must use separate ledgers') + if a.am_ledger.exists(): + read_verified(a.am_ledger) + entry = am.record(str(a.am_ledger), agent='yeoul', action='result', + target=binding['claim_id'], + payload={'status': a.status, 'summary': summary, + 'prereg_seal': binding['seal']}, content=summary) + entries, error = mirror_read_verified(a.am_ledger) + if error or not any(e.get('seal') == entry['seal'] for e in entries): + raise ValueError(f'result was written but could not be verified: {error}') + decision = decide(binding['ledger'], binding['claim_id'], gate='publish', + am_ledger=str(a.am_ledger)) + print(json.dumps({'result_seal': entry['seal'], 'publication_gate': decision, + 'published': False}, ensure_ascii=False)) + return 0 if decision['decision'] == 'GO' else 1 + except (ImportError, OSError, ValueError, TypeError, KeyError) as exc: + print(f'result recording refused: {exc}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/bin/status b/bin/status index f1e686d..f85ef80 100755 --- a/bin/status +++ b/bin/status @@ -22,6 +22,9 @@ _trunc100() { verdict_of() { local proj="$1" local s + local active + active="$(find "$proj/design/arcs" -type f -path '*/ARC/*.md' -not -path '*/_archive/*' 2>/dev/null | wc -l | tr -d ' ' || true)" + if [ "${active:-0}" -gt 0 ]; then echo "IN-PROGRESS ($active active arcs; archived verdict is historical)"; return; fi s="$(ls -t "$proj"/design/arcs/_archive/*/_SUMMARY_*.md 2>/dev/null | head -1 || true)" [ -n "$s" ] || { echo "-"; return; } grep -m1 'Verdict' "$s" 2>/dev/null | sed -E 's/^[[:space:]]*-[[:space:]]*(\*\*)?Verdict(\*\*)?:[[:space:]]*//' | _trunc100 || echo "-" diff --git a/bin/verify-baseline b/bin/verify-baseline new file mode 100755 index 0000000..4311c56 --- /dev/null +++ b/bin/verify-baseline @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +# Supervisor action: freeze the reviewed TODO before giving it to a worker. +. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/_pybin.sh" +PY="$(yeoul_pybin)" || yeoul_pybin_die +exec "$PY" "$(dirname "${BASH_SOURCE[0]}")/verify_core.py" baseline "$@" diff --git a/bin/verify-gate b/bin/verify-gate index 8572ce2..5307c72 100755 --- a/bin/verify-gate +++ b/bin/verify-gate @@ -1,58 +1,5 @@ #!/usr/bin/env bash -set -uo pipefail -# verify-gate [--revert] [--require-verify] -# Harness-enforced verify gate. For every checked item (`- [x]` … verify: `CMD`), the harness -# RE-RUNS CMD itself (cwd = current dir) — it does not trust the agent's claim that verify passed. -# With --revert, any item whose command exits != 0 is flipped back to `- [ ]`. -# Exit 0 = every checked item's verify passed · non-zero = at least one failed. -# -# --require-verify: a checked item with NO `verify:` clause counts as a failure too. -# Why it exists: without it the gate keys on text the agent itself writes, so deleting the -# `verify:` clause while ticking the box made the item invisible to the gate and it survived -# unverified (observed, not hypothetical). `ralph` always passes this flag — its eligibility gate -# has already established that every item in a loop-driven TODO carries a verify command. -# Default stays off so a mixed TODO (loop items + manual items) can still be scanned standalone. - -# Resolve the interpreter by running one — `command -v python3` also finds the Windows Store stub. +set -euo pipefail . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/_pybin.sh" PY="$(yeoul_pybin)" || yeoul_pybin_die - -TODO="${1:-}"; REVERT=0; REQUIRE=0 -for a in "${@:2}"; do case "$a" in - --revert) REVERT=1 ;; - --require-verify) REQUIRE=1 ;; -esac; done -[ -n "$TODO" ] && [ -f "$TODO" ] || { echo "usage: verify-gate [--revert] [--require-verify]" >&2; exit 2; } - -FAIL=0; TMP="$TODO.vg.$$" -: > "$TMP" -while IFS= read -r line || [ -n "$line" ]; do - if [ "$REQUIRE" -eq 1 ] && printf '%s' "$line" | grep -q '^- \[x\]' \ - && ! printf '%s' "$line" | grep -qE 'verify:[[:space:]]*`[^`]+`'; then - # checked but carries no verify command — the gate has nothing to re-run, so it cannot vouch - # for this box. Treat as failed rather than skipping it (skipping is how the clause-deletion - # bypass worked). - FAIL=1 - echo " ✗ checked item has no verify command: ${line:0:60}…" >&2 - if [ "$REVERT" -eq 1 ]; then - line="$(printf '%s' "$line" | sed 's/^- \[x\]/- [ ]/')" - echo " ↩ reverted to [ ] (nothing for the harness to verify)" >&2 - fi - elif printf '%s' "$line" | grep -qE '^- \[x\].*verify:[[:space:]]*`[^`]+`'; then - # extract the FIRST verify block via python (sed's greedy `.*verify:` grabbed the LAST block, - # letting an appended decoy `verify: `true`` override a real failing command). - cmd="$(printf '%s' "$line" | $PY -c 'import sys,re; m=re.search(r"verify:\s*`([^`]+)`", sys.stdin.read()); sys.stdout.write(m.group(1) if m else "")')" - if ! bash -c "$cmd" >/dev/null 2>&1; then - FAIL=1 - short="$(printf '%s' "$line" | sed -E 's/^(- \[x\][^:]{0,50}).*/\1/')" - echo " ✗ verify FAILED: ${short}… ($cmd)" >&2 - if [ "$REVERT" -eq 1 ]; then - line="$(printf '%s' "$line" | sed 's/^- \[x\]/- [ ]/')" - echo " ↩ reverted to [ ] (harness re-ran verify; it did not pass)" >&2 - fi - fi - fi - printf '%s\n' "$line" >> "$TMP" -done < "$TODO" -mv "$TMP" "$TODO" -exit "$FAIL" +exec "$PY" "$(dirname "${BASH_SOURCE[0]}")/verify_core.py" verify "$@" diff --git a/bin/verify_core.py b/bin/verify_core.py new file mode 100644 index 0000000..6f25dbb --- /dev/null +++ b/bin/verify_core.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Shared CLI/MCP/Ralph verification. Baselines belong to the supervisor. + +Only checkbox state may change. This is workflow integrity, not an OS sandbox. +Protect standalone baseline files and test implementations from worker writes. +""" +import argparse +import json +import math +import os +import re +import signal +import subprocess +import sys +import tempfile +from pathlib import Path + +ITEM = re.compile(r'^- \[([ x])\] (.*)$') +VERIFY = re.compile(r'verify:\s*`([^`]+)`') + + +def canonical(text): + return re.sub(r'(?m)^- \[[ x]\]', '- [ ]', text) + + +def eligible(text): + rows = [line for line in text.splitlines() if ITEM.match(line)] + malformed = any(line.startswith('- [') and not ITEM.match(line) for line in text.splitlines()) + return bool(rows) and not malformed and all(VERIFY.search(line) for line in rows) + + +def atomic_write(path, text): + path = Path(path) + with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent, + prefix='.'+path.name, delete=False) as stream: + temp = Path(stream.name) + stream.write(text) + try: + temp.replace(path) + finally: + temp.unlink(missing_ok=True) + + +def execute(args, *, cwd=None, timeout=120, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL): + # POSIX timeout kills this child group only. Windows falls back to direct-child termination. + with subprocess.Popen(args, cwd=cwd, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr, + start_new_session=os.name == 'posix') as child: + try: + return child.wait(timeout=timeout) + except subprocess.TimeoutExpired: + if os.name == 'posix': + try: + os.killpg(child.pid, signal.SIGKILL) + except ProcessLookupError: + pass + else: + child.kill() + child.wait() + return 124 + + +def verify(todo, *, baseline=None, revert=False, require=False, timeout=120): + path = Path(todo) + text = path.read_text(encoding='utf-8') + if baseline is not None and canonical(text) != canonical(baseline): + print('BLOCK: TODO criteria/commands/items changed from the approved baseline', file=sys.stderr) + if revert: + atomic_write(path, canonical(baseline)) + return 3 + failed = False + output = [] + for line in text.splitlines(keepends=True): + item = ITEM.match(line.rstrip('\r\n')) + command = VERIFY.search(line) + if item and item[1] == 'x' and (command or require): + rc = execute([os.environ.get('YEOUL_BASH', 'bash'), '-c', command[1]], timeout=timeout) if command else 1 + if rc: + print(f'verify failed (exit {rc}): {line.strip()}', file=sys.stderr) + failed = True + if revert: + line = line.replace('- [x]', '- [ ]', 1) + output.append(line) + if path.read_text(encoding='utf-8') != text: + print('BLOCK: TODO changed during verification', file=sys.stderr) + return 3 + if revert and failed: + atomic_write(path, ''.join(output)) + return int(failed) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('mode', choices=['check', 'baseline', 'verify']) + p.add_argument('todo', type=Path) + p.add_argument('--baseline', type=Path) + p.add_argument('--current-only', action='store_true', help='manual diagnostic; no criterion protection') + p.add_argument('--require-verify', action='store_true') + p.add_argument('--revert', action='store_true') + p.add_argument('--timeout', type=float, default=120) + a = p.parse_args() + try: + if not math.isfinite(a.timeout) or a.timeout <= 0: + raise ValueError('timeout must be positive') + text = a.todo.read_text(encoding='utf-8') + if a.mode == 'check': + if not eligible(text): + print('not loop-eligible: require at least one item, each with a nonempty backtick verify command') + return 3 + print('loop-eligible: all items have verify commands (criteria not judged)') + return 0 + bp = a.baseline or Path(str(a.todo)+'.verify-baseline.json') + if a.mode == 'baseline': + if not eligible(text): + raise ValueError('cannot approve an empty or ungated TODO') + with bp.open('x', encoding='utf-8') as stream: + json.dump({'version': 1, 'todo': str(a.todo.resolve()), 'text': canonical(text)}, stream) + print(f'baseline created: {bp}; keep it outside the worker write scope') + return 0 + baseline = None + if a.current_only: + print('scope: current commands only; criterion changes NOT checked', file=sys.stderr) + else: + data = json.loads(bp.read_text(encoding='utf-8')) + if data.get('version') != 1 or data.get('todo') != str(a.todo.resolve()): + raise ValueError('baseline version/path mismatch') + baseline = data['text'] + if not isinstance(baseline, str) or not eligible(baseline): + raise ValueError('invalid baseline') + return verify(a.todo, baseline=baseline, revert=a.revert, + require=a.require_verify, timeout=a.timeout) + except (OSError, ValueError, KeyError, TypeError) as exc: + print(f'BLOCK: {exc}', file=sys.stderr) + return 3 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/bin/yeoul-new b/bin/yeoul-new index adef0c2..d02ce37 100755 --- a/bin/yeoul-new +++ b/bin/yeoul-new @@ -57,7 +57,7 @@ cat > "$STAGE/README.md" << MDEOF - design (incubation): [design/](design/) — spec · deliberation arcs · summaries - dev: [dev/](dev/) -- when mature: \`yeoul-graduate $NAME\`. +- when mature: \`graduate $NAME\` (supervisor decision). MDEOF # everything rendered; publish the staged tree in one move, then stop cleaning it up. diff --git a/docs/BOOTSTRAP_PROMPT.md b/docs/BOOTSTRAP_PROMPT.md index 9599763..ca394a2 100644 --- a/docs/BOOTSTRAP_PROMPT.md +++ b/docs/BOOTSTRAP_PROMPT.md @@ -13,7 +13,7 @@ integrity gates. Read docs/METHODOLOGY.md, then adopt these operating rules for SETUP - Yeoul CLI is in ./bin (or on PATH). Projects live under ./projects (or $YEOUL_PROJECTS). - If the `mirror-stack` MCP is available, use it to pre-register kill-conditions and seal closures. If not, - proceed without sealing (note that sealing is a no-op) — do not fabricate seals. + proceed with attestation-only discussion (recording unavailable) — do not fabricate seals. WORKFLOW (follow docs/METHODOLOGY.md) - New idea: run `yeoul-new `, then interview me one spec item at a time, cheapest rejection first. @@ -30,7 +30,8 @@ HARD RULES (do not violate — these are the point of the tool) (amend, don't overwrite). Record negatives and retractions indelibly. - Never automate: pre-registration sealing, PASS/KILL judgment, graduation, external publishing. Those are mine. - In the dev loop, only check off a TODO item after its verify command exits 0; never edit or delete verify - commands. Run `verify_gate` (or `bin/verify-gate --revert --require-verify`) after every round — + commands. Have the supervisor create and protect a `verify-baseline` before work. + Baseline approval is not a worker action. Run `verify_gate` (or `bin/verify-gate --revert --require-verify`) after every round — in backend A that is your job, not the loop's. - Separate the tool from your judgment: only say "a gate refused X" when a script/tool actually returned an error you can quote; say "applying the discipline, I suspect X" for your own reasoning. Never borrow the diff --git a/docs/INTEGRITY.md b/docs/INTEGRITY.md new file mode 100644 index 0000000..1d5846d --- /dev/null +++ b/docs/INTEGRITY.md @@ -0,0 +1,142 @@ +# Integrity contract and v0.3 migration + +Yeoul is a supervised deliberation/development harness, not a proof of scientific +truth or a security sandbox. A passed command proves only what that command tests. +Different role names do not establish independent evidence or independent models. + +## Deliberation and measurement are different + +Unbound discussion arcs remain supported. They close as **attestation-only**, not +as verified research. There is no preregistration-attachment quota for discussion. +Measurement requires its own preregistration and explicit result evidence. + +## Preregistration binding + +`arc-prereg ARC CLAIM LEDGER` first checks the four substantive spec fields, then +records a binding after verifying a complete ledger snapshot. The ledger is also +checked before the spec is judged; invalid input never acquires a link. + +- Every record's MIRROR-SPEC SHA-256 content hash and `prev_seal` link is checked. +- Missing, empty, malformed, duplicate-key and tampered ledgers are refused. +- The first registration wins. A later duplicate cannot repair or replace it. +- Text `kill_condition` or a nonempty structured `kill_threshold` is supported. +- `.prereg` contains claim ID, absolute ledger path and the first registration seal. + `STATE.md` records `PREREG_BOUND` with the same binding. Later valid ledger entries + are allowed; replacing the registration or removing the link is refused. +- `arc-close` rechecks the ledger and binding on every call. Legacy 16-hex hashes + are accepted for compatibility but have weaker collision resistance. + +**Scope:** hash integrity and local binding only. Identity signatures, external +time, content truth and independent reproduction are not verified by Yeoul. +An owner who can rewrite the entire ledger AND all arc files can rewrite local +history. Keep an external anchor/access boundary when that threat matters. + +### Existing arcs + +No existing arc or ledger is rewritten automatically. An old two-line `.prereg` +is **unbound**, not newly certified. Review the original ledger and explicitly run +`arc-prereg ARC SAME_CLAIM SAME_LEDGER` to verify and pin it. If the ledger fails +verification, recover the original evidence; do not rehash damaged data as a repair. +A genuinely different registration belongs in a new arc. Previously archived +records keep their historical meaning; this release does not retroactively certify them. + +## Closure lifecycle + +`In-Progress` -> `Close-Pending` (draft) -> `Closed` (archived). + +A refusal stays pending. Drafting is not closure. Required defense fields cannot +be deleted to evade checks; verdict/stop metadata must match the requested close. +The archive destination must be absent, and a close lock prevents concurrent calls +on the same active arc. After an interrupted call, inspect `.close.lock` before +removing the stale lock and retrying. Do not edit a live call's lock. + +`STATE.md` separately records `ARCHIVE_RECORD recorded|file-only|record-failed`. +Optional `am` recording is best-effort and does not decide the discussion verdict. +`recorded` means the recorder returned success, not independently reproduced truth. +`status` shows active arcs ahead of historical archived verdicts; TODO counts are +checkbox counts, not a new verification run. The knowledge index is a derived +view, not an authoritative proof store. Default index: current workspace's +`KNOWLEDGE_INDEX.md`; override with `YEOUL_INDEX`. + +## Development verification + +Supervisor setup, **before** handing the TODO to a worker: + +```bash +mkdir -p supervisor +verify-baseline projects/example/dev/TODO.md --baseline=supervisor/example-baseline.json +``` + +After each worker round: + +```bash +verify-gate projects/example/dev/TODO.md --baseline=supervisor/example-baseline.json --revert --require-verify +``` + +Only checkbox state may change. Modified commands, reordered/deleted/added items +or changed criteria are refused **before** command execution. On `--revert`, a +criterion mismatch restores the original TODO with its boxes unchecked. Default +baseline path is `TODO.md.verify-baseline.json`; creating an existing baseline is +refused. Baseline approval is a supervisor action, not an automatic MCP tool. +Criteria changes require explicit review and a new baseline path. + +Keep the standalone baseline and verification implementations outside the worker's +write permissions. A directory name alone does not enforce that boundary. +`--current-only` is an explicit manual diagnostic that prints its weaker scope; +it is not protected verification and is not exposed by the MCP verification tool. + +Ralph captures the approved TODO in **parent process memory**, checks already +checked items, and uses that same snapshot through all rounds. `ralph NAME --check` +is read-only: it checks every item's syntax but runs no agent or verification +command. The MCP eligibility tool calls this exact path, including `YEOUL_PROJECTS`. + +Ralph never launches an extra round beyond `--max-rounds`. Logs live in a unique +`dev/ralph_log/run-*` directory per invocation; reruns do not overwrite earlier evidence. +Agent and verification +commands have `--round-timeout` and `--verify-timeout` limits (seconds, default 120). +Token usage is counted from the backend's JSON `usage.input_tokens/output_tokens`; +missing/invalid counts stop as **unmeasured**, not zero. The token budget is a +between-round limit, not a hard provider spending cap: one round can exceed it. +Backend-reported usage is not an independently audited bill. POSIX timeouts kill +the child process group; Windows fallback terminates the direct child only. + +## Explicit Mirror result handoff + +Ordinary `arc-close` records remain discussion events. They are not automatically +converted into results and do not satisfy Mirror's publication gate. + +With `mirror-stack-mcp >=0.2.14` and its compatible `action-mirror` installed: + +```bash +arc-result ARC --status=fail --summary-file=observations/result.md --am-ledger=actions.jsonl +``` + +The supervisor must choose `pass`, `fail` or `inconclusive` and provide evidence. +This writes `action=result`, `target=claim_id`, and payload `status`, `summary`, +`prereg_seal`; it verifies the recorded chain and reports Mirror's publish decision. +It does **not** publish anything. A negative result may legitimately receive +publication GO; GO does not mean the hypothesis succeeded. Records are append-only: +if a post-write check fails, inspect the reported error and ledger before retrying. + +## Installation and verification + +Python >=3.10 and Bash are required (Windows: install Git Bash). The MCP server +uses Git Bash rather than the Windows System32 WSL launcher. Set `YEOUL_BASH` to a +custom Bash executable if discovery is insufficient. Wheels and sdists +include the scripts and spec templates; `YEOUL_BIN` is only an explicit override +for a custom checkout. Test an installed wheel from outside the source directory. +Both source and packaged paths are covered in CI. Commands execute with the +caller's workspace as cwd. CLI scripts are available from a checkout's `bin/`; +installing the Python package provides `yeoul-mcp`, not every CLI name on PATH. + +```bash +bash tests/test_gates.sh +python3 tests/test_hardening.py +python3 mcp/tests/test_run_contract.py +python3 mcp/tests/test_serverinfo_version.py +python3 mcp/tests/test_surface_contract.py # requires the compatible Mirror installation +``` + +Tests use temporary projects, indexes and action ledgers. Never use production +ledgers as fixtures. Cross-platform CI results should be read per platform; +a local Linux pass does not establish Windows/macOS behavior. diff --git a/docs/METHODOLOGY.md b/docs/METHODOLOGY.md index 0b4d848..7dbe41b 100644 --- a/docs/METHODOLOGY.md +++ b/docs/METHODOLOGY.md @@ -45,16 +45,16 @@ self-critique your own proposal · run the 7-check before concluding · don't cl ## ④ Convergence Each round, the relay summarizes and judges. **Every round summary must include 3 lines:** -- **Re-anchor** — still consistent with the spec's success- and kill-conditions? (deliberation drifts 76–89%) -- **Flip log** — who changed position, which direction (right→wrong / wrong→right)? (sycophantic flips are mostly right→wrong) +- **Re-anchor** — still consistent with the spec's success- and kill-conditions? (deliberation can drift) +- **Flip log** — who changed position, which direction (right→wrong / wrong→right)? (record evidence for the change, not agreement alone) - **Consensus quality** — unanimity with no initial disagreement is an **⚠️ alarm** (suspected sycophancy), not a convergence credit; overturning a *wrong* consensus is a credit. `bin/loop-guard` bounds runaway (max-rounds / token-budget / no-progress). Convergence itself is a semantic -call, not the guard's job. **More rounds do not improve quality** — the guards exist because debate drifts. +call, not the guard's job. **More rounds alone do not establish quality** — the guards exist because debate drifts. Close with `bin/arc-close` (2-phase): it drafts a summary; you fill the blanks; re-running seals only when -they're filled. A **falsified/KILL** close (and only that close) additionally requires the **🛡️ KILL-defense 5-check**: +they're filled. Archival and optional action recording have separate states. A **falsified/KILL** close (and only that close) additionally requires the **🛡️ KILL-defense 5-check**: anchor (positive control) reproduced · ≥2 independent angles converged · implementation defect ruled out · catalog cross-check · verbatim kill-wording. This is the anti-premature-closure gate. @@ -62,7 +62,8 @@ catalog cross-check · verbatim kill-wording. This is the anti-premature-closure linked it to the arc (`bin/arc-prereg [ledger]`), the check no longer asks the agent to *type* whether the verdict matches the pre-registration. Instead the harness reads the sealed kill-condition from the ledger and **injects it verbatim** into the record; on close it refuses if that line was edited or -removed. The agent is not the author of the condition, so it cannot be silently widened at close. +removed. v0.3 also verifies all ledger hashes/links and pins the first registration seal. +A mismatched or removed binding is refused; rewriting all local files is outside this trust boundary. This injection is **independent of how the close is labelled**. That matters more than it sounds: the label (`--stop`, the verdict string) is written by the closing agent at closing time, so keying the anchor to it @@ -95,27 +96,24 @@ Run the dev loop two ways (Ralph pattern): - **(A) in-session** — the session drives each round with a subagent: implement the top item → run its `verify:` command → check off only on exit 0 → re-verify prior items. Preferred; no nesting. - **(B) unattended** — `bin/ralph ` from a terminal (it shells out to a headless agent CLI, so it - can't run inside that same agent). Bounded by loop-guard. + can't run inside that same agent). Bounded by the supervisor's in-memory round and reported-token counters. **Loop-forbidden (belongs to the human/session):** measurement runs, sealing, PASS/KILL judgment. The loop's safety comes from the machine-verification gate, not from the loop — it is only as good as your verify commands. +Before backend A starts, the supervisor runs `bin/verify-baseline ` (or supplies +`--baseline=PROTECTED_PATH`). Keep the baseline and test implementations outside worker write access. + The gate is **harness-enforced, not requested**: after each round the harness runs `bin/verify-gate --revert --require-verify`, which independently re-runs the `verify:` command of every checked item and flips any that don't exit 0 back to `[ ]`. `ralph` does this automatically; **in backend A the session must run it too** (MCP: the `verify_gate` tool) — otherwise nothing has been verified but the agent's word. -Scope, honestly: the gate keys on the `verify:` clause, which lives in a file the agent can edit. Deleting the -clause while ticking the box used to make the item invisible to the gate, so it survived unverified. That is what -`--require-verify` closes — a checked item with no verify clause is now reverted too, and `ralph` refuses a TODO -where any item lacks the clause. What remains outside the machine's reach is the *content* of a verify command: -a command that does not actually test the item will still exit 0. Write commands that can fail. - -## Exits -- **graduate** (success): `bin/graduate` → moves the project out of the incubator, leaves a pointer. -- **close-project** (retire/reject): `bin/close-project` → archives with a `_CLOSED.md`, freezes open arcs, - optionally seals the closure. History is preserved — no silent deletion. +Scope: the approved TODO, including commands and criteria, is frozen before work. Ralph keeps +that snapshot in parent memory; standalone verification requires the supervisor's baseline file. +Only checkbox changes are accepted. A verifier that was inadequate at approval time remains +inadequate, and an agent with access to the test implementations can still weaken those tests. +This is not an OS sandbox or an independent proof of scientific results. -## Invariant checkpoints (never automate) -Graduation, closing, and any irreversible/outward action are human confirmations. The loop runtimes are -borrowed; the honesty gates are yours. +See [integrity and migration](INTEGRITY.md) for legacy preregistration upgrades, timeouts, +unknown token usage, packaged installation, and the explicit `arc-result` measurement bridge. diff --git a/examples/demo.sh b/examples/demo.sh index 7fc9b8c..9085422 100755 --- a/examples/demo.sh +++ b/examples/demo.sh @@ -8,6 +8,7 @@ BIN="$(cd "$(dirname "${BASH_SOURCE[0]}")/../bin" && pwd)" WS="$(mktemp -d)"; trap 'rm -rf "$WS"' EXIT cd "$WS" export YEOUL_PROJECTS="$WS/projects" +export AM_LEDGER="$WS/actions.jsonl" YEOUL_INDEX="$WS/index.md" echo "### workspace: $WS" echo @@ -30,7 +31,7 @@ sedi 's/^- \*\*Independent.*/- **Independent angles converged**: 2 independent m sedi 's/^- \*\*Implementation.*/- **Implementation defect ruled out**: cache logic reviewed, not a bug (demo)/' "$SUM" sedi 's/^- \*\*Catalog.*/- **Catalog cross-check**: none (demo)/' "$SUM" sedi 's/^- \*\*Kill wording.*/- **Kill wording match**: matches the pre-registered kill-condition verbatim (demo)/' "$SUM" -echo -n " filled + re-run: "; "$BIN/arc-close" "$ARC" "KILL — no speedup" --stop=falsified >/dev/null 2>&1 && echo "SEALED + archived" || echo "still refused" +echo -n " filled + re-run: "; "$BIN/arc-close" "$ARC" "KILL — batching showed no speedup" --stop=falsified >/dev/null && echo "ARCHIVED (recording state reported separately)" echo echo "### 3) (parallel) a GO project → dev handoff → verify-gate" diff --git a/mcp/README.md b/mcp/README.md index 4a59ec1..c349203 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -19,7 +19,9 @@ pip install git+https://github.com/mirror-stack/yeoul#subdirectory=mcp yeoul-mcp # stdio server ``` -Set `YEOUL_BIN` if the `bin/` scripts are not adjacent to the package. +v0.3.0 wheels and sdists bundle the harness and templates. Python >=3.10 and Bash +(Git Bash on Windows) are required. `YEOUL_BIN` overrides the bundled scripts only +when explicitly pointing to a custom checkout. No checkout is needed for the default MCP setup. ## Tools @@ -30,9 +32,19 @@ Set `YEOUL_BIN` if the `bin/` scripts are not adjacent to the package. linking a seal (so `arc_close` injects the kill-condition verbatim) and re-running a round's verify commands. An agent driving Yeoul purely through MCP could not run either — so neither gate held on that path. -Each returns `{exit_code, stdout, stderr}`. A non-zero `exit_code` on `arc_close` (4 = blanks, 5 = KILL-defense) +Each returns `{exit_code, stdout, stderr}`. Always inspect `exit_code`; a delivered MCP response is not a passing gate. +A non-zero `exit_code` on `arc_close` (4 = blanks, 5 = defense/binding, 8 = record mismatch, 9 = close/archive conflict) or `ralph_gate_check` (3 = ungated item) is an enforced gate, not an error to route around. +`ralph_gate_check` is read-only and calls the same CLI eligibility path. `verify_gate` +requires a supervisor-created baseline (optional `baseline_path`; default +`TODO.md.verify-baseline.json`). Create it with the CLI `verify-baseline` before work. +It is deliberately not a worker-facing MCP approval tool. Missing token counts in +`loop_guard_tick` stay unmeasured rather than becoming zero. + +See [integrity and migration](../docs/INTEGRITY.md) for the complete contract and +the explicit `arc-result` CLI bridge to Mirror. Closing an arc never publishes a result. + ## Language rule A tool result is what the *script* reported. Do not present your own judgment as a tool verdict — say "a gate diff --git a/mcp/pyproject.toml b/mcp/pyproject.toml index 0fa6da5..6f6c8bf 100644 --- a/mcp/pyproject.toml +++ b/mcp/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "yeoul-mcp" -version = "0.2.0" +version = "0.3.0" description = "Gate-enforcing MCP tools over the Yeoul harness (deliberation → pre-registration → dev loop). Composes with mirror-stack." requires-python = ">=3.10" license = { text = "Apache-2.0" } @@ -27,3 +27,6 @@ build-backend = "setuptools.build_meta" [tool.setuptools] packages = ["yeoul_mcp"] + +[tool.setuptools.package-data] +yeoul_mcp = ["_harness/bin/*", "_harness/templates/*", "_harness/LICENSE"] diff --git a/mcp/setup.py b/mcp/setup.py new file mode 100644 index 0000000..8a8e9e7 --- /dev/null +++ b/mcp/setup.py @@ -0,0 +1,36 @@ +"""Bundle the canonical harness into wheels AND sdists without maintaining a second copy.""" +from pathlib import Path +import shutil +from setuptools import setup +from setuptools.command.build_py import build_py +from setuptools.command.sdist import sdist + +HERE = Path(__file__).resolve().parent + + +def bundle(destination): + source = HERE.parent if (HERE.parent / 'bin' / 'arc-close').is_file() else HERE / 'yeoul_mcp' / '_harness' + for directory in ('bin', 'templates'): + target = Path(destination) / directory + target.mkdir(parents=True, exist_ok=True) + for file in (source / directory).iterdir(): + if file.is_file() and not file.name.startswith('_t_'): + shutil.copy2(file, target / file.name) + if directory == 'bin': + (target / file.name).chmod(0o755) + shutil.copy2(source / 'LICENSE', Path(destination) / 'LICENSE') + + +class BuildHarness(build_py): + def run(self): + super().run() + bundle(Path(self.build_lib) / 'yeoul_mcp' / '_harness') + + +class SourceHarness(sdist): + def make_release_tree(self, base_dir, files): + super().make_release_tree(base_dir, files) + bundle(Path(base_dir) / 'yeoul_mcp' / '_harness') + + +setup(cmdclass={'build_py': BuildHarness, 'sdist': SourceHarness}) diff --git a/mcp/tests/test_run_contract.py b/mcp/tests/test_run_contract.py index bca76b2..179fdc2 100644 --- a/mcp/tests/test_run_contract.py +++ b/mcp/tests/test_run_contract.py @@ -121,6 +121,9 @@ def test_missing_script_is_not_a_pass(tmp): def main(): print("mcp _run contract tests") with tempfile.TemporaryDirectory() as tmp: + # Test helpers belong to the test workspace, never the installed package/repo. + server.BIN = Path(tmp) + os.environ['YEOUL_BIN'] = tmp test_stdin_not_inherited(tmp) test_utf8_pinned_under_hostile_locale(tmp) test_missing_script_is_not_a_pass(tmp) diff --git a/mcp/tests/test_surface_contract.py b/mcp/tests/test_surface_contract.py new file mode 100644 index 0000000..7db26e5 --- /dev/null +++ b/mcp/tests/test_surface_contract.py @@ -0,0 +1,97 @@ +"""CLI/MCP decisions and Mirror result interoperability. No production writes.""" +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT/'mcp')) +sys.path.insert(0, str(ROOT/'bin')) +sys.path.insert(0, str(ROOT/'tests')) +from yeoul_mcp import server +from prereg_check import bind, read_verified +from test_hardening import ledger + + +class Surface(unittest.TestCase): + def test_windows_prefers_git_bash_and_rejects_wsl_launcher(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + shell = root/'Git'/'bin'/'bash.exe' + shell.parent.mkdir(parents=True) + shell.touch() + git = root/'Git'/'cmd'/'git.exe' + with patch.dict(os.environ, {}, clear=True), patch.object(server.shutil, 'which', return_value=str(git)): + self.assertEqual(server.bash_command('win32'), str(shell)) + with patch.dict(os.environ, {}, clear=True), patch.object(server.shutil, 'which', + side_effect=lambda cmd: None if cmd == 'git' else 'C:/Windows/System32/bash.exe'): + with self.assertRaises(FileNotFoundError): + server.bash_command('win32') + with patch.dict(os.environ, {'YEOUL_BASH':'explicit-bash'}): + self.assertEqual(server.bash_command('win32'), 'explicit-bash') + + def test_cli_mcp_eligibility_and_nondefault_projects_root(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + projects = root/'custom-projects' + dev = projects/'p'/'dev' + dev.mkdir(parents=True) + for content, expected in [('', 3), ('- [x] no command\n', 3), + ('- [ ] malformed. verify:\n', 3), + ('- [ ] good. verify: `true`\n', 0)]: + with self.subTest(content=content), patch.dict(os.environ, {'YEOUL_PROJECTS':str(projects)}): + (dev/'TODO.md').write_text(content) + result = server.ralph_gate_check('p', workspace=tmp) + self.assertEqual(result['exit_code'], expected, result) + self.assertFalse((dev/'ralph_log').exists(), 'dry check must not create loop state') + + def test_mcp_missing_usage_is_unmeasured(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(server.loop_guard_init(tmp)['exit_code'], 0) + result = server.loop_guard_tick(tmp) + self.assertIn('STOP:unmeasured', result['stdout']) + + def test_result_adapter_matches_mirror_publish_contract(self): + from mirror_stack_mcp.gate import decide + from mirror_stack_mcp.integrity import read_verified as mirror_verified + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + arc = root/'arc' + arc.mkdir() + claims = root/'claims.jsonl' + row = dict(claim_id='c1', metric='m', kill_condition='effect size d < 0.2 over 3 seeds') + ledger(claims, [row]) + bind(arc, 'c1', claims) + self.assertEqual(read_verified(claims), mirror_verified(claims)[0]) + summary = root/'result.md' + summary.write_text('Measured d = 0.05; preregistered effect was not observed.') + for status in ('pass', 'fail', 'inconclusive'): + with self.subTest(status=status): + actions = root/(status+'.jsonl') + result = subprocess.run([sys.executable, str(ROOT/'bin'/'result_record.py'), str(arc), + '--status', status, '--summary-file', str(summary), + '--am-ledger', str(actions)], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout+result.stderr) + self.assertFalse(json.loads(result.stdout)['published']) + entry = read_verified(actions)[0] + self.assertEqual(entry['action'], 'result') + self.assertEqual(entry['payload']['status'], status) + self.assertEqual(decide(claims, 'c1', gate='publish', am_ledger=actions)['decision'], 'GO') + + def test_action_close_is_not_a_measurement_result(self): + from actmirror import am + from mirror_stack_mcp.gate import decide + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + claims, actions = root/'claims.jsonl', root/'actions.jsonl' + ledger(claims, [dict(claim_id='c1', kill_condition='stop at the preregistered bar')]) + am.record(str(actions), agent='test', action='arc-close', target='c1') + self.assertEqual(decide(claims, 'c1', gate='publish', am_ledger=actions)['decision'], 'BLOCK') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/mcp/yeoul_mcp/__init__.py b/mcp/yeoul_mcp/__init__.py index 5a54876..da52943 100644 --- a/mcp/yeoul_mcp/__init__.py +++ b/mcp/yeoul_mcp/__init__.py @@ -1,2 +1,2 @@ """Yeoul MCP — gate-enforcing tools over the Yeoul harness.""" -__version__ = "0.2.0" +__version__ = "0.3.0" diff --git a/mcp/yeoul_mcp/server.py b/mcp/yeoul_mcp/server.py index d93f3c4..894b5b8 100644 --- a/mcp/yeoul_mcp/server.py +++ b/mcp/yeoul_mcp/server.py @@ -11,7 +11,8 @@ """ from __future__ import annotations import os -import shlex +import shutil +import signal import subprocess import sys from pathlib import Path @@ -40,7 +41,33 @@ from yeoul_mcp import __version__ mcp._mcp_server.version = __version__ -BIN = Path(os.environ.get("YEOUL_BIN", Path(__file__).resolve().parents[2] / "bin")) +_BUNDLED = Path(__file__).resolve().parent / "_harness" / "bin" +BIN = Path(os.environ.get("YEOUL_BIN", _BUNDLED if _BUNDLED.is_dir() + else Path(__file__).resolve().parents[2] / "bin")) + + +def bash_command(platform: str | None = None) -> str: + """Prefer Git Bash on Windows; System32/bash.exe is a WSL launcher, not this runtime.""" + if os.environ.get('YEOUL_BASH'): + return os.environ['YEOUL_BASH'] + if (platform or sys.platform) != 'win32': + return 'bash' + candidates = [] + git = shutil.which('git') + if git: + candidates += [Path(git).parent.parent/'bin'/'bash.exe', + Path(git).parent.parent/'usr'/'bin'/'bash.exe'] + for key in ('ProgramFiles', 'ProgramFiles(x86)', 'LOCALAPPDATA'): + if os.environ.get(key): + base = Path(os.environ[key]) + candidates += [base/'Git'/'bin'/'bash.exe', base/'Programs'/'Git'/'bin'/'bash.exe'] + for candidate in candidates: + if candidate.is_file(): + return str(candidate) + found = shutil.which('bash') + if found and 'system32' not in found.lower() and 'windowsapps' not in found.lower(): + return found + raise FileNotFoundError('Git Bash not found; install Git for Windows or set YEOUL_BASH to its bash.exe') def _run(script: str, *args: str, cwd: str | None = None, stdin: str | None = None) -> dict: @@ -48,8 +75,11 @@ def _run(script: str, *args: str, cwd: str | None = None, stdin: str | None = No path = BIN / script if not path.exists(): return {"exit_code": 127, "stdout": "", "stderr": f"script not found: {path}"} - interp = [os.environ.get("YEOUL_BASH", "bash")] if not script.endswith(".py") else [sys.executable] - cmd = [*interp, str(path), *args] + try: + interp = [bash_command()] if not script.endswith(".py") else [sys.executable] + except OSError as exc: + return {"exit_code": 127, "stdout": "", "stderr": str(exc)} + cmd = [*interp, path.as_posix(), *args] # 🔴 stdin: never inherit the parent's. On an MCP STDIO server the parent's stdin IS the # protocol pipe, and a child that inherits it steals protocol bytes — the tool then # hangs until timeout (field report, Windows/Codex, 2026-08-24). @@ -57,15 +87,29 @@ def _run(script: str, *args: str, cwd: str | None = None, stdin: str | None = No # non-UTF-8 default (CP949) the strip fails and a trivial "yes" arrives long enough to # clear the substance checks. That is a gate-integrity bug, not a display bug. env = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"} + if not script.endswith('.py'): + env['YEOUL_BASH'] = interp[0] try: - p = subprocess.run( + with subprocess.Popen( cmd, cwd=cwd or os.getcwd(), - input=stdin if stdin is not None else "", - capture_output=True, text=True, encoding="utf-8", env=env, timeout=120, - ) - return {"exit_code": p.returncode, "stdout": p.stdout, "stderr": p.stderr} - except subprocess.TimeoutExpired: - return {"exit_code": 124, "stdout": "", "stderr": "timeout"} + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, encoding="utf-8", env=env, start_new_session=os.name == "posix", + ) as child: + try: + stdout, stderr = child.communicate(input=stdin if stdin is not None else "", timeout=120) + return {"exit_code": child.returncode, "stdout": stdout, "stderr": stderr} + except subprocess.TimeoutExpired: + if os.name == "posix": + try: + os.killpg(child.pid, signal.SIGKILL) + except ProcessLookupError: + pass + else: + child.kill() + child.communicate() + return {"exit_code": 124, "stdout": "", "stderr": "timeout"} + except (OSError, UnicodeError) as exc: + return {"exit_code": 127, "stdout": "", "stderr": str(exc)} @mcp.tool() @@ -98,10 +142,12 @@ def arc_ticket(arc_dir: str, role: str, slug: str, body: str, ref: str = "") -> @mcp.tool() -def loop_guard_tick(arc_dir: str, tokens: int = 0, progress: bool = True) -> dict: +def loop_guard_tick(arc_dir: str, tokens: int | None = None, progress: bool = True) -> dict: """Tick the runaway guard for a round. Returns CONTINUE or STOP:max-rounds/budget/no-progress.""" - return _run("loop-guard", arc_dir, "tick", f"--tokens={tokens}", - f"--progress={'yes' if progress else 'no'}") + args = [arc_dir, "tick", f"--progress={'yes' if progress else 'no'}"] + if tokens is not None: + args.append(f"--tokens={tokens}") + return _run("loop-guard", *args) @mcp.tool() @@ -124,24 +170,14 @@ def arc_close(arc_dir: str, verdict: str, stop: str = "converged") -> dict: @mcp.tool() def build_handoff(name: str, workspace: str = ".") -> dict: - """Generate dev-plan.md + TODO.md from the spec + closed-arc verdict (GO handoff).""" + """Generate a dev skeleton, NOT authorization to build. Missing/negative verdicts remain manual gates.""" return _run("build-handoff", name, cwd=workspace) @mcp.tool() def ralph_gate_check(name: str, workspace: str = ".") -> dict: - """Dry check: does dev/TODO.md qualify for the autonomous loop? Refuses (exit 3) if any unchecked item - lacks a `verify:` command. (Does NOT run the loop — the unattended loop must be launched from a terminal.)""" - # loop-eligibility is the first thing ralph checks; surface it without running rounds. - todo = Path(workspace) / "projects" / name / "dev" / "TODO.md" - if not todo.exists(): - return {"exit_code": 1, "stdout": "", "stderr": f"no TODO: {todo}"} - bad = [ln for ln in todo.read_text(encoding="utf-8").splitlines() - if ln.startswith("- [ ]") and "verify:" not in ln] - if bad: - return {"exit_code": 3, "stdout": "", "stderr": "not loop-eligible (missing verify: commands):\n" - + "\n".join(" " + b for b in bad)} - return {"exit_code": 0, "stdout": "loop-eligible: all unchecked items have verify commands", "stderr": ""} + """Read-only eligibility check of ALL items, using the real CLI parser. No loop or verification runs.""" + return _run("ralph", name, "--check", cwd=workspace) @mcp.tool() @@ -154,11 +190,14 @@ def arc_prereg(arc_dir: str, claim_id: str, ledger: str = "", workspace: str = " @mcp.tool() def verify_gate(todo_path: str, revert: bool = True, require_verify: bool = True, - workspace: str = ".") -> dict: + workspace: str = ".", baseline_path: str = "") -> dict: """Re-run the `verify:` command of every checked TODO item and revert the boxes that do not pass. This is the harness half of the dev loop — backend A (in-session) MUST call it each round, or nothing has been - verified but the agent's word. require_verify also reverts a checked item whose verify clause is missing.""" + verified but the agent's word. Requires a supervisor-created baseline (default TODO.verify-baseline.json). + Changed criteria are refused BEFORE executing commands. Protect baseline and tests from worker writes.""" args = [todo_path] + (["--revert"] if revert else []) + (["--require-verify"] if require_verify else []) + if baseline_path: + args.append(f"--baseline={baseline_path}") return _run("verify-gate", *args, cwd=workspace) diff --git a/setup/install.sh b/setup/install.sh index d669097..22a5f87 100755 --- a/setup/install.sh +++ b/setup/install.sh @@ -1,55 +1,28 @@ #!/usr/bin/env bash set -euo pipefail -# install.sh — set up Yeoul together with its discipline primitive (mirror-stack). -# Yeoul is the practice layer; mirror-stack is the pre-registration + tamper-evident ledger it seals into. -# Installing both is recommended so sealing is real, not a no-op fallback. -# -# usage: setup/install.sh [--no-mirror-stack] [--print-config] -# --no-mirror-stack : skip installing mirror-stack (Yeoul runs; sealing degrades to no-op) -# --print-config : just print the mcpServers block to merge into your MCP client config - +# Install the tested MCP combination. Requested installation failures are fatal. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO="$(cd "$SCRIPT_DIR/.." && pwd)" WITH_MIRROR=1; PRINT_ONLY=0 for a in "$@"; do case "$a" in --no-mirror-stack) WITH_MIRROR=0 ;; - --print-config) PRINT_ONLY=1 ;; + --print-config) PRINT_ONLY=1 ;; + *) echo "unknown option: $a" >&2; exit 2 ;; esac; done - if [ "$PRINT_ONLY" -eq 1 ]; then cat "$SCRIPT_DIR/mcp-servers.json" exit 0 fi - -echo "── Yeoul setup ──" -echo "1) Yeoul CLI scripts: $REPO/bin (add to PATH, or call by path)" -echo " e.g. export PATH=\"$REPO/bin:\$PATH\"" - +. "$REPO/bin/_pybin.sh" +PY="$(yeoul_pybin)" || yeoul_pybin_die +"$PY" -m pip --version >/dev/null if [ "$WITH_MIRROR" -eq 1 ]; then - echo "2) mirror-stack (discipline primitive: pre-registration + ledger)" - if command -v pip >/dev/null 2>&1; then - echo " installing mirror-stack-mcp ..." - pip install "git+https://github.com/mirror-stack/mirror-stack-mcp" || { - echo " ⚠️ pip install failed — install manually: pip install git+https://github.com/mirror-stack/mirror-stack-mcp" - } - else - echo " ⚠️ pip not found. Install manually: pip install git+https://github.com/mirror-stack/mirror-stack-mcp" - fi + "$PY" -m pip install "git+https://github.com/mirror-stack/mirror-stack-mcp@v0.2.14" else - echo "2) mirror-stack: SKIPPED (--no-mirror-stack). Sealing will be a no-op fallback." + echo "Mirror installation skipped: discussion closes remain explicitly file-only without a recorder." fi - -echo "3) yeoul-mcp (gate-enforcing MCP tools over the bin/ scripts)" -if command -v pip >/dev/null 2>&1; then - echo " installing yeoul-mcp ..." - pip install "$REPO/mcp" || echo " ⚠️ pip install failed — install manually: pip install $REPO/mcp" -else - echo " ⚠️ pip not found. Install manually: pip install $REPO/mcp" -fi - -echo "4) MCP client config — merge this into your mcpServers (Claude Desktop/Code):" -echo -sed 's/^/ /' "$SCRIPT_DIR/mcp-servers.json" -echo -echo " (If you skipped mirror-stack, remove its entry — Yeoul still runs without it.)" -echo "── done ──" +"$PY" -m pip install "$REPO/mcp" +echo "Installed yeoul-mcp (bundled harness). Bash must be available on PATH." +echo "For checkout CLI commands, add $REPO/bin to PATH." +echo "Merge the following MCP configuration (omit mirror-stack if skipped):" +cat "$SCRIPT_DIR/mcp-servers.json" diff --git a/setup/mcp-servers.json b/setup/mcp-servers.json index ae20d0e..b565a02 100644 --- a/setup/mcp-servers.json +++ b/setup/mcp-servers.json @@ -1,5 +1,5 @@ { - "_comment": "Register BOTH servers together. Yeoul (practice layer) composes with mirror-stack (discipline primitive: pre-registration + tamper-evident ledger). Merge this into your MCP client config (Claude Desktop/Code: mcpServers). Without mirror-stack, Yeoul still runs — sealing degrades to a no-op.", + "_comment": "Register BOTH servers together. Yeoul (practice layer) composes with mirror-stack (discipline primitive: pre-registration + tamper-evident ledger). Merge this into your MCP client config (Claude Desktop/Code: mcpServers). Without mirror-stack, Yeoul still runs — discussion closures are explicitly file-only when no recorder is available. Yeoul includes its own harness; no YEOUL_BIN override is needed.", "mcpServers": { "mirror-stack": { "command": "mirror-stack-mcp" diff --git a/tests/seal_fixture.py b/tests/seal_fixture.py new file mode 100644 index 0000000..0f2a860 --- /dev/null +++ b/tests/seal_fixture.py @@ -0,0 +1,16 @@ +"""Turn ONLY test fixtures into genuine MIRROR-SPEC chains; never use on live data.""" +import hashlib +import json +import sys +from pathlib import Path + +path = Path(sys.argv[1]) +rows = [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines() if line.strip()] +previous = 'genesis' +for row in rows: + row.pop('seal', None) + row['prev_seal'] = previous + row['seal'] = hashlib.sha256(json.dumps(row, sort_keys=True, ensure_ascii=False, + allow_nan=False).encode('utf-8')).hexdigest() + previous = row['seal'] +path.write_text(''.join(json.dumps(row, ensure_ascii=False)+'\n' for row in rows), encoding='utf-8') diff --git a/tests/test_gates.sh b/tests/test_gates.sh index da2ab3b..eb6cd86 100755 --- a/tests/test_gates.sh +++ b/tests/test_gates.sh @@ -13,6 +13,7 @@ PY="$(yeoul_pybin)" || yeoul_pybin_die BIN="$(cd "$(dirname "${BASH_SOURCE[0]}")/../bin" && pwd)" WS="$(mktemp -d)"; trap 'rm -rf "$WS"' EXIT cd "$WS"; export YEOUL_PROJECTS="$WS/projects" +export AM_LEDGER="$WS/actions.jsonl" YEOUL_INDEX="$WS/index.md" FAIL=0 # 🔴 count what was collected. "all gate tests passed" is also what a run that collected ZERO # checks prints — the summary has to carry its own denominator, and an empty run has to fail. @@ -82,6 +83,7 @@ grep -q "UNSEALED" "$WS/arcs/_archive"/*_g/_SUMMARY_*.md && echo " ✓ unsealed # --- ① sealed kill-condition injection (harness injects verbatim; agent is not its author) --- LEDGER="$WS/ledger.jsonl" printf '%s\n' '{"claim_id":"c1","metric":"m","kill_condition":"effect size d < 0.2 over >= 3 seeds","kill_threshold":{}}' > "$LEDGER" +"$PY" "$BIN/../tests/seal_fixture.py" "$LEDGER" "$BIN/arc-open" s --topic="sealed gate" --arcs-dir="$WS/arcs" >/dev/null 2>&1 SARC="$(ls -d "$WS"/arcs/*_s)" # A seal may no longer attach to an arc with a blank spec (see the DUAL KEY block below), @@ -158,13 +160,13 @@ printf -- '- [ ] ok. verify: `true`\n' > "$WS/projects/p/dev/TODO.md" # --- harness-enforced verify-gate: a falsely-checked item is re-run and reverted --- T2="$WS/t2.md" printf -- '- [x] lie: claimed done but verify fails. verify: `false`\n- [x] honest. verify: `true`\n' > "$T2" -"$BIN/verify-gate" "$T2" --revert >/dev/null 2>&1; assert "verify-gate flags a failing checked item" 1 $? +"$BIN/verify-gate" "$T2" --current-only --revert >/dev/null 2>&1; assert "verify-gate flags a failing checked item" 1 $? grep -q '^- \[ \] lie' "$T2" && echo " ✓ harness reverted the false [x] → [ ]" || { echo " ✗ false [x] not reverted"; FAIL=1; } grep -q '^- \[x\] honest' "$T2" && echo " ✓ genuine [x] left intact" || { echo " ✗ genuine [x] wrongly reverted"; FAIL=1; } # decoy: an appended `verify: `true`` must NOT override a real failing first command (greedy-extraction bug) T3="$WS/t3.md" printf -- '- [x] decoy. verify: `false` verify: `true`\n' > "$T3" -"$BIN/verify-gate" "$T3" --revert >/dev/null 2>&1 +"$BIN/verify-gate" "$T3" --current-only --revert >/dev/null 2>&1 grep -q '^- \[ \] decoy' "$T3" && echo " ✓ decoy double-verify reverted (first block wins)" || { echo " ✗ decoy passed (greedy bug)"; FAIL=1; } # --- clause-deletion bypass: ticking a box after deleting `verify:` must not survive --- @@ -172,12 +174,12 @@ grep -q '^- \[ \] decoy' "$T3" && echo " ✓ decoy double-verify reverted (firs # to be invisible to it and passed silently. Observed, not hypothetical. T4="$WS/t4.md" printf -- '- [x] deleted its own verify clause\n' > "$T4" -"$BIN/verify-gate" "$T4" >/dev/null 2>&1; assert "clause-less checked item passes without --require-verify (compat)" 0 $? -"$BIN/verify-gate" "$T4" --revert --require-verify >/dev/null 2>&1; assert "clause-less checked item fails with --require-verify" 1 $? +"$BIN/verify-gate" "$T4" --current-only >/dev/null 2>&1; assert "clause-less checked item passes without --require-verify (compat)" 0 $? +"$BIN/verify-gate" "$T4" --current-only --revert --require-verify >/dev/null 2>&1; assert "clause-less checked item fails with --require-verify" 1 $? grep -q '^- \[ \] deleted its own verify clause' "$T4" && echo " ✓ clause-less box reverted to [ ]" || { echo " ✗ clause-less box survived"; FAIL=1; } # a genuine passing item must still survive under the same flag (no false positives) printf -- '- [x] real. verify: `true`\n' > "$T4" -"$BIN/verify-gate" "$T4" --revert --require-verify >/dev/null 2>&1; assert "genuine checked item still passes under --require-verify" 0 $? +"$BIN/verify-gate" "$T4" --current-only --revert --require-verify >/dev/null 2>&1; assert "genuine checked item still passes under --require-verify" 0 $? grep -q '^- \[x\] real' "$T4" && echo " ✓ genuine box left checked" || { echo " ✗ genuine box wrongly reverted"; FAIL=1; } # ralph must refuse a TODO whose CHECKED item lacks a verify clause (was only checking unchecked ones) printf -- '- [x] checked without verify\n- [ ] ok. verify: `true`\n' > "$WS/projects/p/dev/TODO.md" @@ -525,6 +527,7 @@ done # ───────────────────────────────────────────────────────────────────────────────────────── DK="$WS/dk"; mkdir -p "$DK" printf '%s\n' '{"claim_id":"dk-1","kill_condition":"the dual-key gate lets a blank spec through"}' > "$DK/led.jsonl" +"$PY" "$BIN/../tests/seal_fixture.py" "$DK/led.jsonl" # --- the lock: a blank spec may not take a seal --- "$BIN/arc-open" dkblank --arcs-dir="$DK/arcs" >/dev/null 2>&1 @@ -605,7 +608,7 @@ NB="$(ls -d "$DKN"/arcs/*probe 2>/dev/null | head -1)" run_bare arc-list "$BIN/arc-list" --arcs-dir="$DKN/arcs" run_bare arc-roles "$BIN/arc-roles" "$NB" run_bare build-handoff "$BIN/build-handoff" probe -run_bare verify-gate "$BIN/verify-gate" "$DKN/projects/probe/dev/TODO.md" +run_bare verify-gate "$BIN/verify-gate" "$DKN/projects/probe/dev/TODO.md" --current-only run_bare loop-guard "$BIN/loop-guard" "$NB" run_bare arc-close-draft "$BIN/arc-close" "$NB" "GO — no mirror" [ -n "$NB" ] && sedi 's/- (fill in)/- concrete conclusion here/' "$(ls "$NB"/_SUMMARY_*.md)" diff --git a/tests/test_hardening.py b/tests/test_hardening.py new file mode 100644 index 0000000..75eecf1 --- /dev/null +++ b/tests/test_hardening.py @@ -0,0 +1,262 @@ +"""Adversarial contract tests. Every write/record/agent stub is in a temporary workspace.""" +import hashlib +import json +import os +import shlex +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO / 'bin')) +from prereg_check import bind, claim, resolve, read_verified +from verify_core import verify, canonical, eligible + + +def ledger(path, rows, width=64): + previous = 'genesis' + output = [] + for row in rows: + body = {k: v for k, v in row.items() if k not in ('seal', 'sig')} + body['prev_seal'] = previous + seal = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False, + allow_nan=False).encode()).hexdigest()[:width] + output.append(dict(body, seal=seal)) + previous = seal + path.write_text(''.join(json.dumps(row, ensure_ascii=False)+'\n' for row in output), encoding='utf-8') + return output + + +class Hardening(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix='yeoul contract ') + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.env = dict(os.environ, YEOUL_PROJECTS=str(self.root/'projects'), + YEOUL_INDEX=str(self.root/'index.md'), AM_LEDGER=str(self.root/'actions.jsonl'), + YEOUL_LEDGER=str(self.root/'claims.jsonl'), PYTHONDONTWRITEBYTECODE='1') + self.claims = self.root/'claims.jsonl' + self.row = dict(claim_id='c1', metric='m', kill_condition='effect size d < 0.2 over 3 seeds') + self.arc = self.root/'arc' + self.arc.mkdir() + self.todo = self.root/'TODO.md' + + def call(self, script, *args, env=None): + return subprocess.run(['bash', str(REPO/'bin'/script), *map(str, args)], + cwd=self.root, env=env or self.env, capture_output=True, + text=True, encoding='utf-8', timeout=30) + + def prereg(self): + ledger(self.claims, [self.row]) + bind(self.arc, 'c1', self.claims) + + def opened(self): + result = self.call('arc-open', 'audit', '--arcs-dir='+str(self.root/'arcs')) + self.assertEqual(result.returncode, 0, result.stderr) + return next((self.root/'arcs').glob('*_audit')) + + def test_unsealed_ledger_refused(self): + self.claims.write_text(json.dumps(self.row)) + with self.assertRaises(ValueError): + bind(self.arc, 'c1', self.claims) + self.assertFalse((self.arc/'.prereg').exists()) + + def test_tampered_and_malformed_ledgers_refused(self): + ledger(self.claims, [self.row]) + original = self.claims.read_text() + for bad in ['', original.replace('0.2', '0.9'), original+'{bad', '[]', + original.replace('"metric": "m"', '"metric": "m", "metric": "n"')]: + with self.subTest(data=bad[:35]): + self.claims.write_text(bad) + with self.assertRaises(ValueError): + read_verified(self.claims) + + def test_bad_later_entry_invalidates_whole_chain(self): + ledger(self.claims, [self.row, dict(claim_id='c2', kill_condition='stop')]) + self.claims.write_text(self.claims.read_text().replace('"stop"', '"changed"')) + with self.assertRaises(ValueError): + claim(self.claims, 'c1') + + def test_first_write_cannot_be_repaired_by_duplicate(self): + ledger(self.claims, [dict(claim_id='c1', metric='m'), self.row]) + with self.assertRaises(ValueError): + claim(self.claims, 'c1') + + def test_legacy_hash_and_threshold_registration(self): + rows = ledger(self.claims, [dict(claim_id='c1', kill_threshold={'min': 0.2})], width=16) + bind(self.arc, 'c1', self.claims) + binding, condition = resolve(self.arc) + self.assertEqual(binding['seal'], rows[0]['seal']) + self.assertEqual(json.loads(condition), {'min': 0.2}) + + def test_modified_pinned_registration_even_rehashed_is_refused(self): + self.prereg() + ledger(self.claims, [dict(self.row, kill_condition='new threshold')]) + with self.assertRaises(ValueError): + resolve(self.arc) + + def test_appended_valid_records_preserve_pin(self): + self.prereg() + ledger(self.claims, [self.row, dict(claim_id='c2', kill_condition='other bar')]) + self.assertEqual(resolve(self.arc)[0]['claim_id'], 'c1') + + def test_link_removal_and_rebinding_refused(self): + self.prereg() + (self.arc/'.prereg').unlink() + with self.assertRaises(ValueError): + resolve(self.arc) + other = self.root/'other.jsonl' + ledger(other, [dict(self.row, claim_id='c2')]) + with self.assertRaises(ValueError): + bind(self.arc, 'c2', other) + + def test_legacy_link_needs_explicit_verified_upgrade(self): + ledger(self.claims, [self.row]) + (self.arc/'.prereg').write_text(f'c1\n{self.claims}\n') + with self.assertRaises(ValueError): + resolve(self.arc) + bind(self.arc, 'c1', self.claims) + self.assertEqual(resolve(self.arc)[0]['claim_id'], 'c1') + + def test_command_replacement_and_item_deletion_blocked_before_execution(self): + baseline = '- [ ] real requirement. verify: `false`\n' + for changed in ['- [x] real requirement. verify: `touch injected`\n', '', + '- [x] different requirement. verify: `true`\n']: + with self.subTest(changed=changed): + self.todo.write_text(changed) + self.assertEqual(verify(self.todo, baseline=baseline, revert=True, require=True), 3) + self.assertEqual(self.todo.read_text(), baseline) + self.assertFalse((self.root/'injected').exists()) + + def test_true_and_false_verifications(self): + baseline = '- [ ] honest. verify: `true`\n- [ ] broken. verify: `false`\n' + self.todo.write_text(baseline.replace('[ ]', '[x]')) + self.assertEqual(verify(self.todo, baseline=baseline, revert=True, require=True), 1) + self.assertIn('[x] honest', self.todo.read_text()) + self.assertIn('[ ] broken', self.todo.read_text()) + + def test_missing_baseline_fails_closed_and_never_runs(self): + self.todo.write_text('- [x] unsafe. verify: `touch injected`\n') + self.assertEqual(self.call('verify-gate', self.todo).returncode, 3) + self.assertFalse((self.root/'injected').exists()) + + def test_baseline_creation_is_explicit_and_non_overwriting(self): + self.todo.write_text('- [ ] honest. verify: `true`\n') + self.assertEqual(self.call('verify-baseline', self.todo).returncode, 0) + self.assertEqual(self.call('verify-baseline', self.todo).returncode, 3) + self.todo.write_text(self.todo.read_text().replace('[ ]', '[x]')) + self.assertEqual(self.call('verify-gate', self.todo).returncode, 0) + + def test_verify_timeout(self): + baseline = '- [x] bounded. verify: `sleep 5`\n' + self.todo.write_text(baseline) + self.assertEqual(verify(self.todo, baseline=baseline, timeout=0.05, revert=True), 1) + self.assertIn('[ ] bounded', self.todo.read_text()) + + def test_malformed_and_empty_todos_are_ineligible(self): + for text in ['', '# no items', '- [x] absent', '- [ ] missing. verify:', + '- [ ] empty. verify: ``', '- [X] hidden\n- [ ] ok. verify: `true`']: + with self.subTest(text=text): + self.assertFalse(eligible(text)) + + def test_draft_refusal_and_final_archive_states(self): + arc = self.opened() + self.assertEqual(self.call('arc-close', arc, 'GO audit').returncode, 0) + thread = arc/'ARC'/(arc.name+'.md') + self.assertIn('status: "Close-Pending"', thread.read_text()) + self.assertEqual(self.call('arc-close', arc, 'GO audit').returncode, 4) + self.assertNotIn('status: "Closed"', thread.read_text()) + summary = next(arc.glob('_SUMMARY*')) + summary.write_text(summary.read_text().replace('(fill in)', 'concrete conclusion')) + self.assertEqual(self.call('arc-close', arc, 'GO audit').returncode, 0) + archived = arc.parent/'_archive'/arc.name + self.assertIn('status: "Closed"', (archived/'ARC'/thread.name).read_text()) + self.assertIn('ARCHIVE_RECORD ', (archived/'STATE.md').read_text()) + + def test_deleting_required_kill_fields_is_not_a_pass(self): + arc = self.opened() + self.call('arc-close', arc, 'KILL audit') + summary = next(arc.glob('_SUMMARY*')) + text = summary.read_text().replace('(fill in)', 'concrete conclusion') + summary.write_text('\n'.join(line for line in text.splitlines() if '(unfilled)' not in line)) + self.assertEqual(self.call('arc-close', arc, 'KILL audit').returncode, 5) + self.assertTrue(arc.exists()) + + def test_archive_collision_is_not_overwritten(self): + arc = self.opened() + self.call('arc-close', arc, 'GO audit') + summary = next(arc.glob('_SUMMARY*')) + summary.write_text(summary.read_text().replace('(fill in)', 'concrete conclusion')) + archived = arc.parent/'_archive'/arc.name + archived.mkdir(parents=True) + self.assertEqual(self.call('arc-close', arc, 'GO audit').returncode, 9) + self.assertTrue(arc.exists()) + + def test_defense_fields_outside_the_checked_section_do_not_count(self): + arc = self.opened() + self.call('arc-close', arc, 'KILL audit') + summary = next(arc.glob('_SUMMARY*')) + text = summary.read_text().replace('(fill in)', 'concrete conclusion') + moved = [line for line in text.splitlines() if '(unfilled)' in line] + summary.write_text('\n'.join(moved)+'\n'+'\n'.join( + line for line in text.splitlines() if '(unfilled)' not in line)) + # Remove placeholders so failure must come from section membership, not blank scanning. + summary.write_text(summary.read_text().replace('(unfilled)', 'three independent runs agree')) + self.assertEqual(self.call('arc-close', arc, 'KILL audit').returncode, 5) + self.assertTrue(arc.exists()) + + def fake_loop(self, body, *extra): + dev = self.root/'projects'/'p'/'dev' + dev.mkdir(parents=True) + todo = dev/'TODO.md' + todo.write_text('- [ ] real task. verify: `true`\n') + fake = self.root/'fake agent.py' + fake.write_text('import os,json\nfrom pathlib import Path\np=Path(os.environ["AUDIT_TODO"])\n'+body) + env = dict(self.env, AUDIT_TODO=str(todo)) + result = self.call('ralph', 'p', '--agent-cmd='+shlex.join([sys.executable, str(fake)]), *extra, env=env) + return result, todo + + def test_ralph_refuses_worker_criterion_changes(self): + result, todo = self.fake_loop('p.write_text("- [x] changed. verify: `true`\\n")\nprint(json.dumps({"usage":{"input_tokens":1,"output_tokens":1}}))\n') + self.assertEqual(result.returncode, 3, result.stdout+result.stderr) + self.assertIn('[ ] real task', todo.read_text()) + + def test_ralph_one_round_means_one_invocation(self): + result, todo = self.fake_loop('print(json.dumps({"usage":{"input_tokens":1,"output_tokens":1}}))\n', '--max-rounds=1') + self.assertEqual(result.returncode, 2, result.stdout+result.stderr) + self.assertEqual(len(list((todo.parent/'ralph_log').rglob('round_*.json'))), 1) + + def test_ralph_preserves_previous_run_logs(self): + result, todo = self.fake_loop('print(json.dumps({"usage":{"input_tokens":1,"output_tokens":1}}))\n', '--max-rounds=1') + self.assertEqual(result.returncode, 2) + original = list((todo.parent/'ralph_log').rglob('round_*.json')) + before = original[0].read_bytes() + result = self.call('ralph', 'p', '--agent-cmd=true', '--max-rounds=1') + self.assertEqual(result.returncode, 2) + self.assertEqual(original[0].read_bytes(), before) + self.assertEqual(len(list((todo.parent/'ralph_log').rglob('round_*.json'))), 2) + + def test_ralph_missing_usage_is_not_zero(self): + result, _ = self.fake_loop('print("{}")\n') + self.assertEqual(result.returncode, 2) + self.assertIn('STOP:unmeasured', result.stdout) + + def test_ralph_success_and_quoted_agent_path(self): + result, _ = self.fake_loop('p.write_text(p.read_text().replace("[ ]","[x]"))\nprint(json.dumps({"usage":{"input_tokens":1,"output_tokens":1}}))\n', '--max-rounds=1') + self.assertEqual(result.returncode, 0, result.stdout+result.stderr) + self.assertIn('RALPH_DONE', result.stdout) + + def test_ralph_round_timeout(self): + result, _ = self.fake_loop('import time\ntime.sleep(5)\n', '--round-timeout=0.05') + self.assertEqual(result.returncode, 124, result.stdout+result.stderr) + + def test_loop_guard_boundary_and_invalid_counts(self): + self.call('loop-guard', self.arc, 'init', '--max-rounds=1') + self.assertIn('STOP:max-rounds', self.call('loop-guard', self.arc, 'tick', '--tokens=0').stdout) + self.assertNotEqual(self.call('loop-guard', self.arc, 'tick', '--tokens=-1').returncode, 0) + + +if __name__ == '__main__': + unittest.main(verbosity=2)