Skip to content

fix(apply): queue exact drift refreshes without hydration - #1258

Merged
steipete merged 1 commit into
mainfrom
steipete/clawsweeper-direct-drift-refresh-20260826
Aug 27, 2026
Merged

fix(apply): queue exact drift refreshes without hydration#1258
steipete merged 1 commit into
mainfrom
steipete/clawsweeper-direct-drift-refresh-20260826

Conversation

@steipete

@steipete steipete commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Problem and production change

Default apply sent exact drift refreshes through broad planning. Close run 33034908558 acknowledged five dispatches, but planners failed whole-repository hydration with Durable Object overload, before admission.

The production workflow delta is +10/-6 lines; its behavior is:

  1. Reuse clawsweeper_item and existing queue-only legacy intake.
  2. Read the default branch once and at most five item kinds.
  3. Preserve report order, selector, five-item cap and proof cursor.
  4. Preserve default-apply-only and OpenClaw-only guards.
  5. Carry low-priority source_drift_requeue, with supersedes_in_progress: false.
  6. Keep dedupe, backpressure, throttling and leases in the queue.
  7. Preserve pending/leased commands and source authority.
  8. Request explicit current-source review, not scheduled cache reuse.
  9. Surface read/dispatch/intake failures; producer errors stop remaining items.
  10. Add no endpoint, credential, permission, force flag, source pin or bypass.

Real Behavior Proof

PASS: signed Worker/native Durable Object SQL, executed 2026-08-27 at 08:06 UTC. Head: 9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208. The NEW temporary bootstrap.sh ran actual producer/intake Bash, real curl, unmodified Worker HMAC and native workerd SqlStorage. Five admissions, five duplicates, both 401 controls, persisted restart and command/source authority passed. App, command and client exits: 0. Owned resources removed. This is separate from the old committed mock harness.

Provider: approved Docker-backed Crabbox local-container; lease cbx_a2b310396e1c, run run_1c115b737135 (no hosted run URL). Image: node:24-bookworm@sha256:4196d66a565c6f195728d9952f161f4adfe2ad753052a08b7ec7f1c5a6bda42b. Native Linux arm64, Node 24.19.0, Wrangler 4.107.0, workerd 1.20260701.1.

Actual HTTP/native SQL excerpt; counts are observed SQL rows, signatures omitted:

{
  "observedAt": 1787818008530,
  "realCurl": true,
  "POST": "/internal/exact-review/enqueue",
  "selected": [
    43367,
    128515,
    119583,
    121477,
    77508
  ],
  "httpStatuses": [
    202,
    202,
    202,
    202,
    202
  ],
  "storageType": "SqlStorage",
  "nativeItems": 5,
  "deliveryReceipts": 5,
  "stateHash": "c8225be2c17dd02cc48b9b9d28e65a2ade27d8803ee0d5a01010c3304998ee27",
  "duplicates": {
    "items": 5,
    "receipts": 5,
    "replaced": false
  },
  "negativeControls": [
    {
      "mode": "invalid",
      "status": 401,
      "response": {
        "error": "invalid_signature"
      }
    },
    {
      "mode": "tampered",
      "status": 401,
      "response": {
        "error": "invalid_signature"
      }
    }
  ],
  "restart": {
    "sameDoId": true,
    "newInstance": true
  },
  "authority": {
    "sourceAction": "exact_review_command",
    "sourceAuthoritySeq": 7
  },
  "outcome": {
    "passed": true,
    "proofExit": 0,
    "commandExit": 0,
    "clientExit": 0
  }
}

Both 401 controls preserved SQL state/receipts. Restart preserved DO ID, items, receipts and state hash. A command admitted through the signed route, not SQL seeding, retained its marker, synthetic head and sequence 7 after refresh. All items stayed pending without leases/execution; full semantic trace below.

Accepted finding disposition: the 08:22:23.253Z review describes the OLD gh/curl-intercepting test-SQLite harness. The NEW uncommitted 08:06 bootstrap supplies requested native admission/restart and rank-up proof: SHA-256 d51833ed3daf2dc1c243090a979ccb4aa1e665ebcf6a468bacd092b39c493255, full bytes below. The published proof blocker remains; current-head/current-body review is required before landing. No waiver is claimed.

The selector chose five of 15 drift rows in the 27-action report. Only GitHub branch/kind metadata and repository_dispatch were synthetic/captured. The wrapper adds read-only observations; no admission, crypto, storage, alarm or dispatch method is replaced. Its generated fixture key was never printed and was removed.

The local config had no account, routes, production bindings or App credentials; GitHub API was http://127.0.0.1:9. Existing 900000 ms debounce/backoff deferred dispatch; the command exercised credential-free blocked/retry behavior. Limits: no deployed Cloudflare, production credential scopes, hosted GitHub delivery, model execution, publication or close. Closed/missing-target and backpressure controls are supplementary harness coverage, not native-run claims.

Architecture, documentation and Bay

Normalization preserves target/branch/kind, event/action, timeout and non-supersession. Queue authority, executor live-state guards, broad dispatch and close policy are unchanged. The notice distinguishes dispatch acknowledgement from admission/completed review. Transport failures remain possible; existing github.token and public reads stay default-OpenClaw-only.

Scheduler docs cover routing, authority, explicit refresh, errors and Bay. The maintainer changelog entry preserves existing entries in ClawSweeper; OpenClaw's release-owned changelog is untouched per repository policy.

Bay: no change needed. Existing decisions, source_drift_requeue, lifecycle/status fields, schemas and routes are reused. Bay remains public and observer-only: no browser GitHub calls or mutation controls. Proof changes no data contract.

Supporting validation and honest limits

Exact-head CI 33040750328: full pnpm check, sparse build smoke and Windows launcher checks passed. CodeQL and production-automerge E2E passed; automerge was not thereby enabled. Independent precommit review had no accepted/actionable findings. Committed-branch and fresh exact-commit landing autoreviews were clean at P0 only, not an all-severity clearance. Current ClawSweeper has no code/security findings but still blocks on proof.

Supplementary: the committed harness and report fixture use intercepted gh/curl and test SQLite. The controlled proof and 274 focused tests passed: order/cap, normalization, explicit refresh, pending/leased authority, invalid identity, backpressure, no-op/comment-only/nonautomatic/missing-report guards and nonzero transport errors. Four-item probing dispatched two open fixtures, stopped one closed and one missing, leaving the fifth pending. Its long JSON is not repeated or presented as native proof.

Build/static/lint/changed-coverage/actionlint/whitespace checks passed. Local full pnpm run check failed: 3,706 passed, 48 failed, nine skipped, zero cancelled. Baseline: 42 missing origin/* fixture refs under inherited prune behavior; six offline pnpm 10.33.0 resolution failures. No config/pin/policy/timeout changes or full local retry. Hosted CI passed later. Bash 3.2 failed existing mapfile; GNU Bash 5.3.15 passed unchanged.

Proof base: f211e21fb89d00777ac07cc13c358f9f7b02a939. Saved main assessment at 71df3a1ce714d737e250008597075bb5eaeb2ac4: no approved patch or drift-runtime overlap. This is static evidence, not merged-tree proof; head unchanged.

Native run provenance and reproduction

Docker 29.4.0, pnpm 11.10.0, Bash 5.2.15, curl 7.88.1, jq 1.6, YAML 2.9.0. Fresh source, no hydration, host home/auth/SSH mounts, Docker socket or privilege; only the read-only transport bootstrap was bind-mounted. Workload uid 1001, no effective capabilities, seccomp 2, isolated HOME/TMPDIR and env -i. AWS IMDS was inapplicable; provider settings unchanged.

Recorded commands use relative host artifact filenames and container fixture paths. Both exact scripts follow. The lease was removed; reproduction requires a fresh lease ID and isolation inspection. Both scripts assert the head.

CRABBOX_ENV_ALLOW=CI CI=1 crabbox run --provider local-container \
  --local-container-image node:24-bookworm@sha256:4196d66a565c6f195728d9952f161f4adfe2ad753052a08b7ec7f1c5a6bda42b \
  --arch arm64 --local-container-docker-socket=false \
  --local-container-network bridge --local-container-work-root /work/crabbox \
  --no-hydrate --fresh-pr openclaw/clawsweeper#1258 --keep \
  --lease-output lease.json --timing-json \
  --capture-stdout prepare.stdout --capture-stderr prepare.stderr --script prepare.sh

CRABBOX_ENV_ALLOW=CI CI=1 crabbox run --provider local-container \
  --id cbx_a2b310396e1c --no-hydrate --fresh-pr openclaw/clawsweeper#1258 \
  --keep --timing-json --capture-stdout attempt-4.stdout \
  --capture-stderr attempt-4.stderr \
  --download /tmp/clawsweeper-drift-real-admission-proof/local-container/artifacts.tar.gz=attempt-4.tar.gz \
  --script bootstrap.sh

crabbox stop --provider local-container --id cbx_a2b310396e1c

Process-stop 143 was intentional SIGTERM; application/client exits were 0. Both groups emptied and loopback closed. Key, container, claim, transport SSH key and owned transport directory were removed. Stop exit 0; Docker inspect exit 1 confirmed absence. Final cleanup: 08:11:03.959 UTC.

Selected native HTTP and persistence trace

Complete existing selected-public-trace.json (7,992 bytes), without secrets/signatures. Full trace.json SHA-256: e05a193e5fba9abd82376201d73d6f310773de066cd87692343000ff0af0c014; selected projection SHA-256: 64371bffd54646c73f071f0e0dccd6432b26bbf357984ad1e48a48c37613fda5.

Actual semantic trace, before the executable and historical notes
{
  "http": [
    {
      "itemNumber": 43367,
      "requestSha256": "48f2d14dc3e4eb6fea356f6c10e2f45fbf6086717af033601b088acbafd4d082",
      "status": 202,
      "response": {
        "ok": true,
        "queued": true,
        "item_key": "openclaw/openclaw#43367",
        "superseded_publications": 0
      }
    },
    {
      "itemNumber": 128515,
      "requestSha256": "6051dd36fce12be32785aa65925877916c8e58d15a8fc4efdd1f3e2fe542b3ef",
      "status": 202,
      "response": {
        "ok": true,
        "queued": true,
        "item_key": "openclaw/openclaw#128515",
        "superseded_publications": 0
      }
    },
    {
      "itemNumber": 119583,
      "requestSha256": "b5109bffb8f576dbab896a47d990c91ecd6f92ca97629a6a2886cca8493b5ffa",
      "status": 202,
      "response": {
        "ok": true,
        "queued": true,
        "item_key": "openclaw/openclaw#119583",
        "superseded_publications": 0
      }
    },
    {
      "itemNumber": 121477,
      "requestSha256": "90544d0a23b36717f42955aabfe489f908e4dc534286b534f3118105e3f4947f",
      "status": 202,
      "response": {
        "ok": true,
        "queued": true,
        "item_key": "openclaw/openclaw#121477",
        "superseded_publications": 0
      }
    },
    {
      "itemNumber": 77508,
      "requestSha256": "783c7cc53804341b8c4cad5817b4e4240f799a4c55cd94ee8a01089d3b312943",
      "status": 202,
      "response": {
        "ok": true,
        "queued": true,
        "item_key": "openclaw/openclaw#77508",
        "superseded_publications": 0
      }
    }
  ],
  "requestExample": {
    "method": "POST",
    "path": "/internal/exact-review/enqueue",
    "body": {
      "delivery_id": "legacy:43367:1",
      "decision": {
        "targetRepo": "openclaw/openclaw",
        "targetBranch": "release/proof-branch",
        "itemNumber": 43367,
        "itemKind": "issue",
        "sourceEvent": "issues",
        "sourceAction": "source_drift_requeue",
        "supersedesInProgress": false,
        "codexTimeoutMs": 1200000
      }
    },
    "bodySha256": "48f2d14dc3e4eb6fea356f6c10e2f45fbf6086717af033601b088acbafd4d082"
  },
  "nativeSql": {
    "storageType": "SqlStorage",
    "sqliteVersion": "unavailable: workerd disallows sqlite_version()",
    "doId": "dae4233e87282f77ad8c0dfcb2204d25474d5c8f3e7ad241a251c614431406b3",
    "observedAt": 1787818008530,
    "alarmAt": 1787818907882,
    "stateHash": "c8225be2c17dd02cc48b9b9d28e65a2ade27d8803ee0d5a01010c3304998ee27",
    "tables": {
      "exact_review_queue_items": {
        "rows": 5,
        "sha256": "76a0d751c78485ccb6913fcb33ae9384c91ab3c6deab0fd24d13da6f649921c5"
      },
      "exact_review_queue_deliveries": {
        "rows": 5,
        "sha256": "f851c870e5740733846ac9519f51871a88810fc707348552f87a86b88a7c47e6"
      },
      "exact_review_queue_meta": {
        "rows": 1,
        "sha256": "080e609ef0949d1bde2722195e5b838eb889b30d7cc738b110b42c0885c8adf0"
      },
      "exact_review_lifecycle_projection_v1": {
        "rows": 5,
        "sha256": "6984656344be1645bb71af1b03c5d471ae9cd7ea2ce26938f194b4808f484b77"
      }
    },
    "persistedExample": {
      "key": "openclaw/openclaw#43367",
      "decision": {
        "targetRepo": "openclaw/openclaw",
        "targetBranch": "release/proof-branch",
        "itemNumber": 43367,
        "itemKind": "issue",
        "sourceEvent": "issues",
        "sourceAction": "source_drift_requeue",
        "supersedesInProgress": false,
        "codexTimeoutMs": 1200000
      },
      "admissionDeliveryId": "legacy:43367:1",
      "state": "pending",
      "revision": 1,
      "createdAt": 1787818007882,
      "updatedAt": 1787818007882,
      "nextAttemptAt": 1787818907882,
      "backoffReason": "dispatch_debounce",
      "attempts": 0
    }
  },
  "duplicates": {
    "statuses": [
      202,
      202,
      202,
      202,
      202
    ],
    "deduped": [
      true,
      true,
      true,
      true,
      true
    ],
    "items": 5,
    "receipts": 5,
    "itemsHash": "3fea4090d6928fe51ce81dc012187f26afa51cbf580cfd0fa31c0debfce2b72e",
    "replaced": false
  },
  "signatureControls": [
    {
      "phase": "signature_rejection",
      "mode": "invalid",
      "status": 401,
      "response": {
        "error": "invalid_signature"
      },
      "beforeHash": "c8225be2c17dd02cc48b9b9d28e65a2ade27d8803ee0d5a01010c3304998ee27",
      "afterHash": "c8225be2c17dd02cc48b9b9d28e65a2ade27d8803ee0d5a01010c3304998ee27",
      "items": 5,
      "receipts": 5
    },
    {
      "phase": "signature_rejection",
      "mode": "tampered",
      "status": 401,
      "response": {
        "error": "invalid_signature"
      },
      "beforeHash": "c8225be2c17dd02cc48b9b9d28e65a2ade27d8803ee0d5a01010c3304998ee27",
      "afterHash": "c8225be2c17dd02cc48b9b9d28e65a2ade27d8803ee0d5a01010c3304998ee27",
      "items": 5,
      "receipts": 5
    }
  ],
  "restart": {
    "sameDoId": true,
    "newInstance": true,
    "beforeHash": "c8225be2c17dd02cc48b9b9d28e65a2ade27d8803ee0d5a01010c3304998ee27",
    "afterHash": "c8225be2c17dd02cc48b9b9d28e65a2ade27d8803ee0d5a01010c3304998ee27",
    "doId": "dae4233e87282f77ad8c0dfcb2204d25474d5c8f3e7ad241a251c614431406b3",
    "beforeInstance": "2a066c77-8749-4339-a153-fff0597e531e",
    "afterInstance": "77a7150f-a6c2-40de-9b07-071da0f969b6"
  },
  "authority": {
    "commandResult": {
      "mode": "valid",
      "status": 202,
      "response": {
        "ok": true,
        "queued": true,
        "item_key": "openclaw/openclaw#128516",
        "superseded_publications": 0
      }
    },
    "refreshResult": {
      "mode": "valid",
      "status": 202,
      "response": {
        "ok": true,
        "queued": true,
        "item_key": "openclaw/openclaw#128516",
        "superseded_publications": 0
      }
    },
    "beforeItemsHash": "ef652d1f35197a40c6f5f3b742c3c73fc579ecfdb04dbab9fe805e1566277259",
    "afterItemsHash": "ef652d1f35197a40c6f5f3b742c3c73fc579ecfdb04dbab9fe805e1566277259",
    "preserved": {
      "key": "openclaw/openclaw#128516",
      "decision": {
        "targetRepo": "openclaw/openclaw",
        "targetBranch": "release/proof-branch",
        "itemNumber": 128516,
        "itemKind": "pull_request",
        "sourceEvent": "pull_request",
        "sourceAction": "exact_review_command",
        "supersedesInProgress": false,
        "sourceHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "sourceHeadVerified": true,
        "sourceAuthoritySeq": 7,
        "codexTimeoutMs": 1200000,
        "commandStatusMarker": "<!-- clawsweeper-command-status:128516:re_review:fixture -->",
        "statusCommentId": 9001
      },
      "admissionDeliveryId": "fixture-existing-command",
      "state": "pending",
      "revision": 1,
      "createdAt": 1787818010244,
      "updatedAt": 1787818010244,
      "nextAttemptAt": 1787818010244,
      "attempts": 0,
      "sourceAuthorityWatermark": {
        "sequence": 7
      }
    },
    "dispatcher": {
      "state": "blocked",
      "reason": "workflow_status_unavailable",
      "checkedAt": 1787818011252,
      "retryAt": 1787818911252
    },
    "totalItems": 6,
    "receipts": 7,
    "alarmAt": 1787818911252
  },
  "processStops": [
    {
      "phase": "process_stop",
      "sequence": 1,
      "group": 3754,
      "exit": {
        "code": 143,
        "signal": null
      },
      "remaining": [],
      "loopbackClosed": true
    },
    {
      "phase": "process_stop",
      "sequence": "final",
      "group": 4207,
      "exit": {
        "code": 143,
        "signal": null
      },
      "remaining": [],
      "loopbackClosed": true
    }
  ],
  "processCleanup": {
    "phase": "process_cleanup",
    "ownedGroups": [
      3754,
      4207
    ],
    "remaining": []
  },
  "outcome": {
    "passed": true,
    "proofExit": 0,
    "commandExit": 0,
    "clientExit": 0,
    "stage": "complete",
    "processCleanupVerified": true,
    "containerCleanupVerified": true
  }
}

Exact executed native bootstrap

Temporary, uncommitted bootstrap.sh: 28,234 exact bytes, SHA-256 d51833ed3daf2dc1c243090a979ccb4aa1e665ebcf6a468bacd092b39c493255, unminified below. Parent independently matched all 372 source/step manifest entries to the exact head; manifest SHA-256 84ecc7991f98d31de4e95298fe454b3d02dad02760d6c349352012260be04c5f. Tracked source stayed clean; no production edit.

bootstrap.sh — exact executed bytes
#!/usr/bin/env bash
set -euo pipefail
# Temporary admission proof only; never deploy or use production credentials.
ROOT=/tmp/clawsweeper-drift-real-admission-proof/local-container
if [ "${1:-}" != sanitized ]; then
  mkdir -p "$ROOT"
  TASK=$(mktemp -d "$ROOT/runtime.XXXXXX")
  mkdir -p "$TASK/home" "$TASK/tmp"
  exec env -i PATH="$PATH" HOME="$TASK/home" TMPDIR="$TASK/tmp" CI=1 \
    COREPACK_ENABLE_DOWNLOAD_PROMPT=0 COREPACK_ENABLE_PROJECT_SPEC=0 \
    WRANGLER_SEND_METRICS=false WRANGLER_LOG_PATH="$TASK/wrangler-log" \
    bash "$0" sanitized "$TASK" "$PWD"
fi
TASK=$2
REPO=$3
EXPECTED=9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208
STAGE=safety
cd "$TASK"
# Preserve the application exit even when archive/capture fails. On failure the
# archive also travels over captured stdout because --download is success-only.
finish() {
  local proof_rc=$? final_rc archive_rc passed=false
  trap - EXIT
  set +e
  final_rc=$proof_rc
  if [ -f "$TASK/.dev.vars" ]; then
    node --input-type=module <<'REDACT'
import {readFileSync,writeFileSync,readdirSync,unlinkSync} from 'node:fs';
import path from 'node:path';
const secret=readFileSync('.dev.vars','utf8').trim().split('=').slice(1).join('=');
function scrub(dir) {
  for (const e of readdirSync(dir,{withFileTypes:true})) {
    if (['node_modules','home','tmp','compiled','bin','persistence','.dev.vars'].includes(e.name)) continue;
    const f=path.join(dir,e.name);
    if(e.isDirectory()) scrub(f);
    else if(e.isFile()) {const s=readFileSync(f,'utf8');if(secret && s.includes(secret))writeFileSync(f,s.replaceAll(secret,'[REDACTED_FIXTURE_SECRET]'));}
  }
}
scrub('.');unlinkSync('.dev.vars');
REDACT
    redact_rc=$?
    if [ "$redact_rc" -ne 0 ]; then
      printf 'PROOF_OUTCOME exit=%s stage=%s redaction_failed=true archive_withheld=true\n' "$proof_rc" "$STAGE"
      if [ "$final_rc" -eq 0 ]; then final_rc=$redact_rc; fi
      exit "$final_rc"
    fi
  fi
  if [ "$proof_rc" -eq 0 ] && [ "$STAGE" = complete ]; then
    node --input-type=module <<'VERDICT'
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
const rows=JSON.parse(readFileSync('trace.json','utf8'));
const a=rows.find(r=>r.phase==='assertions');
assert(a && a.passed===true && a.accepted===5 && a.duplicateResponses===5);
for(const k of ['actualProducerAndIntake','actualWorkerHmac','nativeSqlStorage','invalidSignature401','tamperedBody401','restartPersistent','commandAndSourceAuthorityPreserved']) assert.equal(a[k],true,k);
assert(!rows.some(r=>r.phase==='failure'));
assert.deepEqual(rows.find(r=>r.phase==='process_cleanup')?.remaining,[]);
VERDICT
    verdict_rc=$?
    if [ "$verdict_rc" -eq 0 ]; then passed=true; else final_rc=$verdict_rc; fi
  elif [ "$proof_rc" -eq 0 ]; then final_rc=1
  fi
  printf '{"passed":%s,"proofExit":%s,"commandExit":%s,"stage":"%s"}\n' "$passed" "$proof_rc" "$final_rc" "$STAGE" > outcome.json
  printf 'PROOF_OUTCOME exit=%s passed=%s stage=%s\n' "$final_rc" "$passed" "$STAGE"
  tar --exclude='./node_modules' --exclude='./home' --exclude='./tmp' \
    --exclude='./compiled' --exclude='./bin' --exclude='./persistence' \
    -czf "$ROOT/artifacts.tar.gz" .
  archive_rc=$?
  printf 'PROOF_ARCHIVE exit=%s\n' "$archive_rc"
  if [ "$archive_rc" -ne 0 ] && [ "$final_rc" -eq 0 ]; then final_rc=$archive_rc; fi
  if [ "$final_rc" -ne 0 ] && [ "$archive_rc" -eq 0 ]; then
    printf 'PROOF_ARCHIVE_BASE64_BEGIN\n'
    base64 "$ROOT/artifacts.tar.gz"
    printf 'PROOF_ARCHIVE_BASE64_END\n'
  fi
  exit "$final_rc"
}
trap finish EXIT
test "$(git -C "$REPO" rev-parse HEAD)" = "$EXPECTED"
test -z "$(git -C "$REPO" status --porcelain --untracked-files=no)"
# Local Docker has no AWS IMDS contract. Verify actual workload isolation before
# importing application code; host-side Docker inspect additionally verifies the
# exact image, mounts, environment names and provider container identity.
node --input-type=module - "$REPO" <<'SAFETY'
import assert from 'node:assert/strict';
import {existsSync,readFileSync,writeFileSync} from 'node:fs';
import {execFileSync} from 'node:child_process';
assert(existsSync('/.dockerenv'));
for(const p of ['/var/run/docker.sock','/run/docker.sock']) assert(!existsSync(p),p);
const names=Object.keys(process.env).sort();
const allowed=new Set(['PATH','HOME','TMPDIR','CI','COREPACK_ENABLE_DOWNLOAD_PROMPT',
  'COREPACK_ENABLE_PROJECT_SPEC','WRANGLER_SEND_METRICS','WRANGLER_LOG_PATH','PWD','OLDPWD','SHLVL','_']);
assert(names.every(n=>allowed.has(n)),'only isolated fixture environment names');
assert(process.env.HOME.startsWith(process.cwd()+'/home'));
assert(process.env.TMPDIR.startsWith(process.cwd()+'/tmp'));
const proc=readFileSync('/proc/self/status','utf8');
assert.equal(proc.match(/^CapEff:\s*(.*)$/m)[1],'0000000000000000');
assert.equal(proc.match(/^Seccomp:\s*(.*)$/m)[1],'2');
const mountTargets=readFileSync('/proc/self/mountinfo','utf8').trim().split('\n').map(s=>s.split(' ')[4]);
for(const p of ['/home','/root','/work/crabbox','/var/run/docker.sock','/run/docker.sock'])
  assert(!mountTargets.includes(p),'no host mount at '+p);
const repo=process.argv[2];
assert.equal(execFileSync('git',['-C',repo,'rev-parse','HEAD'],{encoding:'utf8'}).trim(),
  '9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208');
assert.equal(execFileSync('git',['-C',repo,'remote','get-url','origin'],{encoding:'utf8'}).trim(),
  'https://github.com/openclaw/clawsweeper.git');
const result={provider:'local-container',dockerMarker:true,uid:process.getuid(),
  effectiveCapabilities:'none',seccomp:2,envNames:names,mountTargets,
  noDockerSocket:true,isolatedHome:true,isolatedTmp:true,forwardedCredentials:'none',
  sourceHead:'9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208',sourceOrigin:'https://github.com/openclaw/clawsweeper.git',
  platform:process.platform,arch:process.arch,imds:'not applicable; not probed'};
writeFileSync('isolation.json',JSON.stringify(result,null,2)+'\n');
console.log('SAFETY '+JSON.stringify(result));
SAFETY
# Standard fixture tool only, installed inside the owned ephemeral container.
if ! command -v jq >/dev/null; then
  sudo -n apt-get update > fixture-tools-install.log 2>&1
  sudo -n apt-get install -y --no-install-recommends jq >> fixture-tools-install.log 2>&1
fi
node -e 'if (+process.versions.node.split(".")[0] < 24) throw Error("Node >=24 required")'
command -v corepack >/dev/null
command -v jq >/dev/null
sha256sum "$0" > bootstrap.sha256
STAGE=tooling
printf '{"private":true,"type":"module","packageManager":"pnpm@11.10.0","scripts":{"workflow":"node compiled/src/repair/workflow-utils.js"}}\n' > package.json
corepack pnpm@11.10.0 add --ignore-scripts --save-exact wrangler@4.107.0 yaml@2.9.0 > install.log 2>&1
node node_modules/wrangler/bin/wrangler.js dev --help > wrangler-dev-help.txt
for option in --local --ip --port --persist-to --inspector-port; do
  grep -q -- "$option" wrangler-dev-help.txt
done
cat > fixture.ts <<'WORKER'
import production from '__REPO__/dashboard/worker.ts';
import { ExactReviewQueue, EXACT_REVIEW_QUEUE_NAME } from '__REPO__/dashboard/exact-review-queue.ts';
const trace = [];
const textHash = async value => [...new Uint8Array(await crypto.subtle.digest('SHA-256',
  new TextEncoder().encode(value)))].map(x=>x.toString(16).padStart(2,'0')).join('');
const hash = value => textHash(JSON.stringify(value));
export class AdmissionProof extends ExactReviewQueue {
  instance = crypto.randomUUID();
  async fetch(request) {
    if (request.method !== 'GET' || new URL(request.url).pathname !== '/__proof/snapshot')
      return super.fetch(request);
    // Only the production initializer may write schema; all observations below
    // are reads. No queue, alarm, crypto, storage, or dispatch method is replaced.
    const initialized = await super.fetch(new Request('http://fixture.invalid/__proof/init'));
    if (initialized.status !== 404) throw Error('unexpected initialization result');
    const sql = this.storage.sql;
    const rows = (q,...args) => [...sql.exec(q,...args)];
    const names = rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
      .map(x=>x.name).filter(n=>!n.startsWith('_cf') && !n.startsWith('sqlite_'));
    const data = Object.fromEntries(names.map(n=>[n,rows(`SELECT * FROM "${n}" ORDER BY rowid`)]));
    const tables = {};
    for (const [name,value] of Object.entries(data)) tables[name]={rows:value.length,sha256:await hash(value)};
    const items = rows('SELECT item_key,item_json FROM exact_review_queue_items ORDER BY item_key')
      .map(r=>JSON.parse(r.item_json));
    return Response.json({doId:this.state.id.toString(),instance:this.instance,
      storageType:sql.constructor.name,sqliteVersion:'unavailable: workerd disallows sqlite_version()',
      observedAt:Date.now(),alarmAt:await this.storage.getAlarm(),
      stateHash:await hash(data),tables,items,itemsHash:await hash(items),
      receipts:rows('SELECT * FROM exact_review_queue_deliveries ORDER BY delivery_id'),
      metadata:rows('SELECT * FROM exact_review_queue_meta')});
  }
}
export default {async fetch(request,env,ctx) {
  const p = new URL(request.url).pathname;
  if (request.method === 'GET' && p === '/__proof/snapshot')
    return env.EXACT_REVIEW_QUEUE.get(env.EXACT_REVIEW_QUEUE.idFromName(EXACT_REVIEW_QUEUE_NAME)).fetch(request);
  if (request.method === 'GET' && p === '/__proof/trace') return Response.json(trace);
  // Observe a clone only: pass the original request and environment unchanged.
  const body = await request.clone().text();
  const response = await production.fetch(request,env,ctx);
  trace.push({method:request.method,path:p,requestBody:body,requestSha256:await textHash(body),
    status:response.status,response:await response.clone().json()});
  return response;
}};
WORKER
node --input-type=module - "$REPO" <<'SETUP'
import {readFileSync,writeFileSync,readdirSync,mkdirSync,copyFileSync,realpathSync} from 'node:fs';
import {createRequire} from 'node:module';
import {createHash} from 'node:crypto';
import path from 'node:path';
import YAML from 'yaml';
const repo=process.argv[2];
writeFileSync('fixture.ts',readFileSync('fixture.ts','utf8').replaceAll('__REPO__',repo));
const esbuild=createRequire(realpathSync(path.resolve('node_modules/wrangler/package.json')))('esbuild');
const manifest={};
function walk(dir) {return readdirSync(dir,{withFileTypes:true}).flatMap(e=>e.isDirectory()?walk(path.join(dir,e.name)):[path.join(dir,e.name)]);}
for (const f of [...walk(path.join(repo,'src')),...walk(path.join(repo,'dashboard'))].filter(f=>f.endsWith('.ts'))) {
  const source=readFileSync(f,'utf8'), relative=path.relative(repo,f);
  manifest[relative]=createHash('sha256').update(source).digest('hex');
  if(relative.startsWith('src/')) {
    const dest=path.join('compiled',relative.replace(/\.ts$/,'.js'));
    mkdirSync(path.dirname(dest),{recursive:true});
    writeFileSync(dest,esbuild.transformSync(source,{loader:'ts',format:'esm',target:'node24'}).code);
  }
}
mkdirSync('compiled/config',{recursive:true});
for (const f of ['automation-limits.json','target-repositories.json']) copyFileSync(path.join(repo,'config',f),path.join('compiled/config',f));
const workflow=readFileSync(path.join(repo,'.github/workflows/sweep.yml'),'utf8');
const parsed=YAML.parse(workflow);
for(const [file,job,name] of [
  ['producer.sh','apply-existing','Requeue drift-blocked close reviews'],
  ['intake.sh','legacy-event-queue-intake','Enqueue legacy event through the durable control plane']]) {
  const matches=parsed.jobs[job].steps.filter(s=>s.name===name);
  if(matches.length!==1 || !matches[0].run || matches[0].run.includes('${{')) throw Error('step extraction failed');
  writeFileSync(file,matches[0].run);
  manifest[file]=createHash('sha256').update(matches[0].run).digest('hex');
}
copyFileSync(path.join(repo,'test/fixtures/apply-drift-refresh-report.json'),'apply-report.json');
for (const f of ['.github/workflows/sweep.yml','test/fixtures/apply-drift-refresh-report.json','scripts/e2e/apply-drift-refresh.ts'])
  manifest[f]=createHash('sha256').update(readFileSync(path.join(repo,f))).digest('hex');
writeFileSync('source-manifest.json',JSON.stringify(manifest,null,2)+'\n');
writeFileSync('wrangler.json',JSON.stringify({name:'drift-admission-proof',main:'fixture.ts',
  compatibility_date:'2026-05-11',workers_dev:false,send_metrics:false,
  durable_objects:{bindings:[{name:'EXACT_REVIEW_QUEUE',class_name:'AdmissionProof'}]},
  migrations:[{tag:'v1',new_sqlite_classes:['AdmissionProof']}],
  vars:{GITHUB_API_URL:'http://127.0.0.1:9',TARGET_REPOS:'openclaw/openclaw',PUBLIC_BAY_REPOS:'',
    EXACT_REVIEW_DISPATCH_DEBOUNCE_MS:'900000',EXACT_REVIEW_DISPATCH_DEBOUNCE_MAX_MS:'900000',
    EXACT_REVIEW_WORKFLOW_PAUSED_RETRY_MS:'900000'}},null,2)+'\n');
SETUP
mkdir bin
cat > bin/gh <<'GH'
#!/usr/bin/env node
const fs=require('node:fs'),assert=require('node:assert/strict');
const args=process.argv.slice(2);
assert.equal(args[0],'api');
fs.appendFileSync('gh-transport.jsonl',JSON.stringify({transport:'synthetic-gh',args})+'\n');
const endpoint=args.find(a=>a.startsWith('repos/'));
if(args.includes('POST')) {
  assert.equal(endpoint,'repos/openclaw/clawsweeper/dispatches');
  assert(args.includes('--input'));
  fs.appendFileSync('dispatches.jsonl',JSON.stringify(JSON.parse(fs.readFileSync(0,'utf8')))+'\n');
} else if(endpoint==='repos/openclaw/openclaw') process.stdout.write('release/proof-branch');
else {
  assert.match(endpoint,/^repos\/openclaw\/openclaw\/issues\/\d+$/);
  process.stdout.write([128515,121477].includes(+endpoint.split('/').at(-1))?'pull_request':'issue');
}
GH
# This gh is the ONLY intercepted transport. curl is real; pnpm's launcher pins
# the real package manager rather than replacing the selector or its execution.
chmod +x bin/gh
cat > bin/pnpm <<'PNPM'
#!/usr/bin/env bash
exec corepack pnpm@11.10.0 "$@"
PNPM
chmod +x bin/pnpm
cat > bin/package.json <<'PACKAGE'
{"type":"commonjs"}
PACKAGE
cat > run.mjs <<'DRIVER'
import assert from 'node:assert/strict';
import {spawn,execFileSync} from 'node:child_process';
import {openSync,closeSync,writeFileSync,readFileSync,readdirSync,appendFileSync} from 'node:fs';
import {createHash,createHmac,randomBytes} from 'node:crypto';
import path from 'node:path';
const trace=[],children=[],url='http://127.0.0.1:18787';
const key=randomBytes(32).toString('hex');
const emit=(phase,detail)=>{const row={phase,...detail};trace.push(row);console.log(JSON.stringify(row));};
const sha=f=>createHash('sha256').update(readFileSync(f)).digest('hex');
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
const wait=ms=>new Promise(r=>setTimeout(r,ms));
const env={...process.env,PATH:path.resolve('bin')+':'+process.env.PATH,
  APPLY_TARGET_REPO:'openclaw/openclaw',APPLY_AUTO_SELECTED_BATCH:'true',DISPATCH_REPOSITORY:'openclaw/clawsweeper',
  GITHUB_RUN_ATTEMPT:'1',QUEUE_URL:url,CLAWSWEEPER_WEBHOOK_SECRET:key};
writeFileSync('.dev.vars','CLAWSWEEPER_WEBHOOK_SECRET='+key+'\n',{mode:0o600});
let current;
function ownedPids(group) {
  return execFileSync('ps',['-eo','pid,pgid,stat,comm'],{encoding:'utf8'}).trim().split('\n').slice(1)
    .map(s=>s.trim().split(/\s+/)).filter(a=>+a[1]===group).map(a=>({pid:+a[0],pgid:+a[1],state:a[2],command:a[3]}));
}
async function api(route) {
  const r=await fetch(url+route,{signal:AbortSignal.timeout(5000)});
  assert.equal(r.status,200);return r.json();
}
async function start(sequence) {
  const fd=openSync(`wrangler-${sequence}.log`,'w');
  const child=spawn(process.execPath,[path.resolve('node_modules/wrangler/bin/wrangler.js'),'dev','--local',
    '--ip','127.0.0.1','--port','18787','--inspector-port','18788','--persist-to',path.resolve('persistence'),
    '--config',path.resolve('wrangler.json')],{stdio:['ignore',fd,fd],detached:true});
  closeSync(fd);current=child;children.push(child);
  child.exited=new Promise(resolve=>child.once('exit',(code,signal)=>resolve({code,signal})));
  let snapshot;
  for(let i=0;i<100;i++) {
    if(child.exitCode!==null) throw Error('Wrangler exited before readiness; inspect retained runtime log');
    try {snapshot=await api('/__proof/snapshot');break;} catch(e) {if(i===99)throw e;await wait(300);}
  }
  const pids=ownedPids(child.pid);
  assert(pids.some(p=>p.command.includes('workerd')));
  assert.equal(snapshot.storageType,'SqlStorage');
  emit('process_start',{sequence,group:child.pid,pids,doId:snapshot.doId,instance:snapshot.instance});
  return snapshot;
}
async function stop(sequence) {
  if(!current)return;
  const child=current;current=null;
  try{process.kill(-child.pid,'SIGTERM');}catch(e){if(e.code!=='ESRCH')throw e;}
  let exit=await Promise.race([child.exited,wait(6000).then(()=>null)]);
  if(!exit){try{process.kill(-child.pid,'SIGKILL');}catch(e){if(e.code!=='ESRCH')throw e;}exit=await child.exited;}
  for(let i=0;i<40 && ownedPids(child.pid).some(p=>!p.state.startsWith('Z'));i++)await wait(100);
  let remaining=ownedPids(child.pid).filter(p=>!p.state.startsWith('Z'));
  if(remaining.length){try{process.kill(-child.pid,'SIGKILL');}catch(e){if(e.code!=='ESRCH')throw e;}await wait(200);}
  remaining=ownedPids(child.pid).filter(p=>!p.state.startsWith('Z'));
  assert.equal(remaining.length,0,'owned process group stopped');
  let accepting=false;try{await fetch(url,{signal:AbortSignal.timeout(1000)});accepting=true;}catch{}
  assert.equal(accepting,false,'loopback closed');
  emit('process_stop',{sequence,group:child.pid,exit,remaining,loopbackClosed:true});
}
async function bash(file,extra={}) {
  await new Promise((resolve,reject)=>{
    const fd=openSync('steps.log','a');
    const c=spawn('bash',[path.resolve(file)],{env:{...env,...extra},stdio:['ignore',fd,fd]});closeSync(fd);
    c.once('error',reject);c.once('exit',code=>code===0?resolve():reject(Error(file+' exited '+code)));
  });
}
const selected=[43367,128515,119583,121477,77508];
function normal(snapshot) {
  assert.equal(snapshot.items.length,5);
  for(const n of selected) {
    const item=snapshot.items.find(i=>i.decision.itemNumber===n),d=item.decision;
    assert.equal(item.state,'pending');assert.equal(item.revision,1);assert.equal(item.attempts,0);
    assert.equal(item.backoffReason,'dispatch_debounce');assert(item.nextAttemptAt>snapshot.observedAt);
    assert.equal(d.targetRepo,'openclaw/openclaw');assert.equal(d.targetBranch,'release/proof-branch');
    assert.equal(d.itemKind,[128515,121477].includes(n)?'pull_request':'issue');
    assert.equal(d.sourceEvent,d.itemKind==='pull_request'?'pull_request':'issues');
    assert.equal(d.sourceAction,'source_drift_requeue');assert.equal(d.codexTimeoutMs,1200000);
    assert.equal(d.supersedesInProgress,false);
    for(const f of ['sourceHeadSha','sourceBaseSha','sourceAuthoritySeq','sourceUpdatedAt','sourceDeliveryId',
      'sourceHeadVerified','commandStatusMarker','statusCommentId','force','queue_lease_id']) assert(!Object.hasOwn(d,f),f);
    for(const f of ['leaseId','leaseRevision','claimedRunId']) assert(!Object.hasOwn(item,f),f);
  }
  assert(snapshot.alarmAt>snapshot.observedAt);
}
async function signed(envelope,mode='valid') {
  const original=JSON.stringify(envelope),body=mode==='tampered'?original+' ':original;
  const signature='sha256='+createHmac('sha256',mode==='invalid'?randomBytes(32):key).update(original).digest('hex');
  const r=await fetch(url+'/internal/exact-review/enqueue',{method:'POST',
    headers:{'content-type':'application/json','x-clawsweeper-exact-review-signature':signature},body});
  const response=await r.json();return {mode,status:r.status,response};
}
function files(dir) {
  return readdirSync(dir,{withFileTypes:true}).flatMap(e=>e.isDirectory()?files(path.join(dir,e.name)):
    [{path:path.join(dir,e.name),sha256:sha(path.join(dir,e.name))}]);
}
for(const s of ['SIGTERM','SIGINT'])process.once(s,async()=>{try{await stop(s);}finally{process.exit(128);}});
try {
  const manifest=JSON.parse(readFileSync('source-manifest.json'));
  const wp=readdirSync('node_modules/.pnpm').filter(n=>n.startsWith('workerd@'));assert.equal(wp.length,1);
  emit('runtime',{head:'9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208',base:'f211e21fb89d00777ac07cc13c358f9f7b02a939',
    node:process.version,pnpm:execFileSync('corepack',['pnpm@11.10.0','--version'],{encoding:'utf8'}).trim(),
    bash:execFileSync('bash',['--version'],{encoding:'utf8'}).split('\n')[0],
    curl:execFileSync('curl',['--version'],{encoding:'utf8'}).split('\n')[0],
    wrangler:JSON.parse(readFileSync('node_modules/wrangler/package.json')).version,
    workerd:JSON.parse(readFileSync(`node_modules/.pnpm/${wp[0]}/node_modules/workerd/package.json`)).version,
    fixtureSha256:sha('fixture.ts'),configSha256:sha('wrangler.json'),lockSha256:sha('pnpm-lock.yaml'),
    moduleManifestSha256:sha('source-manifest.json'),sourceHashes:Object.fromEntries([
      '.github/workflows/sweep.yml','producer.sh','intake.sh','test/fixtures/apply-drift-refresh-report.json',
      'dashboard/worker.ts','dashboard/exact-review-queue.ts','dashboard/exact-review-decision.ts',
      'src/repair/workflow-utils.ts'].map(f=>[f,manifest[f]])),
    localOnly:true,debounceMs:900000,githubApi:'http://127.0.0.1:9',githubAppCredentials:'absent'});
  assert.equal(JSON.parse(readFileSync('node_modules/wrangler/package.json')).version,'4.107.0');
  const report=JSON.parse(readFileSync('apply-report.json'));assert.equal(report.length,27);
  assert.equal(report.filter(r=>r.action==='skipped_changed_since_review').length,15);
  await bash('producer.sh');
  const events=readFileSync('dispatches.jsonl','utf8').trim().split('\n').map(JSON.parse);
  assert.deepEqual(events.map(e=>+e.client_payload.item_number),selected);
  for(const e of events){assert.equal(e.event_type,'clawsweeper_item');assert(!Object.hasOwn(e.client_payload,'queue_lease_id'));}
  emit('producer',{recordedRows:27,driftRows:15,selected,events,transport:'synthetic gh metadata and captured repository_dispatch only'});
  const baseline=await start(1);assert.equal(baseline.items.length,0);assert.equal(baseline.receipts.length,0);
  for(const e of events) await bash('intake.sh',{CLIENT_PAYLOAD:JSON.stringify(e.client_payload),GITHUB_RUN_ID:String(e.client_payload.item_number)});
  const admitted=await api('/__proof/snapshot');normal(admitted);assert.equal(admitted.receipts.length,5);
  const requests=await api('/__proof/trace');assert.equal(requests.length,5);
  for(const r of requests){assert.equal(r.status,202);assert.equal(r.response.queued,true);assert.equal(r.response.superseded_publications,0);}
  emit('signed_admission',{requests,snapshot:admitted,realCurl:true});
  for(const e of events)await bash('intake.sh',{CLIENT_PAYLOAD:JSON.stringify(e.client_payload),GITHUB_RUN_ID:String(e.client_payload.item_number)});
  const duplicate=await api('/__proof/snapshot');normal(duplicate);
  assert.deepEqual(duplicate.items,admitted.items);assert.deepEqual(duplicate.receipts,admitted.receipts);
  const duplicateResponses=(await api('/__proof/trace')).slice(5);assert.equal(duplicateResponses.length,5);
  for(const r of duplicateResponses){assert.equal(r.status,202);assert.equal(r.response.deduped,true);}
  emit('duplicate_delivery',{responses:duplicateResponses,itemsHash:duplicate.itemsHash,items:5,receipts:5,replaced:false});
  const envelope=JSON.parse(requests[0].requestBody);envelope.delivery_id='signature-negative-control';
  for(const mode of ['invalid','tampered']) {
    const before=await api('/__proof/snapshot'),result=await signed(envelope,mode),after=await api('/__proof/snapshot');
    assert.equal(result.status,401);assert.equal(result.response.error,'invalid_signature');
    assert.equal(before.stateHash,after.stateHash);assert.deepEqual(before.receipts,after.receipts);
    emit('signature_rejection',{...result,beforeHash:before.stateHash,afterHash:after.stateHash,items:after.items.length,receipts:after.receipts.length});
  }
  const beforeRestart=await api('/__proof/snapshot');
  writeFileSync('worker-trace-1.json',JSON.stringify(await api('/__proof/trace'),null,2)+'\n');
  await stop(1);emit('persisted_files',{files:files('persistence')});
  const reopened=await start(2);normal(reopened);
  assert.equal(reopened.doId,beforeRestart.doId);assert.notEqual(reopened.instance,beforeRestart.instance);
  assert.deepEqual(reopened.items,beforeRestart.items);assert.deepEqual(reopened.receipts,beforeRestart.receipts);
  assert.equal(reopened.stateHash,beforeRestart.stateHash);
  emit('restart',{sameDoId:true,newInstance:true,beforeHash:beforeRestart.stateHash,afterHash:reopened.stateHash,
    snapshot:reopened});
  // Optional command/source authority control: a separate fixture item enters by
  // signed production admission, never by SQL seeding. Missing App configuration
  // makes its immediate alarm take the existing blocked/retry path without I/O.
  const command={delivery_id:'fixture-existing-command',decision:{...JSON.parse(requests[1].requestBody).decision,
    itemNumber:128516,sourceAction:'exact_review_command',
    commandStatusMarker:'<!-- clawsweeper-command-status:128516:re_review:fixture -->',statusCommentId:9001,
    sourceHeadSha:'a'.repeat(40),sourceHeadVerified:true,sourceAuthoritySeq:7}};
  const commandResult=await signed(command);assert.equal(commandResult.status,202);assert(commandResult.response.queued);
  let commandBefore;
  for(let i=0;i<50;i++) {
    commandBefore=await api('/__proof/snapshot');
    const dispatcher=JSON.parse(commandBefore.metadata[0].dispatcher_json||'{}');
    if(dispatcher.state==='blocked' && dispatcher.reason==='workflow_status_unavailable')break;
    if(i===49)throw Error('expected credential-free dispatcher backoff');await wait(200);
  }
  const refresh={delivery_id:'fixture-refresh-over-command',decision:{...JSON.parse(requests[1].requestBody).decision,itemNumber:128516}};
  const refreshResult=await signed(refresh);assert.equal(refreshResult.status,202);
  const commandAfter=await api('/__proof/snapshot');
  assert.deepEqual(commandAfter.items,commandBefore.items);
  const preserved=commandAfter.items.find(i=>i.decision.itemNumber===128516);
  assert.equal(preserved.decision.sourceAuthoritySeq,7);assert.equal(preserved.decision.sourceHeadSha,'a'.repeat(40));
  assert.equal(preserved.decision.commandStatusMarker,command.decision.commandStatusMarker);
  assert.equal(preserved.decision.sourceAction,'exact_review_command');
  assert(commandAfter.items.every(i=>i.state==='pending' && !i.leaseId && i.attempts===0));
  assert(commandAfter.alarmAt>commandAfter.observedAt);
  emit('authority_preserved',{commandResult,refreshResult,beforeItemsHash:commandBefore.itemsHash,
    afterItemsHash:commandAfter.itemsHash,preserved,dispatcher:JSON.parse(commandAfter.metadata[0].dispatcher_json),
    totalItems:commandAfter.items.length,receipts:commandAfter.receipts.length,alarmAt:commandAfter.alarmAt});
  writeFileSync('worker-trace-2.json',JSON.stringify(await api('/__proof/trace'),null,2)+'\n');
  emit('assertions',{passed:true,actualProducerAndIntake:true,actualWorkerHmac:true,nativeSqlStorage:true,
    accepted:5,duplicateResponses:5,invalidSignature401:true,tamperedBody401:true,restartPersistent:true,
    commandAndSourceAuthorityPreserved:true,modelExecution:false,realGithubDispatch:false});
} catch(e) {
  if(current) {
    try {writeFileSync('failure-worker-trace.json',JSON.stringify(await api('/__proof/trace'),null,2)+'\n');} catch {}
    try {writeFileSync('failure-snapshot.json',JSON.stringify(await api('/__proof/snapshot'),null,2)+'\n');} catch {}
  }
  emit('failure',{message:String(e),classification:'inspect assertion/setup evidence; not automatically a product failure'});throw e;
} finally {
  await stop('final');
  const remaining=children.flatMap(c=>ownedPids(c.pid).filter(p=>!p.state.startsWith('Z')));
  emit('process_cleanup',{ownedGroups:children.map(c=>c.pid),remaining});
  writeFileSync('trace.json',JSON.stringify(trace,null,2)+'\n');assert.equal(remaining.length,0);
}
DRIVER
STAGE=admission
node run.mjs
STAGE=source_verification
test "$(git -C "$REPO" rev-parse HEAD)" = "$EXPECTED"
test -z "$(git -C "$REPO" status --porcelain --untracked-files=no)"
printf 'FINAL source_head_unchanged=true tracked_source_clean=true\n'
STAGE=complete
prepare.sh — exact 503-byte source/isolation preflight
#!/usr/bin/env bash
set -euo pipefail
test "$(git rev-parse HEAD)" = 9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208
test -z "$(git status --porcelain --untracked-files=no)"
test -f /.dockerenv
test ! -S /var/run/docker.sock
node -e 'console.log(JSON.stringify({phase:"fresh-source-preflight",head:"9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208",node:process.version,arch:process.arch,envNames:Object.keys(process.env).sort()}))'
printf 'Application code not executed; awaiting host Docker isolation inspection.\n'

Historical failed attempts

AWS: two SSH failures and one temporary pnpm/esbuild lookup failure; all leases released. These are not proof. Container attempts: (1) exit 2, incompatible --fresh-pr/--no-sync, app not run; (2) exit 1, observer omitted Bash's OLDPWD; (3) exit 1, workerd rejected optional sqlite_version(). That observation was removed; SQLite version remains unavailable. Required assertions/production behavior were unchanged. Attempt 4 passed in the same container. No CI/proof rerun for this presentation update.

@steipete
steipete requested a review from a team as a code owner August 27, 2026 04:52
@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 27, 2026, 4:53 AM ET / 08:53 UTC.

ClawSweeper review

What this changes

This PR changes default apply drift refreshes from broad target sweeps to bounded exact-item queue events, with workflow, documentation, and focused regression coverage.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open: current main still sends drift refreshes through broad planning, while this PR routes them through the existing exact-item queue and provides current-head native Worker/Durable Object evidence for that path.

Priority: P2
Reviewed head: 9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused workflow change has strong submitted runtime evidence and no concrete correctness or security finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The current PR body provides after-fix native Worker/Durable Object live output for the exact head, including admission, deduplication, rejection, restart, and authority-preservation observations.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The current PR body provides after-fix native Worker/Durable Object live output for the exact head, including admission, deduplication, rejection, restart, and authority-preservation observations.
Evidence reviewed 6 items Current main still uses broad planning: Current main emits clawsweeper_target_sweep with one-item planner settings for each selected drifted item, so the reported hydration-before-admission failure remains unaddressed there.
Candidate uses the existing queue boundary: The PR emits clawsweeper_item, includes the live item kind, marks the recovery as non-superseding, and dispatches to the repository event intake rather than invoking a planner.
Queue contract preserves recovery priority: The existing queue recognizes source_drift_requeue as low priority, while queue-policy coverage verifies it cannot supersede an active authoritative review and is shed under pending backpressure.
Findings None None.
Security None None.

Live Verification

Command: pnpm run build:all

Result: PASS (completed)

$ pnpm run build && pnpm run build:repair && pnpm run build:dashboard
$ tsc -p tsconfig.json
$ tsc -p tsconfig.repair.json
$ tsc -p tsconfig.dashboard.json
exact-review admission shed {
  event: 'admission_shed',
  category: 'backpressure',
  pending_count: 1,
  configured_limit: 1
}
{
  "artifacts": "/tmp/clawsweeper-live-proof-1258-X3uVNC/profile/tmp/clawsweeper-drift-refresh-sBzKUC",
  "provider": "local-controlled-subprocess",
  "id": "clawsweeper-drift-refresh-sBzKUC",
  "node": "v24.19.0",
  "head": "9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208",
  "workflowSha256": "40ec59f950c0fa30a1e6c67f6021ee53ac009269fb66102e22c9bcd6f76b10b9",
  "reportSha256": "d9a46a48d34a372cac35d7f2441176bebf771deab7de32fe05983c33bf44fb33",
  "recordedRows": 27,
  "driftRows": 15,
  "selected": [
    43367,
    128515,
    119583,
    121477,
    77508
  ],
  "queueAccepted": 5,
  "executorDispatches": 2,
  "stillPending": 1,
  "terminalBeforeDispatch": 2,
  "assertions": "selection/order/cap; exact routing; normalized branch/kind/source/refresh semantics; duplicate, command authority and leased preservation; back
pressure and invalid target; closed/missing live guards; read/dispatch/intake failures; default-apply guards",
  "limits": "Controlled Bash/Node subprocesses and real queue code on local test SQLite storage; synthetic issue/PR kinds, GitHub responses and public fixture s
igning key. No hosted GitHub, real Cloudflare DO, production admission, Codex review, publication, or close executed. No container/image/lease."
}

Assertions:

  • PASS expect_output: "provider": "local-controlled-subprocess"

How this fits together

Apply processes prior close results and refreshes items whose source changed. The refresh dispatch enters the durable exact-review queue, which applies admission, backpressure, leases, and then starts an exact-item review.

flowchart LR
A[Apply report] --> B[Select up to five drifted items]
B --> C[Read branch and item kind]
C --> D[Exact-item event]
D --> E[Durable queue admission]
E --> F[Leased exact review]
F --> G[Review record and guarded apply]
Loading

Before merge

  • Resolve merge risk (P0) - A temporary repository-dispatch or queue-intake outage now defers a source-drift refresh instead of falling back to broad planning; the workflow exposes the failure, and later apply runs can retry it.
  • Complete next step (P2) - No discrete repair finding remains; this PR is ready for normal maintainer merge consideration.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Workflow routing 10 added, 6 removed The production behavior change is confined to one default-apply requeue step.
Validation support test/proof +551, -3 lines The patch adds a focused workflow-to-queue harness, fixture, and assertions around the changed route.

Merge-risk options

Maintainer options:

  1. Accept bounded queue-only recovery (recommended)
    Keep the exact-item route because it avoids the demonstrated broad-planner overload while preserving visible dispatch failures and existing queue recovery controls.

Technical review

Best possible solution:

Land the narrow queue-only routing change while retaining the existing low-priority queue backpressure and lease behavior.

Do we have a high-confidence way to reproduce the issue?

Yes, source-reproducible: current main's workflow still emits a broad target-sweep event for every selected drifted item, while the PR's exact-item event reaches the pre-existing queue intake instead.

Is this the best way to solve the issue?

Yes. Reusing the established signed exact-item queue is the narrowest repair because it removes the unnecessary planner/hydration stage without introducing a bypass, new permission, or parallel queue.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 71df3a1ce714.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The current PR body provides after-fix native Worker/Durable Object live output for the exact head, including admission, deduplication, rejection, restart, and authority-preservation observations.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The current PR body provides after-fix native Worker/Durable Object live output for the exact head, including admission, deduplication, rejection, restart, and authority-preservation observations.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded reliability repair for apply-driven review refreshes.
  • merge-risk: 🚨 availability: Merging changes the recovery path's runtime dependency from broad planning to repository dispatch and durable queue admission.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The current PR body provides after-fix native Worker/Durable Object live output for the exact head, including admission, deduplication, rejection, restart, and authority-preservation observations.
  • proof: sufficient: Contributor real behavior proof is sufficient. The current PR body provides after-fix native Worker/Durable Object live output for the exact head, including admission, deduplication, rejection, restart, and authority-preservation observations.

Evidence

What I checked:

  • Current main still uses broad planning: Current main emits clawsweeper_target_sweep with one-item planner settings for each selected drifted item, so the reported hydration-before-admission failure remains unaddressed there. (.github/workflows/sweep.yml:7043, 71df3a1ce714)
  • Candidate uses the existing queue boundary: The PR emits clawsweeper_item, includes the live item kind, marks the recovery as non-superseding, and dispatches to the repository event intake rather than invoking a planner. (.github/workflows/sweep.yml:7044, 9d8d2ab6f1fe)
  • Queue contract preserves recovery priority: The existing queue recognizes source_drift_requeue as low priority, while queue-policy coverage verifies it cannot supersede an active authoritative review and is shed under pending backpressure. (dashboard/exact-review-decision.ts:12, 9d8d2ab6f1fe)
  • Feature provenance: The existing drift-requeue feature appears to date to the prior apply change, and the proposed workflow update is a focused follow-up by the same area contributor. (.github/workflows/sweep.yml:7022, ce250708c1ea)
  • Real behavior proof: The current PR body records a current-head Docker-backed local-container run using real curl, Worker HMAC, native workerd SqlStorage, restart persistence, duplicate handling, and invalid-signature controls; its stated limits do not claim deployed Cloudflare or hosted GitHub delivery. (9d8d2ab6f1fe)
  • Security scope: The diff adds no credentials, permissions, third-party dependencies, or new endpoint; it passes data through the existing signed queue intake. (.github/workflows/sweep.yml:7024, 9d8d2ab6f1fe)

Likely related people:

  • steipete: History attributes both the original drift-requeue feature and this workflow-path correction to Peter Steinberger. (role: originated the existing drift-requeue behavior and authored the focused follow-up; confidence: high; commits: ce250708c1ea, 9d8d2ab6f1fe; files: .github/workflows/sweep.yml, docs/scheduler.md, dashboard/exact-review-decision.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-27T04:55:54.012Z sha 9d8d2ab :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-27T06:37:31.668Z sha 9d8d2ab :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-27T08:22:23.253Z sha 9d8d2ab :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 27, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The main PR body now contains passing actual signed Worker/native Durable Object admission proof for unchanged head 9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208, including the exact bootstrap and sanitized HTTP/native SQL trace. Docker-backed Crabbox local-container exercised the actual producer/intake, real curl and HMAC verification, five persisted admissions, deduplication, invalid-signature/tamper rejection, restart persistence, and command/source-authority preservation. All owned resources are removed; failed attempts remain disclosed. This resolves the prior missing-runtime-proof request without changing production code or weakening a gate. Exact-head CI and fresh independent review are clean. Please review the current body and proof; this is a review-only request, not an autofix or automerge command.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The main body is now native-proof-first. Both compactIssue and compactPullRequest hydrate only the first 12,000 body characters; the previous detailed native proof began at 14,235 and its HTTP/SQL trace at 19,562, beyond that window. The actual native trace now begins at 1,978, with five real curl/HMAC admissions, native SQL rows, duplicate preservation, both 401 controls, restart persistence and authority checks visible early. This is the existing passing 08:06 UTC Docker-backed local-container run, not the supplementary mocked checked-in harness. Exact head 9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208, executable SHA d51833ed3daf2dc1c243090a979ccb4aa1e665ebcf6a468bacd092b39c493255, full script and full selected trace are unchanged and retained inline. No code, assertion, CI result or proof outcome changed. Please assess the current body and the accepted proof-request disposition; review only, no autofix/automerge.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 27, 2026
@steipete
steipete merged commit 13f7749 into main Aug 27, 2026
35 checks passed
@steipete
steipete deleted the steipete/clawsweeper-direct-drift-refresh-20260826 branch August 27, 2026 09:21
@steipete

Copy link
Copy Markdown
Contributor Author

Merged the approved head 9d8d2ab6f1fe9162ecd25f62a4088c65b6f6c208 as 13f77495c462 at 2026-08-27 09:21:48 UTC. Its parent is 71df3a1ce714d737e250008597075bb5eaeb2ac4; all eight merged files match the reviewed head byte for byte. The PR body was unchanged before merge. The durable review, reviewed at 08:53:45.260 UTC, was freshly verified against the exact head, body and discussion source revision. It reports sufficient proof, no actionable code or security findings, and no remaining rank-up requests or contributor blockers.

Maintainer decision: accept the recommended bounded queue-only availability tradeoff. A repository-dispatch or intake outage remains visible and later apply can retry; broad fallback would reintroduce the demonstrated hydration overload. The existing queue retains admission, backpressure, leases and command authority. Refreshed source remains required before close. This is an explicit availability decision, not a proof waiver or acceptance of a code finding; normal maintainer merge consideration is complete.

Validation: 274 focused tests passed. Exact-head full pnpm check, sparse repair build and Windows launcher CI, CodeQL, and automerge E2E passed. The exact squash-commit main CI run passed within the bounded 15-minute watch: pnpm check and Windows launcher passed; sparse repair smoke was skipped.

The native Docker proof passed on the exact approved head using Crabbox provider local-container, lease cbx_a2b310396e1c, run run_1c115b737135, image node:24-bookworm@sha256:4196d66a565c6f195728d9952f161f4adfe2ad753052a08b7ec7f1c5a6bda42b (native Linux arm64, Node 24.19.0, Wrangler 4.107.0, workerd 1.20260701.1). Actual producer/intake Bash and real curl reached the unmodified Worker HMAC and native Durable Object SqlStorage: five admissions, five duplicates, invalid-signature and tampered-body HTTP 401 controls, restart persistence, and command/source authority preservation passed. All 372 source/step hashes and the executed bootstrap were checked; owned resources were removed. Full executable bytes and traces remain in the PR body; local Docker has no hosted run URL.

Limits and earlier attempts remain explicit: GitHub metadata and repository-dispatch transport were controlled; this does not prove hosted GitHub delivery, deployed Cloudflare, model execution, review publication or close. No new runtime proof was run on the squash commit. Earlier AWS/harness attempts failed and remain documented. The earlier review-context cutoff omitted the native evidence; moving the actual trace earlier while preserving the full script and trace made it visible to the current sufficient-proof review. The earlier full local check still has 48 baseline fixture/offline dependency failures (3,706 passed, nine skipped); it is not relabeled green because hosted CI passed.

OpenClaw Bay needs no change: existing events, decisions, lifecycle/status fields, schemas and routes are reused, and Bay remains observer-only. GitHub's existing automatic cleanup deleted this PR's remote head after merge; the local PR branch and all other existing local branches are retained. No manual branch deletion or repository-setting change was used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant