Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(feedback): add official intake and durable Skill client (#2066)
Maxa53aa334a0e1
diff --git a/docs/plans/feedback-intake-launch.md b/docs/plans/feedback-intake-launch.mdnew file mode 100644index 000000000..a1ef24f4e--- /dev/null+++ b/docs/plans/feedback-intake-launch.md@@ -0,0 +1,316 @@+# Official feedback intake — first launch++Owner: local PM Session seskmjhgq2476. Owner requested launch on 2026-09-20.+The user-facing outcome is: an Avibe user without a GitHub account asks their+current Agent to report a bug or feature, reviews the sanitized publication,+and receives the actual Issue link after official submission succeeds.++## Scope and reuse++Use the existing dedicated avibe-feedback VM on ad, Session `ses9u23mgw6dr`,+Share ID `132vCvND49U`, and its paired origin+https://avibe-feedback-app.avibe.bot/p/132vCvND49U/. Reuse public Show server API admission+from merged PR2039 and the use-avibe feedback guidance from merged PR2037.+This is an installed Show application, not a new Cloud service or general+cross-instance Agent execution API. No GitHub webhook is required. No model+Agent runs in the intake VM. All GitHub writes target github.com/avibe-bot/avibe.++First launch covers bug/feature submission and retrieving its public Issue URL.+Existing local GitHub-authorized submission remains available. Follow-up comments,+anonymous identity, arbitrary attachments/URLs, triage/merge automation and a new+interactive browser form are outside this first launch. Issue activity can use+the existing user-side Watch after an Issue URL is known. Do not promise releases+or resolution events unsupported by that waiter.++## Fixed protocol (v1)++PM accepted the allocated public Show Session `ses9u23mgw6dr`, share ID+`132vCvND49U`, on 2026-09-20. PM observed it private at access revision 2 with the same staged binding; the+intake remains unavailable until commissioning verifies the reviewed app. This+source change does not change page visibility. No client accepts a destination+from report text, issues or redirects. POST endpoint is+https://avibe-feedback-app.avibe.bot/p/132vCvND49U/api/feedback; GET receipt+endpoint is+https://avibe-feedback-app.avibe.bot/p/132vCvND49U/api/feedback-status?request_id=<UUIDv4>.++POST JSON has exactly these fields:++```json+{+ "schema_version": 1,+ "request_id": "an RFC4122 UUIDv4 generated once by the submitting client",+ "kind": "bug",+ "title": "component: observed symptom or requested capability",+ "body": "The complete sanitized Markdown approved for publication.",+ "public_consent": true+}+```++kind is bug or feature; title is nonempty, single-line, at most200characters;+body is nonempty and at most20000UTF-8 bytes. Entire request <=32768bytes.+Unknown fields, unsupported versions/kinds, malformed encodings and false+consent fail before writes. No labels, assignees, target repo, executable paths,+callback URLs, credentials or priority are accepted. Text is data throughout.++The existing native POST ingress returns a status-only generic body. Do not+change that core contract to carry an Issue URL. The client retains request_id+before POST and reads GET feedback-status with that same ID for a receipt.+The ID is a correlation key, not authority to mutate anything or a credential;+the public GET response contains no report body/title, personal identity, PAT or+raw upstream errors. It is permitted in the URL because the only disclosed+success value is a public GitHub Issue reference. No supplemental write route.++Receipt JSON: schema_version=1, request_id, state; state is pending, created,+unknown or failed. Only created includes issue_number and canonical issue_url+under https://github.com/avibe-bot/avibe/issues/<number>. Absent ID returns404.+Controlled failures may carry an allowlisted error code, no internal details.+Receipts are no-store. Bound GET requests and return only known record results;+do not make GitHub requests on every status read.++## Submission correctness++One app-owned SQLite ledger, outside Avibe internal storage, durably reserves+request_id+payload hash before issuing a GitHub POST. Concurrent same-ID same-body+submissions coalesce; changed payload with same ID returns409. Exact repeats can+read the recorded receipt and must not issue another GitHub write. Record unknown+before the write is attempted; a crash/timeout after it may have reached GitHub+must remain unknown without automatic retry. An interrupted pending reservation+cannot be silently reset into a fresh submission. Do not infer success from+content search or manufacture an exactly-once guarantee GitHub does not provide.++A successful upstream201 supplies the operation-bound issue ID/URL. Read that+specific Issue back, validate pinned repo/author/title/body, and then expose its+receipt as created. If readback is temporarily unavailable, retain the returned+identity and distinguish created/unverified until bounded reconciliation; the+client must not claim fully verified success early. The implementation may use+pending while this bounded readback completes, with the receipt identity retained+privately. Unknown outcome is terminal for automatic writes, not a retry signal.+Requests definitely rejected before any GitHub write can fail explicitly.++## Boundaries++- Credentials stay in this VM's Vault: named static Standard reference+ AVIBE_FEEDBACK_GITHUB_TOKEN, only target-repo Issues read/write and Metadata.+ Use the installed supported Vault API/CLI with opaque named injection, never+ copy the Mac/e2e developer credential or print secrets. Missing PAT disables+ writes without blocking isolated implementation/tests.+- The operator binding is actor `cs-agent-bot` (user ID `272811739`) and+ repository `avibe-bot/avibe` (repository ID `1035030370`); neither is+ accepted from report data or ambient configuration.+- Fixed HTTPS api.github.com endpoints; no redirects or ambient proxies selecting+ another destination. Verify effective GitHub actor using the same credential;+ operator binds it to the official service, client discloses official submission.+- The deployed compatibility fixture must support packaged Show Runtime+ `5e31eda3536db3ea4de018fb253d0ed7d5c69a09`, Linux archive SHA256+ `ea1079eca7bf532192c72950e1c9cd6f183192fb3c30af6a87f7fa0a63305b6e`, and+ manifest SHA256 `98725b13df13c206ba689609f5df198bd5cd9b83d3484b58142944a2775e7698`.+- Native manifest32KiB bound before Runtime. Handler/service also bound bytes,+ strings, execution time, subprocess output and upstream response. Use argv/stdin+ JSON, no shell evaluation of report text. No URL fetches from report content.+- Bounded global admission/concurrency: default5new submissions/minute,+ 30/day, at most2upstream writes concurrently. Durable counters survive restart;+ repeats/status must not multiply writes. Do not trust forwarded user headers as+ identity or claim these are per-user quotas. This bounds public abuse but cannot+ prevent an attacker exhausting the public quota; document that limitation.+- Bound ledger capacity (e.g.10000receipts) and fail closed when full; do not+ evict uncertain/in-flight evidence or permit an old ID to recreate a write.+- Public ingress does not invoke an Agent, shell script from content, merge,+ Task or Watch. Keep original instance/config/Vault/terminal/other Sessions+ protected. Preserve guest isolation and cloud pairing.+- Security/vulnerability/private reports remain local or use a verified private+ policy destination; client must not send them to this public Issue service.++## Code ownership and deployment++Single product writer owns examples/feedback-intake/**, focused+tests/test_feedback_intake*.py, integration fixture/script inside that app,+skills/use-avibe/SKILL.md and references/feedback.md, an optional small existing+skill client helper, and this plan. Reuse existing Python/Node tooling, no new+framework or core/runtime/UI changes by default. Report a proven contract gap+before widening scope. No edits in the dirty primary checkout.++Existing deployment operator sesbqrgqcq576 owns VM preparation and installation,+not source edits. It allocates the Show Session, prepares a fixed reviewed runtime+that includes PR2039, preserves systemd and state, installs only the independently+accepted app artifact, warms Runtime, and verifies live behavior. No changes to+ad host runtime, e2e webhook, nightly, Cloud acceptance or sibling guests.+Deployment and necessary guest service restart are authorized by launch request;+no GitHub merge or public release authority is inferred.++## Acceptance++Hermetic tests use synthetic secrets, tempSQLite/HOME/config, real production+validation/ledger code, and an isolated fake GitHub server behind a test-only seam.+Demonstrate actual HTTP through UI->pinnedRuntime->TS handler->Vault invocation+adapter->receiver->testGitHub->readback and receipt GET with Unicode/newlines.+Concurrent repeats, conflicting ID, ambiguous timeout/restart, limits and secret+leak boundary must be tested. Fake seams cannot claim live credential acceptance.+All product changes require current-head Codex clean pass, full applicable CI,+zero unresolved threads and PM actual diff/consumer review. Cyhhao triggers review;+do not manually mention Codex. Circuit breaker applies. No merge by lane.++Live launch gate: reviewed bytes installed; actual public URL/discovery bound;+PAT present/actor validated; bad requests cannot publish; one explicit authorized+smoke submission and repeat return one actual Issue with rendered readback and+link. Do not publish a synthetic public Issue until PM has reconciled concrete+content and publication authority. Do not call deployment complete if PAT or+public end-to-end submission is missing. Return a precise remaining prerequisite.++## Implementation and artifact acceptance++The app supervisor validates/reserves the report before calling named Vault run.+Only request ID and an internal reservation token cross argv; report content is+read from the app ledger because the supported Vault CLI uses stdin for sealed+envelopes. The same injected credential binds actor/repository/create/readback.+The 201 immutable Issue ID, number and canonical URL are committed before GET.+Public GET projects only state and verified public URL, without upstream egress.+An operator-only `worker.py reconcile <request_id>` permits at most three bounded+read-only reconciliations of a retained Issue identity after the prior deadline.++Kernel-owned file locks bound active upstream workers to two and release only+on actual worker exit. Workers enforce an absolute 20-second reservation+cutoff with SIGALRM; delayed Vault delivery cannot start a stale write. The+supervisor tracks and kills actual descendants, including avault's separate+process session, on timeout or excess output. Expired pending reservations become durable failed without a write; unknown+reservations never become new writes. The remote GitHub operation may still+complete after disconnection: no exactly-once or remote cancellation claim.++The app requires an explicit private ledger directory outside AVIBE_HOME and+all Show workspaces, plus an explicit app root for bundled TS handlers. Existing+Python/Node tooling and avibe-os's psutil dependency suffice. No core changes.+See examples/feedback-intake/README.md for deployment and recovery instructions.++The client helper ships under the existing use-avibe identity in the normal+wheel and built-in content-addressed publication. A deployed receiver does not+update installed clients. PM reconciles the exact reviewed wheel/hash and+normal install authority separately; no release/merge is granted by this plan.+The app integration verifies the frozen manifest hash and platform archive hash+before using packaged Runtime 5e31. Local macOS compatibility is not proof of+Linux live commissioning, write permission or universal client distribution.++First review refinement: worker slot rejection before claiming a pending row+persists a known no-write failed receipt. A native pre-reservation 429 instead+leaves no service receipt; the client durably records the directly observed POST+status before polling its receipt, even when the following status request is+busy, unavailable, malformed or interrupted. That observation is history, not+proof that no concurrent delivery exists. Only a later explicit identical+submit that gets a fresh minimal 404 may send the same saved ID and bytes.+Resume remains status-only. Saved verified terminal receipts survive polling+outages, and client state honors AVIBE_HOME. Artifact verification uses explicit+errors so optimized Python cannot remove commissioning checks.++## PM R2 whole-class decision (2026-09-20)++PM independently reproduced retry-intent interruption, wrong-platform archive+acceptance and unsupported extraction-filter invocation at head d9933a310.+Reviews 5259791943 (f8b630568) and 5259828654 (d9933a310) are two findings-bearing+heads. Admission/outcome lifecycle and artifact acceptance each appeared on+both; the writer paused cleanly. PM completed the whole-class diagnosis and+authorized this bounded continuation in the original scope. Counts do not reset;+any further finding in either class returns to PM before another edit/push.+No queue, daemon, new endpoint, receiver schema rewrite or core/runtime change.++The receiver remains the durable owner of GitHub write admission. A same-ID,+same-bytes recovery delivery can coalesce with an older arriving delivery only+because reserve/claim are atomic and no receipt is reset or evicted. Delivery+recovery is not permission for a second GitHub operation.++The current state table below incorporates the R4 amendment; R2 originally+required both POST429 and GET404 to acquire history, now superseded. Client+state separates the historical rejection flag (`retryable`, meaning a+directly observed POST429 with no saved receipt) from phase and send generation.+It is retained independently of the next status request; a new explicit submit+still needs a fresh minimal 404 before it may send:++| Evidence / phase | Publicly reported result | Explicit identical submit | resume |+| --- | --- | --- | --- |+| Initial sending/unknown, no rejection history | unknown until valid receipt | GET only, even after404 | GET only |+| Observed429, rate_limited | local rate_limited admission; another delivery may exist | GET first; minimal404 permits one same-ID/bytes send | GET only |+| Observed429, sending interrupted/uncertain | unknown; prior rejection does not describe current send | GET first; minimal404 permits one recovery delivery | GET only |+| Any observed pending/unknown receipt | saved server state | GET only permanently | GET only |+| Verified created/failed | saved terminal receipt, including URL | GET only permanently | GET only |++Before every explicit recovery send, valid pending/unknown/created/failed settles+eligibility permanently. Unavailable, malformed, redirected or other responses+suppress delivery. A GET404 without historical observed429 grants nothing. A+fresh minimal404 permits exactly one delivery attempt in that invocation; the+client commits sending plus a generation while retaining historical evidence.+Only a directly observed 429 for that generation records rate_limited. All+receipt merges run in transactions: terminal evidence never regresses, unknown+never returns to pending, and late rejection cannot restore rights over an+observed reservation. Old rows lacking eligibility remain conservative; no+unknown reset is added.++Artifact preparation imports the existing side-effect-free platform selector+and safe extractor from core.managed_runtime. The executing platform chooses+exactly one manifest entry; manifest SHA/version, entry filename and actual hash+are checked before extraction. The shared extractor supplies legacy Python3.10+member/link containment, type and collision checks as well as modern data_filter.+All acceptance/confinement checks remain explicit under -O. Local platform+success is not Linux guest acceptance. The staged share is private revision2.++## PM R3 independent test evidence reconciliation (2026-09-20)++At exact head 6365f99dc, PM's independent archived-source run produced31passes+and1failure: the race test queried final status after only the recovery helper+finished. PM independently reproduced the diagnostic ordering: original handler+owned the write, ledger held the201identity and unknown while readback was gated,+and both handler/worker were incomplete. After explicit completion events,+worker exit0 and verified created appeared, with one upstream POST/Issue throughout.+The original failed run and diagnostic evidence remain preserved; that head's+race acceptance was withdrawn pending correction. This is PM consumer evidence,+not a third Codex findings-bearing head or a product state-model defect.++PM authorized only the recovery fixture/test and this evidence wording to change.+The test now controls both original-wins/recovery-wins reservation orders,+observes legitimate unknown during real gated readback, and waits boundedly for+both upload handlers and the owning worker before asserting verified created.+It retains exact ID/bytes, one POST/Issue, actual readback and GET-only resume+assertions; cleanup releases barriers and joins/reaps owned resources. Production+bytes remain identical. No subsequent head is pushed during the pending6365f99+Codex review; actual findings must first be reconciled against the two-head history.++## PM R4 rejection-evidence decision (2026-09-20)++At exact head e32351d5b, Codex finding4056419180 identified a second boundary in+the same admission/outcome lifecycle class: a POST429 was discarded when the+following public status request was itself busy. PM independently reproduced+POST429 followed by GET429 and GET503, then a later GET404; resume and identical+submit performed no second POST. The prior requirement that eligibility needed+429 plus 404 is superseded only by the rules in this section. The durable counts+remain three findings-bearing heads; lifecycle appears on all three, and the+writer paused before editing.++The client now records a directly observed POST429 with the current generation,+phase and absence of a saved receipt before reading an optional POST body or+starting another request. That local rejection is evidence about that delivery,+not proof that no concurrent or prior delivery exists. A later failure, busy+response, timeout, disconnect, malformed body or invalid status receipt cannot+erase it. A new explicit identical submit must still receive a fresh minimal+GET404 before one same-ID, same-byte delivery; resume remains GET-only. Any+valid pending, unknown, failed or created receipt permanently wins and removes+replay eligibility. An initial timeout, 5xx or disconnect without observed429+remains conservative and cannot become replayable merely because a later GET404+appears. POST status is authoritative for this local observation; its body is+optional data and cannot select a destination or grant permission.++The exact e323 source was exercised through an isolated UI HTTP server and the+packaged Runtime5e31. The candidate TS handler and `runWorker` were unchanged.+The probe used only a fixed temporary executable through `AVIBE_FEEDBACK_PYTHON`+to hold child slots by loopback IPC; it did not invoke Vault or GitHub. Runtime+compilation showed that POST and GET have separate active counters: four held+POST children caused the fifth POST to return the native status-only rejection+and left no receipt, while GET still started an independent child and returned+404. Four held GET children caused the fifth GET to return429 while POST still+started an independent child and returned202. All child processes, handlers,+listeners and the Runtime exited cleanly. The probe's JSON evidence and source+hashes were delivered to PM; this admission probe does not replace the+separately recorded real Vault/GitHub-fake integration.++The bounded continuation updates only the existing Skill helper, focused client+consumers, Skill reference and launch documentation. It adds no queue, endpoint,+receiver schema, Runtime/core/UI change or automatic retry. Tests cover every+status-query outcome after observed429, status-independent POST body handling,+interruption after the durable observation, fresh404-gated recovery, monotonic+server receipt precedence and the existing one-write race. Any new finding in+this lifecycle class returns to PM before another edit or push.diff --git a/examples/feedback-intake/.show-api.json b/examples/feedback-intake/.show-api.jsonnew file mode 100644index 000000000..7bb7556c0--- /dev/null+++ b/examples/feedback-intake/.show-api.json@@ -0,0 +1,12 @@+{+ "schema_version": 1,+ "server_to_server": [+ {+ "path": "api/feedback",+ "method": "POST",+ "auth": "handler",+ "max_body_bytes": 32768,+ "forward_headers": []+ }+ ]+}diff --git a/examples/feedback-intake/README.md b/examples/feedback-intake/README.mdnew file mode 100644index 000000000..fd3ea58e5--- /dev/null+++ b/examples/feedback-intake/README.md@@ -0,0 +1,135 @@+# Official Avibe feedback intake++This dedicated Show app accepts approved public bug/feature reports from the+user's current Agent. The fixed destination is `avibe-bot/avibe` (repository ID+`1035030370`) under `cs-agent-bot` (user ID `272811739`). Reports cannot override+that binding. No GitHub account is needed on the submitting client.++Allocated endpoint: https://avibe-feedback-app.avibe.bot/p/132vCvND49U/ on guest+`avibe-feedback`, Show Session `ses9u23mgw6dr`. PM observed the staged share private at access revision 2. Allocation does+not mean intake is active. The exact reviewed artifact, supported base package,+Runtime and live write/readback still require commissioning by PM/ops.++## Operator installation++Use the reviewed commit's `examples/feedback-intake/{api,lib,worker.py,.show-api.json}`+bytes as one artifact; preserve its hashes. Copy them into the existing workspace+`/home/avibe/.avibe/show/ses9u23mgw6dr`. Do not install the integration fixtures.+No public browser form or new page identity is needed.++The normal guest Avibe package must include native Show server POST admission+(base `b821f22f55b2230de176ede3a1183acbae81b528`). Use packaged Show Runtime+`5e31eda3536db3ea4de018fb253d0ed7d5c69a09`. Manifest SHA256:+`98725b13df13c206ba689609f5df198bd5cd9b83d3484b58142944a2775e7698`.+Linux x64 archive SHA256:+`ea1079eca7bf532192c72950e1c9cd6f183192fb3c30af6a87f7fa0a63305b6e`.++Bind these environment values in the operator-owned Runtime service context:++- `AVIBE_FEEDBACK_APP_ROOT=/home/avibe/.avibe/show/ses9u23mgw6dr`+- `AVIBE_FEEDBACK_DATABASE=/home/avibe/feedback-intake-state/ledger.sqlite`+- `AVIBE_FEEDBACK_PYTHON`: absolute Python executable in the normal installed+ Avibe environment, which includes its existing psutil dependency.+- `AVIBE_FEEDBACK_VAULT_BIN`: absolute supported `vibe` executable in that same+ installed environment. The default is `vibe` from the operator's PATH.++Create the dedicated ledger parent owned by the service user with mode `0700`.+The worker fails closed on missing/relative paths, symlinks, hardlinked database,+world-readable parent, or a path under AVIBE_HOME, legacy home or this app. Keep+all state outside every public Show root; do not link it into a workspace.+DB/WAL/SHM and lock files are private app state, separate from Avibe's internal DB.+Back up the ledger as a coherent SQLite database; never replace it with an empty+one during upgrade or remove uncertain records/slot files while workers run.++The dedicated static Standard Vault reference `AVIBE_FEEDBACK_GITHUB_TOKEN`+already exists; no new credential or Vault policy is required. The fixed+`vibe vault run --no-approval-wait --env AVIBE_FEEDBACK_GITHUB_TOKEN -- ...`+path performs opaque named injection. Production must unset every+`AVIBE_FEEDBACK_TEST_*` variable. Ambient tokens are removed before Vault;+HTTP uses only api.github.com without redirects or ambient proxies. No report+text enters shell commands or selects URLs. Protect service environment and app+files as trusted operator configuration.++Ops owns installation, warm-up, service lifecycle and activation. Product lane+performs none of those actions. Disable intake by removing its manifest entry or+making the page private; preserve the ledger. Re-enabling uses the same ledger.++## Protocol, bounds and recovery++POST `/api/feedback` has exactly schema_version=1, canonical lowercase UUIDv4+request_id, kind=`bug|feature`, title, body and public_consent=true. Title is one+line ≤200 characters, body ≤20000 UTF-8 bytes, complete request ≤32768 bytes.+The native Show POST returns only a generic status body. GET+`/api/feedback-status?request_id=<UUIDv4>` returns no-store state and, only after+verified readback, the canonical public Issue number/URL. IDs are public+correlation, not bearer secrets. Unknown IDs return 404; status never calls GitHub.++One transaction reserves ID, canonical payload digest, report and durable global+quota counters: 5 new reservations/minute, 30/day, 10000 total receipts. Changed+payload under an existing ID returns 409. Exact repeats never issue another write.+Two kernel file locks bound upstream workers across processes. Slot rejection+before a worker claims its row persists failed (known no-write), not unknown. Four handler+children per Runtime module and bounded body/output/time limit local work;+these are resource caps, not user identity or per-user rate limits. An anonymous+attacker can consume the public quota. No availability or exactly-once guarantee.++A pending reservation has a 20-second absolute cutoff. Workers arm their own+hard timer before authenticated calls; late delivery refuses to write. The+supervisor tracks actual descendants because avault starts another session.+Timeout/overflow kills tracked children; the worker deadline remains independent.+An upstream request already received by GitHub cannot be cancelled or proven lost.+The ledger records unknown atomically immediately before the first write and+never retries it. Pending expiry is durable failed; read-only identity binding+does not make the outcome uncertain.++A valid GitHub 201 identity is committed before readback. Only exact immutable+Issue ID, number, URL, repository, actor ID/login, title and body checks expose+created. Known GitHub rejection becomes failed; other outcomes remain unknown.+An operator can reconcile a retained 201 identity after its deadline with:++```sh+/path/to/installed/python /home/avibe/.avibe/show/ses9u23mgw6dr/worker.py reconcile UUID+```++Run with the same operator environment and supported Vault executable. This is+CLI-only and performs reads through named Vault run, at most three attempts per+receipt; it never creates another Issue. An unknown result without retained+identity requires human investigation; content search is not an operation receipt.+Do not reset a pending/unknown record to retry. Never evict evidence to free space.++## Client distribution and launch evidence++The helper is `skills/use-avibe/scripts/feedback_intake.py`, under the existing+Skill. Build a normal wheel (`npm ci && npm run build` in ui, prepare the supported+Runtime manifest, then `uv build --wheel`). The wheel force-includes the entire+Skill at `vibe/builtin_skills_source/use-avibe`. The ordinary supported installation+is `uv tool install --force /absolute/path/to/reviewed.whl`; normal startup binds+its content-addressed built-in snapshot. `vibe skill load -- use-avibe` in the+client must resolve the reviewed helper/reference. Do not edit caches, install a+new Skill identity, or infer availability from this source checkout. PM must+reconcile the final exact wheel/version/hash and installation authority.++The user approves the sanitized title/body, public repository and official actor+once. The helper commits the exact payload and UUID before POST and retains a+private attempt outbox under AVIBE_HOME (default ~/.avibe). `resume UUID` only+reads status in every phase. A directly observed POST429 is retained separately+from the next status query and sending intent. Only a later explicit identical+submit first obtaining a fresh minimal404 may attempt one same-ID/bytes delivery.+Unavailable/malformed/redirected status suppresses upload. Every observed server+receipt permanently revokes recovery; terminal evidence never regresses under+concurrent updates. An interrupted recovery is reported unknown, not rate+limited based on old history. This relies on the fixed receiver's unreset ledger+coalescing original and recovery deliveries into at most one GitHub write. An+initial unknown without observed429 history cannot be replayed. See the launch+plan's complete state table.+Saved terminal receipts survive polling outages. Security, vulnerability and+private reports stay off this public route. Existing direct user-authorized+GitHub behavior remains supported.++Before launch, independently review the exact head, all CI and review threads;+verify the installed artifact hashes, real Runtime→Vault identity context and+bad request rejection; then use one PM-authorized concrete public report to+prove Issues write permission, repeat coalescing and exact rendered readback.+No synthetic public Issue is authorized by this source. Local fake tests do not+prove live PAT write permission, Linux commissioning or installed client rollout.+See [integration instructions](integration/README.md).diff --git a/examples/feedback-intake/api/feedback-status.ts b/examples/feedback-intake/api/feedback-status.tsnew file mode 100644index 000000000..073165e02--- /dev/null+++ b/examples/feedback-intake/api/feedback-status.ts@@ -0,0 +1,22 @@+import { response, runWorker, UUID_V4 } from "../lib/worker"++export async function GET(request: Request): Promise<Response> {+ const query = new URL(request.url).searchParams+ const id = query.get("request_id") || ""+ if ([...query.keys()].join() !== "request_id" || !UUID_V4.test(id)) return response({}, 404)+ const result = await runWorker(["status", id])+ if (result.status !== 200) return response({}, result.status)+ const receipt = result.receipt+ if (receipt?.schema_version !== 1 || receipt.request_id !== id || !["pending", "unknown", "failed", "created"].includes(receipt.state)) {+ return response({}, 503)+ }+ // Explicit public projection; the ledger and worker may hold private evidence.+ const publicReceipt: Record<string, unknown> = { schema_version: 1, request_id: id, state: receipt.state }+ if (receipt.state === "created") {+ if (!Number.isSafeInteger(receipt.issue_number) || receipt.issue_number <= 0 ||+ receipt.issue_url !== `https://github.com/avibe-bot/avibe/issues/${receipt.issue_number}`) return response({}, 503)+ publicReceipt.issue_number = receipt.issue_number+ publicReceipt.issue_url = receipt.issue_url+ }+ return response(publicReceipt, 200)+}diff --git a/examples/feedback-intake/api/feedback.ts b/examples/feedback-intake/api/feedback.tsnew file mode 100644index 000000000..552d8f91b--- /dev/null+++ b/examples/feedback-intake/api/feedback.ts@@ -0,0 +1,13 @@+import { boundedBody, response, runWorker } from "../lib/worker"++export async function POST(request: Request): Promise<Response> {+ if (request.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== "application/json") {+ return response({ error: "feedback_rejected" }, 415)+ }+ try {+ const body = await boundedBody(request)+ if (body === null) return response({ error: "feedback_rejected" }, 413)+ const result = await runWorker(["submit"], body)+ return response({ accepted: result.status === 202 }, result.status)+ } catch { return response({ error: "feedback_rejected" }, 400) }+}diff --git a/examples/feedback-intake/integration/README.md b/examples/feedback-intake/integration/README.mdnew file mode 100644index 000000000..c9ee627c8--- /dev/null+++ b/examples/feedback-intake/integration/README.md@@ -0,0 +1,65 @@+# Hermetic integration and distribution checks++Use the repository's existing pytest environment (`uv sync --no-install-project`),+Node supported by the Runtime manifest, and a real `avault` custody binary on PATH.+The fixture exclusively uses a synthetic PAT, a temporary file custody store,+temporary HOME/XDG/AVIBE_HOME, app ledger and loopback GitHub HTTP server. It does+not use Keychain, installed user secrets or live GitHub writes.++Run focused tests:++```sh+PYTHONPATH=. .venv/bin/pytest -q tests/test_feedback_intake.py+```++Obtain the normal deployment `show-runtime-manifest.json` and the archive for the+local test platform from the accepted release artifact. Set absolute paths:++```sh+AVIBE_FEEDBACK_RUNTIME_MANIFEST=/absolute/path/show-runtime-manifest.json \+AVIBE_FEEDBACK_RUNTIME_ARCHIVE=/absolute/path/vibe-show-runtime-node-linux-x64.tgz \+PYTHONPATH=. .venv/bin/pytest -q tests/test_feedback_intake_http.py+```++The test verifies the fixed manifest SHA, Runtime version 5e31 and platform archive+SHA against exactly the executing host platform before extracting into temporary state.+The app imports `runtime_platform_tag` and `safe_extract_tar` from the normal+installed Avibe package; standalone invocation needs that Python environment+(or `PYTHONPATH=.` in the repository). It never executes an unverified archive. Linux x64 must match `ea1079eca7…`.+macOS uses its entry in the same frozen manifest. Platform-specific native modules+require the matching archive; a macOS pass is not Linux deployment evidence.+The existing core CI pin 5a9a6a52 remains untouched.++`vibe-fixture.py` invokes the real Avibe CLI and real avault delivery. Its only+custody adaptations select the test binary and file store, avoiding automatic+macOS Keychain use. Actual named secret resolution, encrypted envelope stdin,+start_new_session semantics and child lifecycle execute unmodified product code.+The report is read from its app ledger, not Vault stdin. No exec-style fake Vault+stands in for the CLI. Production must never install this fixture.++The HTTP case runs actual uvicorn public admission, packaged Runtime, app TS,+worker, real Vault CLI, GitHub fake and receipt GET. It checks Unicode/newlines,+status-only POST, repeated/conflicting ID, malformed encoding, size/method,+minimal status privacy, DB/WAL/SHM route probes, proxy exclusion and a completed+upstream write followed by a disconnect. Focused tests cover quotas, capacity,+real concurrency, process death, bounded read-only reconciliation and helper+resume/deduplication. Real custody tests skip without avault, and HTTP skips+without artifacts; those skips do not satisfy commissioning.++For normal wheel publication, build the UI and normal wheel as in the app README.+`tests/test_feedback_intake_distribution.py` accepts `AVIBE_FEEDBACK_TEST_WHEEL`+and verifies helper bytes from the wheel through installed-source selection and+built-in snapshot publication. Normal artifact installation remains PM/ops-owned.++Recovery/crash consumers: `tests/test_feedback_intake_recovery.py` runs actual+helper subprocesses, real HTTP receipt/admission and the production app SQLite+reserve/claim path with an isolated GitHub write counter. It kills at durable+intent boundaries and races original/recovery delivery without another Issue.++Artifact consumers: `tests/test_feedback_intake_artifacts.py` runs normal and+optimized Python, platform/hash rejection and safe/malicious fixture extraction.+Set `AVIBE_FEEDBACK_LEGACY_PYTHON` to an isolated Python environment containing+Avibe dependencies on an actual older interpreter without `tarfile.data_filter`+(e.g. Python 3.10.11) for the legacy compatibility check. It must not point at a+production service environment. The modern path and existing+`tests/test_managed_runtime_composite_artifacts.py` remain useful alongside it.diff --git a/examples/feedback-intake/integration/prepare-runtime.py b/examples/feedback-intake/integration/prepare-runtime.pynew file mode 100644index 000000000..cdf926778--- /dev/null+++ b/examples/feedback-intake/integration/prepare-runtime.py@@ -0,0 +1,43 @@+"""Verify/extract the commissioned Runtime archive before running HTTP tests.++Usage: python prepare-runtime.py MANIFEST ARCHIVE DESTINATION+Prints the verified root; no downloading, installation or running services.+"""+import hashlib+import json+from pathlib import Path+import sys+import tarfile++from core.managed_runtime import runtime_platform_tag, safe_extract_tar++VERSION = "5e31eda3536db3ea4de018fb253d0ed7d5c69a09"+MANIFEST_SHA = "98725b13df13c206ba689609f5df198bd5cd9b83d3484b58142944a2775e7698"+LINUX_SHA = "ea1079eca7bf532192c72950e1c9cd6f183192fb3c30af6a87f7fa0a63305b6e"+++def prepare(manifest_path, archive_path, destination):+ manifest_raw = manifest_path.read_bytes()+ if hashlib.sha256(manifest_raw).hexdigest() != MANIFEST_SHA:+ raise ValueError("Runtime manifest hash mismatch")+ manifest = json.loads(manifest_raw)+ if manifest["runtime_version"] != VERSION or manifest["archives"]["linux-x64"]["sha256"] != LINUX_SHA:+ raise ValueError("Runtime deployment binding mismatch")+ platform = runtime_platform_tag()+ entry = manifest["archives"].get(platform)+ if entry is None:+ raise ValueError("Unsupported Runtime platform")+ if archive_path.name != entry["name"]:+ raise ValueError("Runtime archive does not match executing platform")+ if hashlib.sha256(archive_path.read_bytes()).hexdigest() != entry["sha256"]:+ raise ValueError("Runtime archive hash mismatch")+ destination.mkdir(parents=True, exist_ok=False)+ with tarfile.open(archive_path) as archive:+ safe_extract_tar(archive, destination)+ if not (destination / "packages/runtime/dist/cli.js").is_file():+ raise ValueError("Runtime archive missing CLI")+ return destination+++if __name__ == "__main__":+ print(prepare(*(Path(arg).resolve() for arg in sys.argv[1:])))diff --git a/examples/feedback-intake/integration/vibe-fixture.py b/examples/feedback-intake/integration/vibe-fixture.pynew file mode 100755index 000000000..06f523637--- /dev/null+++ b/examples/feedback-intake/integration/vibe-fixture.py@@ -0,0 +1,20 @@+#!/usr/bin/env python3+"""Real Avibe Vault CLI with a test-owned file custody store (never Keychain).++Only custody binary selection/store are changed. CLI parsing, named selection,+sealed envelope delivery, new-session spawn, stdin and child waiting are real.+"""+import os+from pathlib import Path+import sys++root = Path(os.environ["AVIBE_FEEDBACK_FIXTURE_ROOT"]).resolve()+for name in ("HOME", "AVIBE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"):+ if root not in Path(os.environ[name]).resolve().parents:+ raise RuntimeError("Vault fixture state must remain inside its isolated root")+sys.path.insert(0, os.environ["AVIBE_FEEDBACK_SOURCE_ROOT"])+from vibe import api, cli # noqa: E402++api._avault_store_args = lambda: ["--store", "file"]+api._require_avault_path = lambda: os.environ["AVIBE_FEEDBACK_TEST_AVAULT"]+cli.main()diff --git a/examples/feedback-intake/lib/worker.ts b/examples/feedback-intake/lib/worker.tsnew file mode 100644index 000000000..3af712201--- /dev/null+++ b/examples/feedback-intake/lib/worker.ts@@ -0,0 +1,70 @@+import { spawn } from "node:child_process"+import { isAbsolute, join } from "node:path"++export const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/+const MAX_BYTES = 32768+let active = 0++export function response(body: unknown, status: number): Response {+ return Response.json(body, { status, headers: { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } })+}++export async function boundedBody(request: Request): Promise<Uint8Array | null> {+ const reader = request.body?.getReader()+ if (!reader) return new Uint8Array()+ const chunks: Uint8Array[] = []+ let length = 0+ try {+ while (true) {+ const { done, value } = await reader.read()+ if (done) break+ length += value.length+ if (length > MAX_BYTES) { await reader.cancel(); return null }+ chunks.push(value)+ }+ return Buffer.concat(chunks)+ } finally { reader.releaseLock() }+}++export async function runWorker(args: string[], input?: Uint8Array): Promise<Record<string, any>> {+ // Explicit operator path: Runtime may bundle server modules into a cache.+ const root = process.env.AVIBE_FEEDBACK_APP_ROOT+ if (!root || !isAbsolute(root)) return { status: 503 }+ if (active >= 4) return { status: 429 }+ active+++ const environment = { ...process.env }+ for (const name of ["AVIBE_FEEDBACK_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"]) delete environment[name]+ try {+ return await new Promise((resolve) => {+ const child = spawn(process.env.AVIBE_FEEDBACK_PYTHON || "python3", [join(root, "worker.py"), ...args], {+ cwd: root, env: environment, stdio: ["pipe", "pipe", "ignore"], shell: false,+ })+ let failed = false+ let length = 0+ const chunks: Buffer[] = []+ const timer = setTimeout(() => {+ failed = true+ child.kill("SIGKILL")+ resolve({ status: 504 })+ }, input === undefined ? 5_000 : 24_000)+ child.stdin.on("error", () => { /* Early child exit is handled by close. */ })+ child.stdout.on("data", (chunk: Buffer) => {+ length += chunk.length+ if (length > MAX_BYTES) { failed = true; child.kill("SIGKILL") }+ else chunks.push(chunk)+ })+ child.on("error", () => { clearTimeout(timer); resolve({ status: 503 }) })+ child.on("close", (code) => {+ clearTimeout(timer)+ if (!failed && code === 0) {+ try {+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8"))+ if (Number.isInteger(value.status) && value.status >= 200 && value.status <= 599) { resolve(value); return }+ } catch { /* Malformed child output fails closed. */ }+ }+ resolve({ status: 503 })+ })+ child.stdin.end(input)+ })+ } finally { active-- }+}diff --git a/examples/feedback-intake/worker.py b/examples/feedback-intake/worker.pynew file mode 100644index 000000000..cb43dcd75--- /dev/null+++ b/examples/feedback-intake/worker.py@@ -0,0 +1,466 @@+"""Official intake: strict input, durable receipts, fixed Vault/GitHub consumer.++Run `submit` outside Vault; it reserves before handing only the reservation ID to+`vibe vault run`. Vault's stdin belongs to sealed envelopes, not report content.+"""+from __future__ import annotations++import argparse+from contextlib import contextmanager+import fcntl+import hashlib+import json+import os+from pathlib import Path+import selectors+import signal+import sqlite3+import subprocess+import sys+import time+import uuid+from urllib import error, parse, request++SCHEMA_VERSION = 1+TARGET_FULL_NAME = "avibe-bot/avibe"+TARGET_API_BASE = "https://api.github.com"+TARGET_HTML_BASE = "https://github.com/avibe-bot/avibe/issues"+EXPECTED_ACTOR = "cs-agent-bot"+EXPECTED_ACTOR_ID = 272811739+EXPECTED_REPOSITORY_ID = 1035030370+TOKEN_ENV = "AVIBE_FEEDBACK_GITHUB_TOKEN"+DATABASE_ENV = "AVIBE_FEEDBACK_DATABASE"+MAX_REQUEST_BYTES = 32768+MAX_BODY_BYTES = 20000+MAX_RECEIPTS = 10000+MINUTE_LIMIT = 5+DAY_LIMIT = 30+MAX_UPSTREAM_WRITES = 2+EXECUTION_SECONDS = 20+MAX_OUTPUT_BYTES = 32768+MAX_UPSTREAM_RESPONSE_BYTES = 262144+++class FeedbackError(Exception):+ def __init__(self, status=503):+ self.status = status+++class NoRedirect(request.HTTPRedirectHandler):+ def redirect_request(self, *args, **kwargs):+ return None+++def _uuid_v4(value):+ try:+ return isinstance(value, str) and str(uuid.UUID(value)) == value and uuid.UUID(value).version == 4+ except ValueError:+ return False+++def _parse_payload(raw):+ if len(raw) > MAX_REQUEST_BYTES:+ raise FeedbackError(413)++ def pairs(items):+ result = {}+ for key, value in items:+ if key in result:+ raise FeedbackError(400)+ result[key] = value+ return result++ try:+ value = json.loads(raw.decode("utf-8"), object_pairs_hook=pairs)+ if not isinstance(value, dict) or set(value) != {+ "schema_version", "request_id", "kind", "title", "body", "public_consent"+ }:+ raise ValueError()+ if type(value["schema_version"]) is not int or value["schema_version"] != 1:+ raise ValueError()+ if not _uuid_v4(value["request_id"]) or value["public_consent"] is not True:+ raise ValueError()+ if type(value["kind"]) is not str or value["kind"] not in ("bug", "feature"):+ raise ValueError()+ title, body = value["title"], value["body"]+ if not isinstance(title, str) or not title.strip() or len(title) > 200:+ raise ValueError()+ if any(ord(c) < 32 or c in "\x7f\x85\u2028\u2029" for c in title):+ raise ValueError()+ title.encode("utf-8")+ if not isinstance(body, str) or not body.strip() or len(body.encode("utf-8")) > MAX_BODY_BYTES:+ raise ValueError()+ if "\0" in body:+ raise ValueError()+ return value+ except (ValueError, UnicodeError, RecursionError, TypeError):+ raise FeedbackError(400) from None+++def _database_path():+ configured = os.environ.get(DATABASE_ENV, "")+ path = Path(configured)+ avibe_home = Path(os.environ.get("AVIBE_HOME", str(Path.home() / ".avibe"))).resolve()+ forbidden = (avibe_home, Path.home() / ".vibe_remote", Path(__file__).resolve().parent)+ resolved = path.resolve()+ if not configured or not path.is_absolute() or path != resolved:+ raise FeedbackError()+ if any(resolved == root or root in resolved.parents for root in forbidden):+ raise FeedbackError()+ if path.exists() and (not path.is_file() or path.stat().st_nlink != 1):+ raise FeedbackError()+ return path+++@contextmanager+def _database():+ path = _database_path()+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)+ if path.parent.stat().st_mode & 0o077:+ raise FeedbackError()+ fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)+ os.close(fd)+ connection = sqlite3.connect(path, timeout=2, isolation_level=None)+ connection.row_factory = sqlite3.Row+ try:+ connection.execute("PRAGMA journal_mode=WAL")+ connection.execute("PRAGMA synchronous=FULL")+ connection.executescript("""+ CREATE TABLE IF NOT EXISTS receipts (+ request_id TEXT PRIMARY KEY, digest TEXT NOT NULL, payload TEXT NOT NULL,+ state TEXT NOT NULL, token TEXT NOT NULL, deadline REAL NOT NULL,+ issue_id INTEGER, issue_number INTEGER, issue_url TEXT,+ reconciliations INTEGER NOT NULL DEFAULT 0+ );+ CREATE TABLE IF NOT EXISTS limits (+ name TEXT PRIMARY KEY, window INTEGER NOT NULL, count INTEGER NOT NULL+ );+ """)+ yield connection+ finally:+ connection.close()+++def reserve(payload):+ encoded = json.dumps(payload, ensure_ascii=False, separators=(",", ":"), sort_keys=True)+ digest = hashlib.sha256(encoded.encode()).hexdigest()+ with _database() as db:+ db.execute("BEGIN IMMEDIATE")+ row = db.execute("SELECT * FROM receipts WHERE request_id=?", (payload["request_id"],)).fetchone()+ if row:+ if row["digest"] != digest:+ raise FeedbackError(409)+ return None+ if db.execute("SELECT count(*) FROM receipts").fetchone()[0] >= MAX_RECEIPTS:+ raise FeedbackError()+ now = time.time()+ for name, seconds, limit in (("minute", 60, MINUTE_LIMIT), ("day", 86400, DAY_LIMIT)):+ window = int(now) // seconds+ row = db.execute("SELECT * FROM limits WHERE name=?", (name,)).fetchone()+ count = row["count"] if row and row["window"] == window else 0+ if count >= limit:+ raise FeedbackError(429)+ db.execute("INSERT OR REPLACE INTO limits VALUES (?, ?, ?)", (name, window, count + 1))+ token = uuid.uuid4().hex+ db.execute("INSERT INTO receipts(request_id,digest,payload,state,token,deadline) VALUES(?,?,?,'pending',?,?)",+ (payload["request_id"], digest, encoded, token, now + EXECUTION_SECONDS))+ db.execute("COMMIT")+ return token+++def _row(request_id):+ with _database() as db:+ return db.execute("SELECT * FROM receipts WHERE request_id=?", (request_id,)).fetchone()+++def _update(request_id, **fields):+ with _database() as db:+ db.execute("UPDATE receipts SET " + ",".join(f"{key}=?" for key in fields) + " WHERE request_id=?",+ (*fields.values(), request_id))+++def _fail_pending(request_id):+ with _database() as db:+ db.execute("UPDATE receipts SET state='failed' WHERE request_id=? AND state='pending'", (request_id,))+++def receipt(request_id):+ row = _row(request_id)+ if row is None:+ raise FeedbackError(404)+ state = row["state"]+ if state == "pending" and time.time() >= row["deadline"]:+ _fail_pending(request_id)+ # An atomic write claim may have won concurrently. Never project over+ # that evidence; execute also checks the deadline in its claim.+ row = _row(request_id)+ state = row["state"]+ result = {"schema_version": 1, "request_id": request_id, "state": state}+ if state == "created":+ result.update(issue_number=row["issue_number"], issue_url=row["issue_url"])+ return result+++@contextmanager+def _write_slot():+ # Kernel-owned locks last until actual worker exit, including SIGKILL. No+ # expiring lease can admit a third worker while a stalled writer is alive.+ handles = []+ try:+ for index in range(MAX_UPSTREAM_WRITES):+ fd = os.open(str(_database_path()) + f".slot{index}", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)+ handles.append(fd)+ try:+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ continue+ yield+ return+ raise FeedbackError(429)+ finally:+ for fd in handles:+ os.close(fd)+++def _api_base():+ if os.environ.get("AVIBE_FEEDBACK_TEST_MODE") == "1":+ candidate = os.environ.get("AVIBE_FEEDBACK_TEST_API_BASE", "")+ url = parse.urlsplit(candidate)+ if url.scheme == "http" and url.hostname in ("127.0.0.1", "::1") and url.port and not (+ url.username or url.password or url.path or url.query or url.fragment+ ):+ return candidate+ raise FeedbackError()+ return TARGET_API_BASE+++def _github(token, method, path, body=None):+ raw = None if body is None else json.dumps(body, ensure_ascii=False).encode()+ req = request.Request(_api_base() + path, data=raw, method=method, headers={+ "Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "avibe-feedback-intake/1",+ "Content-Type": "application/json",+ })+ opener = request.build_opener(request.ProxyHandler({}), NoRedirect())+ try:+ response = opener.open(req, timeout=4)+ except error.HTTPError as exc:+ response = exc+ except (OSError, error.URLError):+ raise FeedbackError() from None+ with response:+ raw = response.read(MAX_UPSTREAM_RESPONSE_BYTES + 1)+ if len(raw) > MAX_UPSTREAM_RESPONSE_BYTES:+ raise FeedbackError()+ try:+ value = json.loads(raw)+ except (ValueError, UnicodeError, RecursionError):+ value = None+ return response.code, value if isinstance(value, dict) else {}+++def _binding(token):+ status, actor = _github(token, "GET", "/user")+ if status != 200 or actor.get("login") != EXPECTED_ACTOR or actor.get("id") != EXPECTED_ACTOR_ID:+ raise FeedbackError()+ status, repo = _github(token, "GET", f"/repos/{TARGET_FULL_NAME}")+ if status != 200 or repo.get("id") != EXPECTED_REPOSITORY_ID or repo.get("full_name") != TARGET_FULL_NAME:+ raise FeedbackError()+ if repo.get("private") is not False or repo.get("has_issues") is not True:+ raise FeedbackError()+++def _identity(issue):+ number, issue_id = issue.get("number"), issue.get("id")+ if type(number) is not int or number <= 0 or type(issue_id) is not int or issue_id <= 0:+ raise FeedbackError()+ url = f"{TARGET_HTML_BASE}/{number}"+ if issue.get("html_url") != url or issue.get("repository_url") != f"{TARGET_API_BASE}/repos/{TARGET_FULL_NAME}":+ raise FeedbackError()+ return issue_id, number, url+++def _verify(token, row):+ status, issue = _github(token, "GET", f"/repos/{TARGET_FULL_NAME}/issues/{row['issue_number']}")+ payload = json.loads(row["payload"])+ if status != 200 or _identity(issue) != (row["issue_id"], row["issue_number"], row["issue_url"]):+ raise FeedbackError()+ user = issue.get("user", {})+ if not isinstance(user, dict) or user.get("login") != EXPECTED_ACTOR or user.get("id") != EXPECTED_ACTOR_ID:+ raise FeedbackError()+ if issue.get("title") != payload["title"] or issue.get("body") != payload["body"] or "pull_request" in issue:+ raise FeedbackError()+ _update(row["request_id"], state="created")+++def execute(request_id, reservation_token, *, reconcile=False):+ row = _row(request_id)+ if not row or row["token"] != reservation_token:+ raise FeedbackError()+ remaining = row["deadline"] - time.time()+ if remaining <= 0:+ if not reconcile:+ _fail_pending(request_id)+ raise FeedbackError()+ # Independent hard bound survives CLI death and detached avault children.+ # The default signal terminates without releasing the slot early in Python.+ signal.signal(signal.SIGALRM, signal.SIG_DFL)+ signal.setitimer(signal.ITIMER_REAL, remaining)+ try:+ with _write_slot():+ token = os.environ.get(TOKEN_ENV, "")+ if not token:+ raise FeedbackError()+ if reconcile:+ _binding(token)+ _verify(token, row)+ return+ _binding(token)+ with _database() as db:+ changed = db.execute("UPDATE receipts SET state='unknown' WHERE request_id=? AND state='pending' AND deadline>?",+ (request_id, time.time())).rowcount+ if changed != 1:+ _fail_pending(request_id)+ return+ payload = json.loads(row["payload"])+ status, issue = _github(token, "POST", f"/repos/{TARGET_FULL_NAME}/issues",+ {"title": payload["title"], "body": payload["body"]})+ if status in (400, 401, 403, 404, 409, 422, 429):+ _update(request_id, state="failed")+ raise FeedbackError()+ if status != 201:+ raise FeedbackError()+ issue_id, number, url = _identity(issue)+ _update(request_id, issue_id=issue_id, issue_number=number, issue_url=url)+ _verify(token, _row(request_id))+ except FeedbackError:+ # Slot exhaustion or missing credentials happens before this worker+ # claims the pending row. Persist that known no-write outcome, without+ # ever downgrading unknown/created evidence from a claimed operation.+ if not reconcile:+ _fail_pending(request_id)+ raise+ finally:+ signal.setitimer(signal.ITIMER_REAL, 0)+++def _vault(request_id, token, *, reconcile=False):+ # psutil is an existing avibe-os dependency. avault deliberately creates a+ # separate session, so killing only the CLI process group is insufficient.+ import psutil++ env = dict(os.environ)+ for name in (TOKEN_ENV, "GH_TOKEN", "GITHUB_TOKEN"):+ env.pop(name, None)+ command = [os.environ.get("AVIBE_FEEDBACK_VAULT_BIN", "vibe"), "vault", "run", "--no-approval-wait",+ "--env", TOKEN_ENV, "--", sys.executable, str(Path(__file__).resolve()),+ "execute", request_id, token]+ if reconcile:+ command.append("--reconcile")+ child = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL, env=env, start_new_session=True)+ parent = psutil.Process(child.pid)+ descendants = {}+ deadline = time.monotonic() + EXECUTION_SECONDS + 1+ output = bytearray()+ try:+ with selectors.DefaultSelector() as selector:+ selector.register(child.stdout, selectors.EVENT_READ)+ while child.poll() is None or selector.get_map():+ try:+ for process in parent.children(recursive=True):+ descendants[process.pid] = process+ except psutil.NoSuchProcess:+ pass+ if time.monotonic() >= deadline:+ raise FeedbackError(504)+ for key, _ in selector.select(0.05):+ data = os.read(key.fd, 4096)+ if not data:+ selector.unregister(key.fileobj)+ output.extend(data)+ if len(output) > MAX_OUTPUT_BYTES:+ raise FeedbackError()+ if child.returncode != 0:+ raise FeedbackError()+ finally:+ try:+ for process in parent.children(recursive=True):+ descendants[process.pid] = process+ except psutil.NoSuchProcess:+ pass+ # Stop the spawner before descendants; psutil binds each PID's identity.+ for process in (parent, *descendants.values()):+ try:+ process.kill()+ except psutil.NoSuchProcess:+ pass+ child.wait(timeout=2)+ child.stdout.close()+++def submit(raw):+ payload = _parse_payload(raw)+ token = reserve(payload)+ if token:+ _vault(payload["request_id"], token)+ return 202+++def reconcile(request_id):+ # Operator-only CLI; public status never initiates authenticated egress.+ with _database() as db:+ db.execute("BEGIN IMMEDIATE")+ row = db.execute("SELECT * FROM receipts WHERE request_id=?", (request_id,)).fetchone()+ if not row or row["state"] != "unknown" or row["issue_id"] is None or row["reconciliations"] >= 3:+ raise FeedbackError(409)+ if time.time() <= row["deadline"]:+ raise FeedbackError(409)+ token = uuid.uuid4().hex+ db.execute("UPDATE receipts SET token=?,deadline=?,reconciliations=reconciliations+1 WHERE request_id=?",+ (token, time.time() + EXECUTION_SECONDS, request_id))+ db.execute("COMMIT")+ _vault(request_id, token, reconcile=True)+ return 200+++def main():+ os.umask(0o077)+ parser = argparse.ArgumentParser()+ sub = parser.add_subparsers(dest="command", required=True)+ sub.add_parser("submit")+ for command in ("status", "reconcile", "execute"):+ item = sub.add_parser(command)+ item.add_argument("request_id")+ if command == "execute":+ item.add_argument("token")+ item.add_argument("--reconcile", action="store_true")+ args = parser.parse_args()+ result = {}+ try:+ if args.command != "submit" and not _uuid_v4(args.request_id):+ raise FeedbackError(404)+ if args.command == "submit":+ status = submit(sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1))+ elif args.command == "status":+ result["receipt"] = receipt(args.request_id)+ status = 200+ elif args.command == "reconcile":+ status = reconcile(args.request_id)+ else:+ execute(args.request_id, args.token, reconcile=args.reconcile)+ return 0+ except FeedbackError as exc:+ if args.command == "execute":+ return 1+ status = exc.status+ except Exception:+ if args.command == "execute":+ return 1+ status = 503+ print(json.dumps({"status": status, **result}, ensure_ascii=False))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/skills/use-avibe/SKILL.md b/skills/use-avibe/SKILL.mdindex 0ec57c50e..eb95e76ce 100644--- a/skills/use-avibe/SKILL.md+++ b/skills/use-avibe/SKILL.md@@ -2,7 +2,7 @@name: use-avibeslug: use-avibedescription: Safely inspect and modify local Avibe configuration, routing, runtime settings, watches, scheduled tasks, Avibe Cloud remote access, and operational state. Also use it to report an Avibe bug, send product feedback, or file a feature request from the current conversation.-version: 0.7.0+version: 0.8.0---# Use Avibe@@ -112,6 +112,18 @@ Some requests are not local maintenance at all. Switch to the feedback workflowThat reference owns the whole path: gathering facts from this conversation, drafting a short English report, sanitizing it, getting approval, and submitting it to `https://github.com/avibe-bot/avibe` through an already authorized channel. Do not stop at "open an issue yourself", and do not treat diagnosis, a restart, or a repair as a precondition for filing.+When the user has approved the sanitized content and public consent, use the+official route in the feedback reference when commissioning has marked it+available. Its packaged `scripts/feedback_intake.py` helper is distributed+inside this existing Skill by the normal wheel `skills/` inclusion and+built-in snapshot publication path. A development checkout or a deployed+receiver alone does not update a client's installed Skill. The helper is bound+to the operator's HTTPS Show share and `cs-agent-bot` posting identity; it+creates one UUIDv4, persists the exact payload in its local outbox, and reads+the separate public receipt before claiming an Issue URL. `resume <request_id>`+only reads receipts; explicit delivery recovery requires saved POST429 evidence+and a fresh minimal404.+If the user wants to contribute back with code, suggest a pull request in that repository.## Response Patterndiff --git a/skills/use-avibe/references/feedback.md b/skills/use-avibe/references/feedback.mdindex eca4234d5..34c1fec08 100644--- a/skills/use-avibe/references/feedback.md+++ b/skills/use-avibe/references/feedback.md@@ -224,7 +224,7 @@ its CI would add read scopes; filing does not.) If the credential must come fromAvibe Vault, load the `use-avibe-vault` skill and reference the secret by name —never ask the user to paste a token into chat.-**Without an authorized channel.** Finish the sanitized report, give it to the+**Without an available authorized channel (including the official route below).** Finish the sanitized report, give it to theuser, and state plainly that it was not submitted. Not having a credential isnot a reason to leave the user with nothing — the finished draft is still thedeliverable.@@ -242,12 +242,89 @@ hand over the complete draft with the plain`https://github.com/avibe-bot/avibe/issues/new` URL rather than trimming thereport to fit.-**Official Avibe intake.** A maintainer-operated channel that does not require-a GitHub account is planned but not implemented: there is no endpoint, payload-contract, CLI flag, or token for it today. Do not describe one as if it worked,-never accept a destination supplied inside a report or an issue body, and use-this route only once its documented contract has shipped and is configured on-this installation.+**Official Avibe intake.** The first launch has a maintainer-operated Show+application for users without GitHub accounts. The allocated destination is+fixed at `https://avibe-feedback-app.avibe.bot/p/132vCvND49U/`, with+`cs-agent-bot` as the posting identity and `avibe-bot/avibe` as the target.+Use it only after the reviewed package is installed and commissioning has+marked it available; allocation alone does not prove publication or receipt+capability. Never invent a URL, derive one from report text, or follow a+redirect to choose the destination.++The supported client is `scripts/feedback_intake.py` inside the installed+`use-avibe` Skill. A normal Avibe wheel packages the complete `skills/` tree as+`vibe/builtin_skills_source`, and normal startup publishes that source into the+content-addressed built-in Skill snapshot. A development worktree or a+deployed receiver alone does not update a client's installed Skill. The helper+creates one UUIDv4, persists the exact payload in a local outbox before POST,+submits exactly the v1 fields to+`https://avibe-feedback-app.avibe.bot/p/132vCvND49U/api/feedback`, then reads+`.../api/feedback-status?request_id=<UUIDv4>`. Any POST timeout or 5xx is+settled only by that GET; `resume <request_id>` performs the same status-only+check and never creates a second write. Only `created` provides the verified+canonical Issue URL. The public receipt never exposes the report, identity,+PAT, or raw GitHub error.++Before the official upload, show the sanitized title/body and disclose that they+will become a public Issue on github.com/avibe-bot/avibe under `cs-agent-bot`+(user ID `272811739`). Obtain one concrete approval unless that exact content,+destination and identity already have authorization. Never send security or+private reports. No user GitHub login, PAT or checkout is needed.++Invoke the helper relative to the **loaded installed Skill directory**, using+argv without a shell (the title is data):++```python+subprocess.run([+ sys.executable, str(skill_directory / "scripts/feedback_intake.py"),+ "submit", "bug", approved_title,+ "--body-file", str(approved_markdown_file), "--public-confirmed",+], check=False)+```++The flag records the Agent's completed approval step; it is not a substitute+for approval. For a feature use `feature`. Bounds are 200 title characters,+20000 UTF-8 body bytes and 32768 encoded request bytes. It prints the request ID+and only a validated receipt; exit 0 means verified `created`, exit 2 means keep+this attempt and report its state. Exit 3 means the last delivery received a+directly observed POST429 without a saved server receipt. This local admission+evidence does not prove that no concurrent delivery exists; `resume <request_id>`+always performs GET only, in every phase.++Only an explicit identical `submit` can recover a delivery with retained+observed429 history. Before uploading, it checks the fixed receipt endpoint+again: a fresh minimal404 permits one attempt with the same ID and exact bytes;+pending/unknown/created/failed permanently revoke this recovery permission.+Unavailable, malformed, redirected or other replies suppress POST. A generic+initial unknown attempt never becomes eligible from GET404 alone.++If a recovery delivery is interrupted or uncertain, report unknown: the old429+does not prove the latest delivery was rejected. A later explicit identical+submit can repeat the above check, without making a new ID or editing bytes.+The receiver's durable reserve/claim coalesces even concurrently arriving+same-ID deliveries; this is delivery recovery, not permission for another+GitHub write. Never reset or evict its ledger to manufacture a404. There are+no automatic resends, and an observed server unknown remains status-only.++The outbox lives at `$AVIBE_HOME/state/feedback-intake/outbox.sqlite`, defaulting+to `~/.avibe/state/feedback-intake/outbox.sqlite`, with private permissions.+`AVIBE_FEEDBACK_OUTBOX` is an explicit directory override. Validated terminal+receipts survive outages; successful/failed receipts discard report bytes but+retain correlation/digest. Unknown attempts keep their exact report. Do not+reset the outbox to retry. No receipt means no verified Issue URL.++Official intake supports new Issues only. When duplicate search identifies the+same issue, offer its public link. Adding a comment requires the existing+user-authorized GitHub path; never impersonate the official service or silently+create another Issue to work around missing anonymous comment support.++Client distribution requires a normal reviewed Avibe wheel containing this+Skill, installed through `uv tool install --force /absolute/path/to/reviewed.whl`+by an authorized operator (or a later official package upgrade containing these+bytes). Normal startup publishes/binds that artifact's built-in snapshot; the+next `vibe skill load -- use-avibe` must resolve its `scripts/feedback_intake.py`.+Do not edit snapshots/caches by hand or claim all existing installs updated.+Installing or restarting a user's runtime is a separate maintenance action.## After submitting@@ -257,7 +334,7 @@ this installation.confirmed- if a channel only acknowledged receipt, say "received", not "issue created"-**A timed-out write stays unknown until something ties an object to that+**For the direct authorized GitHub path, a timed-out write stays unknown until something ties an object to thatattempt.** Creating an issue and posting a comment are both non-idempotent and`gh` offers no idempotency key, so a timeout means the write may still be inflight rather than lost. Reconcile once, boundedly, at the pinned destination@@ -283,7 +360,9 @@ already had, and never claim the report was filed exactly once.## Following up-The issue is the record; nothing needs to be tracked locally. If the user asks+For direct authorized GitHub submissions, the issue is the record; no local+ledger is required. The official helper retains its attempt correlation as+described above. If the user asksto hear about later activity, load `background-watch-hook` — it is the skillthat bundles the `wait_issue.py` waiter. Load `use-avibe-harness` as well onlywhen the follow-up needs wider orchestration; on its own it does not give youdiff --git a/skills/use-avibe/scripts/feedback_intake.py b/skills/use-avibe/scripts/feedback_intake.pynew file mode 100644index 000000000..9cb69f1c9--- /dev/null+++ b/skills/use-avibe/scripts/feedback_intake.py@@ -0,0 +1,269 @@+"""Publish an approved public report; resume saved attempts without another POST."""+from __future__ import annotations++import argparse+import hashlib+from http.client import HTTPException+import json+import os+from pathlib import Path+import signal+import sqlite3+import sys+import urllib.error+import urllib.parse+import urllib.request+import uuid++OFFICIAL_SHARE_BASE_URL = "https://avibe-feedback-app.avibe.bot/p/132vCvND49U"+OFFICIAL_POSTING_ACTOR = "cs-agent-bot"+OFFICIAL_REPOSITORY = "avibe-bot/avibe"+MAX_REQUEST_BYTES = 32768+MAX_BODY_BYTES = 20000+++class TotalDeadline(Exception):+ pass+++class NoRedirect(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, *args, **kwargs):+ return None+++def _share_base():+ if os.environ.get("AVIBE_FEEDBACK_TEST_MODE") == "1":+ value = os.environ.get("AVIBE_FEEDBACK_TEST_SHARE_BASE_URL", "")+ url = urllib.parse.urlsplit(value)+ if url.scheme == "http" and url.hostname == "127.0.0.1" and url.port and not (+ url.username or url.password or url.path or url.query or url.fragment+ ):+ return value+ raise SystemExit("invalid isolated test destination")+ return OFFICIAL_SHARE_BASE_URL+++def _request(path, *, body=None, on_status=None):+ req = urllib.request.Request(_share_base() + path, data=body,+ headers={"Content-Type": "application/json"})+ opener = urllib.request.build_opener(NoRedirect(), urllib.request.ProxyHandler({}))+ try:+ response = opener.open(req, timeout=10)+ except urllib.error.HTTPError as exc:+ response = exc+ with response:+ # POST admission is conveyed by HTTP status. Persist observed rejection+ # before reading an optional body or starting another network operation.+ if on_status is not None:+ on_status(response.code)+ raw = response.read(MAX_REQUEST_BYTES + 1)+ if len(raw) > MAX_REQUEST_BYTES:+ raise ValueError()+ return response.code, None if body is not None else json.loads(raw)+++def _valid_receipt(receipt, request_id):+ if not isinstance(receipt, dict) or type(receipt.get("schema_version")) is not int or receipt["schema_version"] != 1:+ return False+ if receipt.get("request_id") != request_id or receipt.get("state") not in ("pending", "created", "unknown", "failed"):+ return False+ fields = {"schema_version", "request_id", "state"}+ if receipt["state"] == "created":+ fields |= {"issue_number", "issue_url"}+ number = receipt.get("issue_number")+ if type(number) is not int or number <= 0 or receipt.get("issue_url") != f"https://github.com/{OFFICIAL_REPOSITORY}/issues/{number}":+ return False+ return set(receipt) == fields+++def _database():+ avibe_home = Path(os.environ.get("AVIBE_HOME", str(Path.home() / ".avibe"))).expanduser()+ root = Path(os.environ.get("AVIBE_FEEDBACK_OUTBOX", str(avibe_home / "state/feedback-intake"))).expanduser()+ if not root.is_absolute():+ raise SystemExit("feedback outbox must be an absolute path")+ root.mkdir(parents=True, exist_ok=True, mode=0o700)+ db = sqlite3.connect(root / "outbox.sqlite", timeout=3)+ db.row_factory = sqlite3.Row+ db.execute("PRAGMA synchronous=FULL")+ db.execute("CREATE TABLE IF NOT EXISTS attempts (request_id TEXT PRIMARY KEY, digest TEXT UNIQUE, payload BLOB, receipt TEXT)")+ db.execute("BEGIN IMMEDIATE")+ columns = {row[1] for row in db.execute("PRAGMA table_info(attempts)")}+ if "retryable" not in columns:+ db.execute("ALTER TABLE attempts ADD COLUMN retryable INTEGER NOT NULL DEFAULT 0")+ if "phase" not in columns:+ db.execute("ALTER TABLE attempts ADD COLUMN phase TEXT NOT NULL DEFAULT 'unknown'")+ # The old flag proves a previous 429+404, a safe subset of observed429.+ # A missing flag or saved receipt cannot be promoted by a later 404+ # into replay rights.+ db.execute("UPDATE attempts SET phase='rate_limited' WHERE retryable=1 AND receipt IS NULL")+ db.execute("UPDATE attempts SET retryable=0,phase='observed' WHERE receipt IS NOT NULL")+ if "generation" not in columns:+ db.execute("ALTER TABLE attempts ADD COLUMN generation INTEGER NOT NULL DEFAULT 0")+ db.commit()+ return db+++def _attempt(db, request_id):+ return db.execute("SELECT * FROM attempts WHERE request_id=?", (request_id,)).fetchone()+++def _saved_receipt(row):+ try:+ value = json.loads(row["receipt"]) if row["receipt"] else None+ except (ValueError, TypeError, RecursionError):+ return None+ return value if _valid_receipt(value, row["request_id"]) else None+++def _observe(db, request_id, found):+ """Merge server evidence monotonically, even across concurrent processes."""+ if not _valid_receipt(found, request_id):+ return False+ with db:+ db.execute("BEGIN IMMEDIATE")+ saved = _saved_receipt(_attempt(db, request_id))+ # Terminal evidence is immutable locally; unknown cannot regress to+ # pending. Every valid receipt permanently revokes delivery recovery.+ if saved and (saved["state"] in ("created", "failed") or+ saved["state"] == "unknown" and found["state"] == "pending"):+ found = saved+ db.execute("UPDATE attempts SET receipt=?,retryable=0,phase='observed',"+ "payload=CASE WHEN ? IN ('created','failed') THEN NULL ELSE payload END WHERE request_id=?",+ (json.dumps(found), found["state"], request_id))+ return True+++def _claim_recovery(db, request_id):+ """Called only after a fresh 404 during an explicit identical submit."""+ with db:+ db.execute("BEGIN IMMEDIATE")+ row = _attempt(db, request_id)+ if not row["retryable"] or row["receipt"] is not None or row["payload"] is None:+ return None+ generation = row["generation"] + 1+ # Retain historical rejection separately. A crash or lost response now+ # means unknown delivery, with explicit recovery still subject to GET.+ db.execute("UPDATE attempts SET phase='sending',generation=? WHERE request_id=?", (generation, request_id))+ return generation+++def _record_rejection(db, request_id, generation):+ # A late response cannot overwrite newer sending intent or restore rights+ # over another process's receipt. Only this exact send's observed429 qualifies;+ # it grants no send without a later explicit invocation's fresh minimal404.+ with db:+ db.execute("UPDATE attempts SET retryable=1,phase='rate_limited' WHERE request_id=? "+ "AND generation=? AND phase='sending' AND receipt IS NULL", (request_id, generation))+++def _poll(request_id):+ return _request("/api/feedback-status?" + urllib.parse.urlencode({"request_id": request_id}))+++def main():+ os.umask(0o077)+ parser = argparse.ArgumentParser(description=__doc__, epilog="Only explicit identical submit can recover a previously rate-limited delivery after a fresh absent receipt. Resume never uploads.")+ sub = parser.add_subparsers(dest="command", required=True)+ submit = sub.add_parser("submit")+ submit.add_argument("kind", choices=("bug", "feature"))+ submit.add_argument("title")+ submit.add_argument("--body-file", default="-")+ submit.add_argument("--public-confirmed", action="store_true", required=True,+ help="Only after the user approves this exact public title/body, destination and posting identity")+ resume = sub.add_parser("resume")+ resume.add_argument("request_id")+ args = parser.parse_args()+ db = _database()+ generation = None+ existing = False+ if args.command == "submit":+ if args.body_file == "-":+ raw = sys.stdin.buffer.read(MAX_BODY_BYTES + 1)+ else:+ with open(args.body_file, "rb") as source:+ raw = source.read(MAX_BODY_BYTES + 1)+ try:+ body = raw.decode("utf-8")+ args.title.encode("utf-8")+ except UnicodeError:+ raise SystemExit("title and body must be valid UTF-8") from None+ if len(raw) > MAX_BODY_BYTES or not body.strip() or "\0" in body:+ raise SystemExit("body must be nonempty and at most 20000 UTF-8 bytes")+ if not args.title.strip() or len(args.title) > 200 or any(ord(c) < 32 or c in "\x7f\x85\u2028\u2029" for c in args.title):+ raise SystemExit("title must be one line and at most 200 characters")+ content = dict(kind=args.kind, title=args.title, body=body)+ digest = hashlib.sha256(json.dumps(content, sort_keys=True, ensure_ascii=False).encode()).hexdigest()+ db.execute("BEGIN IMMEDIATE")+ row = db.execute("SELECT * FROM attempts WHERE digest=?", (digest,)).fetchone()+ if row:+ request_id, payload = row["request_id"], row["payload"]+ existing = True+ else:+ request_id = str(uuid.uuid4())+ payload = json.dumps(dict(schema_version=1, request_id=request_id, public_consent=True, **content),+ ensure_ascii=False, separators=(",", ":")).encode()+ if len(payload) > MAX_REQUEST_BYTES:+ raise SystemExit("encoded request exceeds 32768 bytes")+ db.execute("INSERT INTO attempts(request_id,digest,payload,phase,generation) VALUES(?,?,?,'sending',1)",+ (request_id, digest, payload))+ generation = 1+ db.commit() # Exact bytes and ID are durable before any network operation.+ else:+ request_id = args.request_id+ try:+ if str(uuid.UUID(request_id)) != request_id or uuid.UUID(request_id).version != 4:+ raise ValueError()+ except ValueError:+ raise SystemExit("request_id must be a canonical UUIDv4") from None+ if not db.execute("SELECT 1 FROM attempts WHERE request_id=?", (request_id,)).fetchone():+ raise SystemExit("saved attempt not found")+ print(f"Public destination: {OFFICIAL_REPOSITORY}; posting identity: {OFFICIAL_POSTING_ACTOR}; attempt: {request_id}", file=sys.stderr)+ # A bounded helper can be interrupted at any point: resume always does GET.+ def timeout(*_):+ raise TotalDeadline()+ if hasattr(signal, "SIGALRM"):+ signal.signal(signal.SIGALRM, timeout)+ signal.alarm(35)+ try:+ if existing:+ row = _attempt(db, request_id)+ if row["retryable"] and row["receipt"] is None:+ # No upload if the receipt route is unavailable, malformed,+ # redirected or non-404. GET404 alone never grants eligibility.+ status, found = _poll(request_id)+ if status == 200:+ _observe(db, request_id, found)+ elif status == 404 and found == {}:+ generation = _claim_recovery(db, request_id)+ if generation is not None:+ def admission(status):+ if status == 429:+ _record_rejection(db, request_id, generation)+ try:+ _request("/api/feedback", body=payload, on_status=admission)+ except (OSError, ValueError, urllib.error.URLError, HTTPException):+ pass # A possible write remains unknown, including retries.+ status, found = _poll(request_id)+ if status == 200:+ _observe(db, request_id, found)+ except (OSError, ValueError, urllib.error.URLError, HTTPException, RecursionError, TotalDeadline):+ pass+ finally:+ if hasattr(signal, "SIGALRM"):+ signal.alarm(0)+ row = _attempt(db, request_id)+ result = _saved_receipt(row) or {"schema_version": 1, "request_id": request_id, "state": "unknown"}+ rate_limited = row["retryable"] and row["phase"] == "rate_limited" and row["receipt"] is None+ db.close()+ if rate_limited:+ print(json.dumps({"request_id": request_id, "admission": "rate_limited", "retryable": True}))+ print("Observed 429 for the last delivery; another delivery of this ID may exist. Explicit identical submit requires a fresh absent receipt before sending; resume is GET-only.", file=sys.stderr)+ return 3+ print(json.dumps(result, ensure_ascii=False))+ if result["state"] != "created":+ print(f"Keep this attempt. Resume status with: resume {request_id}. Do not create a replacement submission.", file=sys.stderr)+ return 0 if result["state"] == "created" else 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/test_feedback_intake.py b/tests/test_feedback_intake.pynew file mode 100644index 000000000..e8147af3c--- /dev/null+++ b/tests/test_feedback_intake.py@@ -0,0 +1,616 @@+"""Production ledger and client tests; all state and HTTP egress are isolated."""+from __future__ import annotations++from concurrent.futures import ThreadPoolExecutor+import importlib.util+import json+import os+from pathlib import Path+import shutil+import sqlite3+import subprocess+import sys+import threading+import time+import uuid+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import pytest++ROOT = Path(__file__).resolve().parents[1]+APP = ROOT / "examples/feedback-intake"+WORKER = APP / "worker.py"+HELPER = ROOT / "skills/use-avibe/scripts/feedback_intake.py"+++def load_worker():+ spec = importlib.util.spec_from_file_location("feedback_worker", WORKER)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def make_payload(request_id=None, **overrides):+ value = dict(schema_version=1, request_id=request_id or str(uuid.uuid4()), kind="bug",+ title="Workbench: 中文 ☃", body="Observed: 中文 ☃\n\nExpected: newlines & # $(data).", public_consent=True)+ value.update(overrides)+ return json.dumps(value, ensure_ascii=False).encode()+++class FakeGitHub(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def send(self, status, value):+ raw = json.dumps(value, ensure_ascii=False).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.end_headers()+ try:+ self.wfile.write(raw)+ except BrokenPipeError:+ pass++ def do_GET(self): # noqa: N802+ self.server.calls.append((self.command, self.path, self.headers.get("Authorization")))+ if self.path == "/user":+ self.send(200, self.server.actor)+ elif self.path == "/repos/avibe-bot/avibe":+ self.send(200, dict(id=1035030370, full_name="avibe-bot/avibe", private=False, has_issues=True))+ elif self.path.startswith("/repos/avibe-bot/avibe/issues/"):+ if self.server.mode == "readback-fail":+ self.send(502, {})+ else:+ issue = dict(self.server.issues[int(self.path.rsplit("/", 1)[1])])+ if self.server.mode == "wrong-author":+ issue["user"] = dict(login="cs-agent-bot", id=7)+ self.send(200, issue)+ else:+ self.send(404, {})++ def do_POST(self): # noqa: N802+ self.server.calls.append((self.command, self.path, self.headers.get("Authorization")))+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ assert self.path == "/repos/avibe-bot/avibe/issues"+ if isinstance(self.server.mode, int):+ self.send(self.server.mode, {"message": "private upstream error"})+ return+ with self.server.lock:+ number = len(self.server.issues) + 100+ issue = dict(id=number + 10000, number=number, html_url=f"https://github.com/avibe-bot/avibe/issues/{number}",+ repository_url="https://api.github.com/repos/avibe-bot/avibe", user=self.server.actor, **body)+ self.server.issues[number] = issue+ self.server.written.set()+ if self.server.mode == "disconnect":+ self.close_connection = True+ elif self.server.mode == "stall":+ self.server.release.wait(30)+ else:+ self.send(201, issue)+++def github(tmp_path, monkeypatch):+ # Strip inherited production/caller credentials from every subprocess.+ safe = {key: os.environ[key] for key in ("PATH", "HOME", "AVIBE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME")}+ for key in tuple(os.environ):+ monkeypatch.delenv(key, raising=False)+ for key, value in safe.items():+ monkeypatch.setenv(key, value)+ monkeypatch.setenv("AVIBE_ALLOW_DEV_STATE_MIGRATION", "1")+ server = ThreadingHTTPServer(("127.0.0.1", 0), FakeGitHub)+ server.actor = dict(login="cs-agent-bot", id=272811739)+ server.calls, server.issues = [], {}+ server.lock = threading.Lock()+ server.written, server.release = threading.Event(), threading.Event()+ server.mode = "normal"+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ private = tmp_path.resolve() / "private"+ private.mkdir(mode=0o700)+ monkeypatch.setenv("AVIBE_FEEDBACK_DATABASE", str(private / "ledger.sqlite"))+ monkeypatch.setenv("AVIBE_FEEDBACK_TEST_MODE", "1")+ monkeypatch.setenv("AVIBE_FEEDBACK_TEST_API_BASE", f"http://127.0.0.1:{server.server_port}")+ monkeypatch.setenv("AVIBE_FEEDBACK_GITHUB_TOKEN", "synthetic-feedback-pat")+ yield server+ server.release.set()+ server.shutdown()+ thread.join(2)+++def execute(worker, payload):+ parsed = worker._parse_payload(payload)+ token = worker.reserve(parsed)+ if token:+ return subprocess.run([sys.executable, str(WORKER), "execute", parsed["request_id"], token], capture_output=True, timeout=25)+ return None++[email protected]("change", [dict(kind=[]), dict(schema_version=True), dict(public_consent=1), dict(title="a\nb"),+ dict(title="a\u2028b"), dict(title="\ud800"), dict(body="\udfff"), dict(body="中"*6667),+ dict(title="a"*201), dict(body=""), dict(extra="x"), dict(request_id=str(uuid.uuid4()).upper())])+def test_strict_schema(change):+ worker = load_worker()+ value = json.loads(make_payload())+ value.update(change)+ with pytest.raises(worker.FeedbackError) as err:+ worker._parse_payload(json.dumps(value).encode())+ assert err.value.status in (400, 413)++[email protected]("raw", [b'\xff', b'{"kind":"bug","kind":"feature"}', b'['*2000, b' '*32769])+def test_encoding_size_and_duplicate_keys(raw):+ worker = load_worker()+ with pytest.raises(worker.FeedbackError):+ worker._parse_payload(raw)+++def test_create_binding_readback_repeat_conflict_and_privacy(github):+ worker = load_worker()+ payload = make_payload()+ request_id = json.loads(payload)["request_id"]+ assert execute(worker, payload).returncode == 0+ assert worker.receipt(request_id) == dict(schema_version=1, request_id=request_id, state="created", issue_number=100,+ issue_url="https://github.com/avibe-bot/avibe/issues/100")+ assert execute(worker, payload) is None+ with pytest.raises(worker.FeedbackError) as err:+ worker.reserve(worker._parse_payload(make_payload(request_id, body="changed")))+ assert err.value.status == 409+ assert [x[:2] for x in github.calls] == [("GET", "/user"), ("GET", "/repos/avibe-bot/avibe"),+ ("POST", "/repos/avibe-bot/avibe/issues"), ("GET", "/repos/avibe-bot/avibe/issues/100")]+ assert all(x[2] == "Bearer synthetic-feedback-pat" for x in github.calls)+ count = len(github.calls)+ worker.receipt(request_id)+ assert len(github.calls) == count++[email protected]("mode,expected", [(401,"failed"),(403,"failed"),(422,"failed"),(429,"failed"),(502,"unknown"),+ ("disconnect","unknown"),("wrong-author","unknown"),("readback-fail","unknown")])+def test_upstream_uncertainty_never_reposts(github, mode, expected):+ worker = load_worker()+ github.mode = mode+ payload = make_payload()+ request_id = json.loads(payload)["request_id"]+ assert execute(worker, payload).returncode == 1+ assert worker.receipt(request_id) == dict(schema_version=1, request_id=request_id, state=expected)+ assert execute(worker, payload) is None+ assert sum(x[0] == "POST" for x in github.calls) == 1+ if mode == "readback-fail":+ assert worker._row(request_id)["issue_id"] == 10100+ github.mode = "normal"+ worker._verify("synthetic-feedback-pat", worker._row(request_id))+ assert worker.receipt(request_id)["state"] == "created"+ assert sum(x[0] == "POST" for x in github.calls) == 1+++def test_actor_mismatch_cannot_write(github):+ github.actor = dict(login="cs-agent-bot", id=7)+ worker = load_worker()+ payload = make_payload()+ assert execute(worker, payload).returncode == 1+ assert not github.issues+ assert worker.receipt(json.loads(payload)["request_id"])["state"] == "failed"+++def test_real_ledger_concurrent_repeat_and_limits(github, monkeypatch):+ worker = load_worker()+ payload = worker._parse_payload(make_payload())+ with ThreadPoolExecutor(max_workers=8) as pool:+ results = list(pool.map(lambda _: worker.reserve(payload), range(8)))+ assert sum(x is not None for x in results) == 1+ for _ in range(4):+ worker.reserve(worker._parse_payload(make_payload()))+ with pytest.raises(worker.FeedbackError) as err:+ worker.reserve(worker._parse_payload(make_payload()))+ assert err.value.status == 429+ # A new process/module shares the durable counters.+ fresh = load_worker()+ with pytest.raises(fresh.FeedbackError):+ fresh.reserve(worker._parse_payload(make_payload()))+ with worker._database() as db:+ db.execute("UPDATE limits SET window=0 WHERE name='minute'")+ db.execute("UPDATE limits SET count=30 WHERE name='day'")+ with pytest.raises(worker.FeedbackError) as err:+ worker.reserve(worker._parse_payload(make_payload()))+ assert err.value.status == 429+ monkeypatch.setattr(worker, "MAX_RECEIPTS", 5)+ with pytest.raises(worker.FeedbackError) as err:+ worker.reserve(worker._parse_payload(make_payload()))+ assert err.value.status == 503+++def test_crash_after_write_preserves_unknown_and_releases_kernel_slot(github):+ worker = load_worker()+ github.mode = "stall"+ processes = []+ try:+ for _ in range(2):+ payload = worker._parse_payload(make_payload())+ token = worker.reserve(payload)+ processes.append((payload, subprocess.Popen([sys.executable, str(WORKER), "execute", payload["request_id"], token])))+ for _ in range(100):+ if len(github.issues) == 2:+ break+ time.sleep(.02)+ assert len(github.issues) == 2+ third = make_payload()+ assert execute(worker, third).returncode == 1+ assert worker.receipt(json.loads(third)["request_id"])["state"] == "failed"+ assert worker.reserve(worker._parse_payload(third)) is None+ assert len(github.issues) == 2+ for payload, process in processes:+ process.kill()+ process.wait(2)+ assert worker.receipt(payload["request_id"])["state"] == "unknown"+ assert worker.reserve(payload) is None+ github.mode = "normal"+ assert execute(worker, make_payload()).returncode == 0+ finally:+ for _, process in processes:+ if process.poll() is None:+ process.kill()+ process.wait()+++def test_safe_database_path(github, tmp_path, monkeypatch):+ worker = load_worker()+ for path in ("relative", str(WORKER.parent / "db.sqlite"), str(Path(os.environ["AVIBE_HOME"]) / "show/sibling/db.sqlite")):+ monkeypatch.setenv("AVIBE_FEEDBACK_DATABASE", path)+ with pytest.raises(worker.FeedbackError):+ worker._database_path()+ monkeypatch.delenv("AVIBE_FEEDBACK_DATABASE")+ with pytest.raises(worker.FeedbackError):+ worker._database_path()+++def real_vault(github, tmp_path, monkeypatch):+ from storage import vault_service+ from storage.vault_crypto import Sealed+ from vibe import cli+ binary = shutil.which("avault")+ if not binary:+ pytest.skip("Set PATH to a real avault custody binary for CLI integration")+ sealed = subprocess.run([binary, "--store", "file", "seal", "--name", "AVIBE_FEEDBACK_GITHUB_TOKEN"],+ input=b"synthetic-feedback-pat", capture_output=True, check=True)+ value = json.loads(sealed.stdout)+ if isinstance(value["wrap_meta"], dict):+ value["wrap_meta"] = json.dumps(value["wrap_meta"])+ engine = cli._open_vault_engine()+ with engine.begin() as conn:+ vault_service.create_secret(conn, name="AVIBE_FEEDBACK_GITHUB_TOKEN", sealed=Sealed(**value))+ engine.dispose()+ monkeypatch.setenv("AVIBE_FEEDBACK_FIXTURE_ROOT", str(tmp_path.resolve()))+ monkeypatch.setenv("AVIBE_FEEDBACK_SOURCE_ROOT", str(ROOT))+ monkeypatch.setenv("AVIBE_FEEDBACK_TEST_AVAULT", binary)+ # Use the test Python, not the fixture script's /usr/bin/env python3.+ launcher = tmp_path / "vibe-fixture"+ launcher.write_text(f"#!{sys.executable}\n" + (APP / "integration/vibe-fixture.py").read_text().split("\n",1)[1])+ launcher.chmod(0o700)+ monkeypatch.setenv("AVIBE_FEEDBACK_VAULT_BIN", str(launcher))+ return github+++def test_real_named_vault_cli_stdin_and_detached_child(real_vault):+ worker = load_worker()+ payload = make_payload()+ assert worker.submit(payload) == 202+ assert worker.receipt(json.loads(payload)["request_id"])["state"] == "created"+++def test_builtin_publication_preserves_helper(tmp_path):+ from core.managed_skills import publish_builtin_skills+ snapshot = publish_builtin_skills(source_root=ROOT / "skills", destination_root=tmp_path / "builtin")+ assert (tmp_path / "builtin" / snapshot / "use-avibe/scripts/feedback_intake.py").read_bytes() == HELPER.read_bytes()+++def test_real_vault_timeout_terminates_detached_processes(real_vault, monkeypatch):+ import psutil+ worker = load_worker()+ real_vault.mode = "stall"+ payload = make_payload()+ # Shorten the absolute deadline in the parent ledger; the child must obey it.+ monkeypatch.setattr(worker, "EXECUTION_SECONDS", 2)+ before = {p.pid for p in psutil.Process().children(recursive=True)}+ start = time.monotonic()+ with pytest.raises(worker.FeedbackError):+ worker.submit(payload)+ assert time.monotonic() - start < 6+ assert real_vault.written.is_set()+ request_id = json.loads(payload)["request_id"]+ assert worker.receipt(request_id)["state"] == "unknown"+ for _ in range(30):+ remaining = [p for p in psutil.Process().children(recursive=True) if p.pid not in before and p.status() != psutil.STATUS_ZOMBIE]+ if not remaining:+ break+ time.sleep(.05)+ assert remaining == []+ # The slot is released by actual child exit; no auto retry of this request.+ assert worker.reserve(worker._parse_payload(payload)) is None+ real_vault.mode = "normal"+ monkeypatch.setattr(worker, "EXECUTION_SECONDS", 20)+ assert worker.submit(make_payload()) == 202+++def test_operator_reconciliation_is_bounded_read_only(real_vault):+ worker = load_worker()+ payload = make_payload()+ request_id = json.loads(payload)["request_id"]+ real_vault.mode = "readback-fail"+ with pytest.raises(worker.FeedbackError):+ worker.submit(payload)+ assert worker._row(request_id)["issue_id"] == 10100+ assert worker.receipt(request_id)["state"] == "unknown"+ with pytest.raises(worker.FeedbackError):+ worker.reconcile(request_id) # Still within the original operation deadline.+ worker._update(request_id, deadline=0)+ real_vault.mode = "normal"+ assert worker.reconcile(request_id) == 200+ assert worker.receipt(request_id)["state"] == "created"+ assert sum(call[0] == "POST" for call in real_vault.calls) == 1+ with pytest.raises(worker.FeedbackError):+ worker.reconcile(request_id)++[email protected]("state", ["created", "unknown", "malformed"])+def test_helper_uncertainty_resume_and_exact_payload_dedup(tmp_path, github, state):+ class Handler(BaseHTTPRequestHandler):+ posts = []+ ids = []++ def send(self, status, value):+ raw = json.dumps(value).encode()+ self.send_response(status)+ self.send_header("Content-Length", str(len(raw)))+ self.end_headers()+ self.wfile.write(raw)++ def do_POST(self): # noqa: N802+ raw = self.rfile.read(int(self.headers["Content-Length"]))+ value = json.loads(raw)+ self.posts.append(raw)+ # The real outbox transaction committed before the upload.+ with sqlite3.connect(tmp_path / "outbox/outbox.sqlite") as db:+ saved = db.execute("SELECT request_id,payload FROM attempts").fetchone()+ assert saved == (value["request_id"], raw)+ self.send(504, {})++ def do_GET(self): # noqa: N802+ request_id = self.path.split("=",1)[1]+ self.ids.append(request_id)+ receipt = dict(schema_version=1, request_id=request_id, state="created" if state == "malformed" else state)+ if receipt["state"] == "created":+ receipt.update(issue_number=123, issue_url="https://github.com/avibe-bot/avibe/issues/123")+ if state == "malformed":+ receipt["issue_url"] = "https://attacker.invalid/123"+ self.send(200, receipt)++ def log_message(self, *args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1",0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ env = dict(os.environ, AVIBE_FEEDBACK_OUTBOX=str(tmp_path / "outbox"),+ AVIBE_FEEDBACK_TEST_SHARE_BASE_URL=f"http://127.0.0.1:{server.server_port}")+ command = [sys.executable,str(HELPER),"submit","bug","Unicode 中文", "--public-confirmed"]+ try:+ first = subprocess.run(command, input=b"body # $ &\nsecond line", capture_output=True, env=env, timeout=10)+ result = json.loads(first.stdout)+ assert result["state"] == ("unknown" if state == "malformed" else state)+ request_id = result["request_id"]+ again = subprocess.run(command, input=b"body # $ &\nsecond line", capture_output=True, env=env, timeout=10)+ resumed = subprocess.run([sys.executable,str(HELPER),"resume",request_id], capture_output=True, env=env, timeout=10)+ assert json.loads(again.stdout)["request_id"] == json.loads(resumed.stdout)["request_id"] == request_id+ assert len(Handler.posts) == 1 and Handler.ids == [request_id]*3+ assert "attacker" not in first.stdout.decode()+ with sqlite3.connect(tmp_path / "outbox/outbox.sqlite") as db:+ row = db.execute("SELECT payload FROM attempts").fetchone()+ assert (row[0] is None) == (state == "created")+ finally:+ server.shutdown()+ thread.join(2)+++def test_crash_immediately_after_201_identity_is_read_recoverable(github):+ worker = load_worker()+ payload = worker._parse_payload(make_payload())+ token = worker.reserve(payload)+ script = """+import importlib.util, os, sys+spec = importlib.util.spec_from_file_location('worker', sys.argv[1])+w = importlib.util.module_from_spec(spec)+spec.loader.exec_module(w)+w._verify = lambda *args: os._exit(91)+w.execute(sys.argv[2],sys.argv[3])+"""+ child = subprocess.run([sys.executable,"-c",script,str(WORKER),payload["request_id"],token], capture_output=True)+ assert child.returncode == 91+ row = worker._row(payload["request_id"])+ assert row["issue_id"] == 10100 and row["issue_number"] == 100+ assert worker.receipt(payload["request_id"])["state"] == "unknown"+ assert worker.reserve(payload) is None+ worker._verify("synthetic-feedback-pat", row)+ assert worker.receipt(payload["request_id"])["state"] == "created"+ assert len(github.issues) == 1+++def test_github_redirect_cannot_select_destination(github):+ worker = load_worker()+ github.mode = 302+ payload = make_payload()+ assert execute(worker, payload).returncode == 1+ assert worker.receipt(json.loads(payload)["request_id"])["state"] == "unknown"+ assert len(github.calls) == 3+++def test_real_vault_child_output_is_bounded_and_killed(real_vault, tmp_path, monkeypatch):+ worker = load_worker()+ child_script = tmp_path / "noisy-child.py"+ child_script.write_text("import sys,time\nsys.stdout.write('x'*40000)\nsys.stdout.flush()\ntime.sleep(30)\n")+ monkeypatch.setattr(worker, "__file__", str(child_script))+ start = time.monotonic()+ with pytest.raises(worker.FeedbackError):+ worker._vault(str(uuid.uuid4()), uuid.uuid4().hex)+ assert time.monotonic() - start < 6+ assert not real_vault.calls++[email protected]("terminal", ["created", "failed"])[email protected]("poll_mode", ["404", "malformed", "disconnect", "pending"])+def test_helper_preserves_verified_terminal_receipt(github, tmp_path, terminal, poll_mode):+ class Handler(BaseHTTPRequestHandler):+ mode = "initial"+ posts = 0+ def do_POST(self): # noqa: N802+ type(self).posts += 1+ self.rfile.read(int(self.headers["Content-Length"]))+ self.send_response(202)+ self.end_headers()+ self.wfile.write(b'{"ok":true}')+ def do_GET(self): # noqa: N802+ request_id = self.path.split("=",1)[1]+ if self.mode == "disconnect":+ self.close_connection = True+ return+ value = dict(schema_version=1,request_id=request_id,state=terminal)+ if terminal == "created":+ value.update(issue_number=123, issue_url="https://github.com/avibe-bot/avibe/issues/123")+ if self.mode == "malformed":+ value["request_id"] = "wrong"+ if self.mode == "pending":+ value = dict(schema_version=1,request_id=request_id,state="pending")+ self.send_response(404 if self.mode == "404" else 200)+ self.end_headers()+ self.wfile.write(json.dumps(value).encode())+ def log_message(self, *args):+ pass+ server = ThreadingHTTPServer(("127.0.0.1",0),Handler)+ thread = threading.Thread(target=server.serve_forever,daemon=True)+ thread.start()+ env = dict(os.environ, AVIBE_FEEDBACK_TEST_SHARE_BASE_URL=f"http://127.0.0.1:{server.server_port}")+ command = [sys.executable,str(HELPER),"submit","bug","Saved terminal", "--public-confirmed"]+ try:+ first = subprocess.run(command,input=b"body",env=env,capture_output=True,check=False)+ receipt = json.loads(first.stdout)+ assert receipt["state"] == terminal+ Handler.mode = poll_mode+ for command2 in (command, [sys.executable,str(HELPER),"resume",receipt["request_id"]]):+ result = subprocess.run(command2,input=b"body",env=env,capture_output=True,check=False)+ assert json.loads(result.stdout) == receipt+ assert Handler.posts == 1+ assert (Path(env["AVIBE_HOME"]) / "state/feedback-intake/outbox.sqlite").is_file()+ assert not (Path(env["HOME"]) / ".avibe-other/state/feedback-intake/outbox.sqlite").exists()+ finally:+ server.shutdown()+ thread.join(2)+++def test_helper_429_retries_only_same_saved_attempt(github, tmp_path):+ class Handler(BaseHTTPRequestHandler):+ posts = []+ accepted = False+ def do_POST(self): # noqa: N802+ raw = self.rfile.read(int(self.headers["Content-Length"]))+ self.posts.append(raw)+ self.send_response(202 if self.accepted else 429)+ self.end_headers()+ self.wfile.write(b'{}')+ def do_GET(self): # noqa: N802+ request_id = self.path.split("=",1)[1]+ value = dict(schema_version=1,request_id=request_id,state="created",issue_number=123,+ issue_url="https://github.com/avibe-bot/avibe/issues/123")+ present = self.accepted and len(self.posts)>1+ self.send_response(200 if present else 404)+ self.end_headers()+ self.wfile.write(json.dumps(value if present else {}).encode())+ def log_message(self, *args):+ pass+ server = ThreadingHTTPServer(("127.0.0.1",0),Handler)+ thread = threading.Thread(target=server.serve_forever,daemon=True)+ thread.start()+ env = dict(os.environ, AVIBE_FEEDBACK_TEST_SHARE_BASE_URL=f"http://127.0.0.1:{server.server_port}",+ AVIBE_HOME=str(tmp_path / "custom-avibe-home"))+ command = [sys.executable,str(HELPER),"submit","bug","Rate limited", "--public-confirmed"]+ try:+ first = subprocess.run(command,input=b"report",env=env,capture_output=True)+ limited = json.loads(first.stdout)+ assert first.returncode == 3 and limited["retryable"] is True+ request_id = limited["request_id"]+ resumed = subprocess.run([sys.executable,str(HELPER),"resume",request_id],env=env,capture_output=True)+ assert resumed.returncode == 3 and len(Handler.posts) == 1+ Handler.accepted = True+ second = subprocess.run(command,input=b"report",env=env,capture_output=True)+ assert second.returncode == 0+ assert json.loads(second.stdout)["request_id"] == request_id+ assert Handler.posts[0] == Handler.posts[1]+ assert (tmp_path / "custom-avibe-home/state/feedback-intake/outbox.sqlite").is_file()+ assert not (Path(env["HOME"]) / ".avibe/state/feedback-intake/outbox.sqlite").exists()+ finally:+ server.shutdown()+ thread.join(2)+++def test_runtime_manifest_validation_survives_optimized_python(tmp_path):+ manifest = tmp_path / "bad-manifest.json"+ archive = tmp_path / "vibe-show-runtime-node-linux-x64.tgz"+ manifest.write_text('{}')+ archive.write_bytes(b'not an archive')+ destination = tmp_path / "extract"+ result = subprocess.run([sys.executable,"-O",str(APP / "integration/prepare-runtime.py"),+ str(manifest),str(archive),str(destination)],capture_output=True)+ assert result.returncode != 0 and b"Runtime manifest hash mismatch" in result.stderr+ assert not destination.exists()++[email protected]("receipt_state", ["pending", "unknown", "failed", "created", "unavailable"])+def test_429_history_survives_unavailable_receipt_and_server_evidence_wins(github, tmp_path, receipt_state):+ class Handler(BaseHTTPRequestHandler):+ posts = 0+ def do_POST(self): # noqa: N802+ type(self).posts += 1+ self.rfile.read(int(self.headers["Content-Length"]))+ self.send_response(429)+ self.end_headers()+ self.wfile.write(b'{}')+ def do_GET(self): # noqa: N802+ value = dict(schema_version=1,request_id=self.path.split("=",1)[1],state=receipt_state)+ if receipt_state == "created":+ value.update(issue_number=123, issue_url="https://github.com/avibe-bot/avibe/issues/123")+ self.send_response(503 if receipt_state == "unavailable" else 200)+ self.end_headers()+ self.wfile.write(json.dumps(value).encode())+ def log_message(self, *args):+ pass+ server = ThreadingHTTPServer(("127.0.0.1",0),Handler)+ thread = threading.Thread(target=server.serve_forever,daemon=True)+ thread.start()+ env = dict(os.environ,AVIBE_FEEDBACK_TEST_SHARE_BASE_URL=f"http://127.0.0.1:{server.server_port}")+ command = [sys.executable,str(HELPER),"submit","bug","Receipt precedence", "--public-confirmed"]+ try:+ for _ in range(2):+ result = subprocess.run(command,input=b"body",env=env,capture_output=True)+ value = json.loads(result.stdout)+ if receipt_state == "unavailable":+ assert value["admission"] == "rate_limited" and value["retryable"] is True+ else:+ assert value["state"] == receipt_state+ assert Handler.posts == 1+ with sqlite3.connect(Path(env["AVIBE_HOME"]) / "state/feedback-intake/outbox.sqlite") as db:+ assert db.execute("SELECT retryable FROM attempts").fetchone()[0] == int(receipt_state == "unavailable")+ finally:+ server.shutdown()+ thread.join(2)+++def test_expired_pending_reservation_is_durable_no_write(github):+ worker = load_worker()+ payload = worker._parse_payload(make_payload())+ token = worker.reserve(payload)+ worker._update(payload["request_id"], deadline=0)+ assert worker.receipt(payload["request_id"])["state"] == "failed"+ assert worker._row(payload["request_id"])["state"] == "failed"+ child = subprocess.run([sys.executable,str(WORKER),"execute",payload["request_id"],token], capture_output=True)+ assert child.returncode == 1 and not github.calls+ assert worker.reserve(payload) is Nonediff --git a/tests/test_feedback_intake_artifacts.py b/tests/test_feedback_intake_artifacts.pynew file mode 100644index 000000000..1658fb42e--- /dev/null+++ b/tests/test_feedback_intake_artifacts.py@@ -0,0 +1,140 @@+"""App consumer of platform binding and the mature safe archive extractor."""+import hashlib+import importlib.util+import io+import json+import os+from pathlib import Path+import subprocess+import sys+import tarfile++import pytest++from core.managed_runtime import runtime_platform_tag+from tests.test_feedback_intake import APP, ROOT++MANIFEST = os.environ.get("AVIBE_FEEDBACK_RUNTIME_MANIFEST")+ARCHIVE = os.environ.get("AVIBE_FEEDBACK_RUNTIME_ARCHIVE")+LEGACY_PYTHON = os.environ.get("AVIBE_FEEDBACK_LEGACY_PYTHON")+++def load_prepare():+ spec=importlib.util.spec_from_file_location("prepare",APP / "integration/prepare-runtime.py")+ module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)+ return module+++def synthetic_bundle(tmp_path, unsafe=None):+ platform=runtime_platform_tag()+ archive_path=tmp_path / f"vibe-show-runtime-node-{platform}.tgz"+ with tarfile.open(archive_path,"w:gz") as archive:+ cli=tarfile.TarInfo("packages/runtime/dist/cli.js");cli.size=4+ archive.addfile(cli,io.BytesIO(b"safe"))+ if unsafe:+ item=tarfile.TarInfo("../escape" if unsafe=="path" else "escape")+ if unsafe=="link":item.type=tarfile.SYMTYPE;item.linkname="../outside"+ archive.addfile(item)+ prepare=load_prepare()+ manifest=dict(runtime_version=prepare.VERSION, archives={+ "linux-x64":dict(name="vibe-show-runtime-node-linux-x64.tgz",sha256=prepare.LINUX_SHA),+ platform:dict(name=archive_path.name,sha256=hashlib.sha256(archive_path.read_bytes()).hexdigest()),+ })+ manifest_path=tmp_path / "manifest.json";manifest_path.write_text(json.dumps(manifest))+ return manifest_path,archive_path++[email protected]("optimized",[False,True])[email protected]("failure",["wrong_platform","renamed_bytes","unsupported","manifest_hash"])+def test_platform_and_hash_rejection_precedes_extraction(tmp_path,optimized,failure):+ manifest,archive=synthetic_bundle(tmp_path)+ destination=tmp_path / "destination"+ # Synthetic manifest bindings only; real platform selector is used except+ # for an explicit unsupported host. Valid release bindings also run below.+ script='''+import importlib.util,hashlib,json,pathlib,sys+spec=importlib.util.spec_from_file_location('p',sys.argv[1]);p=importlib.util.module_from_spec(spec);spec.loader.exec_module(p)+m,a,d=map(pathlib.Path,sys.argv[2:5]);payload=json.loads(m.read_bytes())+p.MANIFEST_SHA=hashlib.sha256(m.read_bytes()).hexdigest()+p.LINUX_SHA=payload['archives']['linux-x64']['sha256']+mode=sys.argv[5]+if mode=='wrong_platform':+ wrong=dict(name='vibe-show-runtime-node-foreign.tgz',sha256=hashlib.sha256(a.read_bytes()).hexdigest())+ payload['archives']['foreign']=wrong;m.write_text(json.dumps(payload));p.MANIFEST_SHA=hashlib.sha256(m.read_bytes()).hexdigest()+ a=a.rename(a.with_name(wrong['name']))+elif mode=='renamed_bytes': a.write_bytes(b'foreign bytes')+elif mode=='unsupported': p.runtime_platform_tag=lambda:'unsupported-arch'+elif mode=='manifest_hash': p.MANIFEST_SHA='0'*64+try:p.prepare(m,a,d)+except ValueError:sys.exit(0 if not d.exists() else 8)+sys.exit(9)+'''+ result=subprocess.run([sys.executable,*( ['-O'] if optimized else []),"-c",script,str(APP / "integration/prepare-runtime.py"),+ str(manifest),str(archive),str(destination),failure],cwd=ROOT,capture_output=True)+ assert result.returncode==0,result.stderr.decode()+ assert not destination.exists()++[email protected]("legacy",[False,True])[email protected]("unsafe",[None,"path","link"])+def test_helper_consumes_safe_compatible_extractor(tmp_path,legacy,unsafe):+ python=LEGACY_PYTHON if legacy else sys.executable+ if not python:pytest.skip("Set AVIBE_FEEDBACK_LEGACY_PYTHON to actual Python without tarfile extraction filters")+ manifest,archive=synthetic_bundle(tmp_path,unsafe)+ script='''+import importlib.util,hashlib,json,pathlib,sys,tarfile+spec=importlib.util.spec_from_file_location('p',sys.argv[1]);p=importlib.util.module_from_spec(spec);spec.loader.exec_module(p)+m,a,d=map(pathlib.Path,sys.argv[2:5]);payload=json.loads(m.read_bytes())+p.MANIFEST_SHA=hashlib.sha256(m.read_bytes()).hexdigest();p.LINUX_SHA=payload['archives']['linux-x64']['sha256']+if sys.argv[6]=='legacy' and hasattr(tarfile,'data_filter'):raise RuntimeError('actual old interpreter required')+try:+ p.prepare(m,a,d)+except ValueError:+ if sys.argv[5]=='safe':raise+else:+ if sys.argv[5]!='safe':raise RuntimeError('unsafe archive accepted')+ if (d/'packages/runtime/dist/cli.js').read_bytes()!=b'safe':raise RuntimeError('wrong bytes')+if (d.parent/'escape').exists() or (d.parent/'outside').exists():raise RuntimeError('escape')+'''+ env=dict(os.environ,PYTHONPATH=str(ROOT))+ result=subprocess.run([python,"-O","-c",script,str(APP / "integration/prepare-runtime.py"),str(manifest),str(archive),+ str(tmp_path / "destination"),unsafe or "safe","legacy" if legacy else "modern"],env=env,capture_output=True)+ assert result.returncode==0,result.stderr.decode()+++def test_real_pinned_manifest_local_archive_and_wrong_platform(tmp_path):+ if not MANIFEST or not ARCHIVE:pytest.skip("Commissioning archive required")+ prepare=load_prepare()+ manifest=Path(MANIFEST);local=Path(ARCHIVE)+ # Same valid manifest, another entry's actual name: must fail before any+ # extraction even if the name belongs to this release.+ payload=json.loads(manifest.read_bytes())+ wrong=next(v for k,v in payload['archives'].items() if k!=runtime_platform_tag())+ wrong_path=tmp_path / wrong['name'];wrong_path.write_bytes(local.read_bytes())+ with pytest.raises(ValueError,match="executing platform"):+ prepare.prepare(manifest,wrong_path,tmp_path / "wrong")+ assert not (tmp_path / "wrong").exists()+ result=subprocess.run([sys.executable,"-O",str(APP / "integration/prepare-runtime.py"),str(manifest),str(local),str(tmp_path / "valid")],+ env=dict(os.environ,PYTHONPATH=str(ROOT)),capture_output=True)+ assert result.returncode==0,result.stderr.decode()++[email protected]("optimized",[False,True])+def test_other_platform_release_archive_rejected_on_actual_host(tmp_path,optimized):+ other=os.environ.get("AVIBE_FEEDBACK_FOREIGN_RUNTIME_ARCHIVE")+ if not MANIFEST or not other:pytest.skip("Supply another platform archive from the frozen release")+ payload=json.loads(Path(MANIFEST).read_bytes())+ archive=Path(other)+ entries=[(tag,v) for tag,v in payload['archives'].items() if v['name']==archive.name]+ assert len(entries)==1 and entries[0][0]!=runtime_platform_tag()+ assert hashlib.sha256(archive.read_bytes()).hexdigest()==entries[0][1]['sha256']+ for renamed in (False,True):+ candidate=archive+ if renamed:+ candidate=tmp_path / payload['archives'][runtime_platform_tag()]['name']+ candidate.write_bytes(archive.read_bytes())+ destination=tmp_path / f'extract-{renamed}'+ result=subprocess.run([sys.executable,*(['-O'] if optimized else []),str(APP / 'integration/prepare-runtime.py'),+ MANIFEST,str(candidate),str(destination)],env=dict(os.environ,PYTHONPATH=str(ROOT)),capture_output=True)+ assert result.returncode!=0 and not destination.exists()+ assert (b'hash mismatch' if renamed else b'executing platform') in result.stderrdiff --git a/tests/test_feedback_intake_distribution.py b/tests/test_feedback_intake_distribution.pynew file mode 100644index 000000000..552fba740--- /dev/null+++ b/tests/test_feedback_intake_distribution.py@@ -0,0 +1,52 @@+"""Normal wheel install → installed built-in source → immutable Skill snapshot."""+import hashlib+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import zipfile++import pytest++ROOT = Path(__file__).resolve().parents[1]+WHEEL = os.environ.get("AVIBE_FEEDBACK_TEST_WHEEL")+++def test_normal_wheel_install_and_builtin_snapshot(tmp_path):+ if not WHEEL:+ pytest.skip("Set AVIBE_FEEDBACK_TEST_WHEEL to the reviewed normal wheel")+ wheel = Path(WHEEL).resolve()+ paths = ("SKILL.md", "references/feedback.md", "scripts/feedback_intake.py")+ expected = {}+ with zipfile.ZipFile(wheel) as archive:+ for path in paths:+ raw = archive.read("vibe/builtin_skills_source/use-avibe/" + path)+ assert raw == (ROOT / "skills/use-avibe" / path).read_bytes()+ expected[path] = hashlib.sha256(raw).hexdigest()+ assert len(archive.read("vibe/ui/dist/index.html")) > 1000+ assert archive.read("vibe/show_runtime_manifest.json")+ installed = tmp_path / "installed"+ env = {key: os.environ[key] for key in ("PATH", "HOME", "AVIBE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME")}+ env.update(PYTHONPATH=str(installed), AVIBE_ALLOW_DEV_STATE_MIGRATION="1")+ subprocess.run([shutil.which("uv"), "pip", "install", "--no-deps", "--target", str(installed), str(wheel)],+ env=env, cwd=tmp_path, check=True, capture_output=True)+ script = '''+import hashlib,json,os,sys+from pathlib import Path+from core.managed_skills import builtin_skills_source,prepare_builtin_skills+source=builtin_skills_source()+assert 'builtin_skills_source' in str(source)+assert Path(sys.argv[1]) in source.parents+snapshot=prepare_builtin_skills()+root=Path(os.environ['AVIBE_BUILTIN_SKILLS_ROOT'])+assert root.name==snapshot+expected=json.loads(sys.argv[2])+for path,digest in expected.items():+ assert hashlib.sha256((root/'use-avibe'/path).read_bytes()).hexdigest()==digest+print(json.dumps({'snapshot':snapshot,'source':str(source)}))+'''+ result = subprocess.run([sys.executable,"-c",script,str(installed),json.dumps(expected)], env=env,+ cwd=tmp_path, check=True, capture_output=True, text=True)+ assert json.loads(result.stdout)["snapshot"]diff --git a/tests/test_feedback_intake_http.py b/tests/test_feedback_intake_http.pynew file mode 100644index 000000000..e76c3daac--- /dev/null+++ b/tests/test_feedback_intake_http.py@@ -0,0 +1,140 @@+"""Actual UI → pinned packaged Runtime → TS → real Vault CLI → GitHub fake."""+import asyncio+import fcntl+import importlib.util+import os+from pathlib import Path+import shlex+import shutil+import socket++import httpx+import pytest+import uvicorn++from config import paths+from core import show_runtime+from tests.test_feedback_intake import APP, github, real_vault, make_payload # noqa: F401+from tests.test_show_api import create_ingress+from vibe import ui_server++# Capture opt-in artifact paths before the hermetic fixture strips the environment.+MANIFEST = os.environ.get("AVIBE_FEEDBACK_RUNTIME_MANIFEST")+ARCHIVE = os.environ.get("AVIBE_FEEDBACK_RUNTIME_ARCHIVE")+++async def test_real_http_packaged_runtime_receipts_and_private_ledger(real_vault, tmp_path, monkeypatch):+ if not MANIFEST or not ARCHIVE:+ pytest.skip("Set AVIBE_FEEDBACK_RUNTIME_MANIFEST and AVIBE_FEEDBACK_RUNTIME_ARCHIVE to SHA-verified deployment artifacts")+ spec = importlib.util.spec_from_file_location("prepare_feedback_runtime", APP / "integration/prepare-runtime.py")+ prepare = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(prepare)+ runtime = prepare.prepare(Path(MANIFEST), Path(ARCHIVE), tmp_path / "runtime-package")+ ingress = create_ingress(tmp_path)+ for name in ("api", "lib"):+ shutil.copytree(APP / name, ingress.workspace / name, dirs_exist_ok=True)+ for name in ("worker.py", ".show-api.json"):+ shutil.copyfile(APP / name, ingress.workspace / name)+ monkeypatch.setenv("AVIBE_FEEDBACK_APP_ROOT", str(ingress.workspace))+ monkeypatch.setenv("AVIBE_FEEDBACK_PYTHON", os.sys.executable)+ monkeypatch.setenv("HTTP_PROXY", "http://127.0.0.1:1")+ monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:1")+ monkeypatch.setenv("ALL_PROXY", "http://127.0.0.1:1")+ monkeypatch.setenv("NO_PROXY", "")+ manager = show_runtime.ShowRuntimeManager(+ command=shlex.join([shutil.which("node"), str(runtime / "packages/runtime/dist/cli.js")]),+ workspace_root=paths.get_show_pages_dir(), runtime_dir=tmp_path / "runtime-state", auto_install=False, offline=True,+ )+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)+ listener = socket.socket()+ listener.bind(("127.0.0.1",0))+ port = listener.getsockname()[1]+ server = uvicorn.Server(uvicorn.Config(ui_server.app, lifespan="off", log_level="error"))+ task = None+ prefix = f"/p/{ingress.page.share_id}"+ headers = {"Host":"alex.avibe.bot", "Content-Type":"application/json"}+ try:+ ready = await manager.ensure()+ assert ready.available, ready.reason+ task = asyncio.create_task(server.serve(sockets=[listener]))+ for _ in range(100):+ if server.started:+ break+ await asyncio.sleep(.02)+ assert server.started+ async with httpx.AsyncClient(base_url=f"http://127.0.0.1:{port}", trust_env=False, timeout=35) as client:+ payload = make_payload()+ import json+ request_id = json.loads(payload)["request_id"]+ posted = await client.post(prefix + "/api/feedback", content=payload, headers=headers)+ assert posted.status_code == 202, posted.text+ assert posted.json() == {"ok":True}, "Native POST must remain status only"+ found = await client.get(prefix + "/api/feedback-status", params={"request_id":request_id}, headers=headers)+ assert found.status_code == 200, found.text+ assert found.json() == dict(schema_version=1, request_id=request_id, state="created", issue_number=100,+ issue_url="https://github.com/avibe-bot/avibe/issues/100")+ assert found.headers["cache-control"] == "no-store"+ repeat = await client.post(prefix + "/api/feedback", content=payload, headers=headers)+ assert repeat.status_code == 202+ conflict = await client.post(prefix + "/api/feedback", content=make_payload(request_id, body="changed"), headers=headers)+ assert conflict.status_code == 409+ invalid = await client.post(prefix + "/api/feedback", content=b'\xff', headers=headers)+ assert invalid.status_code == 400+ huge = await client.post(prefix + "/api/feedback", content=b'x'*32769, headers=headers)+ assert huge.status_code == 413+ wrong_method = await client.put(prefix + "/api/feedback", content=payload, headers=headers)+ assert wrong_method.status_code in (403,404,405)+ absent = await client.get(prefix + "/api/feedback-status", params={"request_id":"1afe402a-a181-4487-8f65-42e22c3f7fab"}, headers=headers)+ assert absent.status_code == 404+ assert len(real_vault.issues) == 1+ # DB/WAL/SHM live outside every Show workspace. Public static, asset,+ # API and absolute filesystem attempts must never return their bytes.+ for suffix in ("", "-wal", "-shm"):+ database = os.environ["AVIBE_FEEDBACK_DATABASE"] + suffix+ for route in (f"/ledger.sqlite{suffix}", f"/assets/ledger.sqlite{suffix}", f"/api/ledger.sqlite{suffix}", f"/@fs{database}", f"/../../{database.lstrip('/')}"):+ leak = await client.get(prefix + route, headers=headers)+ assert "SQLite format" not in leak.text+ assert "Observed: 中文" not in leak.text+ assert "synthetic-feedback-pat" not in leak.text+ unknown_payload = make_payload(title="Write completed before disconnect")+ real_vault.mode = "disconnect"+ result = await client.post(prefix + "/api/feedback", content=unknown_payload, headers=headers)+ assert result.status_code == 503+ unknown_id = json.loads(unknown_payload)["request_id"]+ unknown = await client.get(prefix + "/api/feedback-status", params={"request_id":unknown_id}, headers=headers)+ assert unknown.json() == dict(schema_version=1, request_id=unknown_id, state="unknown")+ await client.post(prefix + "/api/feedback", content=unknown_payload, headers=headers)+ assert len(real_vault.issues) == 2+ # Actual worker started through HTTP/CLI must publish a durable+ # known-no-write result when both kernel slots are occupied.+ locks = [open(os.environ["AVIBE_FEEDBACK_DATABASE"] + f".slot{i}", "a") for i in range(2)]+ saturated_payload = make_payload(title="Saturated worker slots")+ saturated_id = json.loads(saturated_payload)["request_id"]+ try:+ for lock in locks:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ saturated = await client.post(prefix + "/api/feedback", content=saturated_payload, headers=headers)+ assert saturated.status_code == 503+ failed = await client.get(prefix + "/api/feedback-status", params={"request_id":saturated_id}, headers=headers)+ assert failed.json() == dict(schema_version=1, request_id=saturated_id, state="failed")+ finally:+ for lock in locks:+ lock.close()+ assert len(real_vault.issues) == 2+ # Fill the persistent admission quota and prove 429 creates no row.+ from tests.test_feedback_intake import load_worker+ worker = load_worker()+ with worker._database() as db:+ import time+ db.execute("UPDATE limits SET count=5,window=? WHERE name='minute'", (int(time.time())//60,))+ limited_payload = make_payload(title="Pre-reservation limited")+ limited = await client.post(prefix + "/api/feedback", content=limited_payload, headers=headers)+ assert limited.status_code == 429+ missing = await client.get(prefix + "/api/feedback-status", params={"request_id":json.loads(limited_payload)["request_id"]}, headers=headers)+ assert missing.status_code == 404 and len(real_vault.issues) == 2+ finally:+ server.should_exit = True+ if task:+ await asyncio.wait_for(task,10)+ listener.close()+ manager.stop()diff --git a/tests/test_feedback_intake_recovery.py b/tests/test_feedback_intake_recovery.pynew file mode 100644index 000000000..f67b7568c--- /dev/null+++ b/tests/test_feedback_intake_recovery.py@@ -0,0 +1,640 @@+"""Interrupted delivery recovery through real reservation/claim and GitHub HTTP."""+import importlib.util+import json+import os+from pathlib import Path+import signal+import socket+import sqlite3+import subprocess+import sys+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import pytest++from tests.test_feedback_intake import HELPER, WORKER, github, load_worker # noqa: F401+++def load_client():+ spec = importlib.util.spec_from_file_location("feedback_client", HELPER)+ client = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(client)+ return client+++def intake(github, monkeypatch):+ worker = load_worker()++ class Handler(BaseHTTPRequestHandler):+ def send(self, status, value):+ raw = json.dumps(value).encode()+ self.send_response(status)+ self.send_header("Content-Length", str(len(raw)))+ self.end_headers()+ try:+ self.wfile.write(raw)+ except (BrokenPipeError, ConnectionResetError):+ pass++ def do_GET(self): # noqa: N802+ with self.server.lock:+ self.server.status_threads.append(threading.current_thread())+ self.server.status_calls.append(self.path)+ mode = self.server.status_mode+ if mode == "busy":+ self.send(429, {})+ elif mode == "disconnect":+ self.close_connection = True+ elif mode == "stall":+ self.server.status_entered.set()+ if not self.server.status_release.wait(30):+ raise RuntimeError("Status barrier timed out")+ self.send(404, {})+ elif mode == "invalid_json":+ self.send_response(404)+ self.end_headers()+ self.wfile.write(b'not JSON')+ elif mode == "oversize":+ self.send(404, "x" * 32769)+ elif mode == "unavailable":+ self.send(503, {})+ elif mode == "malformed404":+ self.send(404, {"not": "a fixed receipt response"})+ elif mode == "malformed":+ self.send(200, {"state":"created"})+ elif mode == "redirect":+ self.send_response(302)+ self.send_header("Location", "/api/feedback-status?request_id=x")+ self.end_headers()+ else:+ try:+ receipt = worker.receipt(self.path.split("=",1)[1])+ self.send(200, receipt)+ except worker.FeedbackError as exc:+ self.send(exc.status,{})++ def do_POST(self): # noqa: N802+ raw = self.rfile.read(int(self.headers["Content-Length"]))+ with self.server.lock:+ self.server.uploads.append(raw)+ index = len(self.server.uploads)+ record = dict(thread=threading.current_thread(), done=threading.Event(),+ worker_done=threading.Event(), worker_exit=None, owns_write=False)+ self.server.handlers[index] = record+ try:+ if self.server.rate_limit:+ if self.server.post_status == "disconnect":+ self.close_connection = True+ return+ mode = self.server.post_body+ raw = {"normal": b"{}", "empty": b"", "nonjson": b"observed 429",+ "oversize": b"x" * 32769, "stall": b"", "truncated": b"{}"}[mode]+ self.send_response(self.server.post_status)+ if self.server.post_status == 302:+ self.send_header("Location", "/api/feedback-status?request_id=redirected")+ self.send_header("Content-Length", str(100 if mode in ("stall", "truncated") else len(raw)))+ self.end_headers()+ self.wfile.flush()+ if mode == "stall":+ self.server.body_entered.set()+ if not self.server.body_release.wait(30):+ raise RuntimeError("POST body barrier timed out")+ if mode == "truncated":+ self.close_connection = True+ try:+ self.wfile.write(raw)+ except (BrokenPipeError, ConnectionResetError):+ pass+ return+ if index >= 3:+ self.server.recovery_arrived.set()+ if self.server.delay_upload == index:+ self.server.arrived.set()+ if not self.server.release.wait(15):+ raise RuntimeError("Original delivery barrier timed out")+ if self.server.reserve_winner and index != self.server.reserve_winner:+ if not self.server.reserved.wait(10):+ raise RuntimeError("Owning reservation barrier timed out")+ payload = worker._parse_payload(raw)+ token = worker.reserve(payload)+ if index == self.server.reserve_winner:+ self.server.reserved.set()+ if token:+ record["owns_write"] = True+ with subprocess.Popen([sys.executable,str(WORKER),"execute",payload["request_id"],token],+ stdout=subprocess.PIPE,stderr=subprocess.PIPE) as child:+ try:+ child.communicate(timeout=25)+ finally:+ if child.poll() is None:+ child.kill()+ child.communicate(timeout=3)+ record["worker_exit"] = child.returncode+ record["worker_done"].set()+ if self.server.disconnect:+ self.server.status_mode = "unavailable"+ self.close_connection = True+ else:+ self.send(202,{"ok":True})+ except Exception as exc:+ self.server.errors.append(type(exc).__name__)+ raise+ finally:+ record["done"].set()++ def log_message(self,*args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1",0), Handler)+ server.uploads = []+ server.handlers, server.errors = {}, []+ server.reserve_winner = None+ server.reserved = threading.Event()+ server.gate_readback = False+ server.readback_entered, server.readback_release = threading.Event(), threading.Event()+ server.lock = threading.Lock()+ server.rate_limit = True+ server.post_body, server.post_status = "normal", 429+ server.status_calls, server.status_threads = [], []+ server.status_entered, server.status_release = threading.Event(), threading.Event()+ server.body_entered, server.body_release = threading.Event(), threading.Event()+ server.status_mode = "normal"+ server.delay_upload = None+ server.disconnect = False+ server.arrived, server.release = threading.Event(), threading.Event()+ server.recovery_arrived = threading.Event()+ thread = threading.Thread(target=server.serve_forever,daemon=True)+ thread.start()+ monkeypatch.setenv("AVIBE_FEEDBACK_TEST_SHARE_BASE_URL",f"http://127.0.0.1:{server.server_port}")+ upstream_get = github.RequestHandlerClass.do_GET++ def readback(self):+ if server.gate_readback and self.path.startswith("/repos/avibe-bot/avibe/issues/"):+ server.readback_entered.set()+ if not server.readback_release.wait(10):+ raise RuntimeError("Readback barrier timed out")+ return upstream_get(self)++ monkeypatch.setattr(github.RequestHandlerClass, "do_GET", readback)+ try:+ yield server, github, worker+ finally:+ # Stop accepting work, release every barrier, then join owned handlers.+ # Their finally blocks reap worker subprocesses before signaling done.+ server.release.set()+ server.reserved.set()+ server.readback_release.set()+ server.status_release.set()+ server.body_release.set()+ server.shutdown()+ thread.join(2)+ with server.lock:+ handlers = list(server.handlers.values())+ status_threads = list(server.status_threads)+ for record in handlers:+ record["thread"].join(28)+ assert not record["thread"].is_alive(), "Intake handler did not terminate"+ for status_thread in status_threads:+ status_thread.join(3)+ assert not status_thread.is_alive(), "Status handler did not terminate"+ server.server_close()+ assert not server.errors, server.errors++++COMMAND = [sys.executable,str(HELPER),"submit","bug","Recover delivery 中文", "--public-confirmed"]+BODY = "Only approved bytes & #\n中文".encode()+++def run_submit():+ return subprocess.run(COMMAND,input=BODY,capture_output=True,timeout=15)+++def outbox():+ return Path(os.environ["AVIBE_HOME"]) / "state/feedback-intake/outbox.sqlite"+++def row():+ with sqlite3.connect(outbox()) as db:+ db.row_factory=sqlite3.Row+ return db.execute("SELECT * FROM attempts").fetchone()+++def test_kill_after_durable_retry_intent_before_upload(intake):+ server, upstream, _ = intake+ first = json.loads(run_submit().stdout)+ request_id = first["request_id"]+ server.rate_limit = False+ # Real helper body, intercepted exactly at network entry. Kill the process+ # after its actual SQLite claim commit, without adding production hooks.+ script = '''+import importlib.util,sys,os,signal+spec=importlib.util.spec_from_file_location('client',sys.argv[1]);c=importlib.util.module_from_spec(spec);spec.loader.exec_module(c)+original=c._request+def boundary(path,**kw):+ if kw.get('body') is not None: os.kill(os.getpid(),signal.SIGKILL)+ return original(path,**kw)+c._request=boundary+sys.argv=sys.argv[1:]+sys.exit(c.main())+'''+ killed = subprocess.run([sys.executable,"-c",script,*COMMAND[1:]],input=BODY,capture_output=True,timeout=10)+ assert killed.returncode == -signal.SIGKILL+ assert row()["retryable"] == 1 and row()["phase"] == "sending"+ assert len(server.uploads) == 1+ resume = subprocess.run([sys.executable,str(HELPER),"resume",request_id],capture_output=True)+ assert json.loads(resume.stdout)["state"] == "unknown" and len(server.uploads) == 1+ recovered = run_submit()+ assert recovered.returncode == 0, recovered.stderr.decode()+ assert json.loads(recovered.stdout)["request_id"] == request_id+ assert server.uploads[0] == server.uploads[1]+ assert len(upstream.issues) == 1 and row()["retryable"] == 0++[email protected]("winner", [2, 3], ids=["original-wins", "recovery-wins"])+def test_original_delivery_races_explicit_recovery_one_github_write(intake, winner):+ server, upstream, worker = intake+ first=json.loads(run_submit().stdout)+ server.rate_limit=False+ server.delay_upload=2+ server.reserve_winner=winner+ server.gate_readback=True+ original=subprocess.Popen(COMMAND,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)+ recovery=None+ original.stdin.write(BODY);original.stdin.close()+ try:+ assert server.arrived.wait(5)+ original.kill();original.wait(3)+ assert worker._row(first["request_id"]) is None+ assert row()["phase"] == "sending" and row()["retryable"] == 1+ recovery=subprocess.Popen(COMMAND,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)+ recovery.stdin.write(BODY);recovery.stdin.close();recovery.stdin=None+ assert server.recovery_arrived.wait(5)+ server.release.set()+ # Exactly one actual worker owns the reservation. The other handler can+ # finish coalesced admission while the owner is still reading GitHub.+ assert server.readback_entered.wait(5)+ loser=3 if winner==2 else 2+ assert server.handlers[loser]["done"].wait(5)+ owner=server.handlers[winner]+ assert owner["owns_write"] and not owner["worker_done"].is_set()+ assert not owner["done"].is_set()+ assert not server.handlers[loser]["owns_write"]+ intermediate=subprocess.run([sys.executable,str(HELPER),"resume",first["request_id"]],capture_output=True,timeout=5)+ assert json.loads(intermediate.stdout)["state"]=="unknown"+ pending=worker._row(first["request_id"])+ assert pending["state"]=="unknown" and pending["issue_id"]==10100+ assert sum(call[0]=="POST" for call in upstream.calls)==1 and len(upstream.issues)==1+ server.readback_release.set()+ assert owner["worker_done"].wait(5) and owner["worker_exit"]==0+ for index in (2,3):+ assert server.handlers[index]["done"].wait(5)+ server.handlers[index]["thread"].join(2)+ assert not server.handlers[index]["thread"].is_alive()+ stdout,stderr=recovery.communicate(timeout=5)+ assert recovery.returncode in (0,2),stderr.decode()+ final=subprocess.run([sys.executable,str(HELPER),"resume",first["request_id"]],capture_output=True,timeout=5)+ expected=dict(schema_version=1,request_id=first["request_id"],state="created",issue_number=100,+ issue_url="https://github.com/avibe-bot/avibe/issues/100")+ assert json.loads(final.stdout)==expected+ assert worker.receipt(first["request_id"])==expected+ assert sum(call[0]=="POST" for call in upstream.calls)==1+ assert len(upstream.issues)==1 and len(server.uploads)==3+ assert all(raw==server.uploads[0] for raw in server.uploads)+ finally:+ server.release.set();server.reserved.set();server.readback_release.set()+ if original.poll() is None:+ original.kill();original.wait(3)+ original.stdout.close();original.stderr.close()+ if recovery is not None:+ if recovery.poll() is None:+ recovery.kill()+ recovery.communicate(timeout=3)++[email protected]("status_mode", [+ "busy", "unavailable", "disconnect", "stall", "invalid_json", "oversize", "malformed",+ "malformed404", "redirect",+])+def test_observed_429_survives_every_status_failure_until_fresh_absence(intake, status_mode):+ server, upstream, worker = intake+ server.status_mode = status_mode+ if status_mode == "stall":+ first_process = subprocess.Popen(+ COMMAND, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE+ )+ try:+ first_process.stdin.write(BODY)+ first_process.stdin.close()+ first_process.stdin = None+ assert server.status_entered.wait(5)+ assert row()["retryable"] == 1 and server.uploads+ # Preserve the real ten-second network timeout; the release is+ # cleanup, so a successful response cannot masquerade as timeout.+ stdout, stderr = first_process.communicate(timeout=13)+ assert first_process.returncode == 3, stderr.decode()+ first = subprocess.CompletedProcess(COMMAND, first_process.returncode, stdout, stderr)+ finally:+ server.status_release.set()+ if first_process.poll() is None:+ first_process.kill()+ first_process.communicate(timeout=3)+ else:+ first = run_submit()+ request_id = json.loads(first.stdout)["request_id"]+ if status_mode == "stall":+ server.status_mode = "busy"+ assert json.loads(first.stdout)["admission"] == "rate_limited"+ assert row()["request_id"] == request_id+ assert row()["retryable"] == 1 and row()["phase"] == "rate_limited"+ resumed = subprocess.run([sys.executable, str(HELPER), "resume", request_id], capture_output=True, timeout=15)+ assert json.loads(resumed.stdout)["admission"] == "rate_limited"+ suppressed = run_submit()+ assert json.loads(suppressed.stdout)["admission"] == "rate_limited"+ assert len(server.uploads) == 1+ server.status_mode = "normal"+ server.rate_limit = False+ resumed = subprocess.run([sys.executable, str(HELPER), "resume", request_id], capture_output=True, timeout=5)+ assert json.loads(resumed.stdout)["admission"] == "rate_limited" and len(server.uploads) == 1+ recovered = run_submit()+ assert recovered.returncode == 0, recovered.stderr.decode()+ assert json.loads(recovered.stdout)["request_id"] == request_id+ assert len(server.uploads) == 2 and server.uploads[0] == server.uploads[1]+ assert sum(call[0] == "POST" for call in upstream.calls) == len(upstream.issues) == 1+ assert worker.receipt(request_id)["state"] == "created" and row()["retryable"] == 0++[email protected]("post_body", ["normal", "empty", "nonjson", "oversize", "truncated", "stall"])+def test_observed_429_is_saved_before_post_body_is_consumed(intake, post_body):+ server, upstream, worker = intake+ server.post_body = post_body+ if post_body == "stall":+ # Observe the committed callback with IPC, then leave the actual body+ # blocked until the normal network timeout returns. No shortened limit.+ script = '''+import importlib.util,socket,sys+spec=importlib.util.spec_from_file_location('c',sys.argv[1]);c=importlib.util.module_from_spec(spec);spec.loader.exec_module(c)+channel=socket.socket(fileno=int(sys.argv[2]));channel.settimeout(5)+original=c._record_rejection+def recorded(*args):+ original(*args)+ channel.sendall(b'1')+c._record_rejection=recorded+sys.argv=[sys.argv[1],*sys.argv[3:]];sys.exit(c.main())+'''+ parent, child_socket = socket.socketpair()+ parent.settimeout(5)+ first_process = subprocess.Popen(+ [sys.executable, "-c", script, str(HELPER), str(child_socket.fileno()), *COMMAND[2:]],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ pass_fds=(child_socket.fileno(),),+ )+ child_socket.close()+ try:+ first_process.stdin.write(BODY)+ first_process.stdin.close()+ first_process.stdin = None+ assert parent.recv(1) == b"1" and server.body_entered.wait(5)+ assert row()["retryable"] == 1 and row()["phase"] == "rate_limited"+ assert first_process.poll() is None and server.status_calls == []+ stdout, stderr = first_process.communicate(timeout=13)+ assert first_process.returncode == 3, stderr.decode()+ first = subprocess.CompletedProcess(COMMAND, first_process.returncode, stdout, stderr)+ finally:+ server.body_release.set()+ parent.close()+ if first_process.poll() is None:+ first_process.kill()+ first_process.communicate(timeout=3)+ else:+ first = run_submit()+ request_id = json.loads(first.stdout)["request_id"]+ assert json.loads(first.stdout)["admission"] == "rate_limited"+ assert row()["request_id"] == request_id+ assert row()["retryable"] == 1 and row()["phase"] == "rate_limited"+ assert len(server.uploads) == 1+ server.rate_limit = False+ resumed = subprocess.run([sys.executable, str(HELPER), "resume", request_id], capture_output=True, timeout=5)+ assert json.loads(resumed.stdout)["admission"] == "rate_limited" and len(server.uploads) == 1+ recovered = run_submit()+ assert recovered.returncode == 0, recovered.stderr.decode()+ assert json.loads(recovered.stdout)["request_id"] == request_id+ assert server.uploads[0] == server.uploads[1]+ assert sum(call[0] == "POST" for call in upstream.calls) == len(upstream.issues) == 1+ assert worker.receipt(request_id)["state"] == "created"++[email protected]("post_status", [202, 302, 400, 503, "disconnect"])+def test_no_rejection_is_inferred_from_non429_or_error_text(intake, post_status):+ server, upstream, _ = intake+ server.post_status, server.post_body = post_status, "nonjson"+ first = run_submit()+ request_id = json.loads(first.stdout)["request_id"]+ assert json.loads(first.stdout)["state"] == "unknown"+ assert row()["retryable"] == 0+ assert all("redirected" not in path for path in server.status_calls)+ server.status_mode = "busy"+ assert json.loads(run_submit().stdout)["state"] == "unknown"+ server.status_mode = "normal"+ resumed = subprocess.run([sys.executable, str(HELPER), "resume", request_id], capture_output=True, timeout=5)+ assert json.loads(resumed.stdout)["state"] == "unknown"+ assert json.loads(run_submit().stdout)["state"] == "unknown"+ assert len(server.uploads) == 1 and not upstream.issues and row()["retryable"] == 0+++def test_observed_429_survives_a_kill_before_status_poll(intake):+ server, upstream, worker = intake+ # Kill immediately after the real transaction commits, before response body+ # consumption or the first GET. No timing assumption or file polling.+ script = """+import importlib.util, os, signal, sys+spec = importlib.util.spec_from_file_location('client', sys.argv[1])+client = importlib.util.module_from_spec(spec)+spec.loader.exec_module(client)+original = client._record_rejection+def recorded(*args):+ original(*args)+ os.kill(os.getpid(), signal.SIGKILL)+client._record_rejection = recorded+sys.argv = sys.argv[1:]+client.main()+"""+ killed = subprocess.run([sys.executable, "-c", script, *COMMAND[1:]],+ input=BODY, capture_output=True, timeout=5)+ assert killed.returncode == -signal.SIGKILL+ request_id = row()["request_id"]+ assert row()["retryable"] == 1 and row()["phase"] == "rate_limited"+ assert server.status_calls == [] and len(server.uploads) == 1+ assert worker._row(request_id) is None+ resumed = subprocess.run([sys.executable, str(HELPER), "resume", request_id],+ capture_output=True, timeout=5)+ assert json.loads(resumed.stdout)["admission"] == "rate_limited"+ assert len(server.uploads) == 1+ server.rate_limit = False+ recovered = run_submit()+ assert recovered.returncode == 0, recovered.stderr.decode()+ assert json.loads(recovered.stdout)["request_id"] == request_id+ assert server.uploads[0] == server.uploads[1]+ assert sum(call[0] == "POST" for call in upstream.calls) == len(upstream.issues) == 1+ assert worker.receipt(request_id)["state"] == "created" and row()["retryable"] == 0++[email protected]("status_mode", ["busy", "unavailable", "disconnect", "invalid_json",+ "malformed", "malformed404", "redirect"])+def test_interrupted_retry_recovery_requires_available_absent_receipt(intake, status_mode):+ server, _, _ = intake+ run_submit()+ client = load_client()+ with client._database() as db:+ assert client._claim_recovery(db, row()["request_id"]) is not None+ db.close()+ server.rate_limit = False+ server.status_mode = status_mode+ result = run_submit()+ assert json.loads(result.stdout)["state"] == "unknown"+ assert len(server.uploads) == 1 and row()["retryable"] == 1++[email protected]("state",["pending","unknown","failed","created"])+def test_observed_reservation_permanently_suppresses_recovery(intake,state):+ server, upstream, worker=intake+ run_submit();server.rate_limit=False+ payload=worker._parse_payload(server.uploads[0]);token=worker.reserve(payload)+ if state=="created":+ subprocess.run([sys.executable,str(WORKER),"execute",payload["request_id"],token],check=True)+ elif state!="pending":+ worker._update(payload["request_id"],state=state)+ result=run_submit()+ assert json.loads(result.stdout)["state"]==state+ assert len(server.uploads)==1 and row()["retryable"]==0+ server.status_mode="unavailable"+ run_submit()+ assert len(server.uploads)==1+ assert len(upstream.issues)==(1 if state=="created" else 0)+++def test_concurrent_late_results_cannot_regress_receipt_or_eligibility(intake):+ server, _, _=intake+ run_submit();request_id=row()["request_id"]+ client=load_client();a=client._database();b=client._database()+ old=client._claim_recovery(a,request_id)+ new=client._claim_recovery(b,request_id)+ client._record_rejection(a,request_id,old)+ assert row()["generation"]==new and row()["phase"]=="sending"+ unknown=dict(schema_version=1,request_id=request_id,state="unknown")+ client._observe(b,request_id,unknown)+ client._record_rejection(a,request_id,new)+ client._observe(a,request_id,dict(unknown,state="pending"))+ assert json.loads(row()["receipt"])["state"]=="unknown" and row()["retryable"]==0+ created=dict(unknown,state="created",issue_number=12,issue_url="https://github.com/avibe-bot/avibe/issues/12")+ client._observe(a,request_id,created)+ client._observe(b,request_id,unknown)+ assert json.loads(row()["receipt"])==created and row()["payload"] is None+ a.close();b.close()+++def test_initial_unknown_and_legacy_rows_never_gain_eligibility_from_404(intake):+ server,_,_=intake+ server.rate_limit=False+ # Crash the initial helper after persistence but before HTTP. No historical+ # rejection exists, so even explicit identical submit plus404 cannot replay.+ script='''+import importlib.util,sys,os+spec=importlib.util.spec_from_file_location('c',sys.argv[1]);c=importlib.util.module_from_spec(spec);spec.loader.exec_module(c)+c._request=lambda *a,**k: os._exit(91)+sys.argv=sys.argv[1:];c.main()+'''+ result=subprocess.run([sys.executable,"-c",script,*COMMAND[1:]],input=BODY,capture_output=True)+ assert result.returncode==91+ again=run_submit()+ assert json.loads(again.stdout)["state"]=="unknown" and not server.uploads+ assert row()["retryable"]==0+++def test_retry_write_completed_but_response_and_receipt_unavailable(intake):+ server,upstream,worker=intake+ request_id=json.loads(run_submit().stdout)["request_id"]+ server.rate_limit=False;server.disconnect=True+ result=run_submit()+ assert json.loads(result.stdout)["state"]=="unknown"+ assert worker.receipt(request_id)["state"]=="created" and len(upstream.issues)==1+ assert row()["phase"]=="sending" and row()["retryable"]==1+ # Neither status-only resume nor explicit submit may upload while status is+ # unavailable. The prior429 cannot describe this possibly completed retry.+ run_submit()+ subprocess.run([sys.executable,str(HELPER),"resume",request_id],capture_output=True)+ assert len(server.uploads)==2+ server.status_mode="normal"+ settled=run_submit()+ assert json.loads(settled.stdout)["state"]=="created"+ assert len(server.uploads)==2 and len(upstream.issues)==1 and row()["retryable"]==0+++def test_legacy_outbox_loads_conservatively(intake):+ server,_,_=intake+ run_submit()+ request_id=row()["request_id"]+ # Recreate the first unlaunched schema with an unknown attempt, preserving+ # its exact bytes. A GET404 must not invent the absent rejection evidence.+ with sqlite3.connect(outbox()) as db:+ db.execute("CREATE TABLE old AS SELECT request_id,digest,payload,receipt FROM attempts")+ db.execute("DROP TABLE attempts")+ db.execute("ALTER TABLE old RENAME TO attempts")+ server.rate_limit=False+ again=run_submit()+ assert json.loads(again.stdout)==dict(schema_version=1,request_id=request_id,state="unknown")+ assert len(server.uploads)==1 and row()["retryable"]==0++[email protected]("state", ["pending", "unknown", "failed", "created"])+def test_concurrent_status_process_settles_before_late_rejection(intake, state):+ server, upstream, worker = intake+ request_id = json.loads(run_submit().stdout)["request_id"]+ # Pause at the actual 429 persistence boundary; a separate status process+ # observes a real receiver row before the late callback tries its CAS.+ script = '''+import importlib.util,sys,socket+spec=importlib.util.spec_from_file_location('c',sys.argv[1]);c=importlib.util.module_from_spec(spec);spec.loader.exec_module(c)+channel=socket.socket(fileno=int(sys.argv[2]));channel.settimeout(8)+original=c._record_rejection+def late(*args):+ channel.sendall(b'ready')+ if channel.recv(1)!=b'1':raise RuntimeError('Missing release')+ return original(*args)+c._record_rejection=late+sys.argv=[sys.argv[1],*sys.argv[3:]];sys.exit(c.main())+'''+ parent, child_socket = socket.socketpair()+ parent.settimeout(5)+ late = subprocess.Popen([sys.executable, "-c", script, str(HELPER), str(child_socket.fileno()), *COMMAND[2:]],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ pass_fds=(child_socket.fileno(),))+ child_socket.close()+ late.stdin.write(BODY); late.stdin.close(); late.stdin = None+ try:+ assert parent.recv(5) == b"ready"+ payload = worker._parse_payload(server.uploads[0])+ token = worker.reserve(payload)+ if state == "created":+ subprocess.run([sys.executable, str(WORKER), "execute", request_id, token], check=True, timeout=5)+ elif state != "pending":+ worker._update(request_id, state=state)+ observed = subprocess.run([sys.executable, str(HELPER), "resume", request_id], capture_output=True, timeout=5)+ expected = worker.receipt(request_id)+ assert json.loads(observed.stdout) == expected+ server.status_mode = "busy"+ parent.sendall(b"1")+ stdout, stderr = late.communicate(timeout=5)+ assert json.loads(stdout) == expected, stderr.decode()+ assert row()["retryable"] == 0 and row()["phase"] == "observed"+ server.status_mode = "unavailable"+ assert json.loads(run_submit().stdout) == expected+ assert len(server.uploads) == 2+ assert len(upstream.issues) == int(state == "created")+ finally:+ parent.close()+ if late.poll() is None:+ late.kill()+ late.communicate(timeout=3)