diff --git a/.agent/context/20260906T180746Z-expanded-plan.md b/.agent/context/20260906T180746Z-expanded-plan.md new file mode 100644 index 0000000..ddab41b --- /dev/null +++ b/.agent/context/20260906T180746Z-expanded-plan.md @@ -0,0 +1,88 @@ +# Session Context: Expanded Independent Milestone Plan + +## Date/time + +- UTC: 2026-09-06T18:07:46Z + +## User goal + +Create a new branch, expand `plan.md`, and split the delivery plan into many smaller milestones for three coders so each coder can work asynchronously and close their work without waiting for another coder. Keep frontend work at the end. + +## Original prompt/request + +The user asked in Russian for a new branch and a substantially more detailed `plan.md`, followed by a `milestones` folder containing many small tasks assigned across three coders. The essential scheduling constraint is asynchronous progress with no cross-coder waiting to close a milestone; frontend remains last. + +## Assumptions + +- The requested branch should start from the current reviewed `agents-setup` merge commit because it contains the existing plan and reconciled agent policy. +- The correctly spelled directory is `milestones/`. +- Absolute independence is impossible for the final integrated product, so coder work-packet closure is independent while project Gates P4–P6 perform convergence without reopening completed packets. +- Existing same-day primary-source integration research remains the technical basis; this task adds no new version-sensitive integration claim. + +## Plan + +1. Load canonical policy, project/security/sponsor/test documents, repository skills, existing research, context, and the complete current plan. +2. Create `milestone/expand-product-plan` from the clean reviewed setup commit. +3. Replace the phase-oriented plan with a detailed three-lane operating plan and frozen contract pack. +4. Add 18 independently closable milestone packets, six per coder, containing small commit-sized tasks, acceptance evidence, tests, contract handoffs, and no-wait continuation. +5. Validate links, ownership, dependency rules, frontend ordering, Markdown, secrets, and Git scope. +6. Run required independent review against the exact candidate tree before any commit. + +## Key decisions + +- Replaced shared phase milestones with 18 independently closable work packets: A01–A06, B01–B06, and C01–C06. +- Each packet has at least five commit-sized tasks, explicit local acceptance evidence, a contract-pack handoff, non-goals, and a no-wait continuation instruction. +- A packet may depend only on the frozen v1 contract pack, the same coder's previous packet, and—only for frontend—the project Gate P4. +- Cross-coder artifacts are consumed through immutable contracts, schemas, fixtures, simulators, and public package entry points, never active branches or private implementation imports. +- A04/B04/C04 close against simulators. Project Gate P4 later composes exact reviewed packages and live testnet evidence without reopening the completed packets. +- Production frontend remains last: A05/B05/C05 cannot start until P4 freezes OpenAPI and recovery semantics. +- Added explicit path ownership, compatibility protocol, execution environments, project gates, integration procedure, escalation policy, scope-cut order, evidence manifest, and final readiness audit. + +## Files/components touched + +- `plan.md` — expanded 579-line master delivery plan. +- `milestones/README.md` — operating instructions for asynchronous packet execution. +- `milestones/CONTRACTS.md` — frozen v1 product/port/state/fixture contract pack. +- `milestones/coder-a/` — lane README and six domain/orchestration packets. +- `milestones/coder-b/` — lane README and six Privy/Arc packets. +- `milestones/coder-c/` — lane README and six reconciliation/Graph packets. +- `.agent/context/20260906T180746Z-expanded-plan.md` — this durable context record. + +## Commands/checks + +- Initial `git status --short --branch` — clean on `agents-setup`. +- Canonical policy, planning references, all three required repository skills, research, context policy, and existing `plan.md` — read completely. +- `git switch -c milestone/expand-product-plan` — branch created from reviewed merge commit `fcc48d37bd46f9ed727b33e1cc62fcc6a75f9a07`. +- Structural plan validator — PASS: 18 uniquely indexed packets, exactly six per coder, required sections present, at least five small tasks per packet, no cross-coder metadata dependency, all local links resolve, frontend-last guard present, and no placeholder/secret-shaped content. +- Planning-set measurement — 2,004 lines and 13,285 words; master `plan.md` is 579 lines and 4,870 words. +- Markdown/Git whitespace validation — PASS after formatting-only removal of Markdown hard-break spaces. +- Repository agent-policy validation — PASS. +- Conflict-marker and credential-shaped secret scans — PASS. +- Staged scope — 25 intended files: expanded `plan.md`, 23 files under `milestones/`, and this context record; no product code or unrelated file is included. + +## External-doc findings + +- No new browsing required. The expanded plan relies on `.agent/research/20260906-integration-decisions.md`, produced from primary sources earlier the same day. + +## Unresolved questions + +- None. The plan explicitly separates independently closable coder packets from unavoidable final product-integration gates. + +## Git and PR state + +- Branch: `milestone/expand-product-plan` +- Starting commit: `fcc48d37bd46f9ed727b33e1cc62fcc6a75f9a07` +- Candidate state: all 25 intended files staged; exact tree is captured again after this final context update. +- Commit: not created; Gate A must pass first. +- Push/PR: not performed. + +## Review gates + +- Gate A: local validation passed; fresh independent review pending the final staged tree identity. +- Gate B: not applicable; no PR requested. + +## Handoff/next steps + +1. Stage this final context update and capture the exact candidate tree. +2. Run one fresh Gate A review against that tree. +3. If PASS, commit without changing the reviewed tree; do not push or create a PR unless requested. diff --git a/milestones/CONTRACTS.md b/milestones/CONTRACTS.md new file mode 100644 index 0000000..27c6ed2 --- /dev/null +++ b/milestones/CONTRACTS.md @@ -0,0 +1,186 @@ +# Frozen v1 Contract Pack + +Status: proposed freeze for project Gate P0 +Owners: A owns canonical schemas; B and C own additive provider/recovery extensions +Change rule: expand-migrate-contract only + +## 1. Immutable product semantics + +- Cardinality: `1 Business Intent / N Attempts / <= 1 committed Settlement`. +- `business_intent_id` is stable across retries, redelivery, restarts, workers, and agents. +- OneShot durable state grants submission ownership. +- Privy authorizes and constrains the wallet action but is not the durable duplicate lock. +- Arc receipt plus expected ERC-20 Transfer evidence establishes committed settlement. +- The Graph is non-authoritative recovery/history evidence. +- Any possibly submitted but unconfirmed outcome is `UNKNOWN`; reconciliation precedes another submission. + +## 2. Canonical identifiers and money + +| Field | Rule | Redaction | +| --- | --- | --- | +| `business_intent_id` | caller-supplied UUID/opaque stable string; length bounded | safe operational ID | +| `attempt_id` | server-generated UUID; append-only attempt identity | safe operational ID | +| `correlation_id` | validated inbound or generated; never grants idempotency | safe if non-secret | +| `payload_fingerprint` | deterministic hash of normalized immutable payload | safe hash | +| `amount_atomic` | canonical unsigned base-10 integer string, no sign/decimal/exponent/whitespace | safe business datum; do not over-log | +| `asset` | exactly `USDC` | public | +| `network` | exactly `eip155:5042002` | public | +| `token_contract` | exactly `0x3600000000000000000000000000000000000000` | public | +| `recipient` | normalized EVM address; allowlist/policy checked | display only where required | +| `privy_idempotency_key` | stable derivative of intent identity; same key requires same body | never log raw if classified sensitive | +| `privy_reference_id` | stable lookup identity derived from intent | sanitized evidence only | + +`purpose` is a bounded, non-secret display/audit string. It participates in the immutable payload fingerprint and is redacted from routine logs by default. + +## 3. Create-intent command + +```json +{ + "business_intent_id": "018f-example-stable-id", + "recipient": "0x1111111111111111111111111111111111111111", + "amount_atomic": "1250000", + "asset": "USDC", + "network": "eip155:5042002", + "purpose": "Invoice INV-1001" +} +``` + +Normalization order is fixed: validate types and bounds; normalize EVM address; retain canonical integer string; encode asset/network constants; normalize the permitted purpose representation; serialize with a deterministic field order; hash the canonical bytes. + +Identical ID and fingerprint is a replay. Identical ID with a different fingerprint is `INTENT_PAYLOAD_CONFLICT` and creates no new settlement right. + +## 4. Public HTTP seam + +| Operation | Success behavior | Stable error families | +| --- | --- | --- | +| `POST /v1/intents` | `202` accepted; `200` identical replay | `400 INVALID_REQUEST`, `401/403 UNAUTHORIZED`, `409 INTENT_PAYLOAD_CONFLICT`, `429 RATE_LIMITED` | +| `GET /v1/intents/{id}` | authoritative intent, attempts, settlement, sanitized evidence, version | `404 INTENT_NOT_FOUND` | +| `POST /v1/intents/{id}/reconcile` | enqueue/read-trigger only; never submit | `404 INTENT_NOT_FOUND`, `409 RECONCILIATION_NOT_ALLOWED` | +| `GET /v1/intents/{id}/recovery-view` | local authority plus labeled provider/index observations | `404 INTENT_NOT_FOUND`, `503 EVIDENCE_UNAVAILABLE` with local state retained | +| `GET /health/live` | process liveness only | `503` when process cannot serve | +| `GET /health/ready` | DB/config ready and Arc identity checks satisfied | `503 NOT_READY` with sanitized reason | + +Mutations require service authentication, schema validation, request-size limits, correlation IDs, rate limits, and sanitized stable errors. + +## 5. Port contracts + +### AuthorizationPort.evaluate + +Input includes intent/attempt identity, immutable request fingerprint, wallet/policy expectation, recipient, amount, network, token, method, native value, and correlation identity. + +Results: + +- `AUTHORIZED`: exact expected scope is permitted. +- `DENIED`: no submission; terminal authorization rejection for this attempt. +- `UNAVAILABLE`: retryable only before submission ownership crosses the external boundary. + +### SettlementPort.submit + +Input includes persisted Privy idempotency key/reference ID and exact request fingerprint. + +Results: + +- `CONFIRMED`: verified final Arc receipt and exactly matching Transfer evidence. +- `DEFINITELY_NOT_SUBMITTED`: narrow documented proof that no broadcast or external effect occurred. +- `POSSIBLY_SUBMITTED`: timeout, lost/truncated response, uncertain provider/RPC failure, crash window, or any doubt. + +### EvidencePort.lookup + +Results: + +- `FINAL_SUCCESS` +- `FINAL_REVERT` +- `PENDING` +- `NOT_FOUND` +- `UNAVAILABLE` + +`NOT_FOUND` alone never proves that no payment occurred. + +### IndexViewPort.lookup + +Returns observations plus indexed block, block timestamp, deployment ID, chain-head comparison, lag, `hasIndexingErrors`, retrieval time, and health classification: `FRESH`, `LAGGING`, `UNHEALTHY`, `UNAVAILABLE`, or `UNKNOWN_FRESHNESS`. + +No IndexViewPort result grants settlement permission. + +## 6. Durable state machine + +| Current | Trigger | Next | Submission permission | +| --- | --- | --- | --- | +| `NONE` | validated intent accepted | `AUTHORIZING` | No | +| `AUTHORIZING` | policy authorizes | `READY` | No | +| `AUTHORIZING` | policy denies | `REJECTED` | No; terminal | +| `READY` | atomic owner grant persists request identity | `SUBMITTING` | Exactly one owner crosses boundary | +| `SUBMITTING` | verified final receipt/Transfer | `COMMITTED` | No; terminal | +| `SUBMITTING` | authoritative proof of no submission/final failure | `FAILED_SAFE` | Policy may schedule a new attempt | +| `SUBMITTING` | possible submission, crash, timeout, doubt | `UNKNOWN` | No | +| `UNKNOWN` | verified success | `COMMITTED` | No; terminal | +| `UNKNOWN` | authoritative matching final revert/no-effect proof | `FAILED_SAFE` | Policy may schedule a new attempt | +| `UNKNOWN` | pending/not found/unavailable/lag/error/contradiction | `UNKNOWN` | No; escalate by age | + +All transitions are compare-and-set with monotonic versioning. No database transaction remains open during a provider/RPC call. Startup treats orphaned `SUBMITTING` work as reconciliation-required `UNKNOWN`, never as a new lease to submit. + +## 7. Required durable records + +- Business Intent primary identity and immutable fingerprint. +- Append-only Attempts with stage, timestamps, sanitized error class, and correlation ID. +- At most one Settlement row per Business Intent; provider transaction hash unique when present. +- Transactional outbox/job record. +- Persisted request body fingerprint, Privy request identities, wallet/policy identity, chain/token/recipient/amount, provider transaction ID/hash/nonce when learned. +- Receipt block/hash/status and verified Transfer log transaction hash plus log index. +- Append-only evidence observations with source, retrieval time, block/freshness, sanitized payload or digest, and authority label. + +## 8. Fixture catalog + +The canonical fixture root is `packages/contracts/fixtures/v1/`. Every fixture has a JSON Schema validation test and explicit expected durable transition and external-submission count. + +| Fixture | Required expectation | +| --- | --- | +| `intent/accepted.json` | new intent, one queued execution, zero settlement at API boundary | +| `intent/replay-identical.json` | same durable intent, no duplicate job/right | +| `intent/replay-conflict.json` | `409`, explicit conflict, zero additional right | +| `authorization/allowed.json` | exact scope authorized | +| `authorization/denied-*.json` | wrong chain/token/method/recipient/value/amount denied, zero submission | +| `settlement/confirmed.json` | matching final receipt and one Transfer | +| `settlement/final-revert.json` | final failure, zero committed settlement | +| `settlement/pending.json` | remain unresolved, no resubmission | +| `settlement/lost-response.json` | `POSSIBLY_SUBMITTED` -> durable `UNKNOWN` | +| `settlement/mismatched-transfer.json` | not confirmed, hold safely | +| `evidence/not-found.json` | no permission change | +| `graph/empty.json` | labeled observation through indexed block, no permission change | +| `graph/lagging.json` | `LAGGING`, no permission change | +| `graph/indexing-error.json` | `UNHEALTHY`, no permission change | +| `graph/unavailable.json` | `UNAVAILABLE`, local authority still returned | + +## 9. Simulator behavior + +- Domain simulator exposes the HTTP seam and deterministic clock/IDs with an external-submission counter. +- Settlement simulator consumes canonical requests and emits each SettlementPort/EvidencePort result family without network access. +- Recovery simulator consumes local state plus provider/Arc/Graph fixtures and emits deterministic commands and labeled recovery view. +- Simulators reject unknown fixture versions and schema drift. +- Simulators never silently default an unknown enum to a successful or retryable result. + +## 10. Public test seams + +1. HTTP API plus returned durable state. +2. Worker task plus durable state and external-submission counter. +3. Adapter ports plus official-response fixtures. +4. Reconciliation command plus durable transition and evidence record. +5. Subgraph mapping/GraphQL query plus entity and `_meta` classification. +6. Browser UI through frozen OpenAPI/mock server after Gate P4. + +## 11. Compatibility and ownership + +- A owns base schemas, OpenAPI, error codes, state vocabulary, and fixture validation tooling. +- B owns provider-specific optional evidence fields and response-to-port classification fixtures. +- C owns index/recovery observation fields and reconciliation-decision fixtures. +- Optional fields must not change existing result meaning. +- Unknown enum values fail closed at boundaries. +- A breaking change requires ADR, new fixture version, dual-form simulator support, independent consumer migration, and later removal. + +## 12. Freeze exit checklist + +- Every field has type, normalization, authority, and redaction rules. +- Every terminal result has a durable transition and external-submission expectation. +- Every lane can run a simulator with no credentials. +- No unresolved item can change settlement cardinality, monetary precision, Privy enforcement, Arc identity, or `UNKNOWN` semantics. +- Human approval records the exact Git tree containing this contract pack. diff --git a/milestones/README.md b/milestones/README.md new file mode 100644 index 0000000..3a30f40 --- /dev/null +++ b/milestones/README.md @@ -0,0 +1,92 @@ +# OneShot Independent Milestones + +This directory turns `plan.md` into small, independently closable work packets for exactly three coders. The folder name is intentionally spelled `milestones`. + +## Start here + +1. Read root `AGENTS.md` and the documents it routes. +2. Read [`CONTRACTS.md`](CONTRACTS.md); it is the frozen v1 seam for every lane. +3. Open only your coder directory and current packet. +4. Create one branch/PR for that packet. +5. Close the packet using its local acceptance evidence, publish its contract pack, and start the next same-owner packet immediately. + +## Lanes + +- [`coder-a/`](coder-a/README.md): domain, storage, API, worker, composition, intent/status UI, operations. +- [`coder-b/`](coder-b/README.md): Privy, Arc, request/receipt safety, provider ambiguity, settlement UI, sponsor evidence. +- [`coder-c/`](coder-c/README.md): Subgraph, Graph client, reconciliation, failure injection, recovery UI, qualification. + +Each lane has six ordered packets. A packet depends only on the frozen contract pack and the preceding packet in the same directory. A real package from another coder is never required for packet closure; use the checked simulator until project Gate P4. + +## Packet status + +Use these states in the PR or project tracker: + +- `READY`: frozen inputs exist; work may start. +- `ACTIVE`: owner is implementing. +- `REVIEW`: local acceptance passed and exact candidate is under review. +- `DONE`: focused artifact, checks, contract pack, and review evidence are complete. +- `BLOCKED_EXTERNAL`: a live-evidence step needs a human credential/service; offline packet acceptance must still be completed. + +`BLOCKED_EXTERNAL` does not prevent starting the next packet if its offline inputs exist. + +## Independence rules + +- Never depend on another coder’s active branch. +- Never import another coder’s private implementation path. +- Consume only frozen schemas, fixtures, simulators, or reviewed package exports. +- Preserve backward compatibility within a delivery wave. +- Convert breaking proposals into additive versioned contracts. +- A project integration failure creates a focused ticket for the owning lane; it does not reopen unrelated completed packets. +- Status meetings and review availability do not gate coding. Record assumptions and continue fail-closed. + +## Small-task sizing + +Every numbered task inside a packet should fit one coherent commit, normally two to six focused hours. If a task cannot be reviewed independently, split it by observable behavior, not by internal layer. + +Good split: schema + migration, replay behavior, conflict behavior, concurrency proof. +Bad split: “all database code,” “all tests,” or “finish integration.” + +## Contract-pack checklist + +Each packet that publishes a seam includes: + +- semantic version or fixture-set version; +- exported types/schema; +- success and terminal/error fixtures; +- deterministic simulator or fake; +- package-local verification command; +- compatibility and redaction notes. + +## Branch naming + +Use `milestone/-`, for example: + +```text +milestone/a02-durable-intents +milestone/b03-live-settlement-harness +milestone/c04-recovery-matrix +``` + +Each PR targets the current integration branch chosen by the human owner and follows `.agent/IMPLEMENTATION_LOOP.md`. + +## Project gates versus packet closure + +P0–P6 in `plan.md` are product-level evidence gates. They do not redefine packet `DONE`. + +- A04/B04/C04 close against simulators and contract packs. +- P4 later replaces simulators with exact reviewed package versions and runs live/integrated proof. +- A05/B05/C05 are held in `READY` until P4 because frontend is intentionally last. +- A coder who reaches this hold early improves backend tests, docs, fixtures, or operational evidence; they do not start production UI early. + +## Change protocol + +For a required contract change: + +1. Open a short ADR explaining safety and compatibility impact. +2. Add the new field/result/version without deleting the old one. +3. Add fixtures and simulator behavior for both forms. +4. Let each owner migrate independently. +5. Remove the old form only in a later, separately reviewed packet. + +Never reinterpret `UNKNOWN`, monetary precision, settlement ownership, or Graph authority through a compatibility shortcut. diff --git a/milestones/coder-a/A01-foundation-contracts.md b/milestones/coder-a/A01-foundation-contracts.md new file mode 100644 index 0000000..54e1a04 --- /dev/null +++ b/milestones/coder-a/A01-foundation-contracts.md @@ -0,0 +1,63 @@ +# A01 — Foundation and Contract Runtime + +Owner: Coder A +Forecast: 3 working days +Branch: `milestone/a01-foundation-contracts` +Depends on: frozen `milestones/CONTRACTS.md` only +Next: A02 immediately after closure + +## Outcome + +A strict, independently runnable workspace exposes the frozen contracts, OpenAPI, deterministic domain simulator, and package-local quality commands. B and C can validate their fixtures without using A’s active branch. + +## Small tasks + +### A01.1 — Workspace baseline + +- Create the `pnpm` workspace, pinned Node/package-manager metadata, strict TypeScript base config, formatter, linter, unit-test runner, and build scripts. +- Add root commands that delegate; package-local commands remain independently executable. +- Enable lockfile and generated-artifact drift checks. Do not weaken strictness for incomplete packages. + +### A01.2 — Contract package + +- Define branded/string types for intent, attempt, correlation, provider, transaction, block, and deployment identities. +- Define canonical integer-string validation and JSON-safe money serialization. +- Encode port request/result discriminated unions with exhaustive matching and unknown-enum rejection. + +### A01.3 — OpenAPI v1 + +- Specify every endpoint, success/error response, authentication requirement, limits, examples, and stable error code from the frozen pack. +- Generate JSON Schema/TypeScript artifacts and add a drift test. +- Ensure no endpoint directly grants a settlement retry. + +### A01.4 — Fixture validator + +- Create the v1 fixture directories and schema validation command. +- Include accepted, replay, conflict, authorization, settlement, evidence, and Graph fixture placeholders with safe synthetic values. +- Reject unversioned, extra-sensitive, malformed, float-money, and unknown-result fixtures. + +### A01.5 — Domain simulator + +- Implement an in-memory deterministic API/worker simulator with injectable clock/IDs and external-submission counter. +- Consume the same public schemas as production code. +- Support every port result family without importing provider packages. + +## Acceptance evidence + +- Clean install, lint, type, unit, and build succeed from a fresh checkout. +- Package-local `contracts` and `testkit-domain` checks run without PostgreSQL, network, or credentials. +- OpenAPI generation is deterministic and drift fails CI. +- Invalid money, unknown enum, missing identity, and unexpected fixture fields fail closed. +- Simulator can create one intent and expose zero/one synthetic external submissions deterministically. + +## Handoff artifact + +Publish contract pack `contracts-v1`, validated fixtures, generated schema digest, simulator entry point, and exact verification commands. Consumers use the committed pack, not this branch. + +## No-wait continuation + +Start A02 after A01 local review. Missing provider examples become additive fixture tickets and do not block durable-intent implementation. + +## Non-goals + +No PostgreSQL persistence, real worker queue, provider SDK, real settlement, Subgraph, or production UI. diff --git a/milestones/coder-a/A02-durable-intents.md b/milestones/coder-a/A02-durable-intents.md new file mode 100644 index 0000000..9d7b06a --- /dev/null +++ b/milestones/coder-a/A02-durable-intents.md @@ -0,0 +1,62 @@ +# A02 — Durable Intent Ledger and API + +Owner: Coder A +Forecast: 3 working days +Branch: `milestone/a02-durable-intents` +Depends on: A01 only +Next: A03 immediately after closure + +## Outcome + +PostgreSQL becomes authoritative for Business Intents, Attempts, Settlement identity, evidence, and transactional work. Create/replay/conflict/status behavior is complete without real adapters. + +## Small tasks + +### A02.1 — Schema and migration safety + +- Add intent, attempt, settlement, evidence, outbox/job, and schema-version tables. +- Enforce unique intent identity, immutable payload fingerprint, one settlement row per intent, and unique transaction hash when present. +- Test empty bootstrap, forward migration, transactional failure, and safe rollback/disable notes. + +### A02.2 — Canonical fingerprint + +- Validate and normalize recipient, atomic amount, asset, network, and purpose before hashing. +- Add golden vectors and ordering/Unicode/address-case tests. +- Reject negative, signed, decimal, exponent, padded, overflow-policy, and malformed amounts. + +### A02.3 — Create, replay, and conflict + +- Implement atomic insert-or-replay behavior. +- Enqueue initial work transactionally only for a new valid intent. +- Return `202`, `200`, or `409` with stable sanitized bodies. + +### A02.4 — Query seams + +- Implement intent status and recovery-view local-authority projection. +- Preserve append-only attempts and evidence order. +- Add pagination/bounds where collections can grow. + +### A02.5 — Boundary controls + +- Add service authentication interface, request-size limit, schema validation, rate-limit seam, correlation ID handling, and sanitized errors. +- Keep provider material out of API responses and logs. + +## Acceptance evidence + +- Real PostgreSQL tests prove identical replay creates one intent and one queued execution. +- Conflicting payload returns `409` and creates no extra job, attempt, settlement row, or submission right. +- State survives API restart and concurrent duplicate POSTs. +- Constraint failures are mapped to stable errors without leaking SQL or payloads. +- Public API contract matches A01 OpenAPI and fixture digests. + +## Handoff artifact + +Publish migration set, `storage-v1` schema digest, API contract tests, synthetic database fixtures, and a containerized test command. + +## No-wait continuation + +Start A03 with the settlement simulator. Real B output and C recovery code are not required. + +## Non-goals + +No external wallet call, Arc transaction, Graph query, or frontend. diff --git a/milestones/coder-a/A03-atomic-worker.md b/milestones/coder-a/A03-atomic-worker.md new file mode 100644 index 0000000..0e279dc --- /dev/null +++ b/milestones/coder-a/A03-atomic-worker.md @@ -0,0 +1,61 @@ +# A03 — Atomic At-Most-Once Worker + +Owner: Coder A +Forecast: 3 working days +Branch: `milestone/a03-atomic-worker` +Depends on: A02 only +Next: A04 immediately after closure + +## Outcome + +Duplicate delivery and concurrent workers converge on exactly one submission owner. Every simulator result is durably classified before task completion, and uncertainty can never cause a blind retry. + +## Small tasks + +### A03.1 — Transactional work delivery + +- Integrate Graphile Worker with the same PostgreSQL database and transactional enqueueing. +- Configure `submit_settlement` for one queue attempt. +- Treat queue job keys as scheduling hygiene, not the duplicate lock. + +### A03.2 — Submission ownership CAS + +- Implement `AUTHORIZING -> READY -> SUBMITTING` compare-and-set transitions with monotonic version. +- Persist request fingerprint and provider identities before calling the port. +- Ensure database transactions end before network/simulator calls. + +### A03.3 — Result persistence + +- Map `CONFIRMED`, `DEFINITELY_NOT_SUBMITTED`, and `POSSIBLY_SUBMITTED` exhaustively. +- Persist `COMMITTED`, `FAILED_SAFE`, or `UNKNOWN` before returning from the task. +- Reject unexpected/partial adapter results as `UNKNOWN`. + +### A03.4 — Concurrency proof + +- Test one job, ten sequential deliveries, ten parallel workers, and two worker processes. +- Assert stable intent ID, append-only attempts, final durable state, external-submission count, and committed-settlement count. + +### A03.5 — External-boundary failure points + +- Kill before submission: zero call and safe continuation. +- Kill after persisted `SUBMITTING` and before/after simulator response: `UNKNOWN`, no new submission. +- Fail downstream work after commit: retain original settlement permanently. + +## Acceptance evidence + +- All required A-owned rows from `.agent/TEST_MATRIX.md` pass against real PostgreSQL and deterministic simulator counter. +- Ten parallel workers and two processes result in at most one external call/commit. +- No exception path leaves a possibly submitted intent retryable. +- Redelivery is idempotent after every durable transition. + +## Handoff artifact + +Publish worker contract tests, concurrency runner, failure-point catalog, database-state snapshots, and concise result table. + +## No-wait continuation + +Start A04 using B/C simulators. A project gate will later repeat these proofs with reviewed real adapters. + +## Non-goals + +No real Privy/Arc call, Graph lookup, automatic replacement, or UI. diff --git a/milestones/coder-a/A04-restart-operations-composition.md b/milestones/coder-a/A04-restart-operations-composition.md new file mode 100644 index 0000000..edc06e0 --- /dev/null +++ b/milestones/coder-a/A04-restart-operations-composition.md @@ -0,0 +1,62 @@ +# A04 — Restart Safety, Operations, and Simulator Composition + +Owner: Coder A +Forecast: 4 working days +Branch: `milestone/a04-restart-operations-composition` +Depends on: A03 only +Next: hold A05 until project Gate P4; improve backend evidence while waiting + +## Outcome + +The backend survives restarts, exposes safe operations, and composes every production port behind frozen interfaces. This packet closes with simulators; real adapter convergence is Gate P4. + +## Small tasks + +### A04.1 — Startup recovery + +- Detect orphaned `SUBMITTING` records and route them to reconciliation-required `UNKNOWN` handling. +- Resume safe jobs after API/worker/database restarts. +- Prove lease expiry never grants a new settlement submission. + +### A04.2 — Safe disable + +- Add an audited configuration switch that stops new submission ownership. +- Keep liveness, status, evidence ingestion, and reconciliation reads available. +- Fail readiness when chain/policy/config identity is invalid without exposing secrets. + +### A04.3 — Structured telemetry + +- Emit correlation-safe state-transition logs with explicit redaction. +- Add metrics for states, oldest/count `UNKNOWN`, CAS conflicts, queue lag, duplicates, policy denials, provider errors, and reconciliation outcomes. +- Add alert threshold configuration with safe defaults. + +### A04.4 — Port composition + +- Wire dependency injection for production B/C entry points without importing internal modules. +- Create a composition profile using settlement and recovery simulators. +- Add contract-version/readiness mismatch failures. + +### A04.5 — Root verification + +- Run empty/upgrade migrations, lint, type, unit, integration, contract, build, concurrency, restart, and secret checks. +- Produce the Gate P4 composition checklist and exact package-version slots. + +## Acceptance evidence + +- Restart after intent creation, job claim, `SUBMITTING`, adapter result, and settlement commit preserves the invariant. +- Simulator-composed backend passes the complete applicable matrix with recorded settlement counts. +- Safe disable prevents new external calls while read/recovery paths remain healthy. +- Logs and metrics contain no raw provider body, credentials, authorization signatures, or private wallet material. +- Unknown or incompatible adapter contract versions fail readiness. + +## Handoff artifact + +Publish backend composition manifest, simulator lock, restart runner, dashboards/alert definitions, safe-disable runbook, and Gate P4 command list. + +## No-wait continuation + +A04 is `DONE` on simulator evidence. Do not start production frontend. While P4 awaits real artifacts, add backend tests, migration evidence, docs, or performance baselines as separately scoped tasks. + +## Non-goals + +No claim that live sponsor integration is qualified and no frontend implementation. diff --git a/milestones/coder-a/A05-frontend-intent-status.md b/milestones/coder-a/A05-frontend-intent-status.md new file mode 100644 index 0000000..48e9bbc --- /dev/null +++ b/milestones/coder-a/A05-frontend-intent-status.md @@ -0,0 +1,63 @@ +# A05 — Frontend Intent and Authoritative Status + +Owner: Coder A +Forecast: 2 working days +Branch: `milestone/a05-frontend-intent-status` +Depends on: A04 and project Gate P4 +Next: A06 immediately after closure + +## Start gate + +Do not start until P4 freezes OpenAPI and recovery semantics. Before P4, fixtures and mock-server examples may be refined, but no production UI code is allowed. + +## Outcome + +A minimal accessible application shell creates/replays intents and displays authoritative local status without inventing settlement actions. + +## Small tasks + +### A05.1 — Application shell + +- Add routing, API client generation, demo-appropriate service-auth handoff, error boundary, and test harness. +- Pin UI dependencies and keep source maps/secret behavior safe for the target environment. + +### A05.2 — Intent form + +- Validate stable ID, recipient, purpose, and atomic amount at the boundary. +- Format six-decimal USDC for humans without converting monetary values through floating point. +- Display Arc Testnet/USDC explicitly and separate native gas information. + +### A05.3 — Replay/conflict behavior + +- Preserve the same Business Intent ID on retry. +- Explain identical replay and same-ID payload conflict distinctly. +- Generate a new ID only for an explicitly new obligation. + +### A05.4 — Status polling + +- Render authoritative states and version, attempts summary, loading/error/offline behavior, and bounded polling/backoff. +- Treat `UNKNOWN` as blocked/reconciling, never as failed-safe. + +### A05.5 — Browser/accessibility tests + +- Cover create, replay, conflict, rate limit, unauthorized, unavailable, and all authoritative status families. +- Run keyboard, label, focus, contrast smoke, responsive viewport, lint, type, and build checks. + +## Acceptance evidence + +- Tests run against frozen mock server; no B/C UI code is needed. +- The UI cannot call a settlement port or create an unguarded retry. +- All displayed monetary values round-trip exact atomic units. +- Unknown API fields fail safely or remain non-authoritative. + +## Handoff artifact + +Publish shell/component entry points, browser fixtures, screenshots if useful, mock-server version, and composition note. + +## No-wait continuation + +Start A06. Final assembly of B05/C05 is project Gate P5, not A05 closure. + +## Non-goals + +No settlement details, Graph timeline, visual polish campaign, or force-pay action. diff --git a/milestones/coder-a/A06-release-operations.md b/milestones/coder-a/A06-release-operations.md new file mode 100644 index 0000000..718a45f --- /dev/null +++ b/milestones/coder-a/A06-release-operations.md @@ -0,0 +1,58 @@ +# A06 — Operational Demo and Release Bundle + +Owner: Coder A +Forecast: 2 working days +Branch: `milestone/a06-release-operations` +Depends on: A05 only +Project convergence: Gate P6 + +## Outcome + +The authoritative-state and operations portion of the demo is repeatable from a clean testnet environment and produces sanitized evidence for release review. + +## Small tasks + +### A06.1 — Reset/bootstrap runbook + +- Automate safe local database bootstrap/migration and demo fixture reset. +- Never delete or mutate external chain history; label testnet artifacts. +- Document prerequisites and rollback/safe-disable behavior. + +### A06.2 — Invariant scenarios + +- Script identical replay, conflicting replay, ten parallel workers, two processes, restart, lost response, and downstream failure. +- Record Business Intent ID, durable final state, attempt count, and external settlement count. + +### A06.3 — Operations evidence + +- Demonstrate readiness/liveness boundaries, safe disable, `UNKNOWN` alerts, queue lag, and redacted logs. +- Verify no manual database edit is needed for normal recovery. + +### A06.4 — Documentation + +- Finalize architecture, API/worker operation, migrations, debugging, recovery escalation, and known limitations. +- Link exact B/C evidence slots without copying secrets or raw provider responses. + +### A06.5 — Candidate verification + +- Run root quality, migration, matrix, browser, secret, and intended-file checks against the exact candidate. +- Prepare concise release evidence for mandatory independent review and human merge. + +## Acceptance evidence + +- Clean bootstrap and repeatable demo work without manual database surgery. +- Every scripted money/retry case includes durable state and settlement count. +- Safe disable halts new submissions and retains recovery visibility. +- Evidence contains no credentials, private wallet material, or sensitive provider payloads. + +## Handoff artifact + +Publish the operations runbook, invariant scenario runner, sanitized result table, architecture/API links, and release checklist. + +## No-wait continuation + +A06 closes independently. Gate P6 composes exact reviewed A06/B06/C06 artifacts; any mismatch becomes an owner-specific fix ticket. + +## Non-goals + +No mainnet readiness claim, production compliance certification, or agent-performed merge. diff --git a/milestones/coder-a/README.md b/milestones/coder-a/README.md new file mode 100644 index 0000000..1398dd7 --- /dev/null +++ b/milestones/coder-a/README.md @@ -0,0 +1,16 @@ +# Coder A Lane — Domain and Orchestration + +Mission: build the authoritative intent ledger, API, worker, concurrency guarantees, root composition, intent/status frontend slice, and operational release proof. + +Exclusive paths are listed in `plan.md`. Do not implement provider-specific logic; consume `AuthorizationPort`, `SettlementPort`, `EvidencePort`, and `IndexViewPort` through contracts and simulators. + +## Sequence + +1. [A01 — Foundation and contracts](A01-foundation-contracts.md) +2. [A02 — Durable intents](A02-durable-intents.md) +3. [A03 — Atomic worker](A03-atomic-worker.md) +4. [A04 — Restart, operations, and composition](A04-restart-operations-composition.md) +5. [A05 — Frontend intent and status](A05-frontend-intent-status.md), held until project Gate P4 +6. [A06 — Release operations](A06-release-operations.md) + +A01–A04 depend only on this lane’s previous packet and frozen simulators. Close A04 against simulator packages even if B04/C04 are not ready. Real adapter replacement belongs to project Gate P4. diff --git a/milestones/coder-b/B01-sdk-network-compatibility.md b/milestones/coder-b/B01-sdk-network-compatibility.md new file mode 100644 index 0000000..568fe5b --- /dev/null +++ b/milestones/coder-b/B01-sdk-network-compatibility.md @@ -0,0 +1,61 @@ +# B01 — SDK and Arc Network Compatibility + +Owner: Coder B +Forecast: 3 working days +Branch: `milestone/b01-sdk-network-compatibility` +Depends on: frozen `milestones/CONTRACTS.md` only +Next: B02 immediately after closure + +## Outcome + +A package-local spike pins compatible Privy and Ethereum tooling, validates Arc identity, and exposes a fail-closed configuration/readiness contract without requiring the domain service. + +## Small tasks + +### B01.1 — Version compatibility matrix + +- Test current supported Node LTS, Privy Node SDK, Ethereum client, TypeScript, module format, and test runner together. +- Pin exact versions only after request-signing and Arc chain support compile/run in an isolated spike. +- Record rejected combinations and upgrade constraints. + +### B01.2 — Arc constants + +- Encode chain ID `5042002`, CAIP-2 `eip155:5042002`, RPC/explorer configuration, ERC-20 USDC address, and six decimals. +- Separate ERC-20 settlement amounts from native USDC gas accounting. +- Reject runtime overrides that silently change network, token, or precision. + +### B01.3 — Configuration schema + +- Classify each variable as public, secret, optional, or human-only. +- Validate wallet, policy, network, token, recipient allowlist, cap, RPC, timeout, and feature switches. +- Produce safe `.env.example` entries with placeholders only. + +### B01.4 — Readiness probe library + +- Assert RPC chain ID and bytecode at the configured token contract. +- Validate expected wallet/policy identity format without printing credentials. +- Classify unavailable versus identity mismatch; mismatch fails closed. + +### B01.5 — Fixture capture boundary + +- Define sanitized official-response fixture wrappers and redaction tests. +- Prohibit headers, tokens, signatures, key material, and raw authorization responses from fixtures/logs. + +## Acceptance evidence + +- Package install, lint, type, unit, and build pass independently. +- Wrong chain, missing bytecode, wrong token, invalid recipient/cap, or policy mismatch fails readiness. +- No credential is needed for offline checks; network probes are explicitly separate. +- Version decision and upgrade risks are documented. + +## Handoff artifact + +Publish `settlement-config-v1`, pinned dependency rationale, Arc constants, readiness simulator/fixtures, redaction test, and package-local commands. + +## No-wait continuation + +Start B02 using frozen request fixtures. A’s workspace composition is not required. + +## Non-goals + +No wallet provisioning, policy mutation, transaction submission, durable state transition, or UI. diff --git a/milestones/coder-b/B02-request-policy-receipt.md b/milestones/coder-b/B02-request-policy-receipt.md new file mode 100644 index 0000000..57b1e05 --- /dev/null +++ b/milestones/coder-b/B02-request-policy-receipt.md @@ -0,0 +1,62 @@ +# B02 — Canonical Request, Policy, and Receipt Verification + +Owner: Coder B +Forecast: 3 working days +Branch: `milestone/b02-request-policy-receipt` +Depends on: B01 only +Next: B03 immediately after closure + +## Outcome + +Pure adapter logic builds one byte-stable ERC-20 request, expresses the expected fail-closed Privy policy, and confirms settlement only from an exact final Arc receipt and Transfer log. + +## Small tasks + +### B02.1 — ERC-20 calldata builder + +- Encode `transfer(address,uint256)` for the normalized recipient and `bigint` amount. +- Require exact chain/token/method, zero native transaction value, and six-decimal semantic boundary. +- Add golden calldata and request-fingerprint vectors. + +### B02.2 — Privy request identity + +- Build the request with persisted idempotency key, stable reference ID, deterministic body, and correlation metadata. +- Reject reuse of one key with a different body fingerprint. +- Document the 24-hour provider idempotency window as supplemental only. + +### B02.3 — Policy fixture + +- Define default-deny restrictions for chain, token contract, method selector, recipient, amount cap, and zero native value. +- Add deny fixtures for each wrong dimension and expired/invalid authorization. +- Produce policy identity/fingerprint expectations for readiness. + +### B02.4 — Receipt verifier + +- Verify transaction hash, chain, sender/wallet, token address, receipt status, block, recipient, amount, and unique Transfer log identity. +- Require exactly the expected transfer; unrelated logs do not count. +- Treat success status without matching Transfer as unresolved/failure, never confirmed. + +### B02.5 — Outcome classifier skeleton + +- Map official response fixtures to `CONFIRMED`, `DEFINITELY_NOT_SUBMITTED`, or `POSSIBLY_SUBMITTED` exhaustively. +- Unknown/malformed/partial response fails to `POSSIBLY_SUBMITTED`. +- Keep pure classification free of network and durable-state behavior. + +## Acceptance evidence + +- Golden inputs produce byte-identical calldata, body fingerprint, idempotency/reference identity, and expected receipt result. +- Wrong chain/token/method/recipient/value/amount is rejected before submission. +- `status: 0` is final revert; `status: 1` without exact Transfer is not confirmed. +- Timeout/lost/truncated/malformed fixtures never become safe retry. + +## Handoff artifact + +Publish `settlement-adapter-contract-v1`, policy fixture/digest, canonical request fixtures, receipt corpus, classifier simulator, and verification command. + +## No-wait continuation + +Start B03 in offline mode. Human provisioning may happen asynchronously. + +## Non-goals + +No production credentials, domain state mutation, Graph query, or frontend. diff --git a/milestones/coder-b/B03-live-settlement-harness.md b/milestones/coder-b/B03-live-settlement-harness.md new file mode 100644 index 0000000..9dc43b2 --- /dev/null +++ b/milestones/coder-b/B03-live-settlement-harness.md @@ -0,0 +1,66 @@ +# B03 — Offline-Complete and Live-Ready Settlement Harness + +Owner: Coder B +Forecast: 3 working days +Branch: `milestone/b03-live-settlement-harness` +Depends on: B02 only +Next: B04 immediately after offline closure + +## Outcome + +A standalone harness proves the complete adapter workflow with sanitized fixtures and, when a human provides approved credentials/funds, captures one real policy-constrained Arc Testnet settlement. Live availability does not block offline packet closure. + +## Small tasks + +### B03.1 — Human setup guide + +- Guide a human through Privy application, execution wallet, owner/key quorum, policy attachment, recipient/cap choice, Arc funding, and approved secret storage. +- Confirm before external mutation; hide secret input. +- Add a read-only verification mode and cleanup/rotation notes. + +### B03.2 — Standalone harness + +- Accept a frozen SettlementPort request fixture. +- Persist/request exact identity locally in ignored test runtime state before submission. +- Emit only normalized, sanitized port results and evidence. + +### B03.3 — Policy negative suite + +- Exercise wrong chain, contract, method, recipient, above cap, non-zero native value, and expired/invalid authorization. +- Count external committed transfers and prove every denial is zero. + +### B03.4 — Allowed settlement + +- Submit one approved ERC-20 USDC transfer on Arc Testnet through Privy. +- Poll provider/Arc evidence, verify final receipt and Transfer, and capture sanitized IDs/explorer URL. +- Ensure rerunning the same intent/key/body does not create another settlement. + +### B03.5 — Live-to-fixture conversion + +- Convert safe response shapes into synthetic/sanitized fixtures. +- Strip headers, credentials, signatures, private metadata, and unnecessary payload fields. +- Verify fixtures reproduce classifier and receipt results offline. + +## Acceptance evidence + +Offline closure: + +- Full harness flow and all allow/deny/error families pass with checked fixtures and deterministic call counter. +- Setup guide, redaction checks, and live command dry-run pass. + +Additional Gate P4 evidence when available: + +- One real allowed Arc Testnet transfer is final and verified. +- Every real policy denial produces zero settlement. + +## Handoff artifact + +Publish harness version, sanitized fixture pack, exact offline command, human-only live procedure, and a `LIVE_NOT_RUN` or sanitized live-evidence statement. + +## No-wait continuation + +Mark B03 `DONE` when offline criteria pass, even if live setup is pending. Start B04; track live execution as Gate P4 evidence. + +## Non-goals + +No mainnet, automatic funding, unattended policy mutation, domain database write, or qualification claim from fixtures alone. diff --git a/milestones/coder-b/B04-ambiguity-integration.md b/milestones/coder-b/B04-ambiguity-integration.md new file mode 100644 index 0000000..239557b --- /dev/null +++ b/milestones/coder-b/B04-ambiguity-integration.md @@ -0,0 +1,62 @@ +# B04 — Provider Ambiguity and Production Adapter Pack + +Owner: Coder B +Forecast: 4 working days +Branch: `milestone/b04-ambiguity-integration` +Depends on: B03 only +Next: hold B05 until project Gate P4 + +## Outcome + +Production-ready adapter entry points conservatively classify realistic provider/RPC failures, support idempotent evidence lookup, and pass A’s composition contract through a simulator-hosted integration test. + +## Small tasks + +### B04.1 — Submission failure taxonomy + +- Inject DNS failure, refusal, TLS/network interruption, timeout, 429/5xx, truncated/malformed response, and lost success response. +- Mark only documented pre-broadcast proof as `DEFINITELY_NOT_SUBMITTED`. +- Route every doubtful case to `POSSIBLY_SUBMITTED`. + +### B04.2 — Transaction lifecycle lookup + +- Implement Privy transaction lookup and Arc receipt/log lookup using persisted identities. +- Return `FINAL_SUCCESS`, `FINAL_REVERT`, `PENDING`, `NOT_FOUND`, or `UNAVAILABLE` with sanitized evidence. +- Never treat `NOT_FOUND` as resubmission permission. + +### B04.3 — Pending/evicted/mismatch cases + +- Cover long pending, replaced/evicted visibility, wrong nonce/hash, wrong chain/token/wallet, multiple/mismatched Transfer logs, and contradictory provider/RPC states. +- Preserve ambiguity when evidence cannot be bound to the exact request. + +### B04.4 — Policy/readiness hardening + +- Recheck expected policy identity/fingerprint and Arc identity at startup and before sensitive use as appropriate. +- Fail closed on changed policy, wallet, network, token, or cap. +- Keep optional webhooks disabled unless plan availability and signature verification are proven; polling remains complete. + +### B04.5 — Production entry point + +- Export only frozen port interfaces and sanitized errors. +- Add simulator-hosted contract integration tests and compatibility metadata. +- Ensure no import reaches A/C internal packages. + +## Acceptance evidence + +- Every injected failure has an explicit result and no ambiguous case is safe retry. +- Repeated lookup is idempotent and causes zero submissions. +- Adapter restarts preserve request identity supplied by the caller. +- Package-local lint/type/test/build and contract compatibility pass without A/C implementations. +- Live-only gaps are listed for P4 and do not masquerade as completed evidence. + +## Handoff artifact + +Publish production package version, error taxonomy, lookup fixture pack, compatibility manifest, redaction report, and P4 replacement instructions. + +## No-wait continuation + +B04 closes against the contract host. Do not start production frontend until P4. While held, strengthen provider fixtures, upgrade tests, and live evidence as focused tasks. + +## Non-goals + +No reconciliation decision, Graph authority, automatic transaction replacement, or UI. diff --git a/milestones/coder-b/B05-frontend-settlement-details.md b/milestones/coder-b/B05-frontend-settlement-details.md new file mode 100644 index 0000000..e71e7d9 --- /dev/null +++ b/milestones/coder-b/B05-frontend-settlement-details.md @@ -0,0 +1,62 @@ +# B05 — Frontend Authorization and Settlement Details + +Owner: Coder B +Forecast: 2 working days +Branch: `milestone/b05-frontend-settlement-details` +Depends on: B04 and project Gate P4 +Next: B06 immediately after closure + +## Start gate + +Do not write production UI before P4 freezes OpenAPI. Use the frozen mock server and sanitized UI fixtures. + +## Outcome + +An independently composable frontend slice explains policy, authorization, submission, and final transaction evidence without exposing secrets or offering bypass actions. + +## Small tasks + +### B05.1 — Policy summary + +- Render network, asset, allowed recipient, cap, and policy status from sanitized API fields. +- Never display authorization keys, signatures, owner secrets, or raw policy responses. + +### B05.2 — Authorization states + +- Distinguish checking, authorized, denied, unavailable, and configuration mismatch. +- Explain denials without suggesting a bypass. + +### B05.3 — Settlement states + +- Render ready, submitting, pending/unknown, committed, final revert/failed-safe, and unavailable evidence. +- `UNKNOWN` disables any new settlement action. +- Do not show confirmation counts; Arc is pending or final. + +### B05.4 — Verified transaction details + +- Display sanitized transaction hash, block, token, recipient, exact amount, Transfer identity, and Arc explorer link only when verified. +- Validate outbound explorer URL and prevent unsafe interpolation. + +### B05.5 — Component tests + +- Cover all fixtures, redaction, malicious strings/URLs, unavailable evidence, and exact amount formatting. +- Run accessibility, keyboard, responsive, lint, type, and build checks package-locally. + +## Acceptance evidence + +- Slice passes independently in Storybook/test host or equivalent using frozen fixtures. +- No force-pay, policy-bypass, resend, or direct adapter action exists. +- Secrets/raw provider payloads have no component prop or rendered path. +- Unknown states remain visibly non-terminal and non-retryable. + +## Handoff artifact + +Publish component entry point, route slot, fixture stories/tests, mock-server version, and composition note. + +## No-wait continuation + +Start B06. Project Gate P5 composes A/B/C slices later. + +## Non-goals + +No app shell, create form, recovery timeline, or final visual polish. diff --git a/milestones/coder-b/B06-sponsor-evidence.md b/milestones/coder-b/B06-sponsor-evidence.md new file mode 100644 index 0000000..46b8acb --- /dev/null +++ b/milestones/coder-b/B06-sponsor-evidence.md @@ -0,0 +1,57 @@ +# B06 — Privy and Arc Sponsor Evidence + +Owner: Coder B +Forecast: 2 working days +Branch: `milestone/b06-sponsor-evidence` +Depends on: B05 only +Project convergence: Gate P6 + +## Outcome + +A sanitized, repeatable evidence bundle demonstrates Privy as the real authorization boundary and Arc Testnet as the real USDC settlement rail, with limitations stated honestly. + +## Small tasks + +### B06.1 — Privy evidence script + +- Demonstrate execution wallet, expected policy identity/scope, normal-path enforcement, and no bypass path. +- Show wrong-scope and above-cap denials with zero committed settlement. + +### B06.2 — Arc evidence script + +- Demonstrate one authorized ERC-20 USDC settlement on Arc Testnet. +- Bind Privy request identity to transaction hash, final receipt, exact Transfer log, and explorer URL. + +### B06.3 — Ambiguity scenario + +- Intentionally lose the local success response after possible submission. +- Show B adapter reports ambiguity and evidence lookup locates the original transaction without submitting another. + +### B06.4 — Sanitization audit + +- Review screenshots, logs, fixtures, commands, and docs for keys, tokens, signatures, private wallet data, raw authorization responses, and environment contents. +- Retain only public/sanitized testnet identifiers. + +### B06.5 — Qualification input + +- Provide code, test, live-demo, network, transaction, policy, and limitation references for `sponsor-qualification`. +- Use `NOT VERIFIED` when live proof is missing; never promote fixtures into qualification. + +## Acceptance evidence + +- Privy policy materially constrains the normal path and denials settle zero. +- Arc evidence proves a real final ERC-20 transfer, not only a label or explorer screenshot. +- Repeated demo/reset does not create an unintended second settlement. +- Bundle passes secret/redaction and reproducibility checks. + +## Handoff artifact + +Publish sanitized Privy/Arc evidence index, exact demo commands, transaction/policy references, denial table, and limitation statement. + +## No-wait continuation + +B06 closes independently. Gate P6 consumes its exact reviewed bundle alongside A06/C06; mismatches return only to B-owned evidence/code. + +## Non-goals + +No mainnet claim, wallet-key export, external-account mutation by an agent, or final sponsor verdict for The Graph. diff --git a/milestones/coder-b/README.md b/milestones/coder-b/README.md new file mode 100644 index 0000000..4b4d43d --- /dev/null +++ b/milestones/coder-b/README.md @@ -0,0 +1,16 @@ +# Coder B Lane — Privy Authorization and Arc Settlement + +Mission: provide a conservative, policy-constrained Privy/Arc adapter with exact request identity, receipt proof, realistic ambiguity classification, settlement UI details, and sponsor evidence. + +Stay inside B-owned packages and fixtures. Consume domain requests from the frozen contract pack; never redefine durable states or edit migrations. + +## Sequence + +1. [B01 — SDK and network compatibility](B01-sdk-network-compatibility.md) +2. [B02 — Request, policy, and receipt](B02-request-policy-receipt.md) +3. [B03 — Live settlement harness](B03-live-settlement-harness.md) +4. [B04 — Ambiguity and integration](B04-ambiguity-integration.md) +5. [B05 — Frontend settlement details](B05-frontend-settlement-details.md), held until project Gate P4 +6. [B06 — Sponsor evidence](B06-sponsor-evidence.md) + +All packets have an offline fixture/simulator closure path. Human credentials and live testnet availability add project evidence but do not leave the coder idle. diff --git a/milestones/coder-c/C01-subgraph-index-health.md b/milestones/coder-c/C01-subgraph-index-health.md new file mode 100644 index 0000000..4b6c7e5 --- /dev/null +++ b/milestones/coder-c/C01-subgraph-index-health.md @@ -0,0 +1,61 @@ +# C01 — Subgraph Mapping and Index Health + +Owner: Coder C +Forecast: 3 working days +Branch: `milestone/c01-subgraph-index-health` +Depends on: frozen `milestones/CONTRACTS.md` only +Next: C02 immediately after closure + +## Outcome + +A standalone Subgraph maps Arc USDC Transfer fixtures, and a Graph client returns freshness-labeled observations including `_meta`, deployment, lag, and indexing health. + +## Small tasks + +### C01.1 — Subgraph schema + +- Define transfer entity identity as transaction hash plus log index. +- Store sender, recipient, Graph `BigInt` amount, transaction hash, log index, block number, and block timestamp. +- Document public/sanitized fields and immutable IDs. + +### C01.2 — Manifest and mapping + +- Target Arc Testnet and the exact ERC-20 USDC Transfer event. +- Map duplicate/out-of-order fixture events deterministically. +- Reject assumptions that one transaction has only one log. + +### C01.3 — Mapping tests + +- Add Matchstick/unit fixtures for normal, multiple-log, duplicate delivery, wrong contract/topic, zero/large amount, and ordering behavior. +- Assert exact decimal-string/BigInt preservation. + +### C01.4 — Graph query client + +- Query transfers plus `_meta` block, deployment identity, timestamp, and `hasIndexingErrors`. +- Compare indexed block with chain head supplied through an injectable seam. +- Validate all untrusted GraphQL output. + +### C01.5 — Freshness classifier + +- Emit `FRESH`, `LAGGING`, `UNHEALTHY`, `UNAVAILABLE`, or `UNKNOWN_FRESHNESS` with observed-through bounds. +- Make empty data distinct from authoritative non-payment. +- Add simulator fixtures for every health/result combination. + +## Acceptance evidence + +- Subgraph tests run without network or credentials. +- Identity remains transaction hash plus log index and amount never becomes a JS float. +- Missing `_meta`, indexing errors, head-query failure, or excessive lag is visibly non-fresh. +- Empty result says only “not observed through block N” and grants no permission. + +## Handoff artifact + +Publish `index-view-v1`, schema/manifest digest, mapping fixture pack, Graph query schema, freshness simulator, and package-local commands. + +## No-wait continuation + +Start C02 with synthetic local/Privy/Arc evidence. A/B packages and live deployment are not required. + +## Non-goals + +No durable state authority, settlement submission, provider wallet operation, or UI. diff --git a/milestones/coder-c/C02-reconciliation-engine.md b/milestones/coder-c/C02-reconciliation-engine.md new file mode 100644 index 0000000..51e4092 --- /dev/null +++ b/milestones/coder-c/C02-reconciliation-engine.md @@ -0,0 +1,61 @@ +# C02 — Deterministic Reconciliation Engine + +Owner: Coder C +Forecast: 3 working days +Branch: `milestone/c02-reconciliation-engine` +Depends on: C01 only +Next: C03 immediately after closure + +## Outcome + +A pure decision engine combines authoritative local/Arc evidence, provider lookup, and non-authoritative Graph observations to emit safe reconciliation commands and a provenance-labeled recovery view. It can never submit payment. + +## Small tasks + +### C02.1 — Evidence model + +- Define source, authority class, request binding, retrieval time, block/finality/freshness, sanitized reason, and digest. +- Reject evidence that cannot bind to the exact intent/request/transaction identity. + +### C02.2 — Precedence table + +- Make durable committed record and exact verified Arc receipt authoritative. +- Use Privy status to locate provider activity and The Graph only to corroborate/explain. +- Encode contradictory, stale, missing, and unavailable combinations explicitly. + +### C02.3 — Reconciliation commands + +- Emit `MARK_COMMITTED`, `MARK_FAILED_SAFE`, `HOLD_UNKNOWN`, or `ESCALATE_UNKNOWN` with expected state version. +- Require exact verified success for commit and authoritative matching final failure/no-effect proof for failed-safe. +- Never emit a submit/retry command. + +### C02.4 — Recovery view + +- Separate authoritative state from provider/Arc/indexed observations. +- Include observed-through block/time, lag, health, and contradiction warnings. +- Sanitize raw payloads and bound collection sizes. + +### C02.5 — Idempotency tests + +- Repeat decisions, reorder/duplicate observations, change retrieval time, and replay webhooks/provider events. +- Prove deterministic semantic command and zero external submissions. + +## Acceptance evidence + +- Verified matching success resolves `UNKNOWN -> COMMITTED`. +- Matching final revert/no-effect proof may resolve `UNKNOWN -> FAILED_SAFE`. +- Pending, not found, unavailable, empty/lagging/unhealthy Graph, mismatch, or contradiction remains `UNKNOWN`. +- Every decision explains authority and provenance without leaking raw sensitive data. +- Package imports no A/B implementation and contains no SettlementPort call. + +## Handoff artifact + +Publish `reconciliation-v1`, complete decision matrix, command schema, evidence/recovery fixtures, pure simulator, and verification command. + +## No-wait continuation + +Start C03 using the local state and provider simulators from the frozen pack. + +## Non-goals + +No direct database mutation, queue ownership, settlement submission, live Graph requirement, or frontend. diff --git a/milestones/coder-c/C03-failure-injection.md b/milestones/coder-c/C03-failure-injection.md new file mode 100644 index 0000000..3fdcf40 --- /dev/null +++ b/milestones/coder-c/C03-failure-injection.md @@ -0,0 +1,59 @@ +# C03 — Cross-Source Failure Injection + +Owner: Coder C +Forecast: 3 working days +Branch: `milestone/c03-failure-injection` +Depends on: C02 only +Next: C04 immediately after closure + +## Outcome + +A deterministic chaos harness proves that crashes, lost responses, duplicate/out-of-order evidence, Graph degradation, and provider/RPC contradictions cannot turn uncertainty into settlement permission. + +## Small tasks + +### C03.1 — Failure timeline DSL + +- Define injection points: definitely before submission, possibly submitted, and definitely confirmed. +- Model process kill, timeout, disconnect, response loss, delayed evidence, and restart between durable transitions. +- Make each scenario deterministic and seed-recorded. + +### C03.2 — Graph degradation suite + +- Delay/empty results, trail chain head, set indexing errors, omit `_meta`, fail query, return duplicates/out-of-order events, and switch deployment identity. +- Assert health labels and no permission change. + +### C03.3 — Provider/RPC contradiction suite + +- Combine provider pending/success/not-found/unavailable with Arc pending/success/revert/mismatch/unavailable. +- Bind evidence to intent/request/transaction and hold on mismatch. + +### C03.4 — Restart/evidence replay + +- Persist synthetic evidence feed, restart the harness, replay/reorder it, and compare decisions. +- Prove semantic idempotency and stable audit chronology. + +### C03.5 — UNKNOWN aging and escalation + +- Add configurable age buckets, alerts, operator context, and escalation outcomes. +- Ensure runbook language never instructs “just retry” or treats lease expiry as permission. + +## Acceptance evidence + +- Every `.agent/TEST_MATRIX.md` case involving ambiguity/evidence has a deterministic scenario. +- Crash/lost response after possible submission remains `UNKNOWN` until authoritative resolution. +- Empty, delayed, unhealthy, contradictory, or unavailable sources never unlock payment. +- Repeated/reordered evidence causes zero settlement calls and stable commands. +- Harness runs with no network or credentials. + +## Handoff artifact + +Publish failure DSL/schema, scenario catalog, one-command matrix runner, deterministic seeds, result table, and escalation runbook draft. + +## No-wait continuation + +Start C04 using A/B simulators. Integrated process kills and live evidence are added at Gate P4. + +## Non-goals + +No destructive live-funds testing, automatic remediation, provider mutation, or UI. diff --git a/milestones/coder-c/C04-recovery-matrix-integration.md b/milestones/coder-c/C04-recovery-matrix-integration.md new file mode 100644 index 0000000..dca8fcb --- /dev/null +++ b/milestones/coder-c/C04-recovery-matrix-integration.md @@ -0,0 +1,60 @@ +# C04 — Recovery Matrix and Simulator Integration + +Owner: Coder C +Forecast: 4 working days +Branch: `milestone/c04-recovery-matrix-integration` +Depends on: C03 only +Next: hold C05 until project Gate P4 + +## Outcome + +The recovery service composes frozen local-state, provider/Arc, and Graph simulators, persists sanitized evidence through its command seam, and produces the complete pre-live safety matrix. + +## Small tasks + +### C04.1 — Service boundary + +- Implement reconciliation job/command handler around the pure engine. +- Consume state snapshots and emit versioned commands; never write A tables or call settlement. +- Add retry-safe reads and duplicate event handling. + +### C04.2 — Evidence persistence contract + +- Emit append-only observation records with provenance, retrieval time, block/freshness, authority, reason, and digest. +- Redact provider bodies and secrets before crossing the boundary. + +### C04.3 — Simulator composition + +- Host A local-state and B evidence simulators behind frozen ports. +- Verify contract version mismatch and unknown result fail closed. +- Run all combinations without importing internal implementation paths. + +### C04.4 — Matrix report + +- Generate a sanitized table containing scenario, stable intent, starting/final state, evidence sources, decision, and external-submission count. +- Cover normal, duplicate, concurrency, crash, lost response, Graph delay/error, denial, restart, downstream failure, and two-agent cases at the recovery seam. + +### C04.5 — Gate P4 replacement guide + +- Document exact simulator-to-reviewed-package replacement points. +- Define live Graph deployment checks, lag thresholds, expected package versions, and rollback to safe simulator/read-only mode. + +## Acceptance evidence + +- Package-local lint/type/test/build and full fixture matrix pass. +- Reconciliation retries are idempotent and zero-submit by construction. +- Recovery view always distinguishes authority and observation freshness. +- Contract mismatch, missing `_meta`, raw provider payload, and unknown enum fail closed. +- Packet closes with simulators; live gaps are explicit Gate P4 items. + +## Handoff artifact + +Publish recovery service package, evidence command pack, matrix report, simulator lock, live replacement guide, and Graph deployment checklist. + +## No-wait continuation + +C04 is `DONE` on simulator proof. Do not start production frontend until P4. While held, expand chaos coverage, auditability, docs, or performance baselines. + +## Non-goals + +No production frontend, direct settlement, Graph-based authorization, or sponsor qualification from offline data. diff --git a/milestones/coder-c/C05-frontend-recovery.md b/milestones/coder-c/C05-frontend-recovery.md new file mode 100644 index 0000000..205e3f3 --- /dev/null +++ b/milestones/coder-c/C05-frontend-recovery.md @@ -0,0 +1,61 @@ +# C05 — Frontend Recovery Timeline and Indexed History + +Owner: Coder C +Forecast: 2 working days +Branch: `milestone/c05-frontend-recovery` +Depends on: C04 and project Gate P4 +Next: C06 immediately after closure + +## Start gate + +Do not write production UI before P4 freezes recovery-view semantics. Build against the frozen mock server and sanitized fixtures. + +## Outcome + +An independently composable recovery slice shows authoritative state, attempts, reconciliation, provider/Arc evidence, and Graph observations with clear provenance and no retry shortcut. + +## Small tasks + +### C05.1 — Attempt/reconciliation timeline + +- Render ordered attempts, durable transitions, evidence retrieval, reconciliation decisions, and current authoritative state. +- Handle pagination, duplicate observations, and clock/order ambiguity safely. + +### C05.2 — Evidence provenance + +- Label local, Privy, Arc, and Graph sources plus authority class. +- Show verified transaction binding and contradiction warnings without raw sensitive payloads. + +### C05.3 — Graph freshness + +- Display deployment, indexed-through block/time, chain-head lag, health, indexing errors, and unavailable state. +- Empty result reads “not observed through block N,” never “not paid.” + +### C05.4 — UNKNOWN experience + +- Explain why new settlement is blocked and what reconciliation/operator action is safe. +- Provide escalation/status refresh only; no generic retry or force-pay button. + +### C05.5 — Component tests + +- Cover fresh, empty, lagging, unhealthy, unavailable, contradictory, pending, committed, failed-safe, and aged-UNKNOWN fixtures. +- Test malicious evidence strings, accessibility, keyboard, responsive layout, lint, type, and build. + +## Acceptance evidence + +- Slice passes independently against frozen fixtures and mock server. +- Authority and observation are never visually conflated. +- Empty/lagging/error Graph states cannot imply non-payment or enable retry. +- No secret/raw provider body has a component input or render path. + +## Handoff artifact + +Publish component/route entry point, fixture stories/tests, mock-server version, copy glossary, and composition note. + +## No-wait continuation + +Start C06. Project Gate P5 composes A/B/C slices later. + +## Non-goals + +No app shell, create form, policy controls, settlement action, or broad visual redesign. diff --git a/milestones/coder-c/C06-qualification-demo.md b/milestones/coder-c/C06-qualification-demo.md new file mode 100644 index 0000000..92446ab --- /dev/null +++ b/milestones/coder-c/C06-qualification-demo.md @@ -0,0 +1,58 @@ +# C06 — The Graph, Recovery, and Qualification Bundle + +Owner: Coder C +Forecast: 2 working days +Branch: `milestone/c06-qualification-demo` +Depends on: C05 only +Project convergence: Gate P6 + +## Outcome + +A repeatable recovery demo proves live indexed Arc observations add useful history/recovery context while degraded Graph states remain non-authoritative, and it supplies evidence-based sponsor qualification inputs. + +## Small tasks + +### C06.1 — Live index health + +- Query the pinned live Arc Testnet deployment with `_meta`, deployment ID, indexed block/time, chain head, lag, and indexing errors. +- Record sanitized endpoint/deployment evidence and freshness threshold. + +### C06.2 — Recovery story + +- Show one exact transaction in durable/Privy/Arc evidence and indexed history. +- Demonstrate `UNKNOWN` reconciliation to the original transaction with no new submission. + +### C06.3 — Degraded index story + +- Run delayed, empty, unhealthy, unavailable, missing `_meta`, and contradictory fixtures against the same recovery UI/engine. +- Show safe hold/escalation and accurate observed-through language. + +### C06.4 — Audit and repeatability + +- Verify evidence survives service restart, can be replayed, and contains no provider secret/raw credential data. +- Document reset steps that do not rewrite chain history or require database surgery. + +### C06.5 — Sponsor qualification + +- Run `sponsor-qualification` against actual code, tests, live demo, network, deployment, and known limitations. +- Report Privy, Arc, and The Graph individually as `QUALIFIED`, `NOT QUALIFIED`, or `NOT VERIFIED`. +- Never treat plans, mocks, variables, labels, or dependency declarations as proof. + +## Acceptance evidence + +- Live indexed data is demonstrably used for recovery/history or agent decision support. +- OneShot remains authoritative and Graph degradation never unlocks settlement. +- Demo is repeatable and evidence is sanitized. +- Qualification verdicts cite concrete code, test, and live evidence or honestly remain `NOT VERIFIED`. + +## Handoff artifact + +Publish Graph/recovery evidence index, live health snapshot, degraded-state matrix, demo steps, qualification report, and limitations. + +## No-wait continuation + +C06 closes independently. Gate P6 composes exact reviewed A06/B06/C06 bundles; any failed qualification returns to the owning implementation/evidence lane. + +## Non-goals + +No Graph authority claim, production SLA, mainnet evidence, external mutation by an agent, or agent-performed merge. diff --git a/milestones/coder-c/README.md b/milestones/coder-c/README.md new file mode 100644 index 0000000..065bfe5 --- /dev/null +++ b/milestones/coder-c/README.md @@ -0,0 +1,16 @@ +# Coder C Lane — Reconciliation and Indexed Recovery + +Mission: index Arc transfer observations, classify Graph health/freshness, reconcile ambiguous settlement evidence without submitting payments, build failure-injection proof, render recovery UI, and assemble qualification evidence. + +Stay inside C-owned paths. The reconciliation package emits frozen commands; it never writes A’s tables directly and never calls SettlementPort. + +## Sequence + +1. [C01 — Subgraph and index health](C01-subgraph-index-health.md) +2. [C02 — Reconciliation engine](C02-reconciliation-engine.md) +3. [C03 — Failure injection](C03-failure-injection.md) +4. [C04 — Recovery matrix and integration](C04-recovery-matrix-integration.md) +5. [C05 — Frontend recovery](C05-frontend-recovery.md), held until project Gate P4 +6. [C06 — Qualification demo](C06-qualification-demo.md) + +C01–C04 close against frozen local/provider/Graph fixtures. A/B implementations and a deployed live Subgraph are project-gate evidence, not reasons to stop local progress. diff --git a/plan.md b/plan.md old mode 100755 new mode 100644 index d6b0dca..e82186c --- a/plan.md +++ b/plan.md @@ -1,521 +1,579 @@ -# OneShot Product Implementation Plan +# OneShot Product Delivery Plan -Status: implementation-ready proposal -Team: exactly three engineers -Planning horizon: 20 working days, recalibrated after Milestone 1 -Base for implementation: current `develop` after the agent-infrastructure work is human-reviewed and merged +Status: implementation-ready planning baseline +Team: exactly three coders +Planning horizon: 20 working days, recalibrated after Backend Wave 1 +Implementation base: the human-approved commit containing this plan Research basis: `.agent/research/20260906-integration-decisions.md` +Detailed work packets: [`milestones/README.md`](milestones/README.md) -## 1. Outcome +## 1. Mission -Deliver a testnet application that accepts one approved Business Intent, safely survives retries, crashes, duplicate delivery, parallel workers, and ambiguous provider responses, and produces at most one committed USDC settlement on Arc Testnet through a Privy-controlled corporate wallet. The Graph supplies live indexed history and recovery evidence without becoming an authorization source. +Deliver a testnet application that accepts one approved Business Intent, safely survives retries, crashes, duplicate delivery, parallel workers, and ambiguous provider responses, and produces at most one committed ERC-20 USDC settlement on Arc Testnet through a Privy-controlled corporate wallet. The Graph supplies live indexed recovery and history evidence without becoming settlement authority. The release claim is: `1 Business Intent / N Attempts / <= 1 committed Settlement` -The milestone plan is deliberately backend-first. No production frontend work begins until the backend integration and failure suite pass in Milestone 4. +The delivery plan is backend-first. Frontend implementation is deliberately placed in Wave 5 and may start only after the backend contract-freeze gate has passed. -## 2. Success criteria +## 2. Planning objectives -- A caller creates a Business Intent with a stable `business_intent_id`; identical replays return the same durable result and conflicting payloads under the same ID fail explicitly. -- Privy authorization and wallet policy constrain every normal settlement path. Wrong network, asset, recipient, method, or above-cap amount results in zero settlement. -- A valid intent produces a real ERC-20 USDC transfer on Arc Testnet and stores the final receipt and transfer identity. -- A timeout, lost response, or crash after possible submission produces durable `UNKNOWN`; no new settlement submission is allowed until reconciliation resolves it. -- Ten sequential retries, ten parallel workers, a restart, and two agent instances cannot produce more than one committed settlement. -- Live The Graph data explains settlement history and supports recovery. Empty, delayed, or unhealthy indexed data never unlocks another payment. -- Money remains an integer string/`bigint` in six-decimal ERC-20 USDC atomic units from API through policy evaluation, storage, calldata, indexing, and UI. -- The final demo proves Privy, Arc, and The Graph requirements with testnet evidence and exposes no secrets. +This plan optimizes for five properties: -## 3. Scope +1. Safety: uncertainty never becomes permission to pay again. +2. Independent progress: no coder waits for another coder’s implementation to close a work packet. +3. Low merge contention: each coder owns disjoint directories and shared files have a single editor. +4. Verifiable handoffs: ports, OpenAPI, schemas, fixtures, and simulators are versioned artifacts. +5. Late frontend: UI work consumes a stable backend contract instead of driving it. -### In scope +## 3. Product success criteria -- TypeScript backend, worker, shared contracts, PostgreSQL state, and migrations. -- Privy execution-wallet authorization and a fail-closed wallet policy. -- Arc Testnet ERC-20 USDC submission, receipt verification, and explorer evidence. -- Durable reconciliation using OneShot state, Privy identifiers/status, Arc RPC receipts, and The Graph evidence. -- A custom Subgraph plus freshness and indexing-health classification. -- Failure injection, concurrency tests, service restart tests, audit-safe structured logs, metrics, and a demo runbook. -- A minimal operator/user frontend only after backend acceptance. +- Identical requests reuse the same durable Business Intent; conflicting payloads under the same ID fail explicitly. +- Privy authorization constrains every normal settlement path. Wrong network, token, method, recipient, value, or above-cap amount produces zero settlement. +- A valid intent can produce one real ERC-20 USDC transfer on Arc Testnet and persist a verified receipt and Transfer identity. +- A timeout, disconnect, lost response, or crash after possible submission produces durable `UNKNOWN`; a new payment is forbidden until authoritative reconciliation resolves it. +- Ten sequential retries, ten parallel workers, restart recovery, queue redelivery, and two agent instances never produce more than one committed settlement. +- Live The Graph data supports history and recovery. Empty, delayed, unhealthy, or contradictory indexed data never authorizes payment. +- Money remains a canonical integer string at JSON boundaries and `bigint` internally, using six-decimal ERC-20 USDC atomic units. +- The demo proves working Privy, Arc, and The Graph integrations with sanitized testnet evidence and no exposed secrets. -### Explicit non-goals +## 4. Scope -- Mainnet, multi-chain, multi-asset, swaps, bridging, fiat on/off ramps, or custody beyond the configured Privy testnet wallet. -- Treating The Graph as authoritative settlement state or as permission to retry. -- Automatic same-nonce transaction replacement in the first release. -- General workflow automation, arbitrary supplier integrations, accounting/ERP integrations, or production compliance certification. -- Production-scale multi-region deployment, high availability, or a native mobile client. +### Included -## 4. Fixed technical decisions +- Strict TypeScript monorepo, shared contracts, API, worker, PostgreSQL state, migrations, and transactional jobs. +- Privy execution-wallet authorization and fail-closed wallet policy. +- Arc Testnet ERC-20 USDC request construction, submission, receipt verification, and explorer evidence. +- Durable reconciliation using OneShot state, Privy identifiers/status, Arc RPC receipts, and The Graph observations. +- Custom Subgraph, indexed-history query, freshness and health classification. +- Contract simulators, failure injection, concurrency and restart testing, structured logs, metrics, and operator runbooks. +- Minimal operator/user frontend after backend acceptance. -These decisions are frozen for the first implementation. Changing one requires a short ADR, updated contract fixtures, and approval from all affected owners. +### Excluded -| Area | Decision | Reason | -| --- | --- | --- | -| Runtime | Node.js LTS + strict TypeScript; exact versions pinned in Milestone 1 | One language across API, worker, Privy, Arc, Subgraph tooling, and frontend | -| Repository | `pnpm` workspace with independently testable packages | Each owner can build and test without waiting for root integration | -| API | HTTP JSON described by OpenAPI; generated schemas are checked for drift | Stable seam for simulators and the late frontend | -| Durable state | PostgreSQL | Atomic conditional transitions, constraints, transactional enqueueing | -| Work delivery | Graphile Worker in the same PostgreSQL database | At-least-once work without adding Redis; transactional enqueueing | -| Money | Decimal-free integer strings at boundaries and `bigint` internally | Prevents floating-point loss and JSON `bigint` ambiguity | -| Settlement asset | Arc Testnet ERC-20 USDC at `0x3600000000000000000000000000000000000000`, six decimals | One canonical payment representation; native USDC is gas accounting only | -| Privy | Execution wallet with authorization owner/key quorum and one fail-closed policy | Privy remains a real authorization boundary, not branding | -| Chain access | Arc RPC with startup checks for chain ID `5042002` and USDC bytecode | Fails closed on misconfiguration | -| Indexed view | Custom Subgraph on `arc-testnet`, queried with `_meta` and explicit freshness | Live recovery/history with visible limitations | -| External-effect queueing | `submit_settlement` gets one queue attempt; reconciliation reads may retry | Prevents the queue from blindly repeating an ambiguous payment | - -## 5. Architecture and ownership boundaries +- Mainnet, additional chains/assets, swaps, bridges, fiat rails, automatic transaction replacement, or unrestricted payment overrides. +- The Graph as duplicate lock, durable intent store, or proof that another settlement is safe. +- General workflow automation, arbitrary supplier/ERP integrations, native mobile clients, production compliance certification, or multi-region HA. +- UI polish that is not necessary to demonstrate the invariant and sponsor requirements. + +## 5. Fixed technical baseline + +| Area | Decision | +| --- | --- | +| Runtime | Node.js LTS and strict TypeScript; A01 pins the workspace runtime, while B01 proves SDK compatibility independently and reports any mismatch at P2 | +| Workspace | `pnpm` workspace with package-local lint, type, test, and build commands | +| API | HTTP JSON, OpenAPI source of truth, generated-schema drift check | +| State | PostgreSQL with constraints, compare-and-set transitions, and transactional enqueueing | +| Queue | Graphile Worker; at-least-once delivery is assumed | +| Money | Integer strings at boundaries, `bigint` internally, no JavaScript monetary floats | +| Settlement | Arc Testnet `eip155:5042002`, ERC-20 USDC `0x3600000000000000000000000000000000000000`, six decimals | +| Authorization | Privy execution wallet with explicit fail-closed policy and persisted request identity | +| Submission jobs | One queue attempt; task persists `COMMITTED`, `FAILED_SAFE`, or `UNKNOWN` before returning | +| Recovery | OneShot and verified Arc evidence authoritative; The Graph is freshness-labeled observation only | +| Frontend | Begins after Gate P4; consumes frozen OpenAPI and mock server | + +The exact v1 contracts, state table, fixture catalog, redaction rules, and change protocol are frozen in [`milestones/CONTRACTS.md`](milestones/CONTRACTS.md). + +## 6. Architecture ```text Caller / late frontend | v -HTTP API ---------> PostgreSQL authoritative ledger <------ Worker claims - | | | - | +---- durable outbox/jobs ---+ - | - +--> AuthorizationPort --> Privy policy + wallet - +--> SettlementPort ----> Arc ERC-20 USDC - +--> EvidencePort ------> Privy status + Arc RPC - +--> IndexViewPort -----> The Graph (non-authoritative) +HTTP API ----------> PostgreSQL authoritative ledger <--------- Worker + | | | + | +-- transactional jobs/outbox -+ + | + +--> AuthorizationPort --> Privy policy/wallet + +--> SettlementPort ----> Arc ERC-20 USDC + +--> EvidencePort ------> Privy status + Arc RPC + +--> IndexViewPort -----> The Graph observation ``` -### Person A — Domain, storage, API, and work delivery +OneShot decides whether settlement may be attempted. Privy constrains authorized wallet actions. Arc provides final settlement evidence. The Graph explains indexed history and freshness but grants no settlement right. -Owns `packages/contracts`, `packages/domain`, `packages/storage-postgres`, `apps/api`, `apps/worker`, migrations, OpenAPI, and the domain adapter simulator. Person A does not implement Privy, Arc, or The Graph clients. +## 7. Team topology and exclusive ownership -### Person B — Privy authorization and Arc settlement +### Coder A — domain and orchestration -Owns `packages/privy-adapter`, `packages/arc-adapter`, policy fixtures, Arc chain configuration, transaction construction, receipt verification, provider error classification, and the settlement-adapter simulator. Person B does not change domain states or database tables directly. +Owns: -### Person C — Reconciliation, The Graph, and reliability evidence +- `packages/contracts` +- `packages/domain` +- `packages/storage-postgres` +- `packages/testkit-domain` +- `apps/api` +- `apps/worker` +- root workspace/build configuration after the initial scaffold +- migrations and OpenAPI -Owns `packages/reconciliation`, `packages/graph-client`, `subgraph`, recovery-view contracts, freshness/health classification, and the failure-injection harness. Person C may propose state transitions only through the frozen reconciliation command port. +Coder A never implements provider-specific Privy, Arc, or Graph behavior. -### Shared files and conflict rule +### Coder B — authorization and settlement adapters -- Only Person A edits root workspace/build configuration after Milestone 1. -- Every package must have a package-local test command so Persons B and C can run independently before root composition exists. -- Contract changes are additive during a milestone. Breaking changes require an ADR and all three owners' approval; consumers retain the old form until migration is complete. -- No owner imports another owner's implementation package. Integration happens only through ports and JSON fixtures defined below. +Owns: -## 6. Contract freeze — the mechanism that removes day-to-day blockers +- `packages/privy-adapter` +- `packages/arc-adapter` +- `packages/testkit-settlement` +- Privy policy and official-response fixtures +- Arc network, transaction, and receipt validation +- human-run provider setup documentation -The following semantics are the Milestone 0 contract. Implementation details may vary, but no track may reinterpret them. +Coder B never changes domain tables or state meanings directly. -### 6.1 Create-intent command +### Coder C — reconciliation and indexed recovery -Required input: +Owns: -- `business_intent_id`: caller-supplied UUID/opaque stable ID. -- `recipient`: checksummed or normalized EVM address. -- `amount_atomic`: canonical base-10, non-negative integer string; no signs, decimals, exponent, or leading whitespace. -- `asset`: exactly `USDC`. -- `network`: exactly `eip155:5042002`. -- `purpose`: non-secret, length-bounded human description used only for display/audit. +- `packages/reconciliation` +- `packages/graph-client` +- `packages/testkit-failures` +- `subgraph/` +- recovery-view schemas and queries +- failure matrix orchestration and recovery runbooks -The server computes an immutable payload fingerprint from normalized recipient, amount, asset, network, and purpose. Reusing the ID with the same fingerprint is a replay; reusing it with a different fingerprint is a conflict and never creates another settlement right. +Coder C issues state commands only through the frozen reconciliation command contract. -### 6.2 Public HTTP seam +### Shared-file rule -| Operation | Required behavior | -| --- | --- | -| `POST /v1/intents` | Create or replay an intent; return `202` for accepted, `200` for identical replay, `409` for same-ID conflict, and no external effect in the request transaction | -| `GET /v1/intents/{id}` | Return intent, attempts, settlement state, sanitized evidence, and stable version | -| `POST /v1/intents/{id}/reconcile` | Enqueue/read-trigger reconciliation only; never directly submit settlement | -| `GET /v1/intents/{id}/recovery-view` | Return authoritative local state plus clearly labeled indexed/provider evidence and freshness | -| `GET /health/live` | Process liveness without external dependency claims | -| `GET /health/ready` | Database plus configuration readiness; fail on wrong Arc chain ID or invalid required configuration | - -Every mutation uses service authentication, request-size limits, schema validation, a correlation ID, and rate limiting. API errors use stable machine codes and never expose provider secrets or raw authorization material. +- Coder A is the sole editor of root workspace files, root scripts, OpenAPI, and migrations after scaffold freeze. +- B and C provide package-local manifests, fixtures, and integration notes; A composes them through additive root changes. +- A shared contract change is additive first. Removal occurs only after all consumers have migrated. +- No package imports another owner’s implementation package. Cross-track use occurs through contracts, fixtures, simulators, or published package entry points. -### 6.3 Port result contracts - -| Port | Terminal result families | Required meaning | -| --- | --- | --- | -| `AuthorizationPort.evaluate` | `AUTHORIZED`, `DENIED`, `UNAVAILABLE` | `DENIED` and invalid scope produce zero submission; `UNAVAILABLE` is retryable only before submission | -| `SettlementPort.submit` | `CONFIRMED`, `DEFINITELY_NOT_SUBMITTED`, `POSSIBLY_SUBMITTED` | The adapter must never collapse an ambiguous response into a safe retry | -| `EvidencePort.lookup` | `FINAL_SUCCESS`, `FINAL_REVERT`, `PENDING`, `NOT_FOUND`, `UNAVAILABLE` | `NOT_FOUND` alone cannot authorize a new submission | -| `IndexViewPort.lookup` | evidence plus indexed block, timestamp, deployment, lag, health | Data is explanatory; missing/unhealthy data cannot transition `UNKNOWN` to retryable | +## 8. Independence model -All port requests contain the stable Business Intent ID, immutable payload fingerprint, Arc/USDC identifiers, persisted provider idempotency key, correlation ID, and attempt ID. Simulators must read and emit the same checked JSON fixtures as production adapters. - -### 6.4 Durable state model - -Keep separate records for Business Intent, Attempt, and Settlement. A compact settlement state machine is: - -| Current | Trigger | Next | External submission allowed? | -| --- | --- | --- | --- | -| `NONE` | validated intent accepted | `AUTHORIZING` | No | -| `AUTHORIZING` | Privy policy authorizes | `READY` | No | -| `AUTHORIZING` | policy denies | `REJECTED` | No, terminal | -| `READY` | atomic owner grant persists request identity | `SUBMITTING` | Exactly one owner may cross the boundary | -| `SUBMITTING` | verified final receipt and expected Transfer log | `COMMITTED` | No, terminal | -| `SUBMITTING` | narrow proof of no broadcast | `FAILED_SAFE` | A new attempt may be scheduled by policy | -| `SUBMITTING` | timeout, disconnect, lost response, crash, or doubt | `UNKNOWN` | No | -| `UNKNOWN` | reconciliation finds verified success | `COMMITTED` | No, terminal | -| `UNKNOWN` | reconciliation proves final revert/no settlement with authoritative evidence | `FAILED_SAFE` | Only then may policy schedule a new attempt | -| `UNKNOWN` | pending, not found, lagging, unhealthy, or contradictory evidence | `UNKNOWN` | No; operator attention if deadline exceeded | - -Mandatory storage constraints and records: - -- Primary/unique Business Intent ID plus immutable fingerprint. -- At most one Settlement row per Business Intent; provider transaction hash unique when present. -- N append-only Attempt rows with stage, timestamps, sanitized error class, and correlation ID. -- Persisted Privy idempotency key, reference ID, request fingerprint, wallet ID, recipient, amount, chain, token contract, transaction ID/hash/nonce when learned, receipt block/hash/status, and verified Transfer log identity. -- Compare-and-set state transitions with a monotonically increasing version. No database transaction spans an external network call. -- Transactional outbox/job insertion. Queue delivery and API retries are assumed duplicate and out of order. -- On worker startup, any orphaned `SUBMITTING` record is conservatively moved/treated as `UNKNOWN` for reconciliation; lease expiry never grants a blind resubmission. - -### 6.5 Agreed test seams - -Tests observe behavior through these public seams only: - -1. HTTP API plus returned durable state. -2. Worker task input/output plus durable state and external-submission counter. -3. Adapter ports with official-response fixtures. -4. Reconciliation command plus durable transition and evidence record. -5. Subgraph mappings/GraphQL query plus indexed entity and `_meta` classification. -6. Browser UI through the public API contract in Milestone 5. - -Each implementation ticket uses one red-green vertical slice at a time. Tests must assert both durable state and settlement count; HTTP status alone is insufficient. - -## 7. Milestone overview and dependency graph - -| Milestone | Days | Exit outcome | -| --- | ---: | --- | -| M0 — Contract and safety freeze | 0.5 | This plan, research, ports, fixtures, states, ownership, and test seams accepted | -| M1 — Three independent walking skeletons | 1–4 | Each track runs locally with its own simulator and no cross-track implementation import | -| M2 — Safety-critical vertical slices | 5–8 | Domain concurrency, real policy/transaction adapter, and reconciliation logic pass independently | -| M3 — Failure and operational hardening | 9–12 | Each track passes its assigned fault, restart, and observability evidence | -| M4 — Integrated backend and live testnet proof | 13–15 | All adapters compose; full matrix passes; one real authorized settlement is recorded and indexed | -| M5 — Frontend, last | 16–18 | Minimal intent, status, and recovery UI works against the stable backend | -| M6 — Demo qualification and release candidate | 19–20 | Scripted demo, sponsor evidence, runbooks, and release checks pass | - -```text -A1 -> A2 -> A3 --\ -B1 -> B2 -> B3 ----> M4 integrated backend -> M5 frontend -> M6 demo/release -C1 -> C2 -> C3 --/ -``` +### 8.1 Work-packet closure -There are no cross-person blockers through M3. Each task depends only on the same owner's prior task. M4 is the first convergence dependency; its build work can continue against simulators, but its exit test requires all three artifacts. This is intentional and cannot be removed without pretending integration is optional. +Each file under `milestones/coder-a`, `milestones/coder-b`, or `milestones/coder-c` is an independently closable milestone. A coder closes it when its local acceptance criteria, package checks, handoff artifact, and review requirements pass. Closure never requires another coder’s branch, approval, credentials, service, or unfinished implementation. -## 8. Detailed milestones +### 8.2 Allowed prerequisites -### M0 — Contract and safety freeze (all three, half day) +A work packet may depend only on: -Deliverables: +- the frozen v1 contract pack in `milestones/CONTRACTS.md`; +- committed fixtures or simulators included in that contract pack; +- the same coder’s immediately preceding packet; +- human-provided credentials only for explicitly marked live-evidence checks, with an offline fixture path that still allows packet closure. -- Accept Sections 4–6 as the initial ADR-equivalent contract. -- Create versioned JSON fixtures for identical replay, conflicting replay, authorization denial, confirmed transfer, final revert, pending transaction, lost response, empty Graph result, lagging Graph result, and indexing error. -- Confirm package/file ownership and the no-cross-implementation-import rule. -- Record required environment-variable names in `.env.example` with placeholders only; classify each as secret or public. -- Confirm the six public test seams before any test is written. +Cross-coder artifacts are integration inputs, never closure prerequisites. If a real artifact is unavailable, the consumer uses the versioned simulator and records final live verification under a project gate. -Exit criteria: +### 8.3 No-wait continuation rule -- Each person can run their package tests with local fakes and no credentials. -- Every contract field has one owner, type, normalization rule, and redaction rule. -- No unresolved decision can change settlement cardinality, money representation, or the classification of `UNKNOWN`. +When a coder closes a packet, they immediately begin their next packet. They do not wait for a global milestone meeting. A broken cross-track contract opens a small additive compatibility ticket; it does not freeze unrelated work. -### M1 — Three independent walking skeletons (days 1–4) +### 8.4 Contract packs -#### A1 — Durable intent skeleton (Person A; blockers: M0 only) +Every producer publishes a package-local contract pack containing: -What it delivers: an intent can be accepted, replayed, queried, queued, and observed end to end using fake authorization/settlement ports. +- version and compatibility range; +- TypeScript types or JSON Schema; +- one happy-path fixture and every relevant terminal/error fixture; +- deterministic simulator; +- package-local verification command; +- redaction statement; +- short migration note for additive changes. -Work: +Consumers validate against the pack, not against a producer’s active branch. -- Create the workspace, strict compiler/lint/test/build commands, API/worker entry points, OpenAPI validation, and package-local commands. -- Add PostgreSQL migrations for intents, attempts, settlements, outbox/jobs, evidence, and schema versioning. -- Implement normalized fingerprinting, create/replay/conflict behavior, GET status, atomic state transitions, and a fake adapter with an external-settlement counter. -- Add containerized PostgreSQL test support and deterministic clock/ID seams. +### 8.5 Async communication -Acceptance: +- Each PR description is the handoff record: outcome, immutable contract version, commands, evidence, risks, and safe-disable behavior. +- Questions default to a written assumption plus a fail-closed implementation. Only decisions that could weaken settlement cardinality, money representation, authorization, or `UNKNOWN` handling require synchronous escalation. +- Daily status is informational and never an approval gate. -- Identical request twice returns the same Business Intent and one queued execution. -- Conflicting payload under the same ID returns `409`, records the conflict safely, and creates zero extra settlement rights. -- State survives API and worker restarts. -- Package tests prove constraints using a real PostgreSQL transaction, not only mocks. +## 9. Delivery waves -#### B1 — Privy/Arc adapter skeleton (Person B; blockers: M0 only) +| Wave | Days | A | B | C | Project gate | +| --- | ---: | --- | --- | --- | --- | +| W0 | 0 | Read frozen pack; branch | Read frozen pack; branch | Read frozen pack; branch | P0 plan/contract approval | +| W1 | 1–4 | A01 | B01 | C01 | Independent toolchains runnable | +| W2 | 4–7 | A02 | B02 | C02 | Contract packs v1 emitted | +| W3 | 7–10 | A03 | B03 | C03 | Safety behavior proven independently | +| W4 | 10–14 | A04 | B04 | C04 | P4 backend convergence and live proof | +| W5 | 15–18 | A05 | B05 | C05 | P5 frontend acceptance | +| W6 | 18–20 | A06 | B06 | C06 | P6 release candidate | -What it delivers: a standalone adapter can validate configuration, build exactly one canonical ERC-20 transfer request, classify official-response fixtures, and verify receipts without a real domain service. +Dates are forecasts, not permission to cut safety. Each coder may move to the next packet as soon as their current packet closes. -Work: +## 10. Work-packet inventory -- Pin and validate the Privy Node SDK plus Arc client library in a package-local compatibility test. -- Define Arc Testnet configuration and readiness checks for chain ID, USDC contract code, wallet address, and amount precision. -- Build six-decimal ERC-20 transfer calldata and the Privy request with stable idempotency/reference identifiers. -- Implement receipt verification: chain, sender, token contract, status, recipient, amount, transaction hash, block, and unique Transfer log. -- Draft the fail-closed Privy wallet policy fixture; do not store credentials. +| ID | Owner | Estimate | Own-track prerequisite | Independently verifiable output | +| --- | --- | ---: | --- | --- | +| [A01](milestones/coder-a/A01-foundation-contracts.md) | A | 3 d | Frozen contract pack | Workspace, contracts package, OpenAPI, domain simulator | +| [A02](milestones/coder-a/A02-durable-intents.md) | A | 3 d | A01 | PostgreSQL intent/replay/conflict API | +| [A03](milestones/coder-a/A03-atomic-worker.md) | A | 3 d | A02 | Atomic worker and at-most-once fake-port proof | +| [A04](milestones/coder-a/A04-restart-operations-composition.md) | A | 4 d | A03 | Restart-safe orchestration and simulator composition | +| [A05](milestones/coder-a/A05-frontend-intent-status.md) | A | 2 d | A04 + project Gate P4 | Intent/status frontend slice against mock server | +| [A06](milestones/coder-a/A06-release-operations.md) | A | 2 d | A05 | Operational demo and release bundle | +| [B01](milestones/coder-b/B01-sdk-network-compatibility.md) | B | 3 d | Frozen contract pack | SDK/network compatibility and readiness package | +| [B02](milestones/coder-b/B02-request-policy-receipt.md) | B | 3 d | B01 | Canonical request, policy, and receipt verifier | +| [B03](milestones/coder-b/B03-live-settlement-harness.md) | B | 3 d | B02 | Offline-complete plus live-ready settlement harness | +| [B04](milestones/coder-b/B04-ambiguity-integration.md) | B | 4 d | B03 | Conservative outcomes and production adapter pack | +| [B05](milestones/coder-b/B05-frontend-settlement-details.md) | B | 2 d | B04 + project Gate P4 | Authorization/settlement UI slice against fixtures | +| [B06](milestones/coder-b/B06-sponsor-evidence.md) | B | 2 d | B05 | Privy/Arc sanitized evidence bundle | +| [C01](milestones/coder-c/C01-subgraph-index-health.md) | C | 3 d | Frozen contract pack | Subgraph mappings and Graph health client | +| [C02](milestones/coder-c/C02-reconciliation-engine.md) | C | 3 d | C01 | Deterministic reconciliation and evidence contract | +| [C03](milestones/coder-c/C03-failure-injection.md) | C | 3 d | C02 | Cross-source chaos and restart harness | +| [C04](milestones/coder-c/C04-recovery-matrix-integration.md) | C | 4 d | C03 | Recovery matrix and simulator integration pack | +| [C05](milestones/coder-c/C05-frontend-recovery.md) | C | 2 d | C04 + project Gate P4 | Recovery timeline UI slice against fixtures | +| [C06](milestones/coder-c/C06-qualification-demo.md) | C | 2 d | C05 | Graph/recovery qualification bundle | -Acceptance: +Each packet contains smaller, one-commit-sized tasks, exact acceptance criteria, tests, output artifacts, and a no-wait continuation instruction. -- Golden fixtures produce byte-for-byte stable request fingerprints and calldata. -- Wrong chain, token, recipient, amount format, or native value is rejected before signing. -- `status: 1` without the expected Transfer log is not `CONFIRMED`; `status: 0` is final revert. -- Timeout/lost-response fixtures return `POSSIBLY_SUBMITTED`, never safe retry. +## 11. Dependency graph -#### C1 — Indexed recovery skeleton (Person C; blockers: M0 only) - -What it delivers: a standalone Subgraph and recovery package map Arc USDC Transfer fixtures and expose a freshness-labeled recovery view against a fake domain/evidence host. - -Work: - -- Create Subgraph schema, manifest, mapping, and Matchstick/unit fixtures for the Arc USDC contract. -- Create the Graph client query including `_meta`, deployment, block, timestamp, and indexing errors. -- Implement freshness states: `FRESH`, `LAGGING`, `UNHEALTHY`, `UNAVAILABLE`, `UNKNOWN_FRESHNESS`. -- Create the reconciliation decision table and a simulator for local state, Privy evidence, Arc receipts, and indexed evidence. - -Acceptance: - -- Mapping identity is transaction hash plus log index; amount remains Graph `BigInt`/decimal string. -- Empty or lagging Graph fixtures never return permission to resubmit. -- Recovery output labels which facts are authoritative and which are indexed observations. -- Package tests run with no network or credentials. +```text +Frozen v1 contract pack + |--------------------|--------------------| + v v v + A01 -> A02 -> A03 -> A04 A05 -> A06 + B01 -> B02 -> B03 -> B04 -- P4 backend -> B05 -> B06 + C01 -> C02 -> C03 -> C04 gate C05 -> C06 + | + real adapters replace simulators +``` -M1 exit: all three package suites pass independently. Re-estimate M2–M6 from actual SDK, chain, and Subgraph friction; do not reduce safety acceptance to preserve the date. +The lane arrows are same-owner dependencies. Gate P4 is the only intentional convergence point before frontend. No backend work packet waits for P4 to close; A04/B04/C04 close against their own contract simulators. P4 only decides whether frontend may begin. -### M2 — Safety-critical vertical slices (days 5–8) +## 12. Project gates -#### A2 — Atomic at-most-once engine (Person A; blockers: A1 only) +Project gates coordinate the product but are not coder work-packet closure conditions. -What it delivers: duplicate deliveries and concurrent workers converge on one submission owner and at most one committed settlement in the fake-adapter system. +### P0 — plan and contract approval -Work and acceptance: +- Human accepts the product scope, v1 state machine, port semantics, ownership, fixture catalog, and test seams. +- The plan commit is present on the chosen implementation base. +- Each coder creates a worktree/branch from the same base SHA. -- Implement transactional authorization-to-ready and ready-to-submitting compare-and-set transitions. -- Configure `submit_settlement` with one queue attempt and catch/classify all adapter results into durable states before returning. -- Prove one normal job, 10 sequential retries, 10 parallel workers, and two worker/agent instances produce exactly one external submission/commit. -- Kill before external call: zero settlement and safe retry. Kill after the boundary: durable `UNKNOWN` and no new submission. -- Preserve a committed Settlement when a downstream/supplier simulation fails. +### P1 — independent toolchains -#### B2 — Authorized Arc Testnet settlement (Person B; blockers: B1 only) +- A01, B01, and C01 each pass package-local checks without third-party credentials. +- Every lane can continue using only committed fixtures and simulators. +- Forecast is recalibrated from actual SDK/tooling friction. -What it delivers: the adapter executes one policy-constrained testnet USDC settlement from the standalone harness and returns verified normalized evidence. +### P2 — contract-pack compatibility -Work and acceptance: +- A02, B02, and C02 contract packs validate against the frozen schemas. +- Drift checks show no breaking change. +- Any additive extension has a compatibility note and old fixture support. -- Provision the execution wallet, owner/key quorum, and one attached policy through a human-run setup procedure; write secrets only to ignored runtime storage/approved CI secrets. -- Test policy allow and deny cases against Arc Testnet: wrong chain, wrong contract/method, wrong recipient, above cap, non-zero native value, expired authorization. -- Submit via Privy with `eip155:5042002`, persisted idempotency key, and stable reference ID; capture Privy transaction ID/hash and Arc receipt. -- Prove one allowed transfer commits once and every denial produces zero settlement. -- Produce sanitized fixtures from real response shapes for Person A and C without exposing secrets. +### P3 — independent safety proofs -#### C2 — UNKNOWN reconciliation engine (Person C; blockers: C1 only) +- A03 proves atomic submission ownership with a fake counter. +- B03 proves conservative provider outcomes offline and is ready for human-enabled testnet evidence. +- C03 proves missing, lagging, contradictory, and unavailable evidence cannot unlock payment. -What it delivers: a deterministic read-only reconciliation decision engine resolves authoritative evidence or holds safely without ever submitting a payment. +### P4 — backend convergence and live proof -Work and acceptance: +This is the frontend unlock gate. -- Implement evidence precedence: durable committed record and verified Arc receipt are authoritative; Privy status locates provider activity; Graph corroborates/history only. -- Resolve verified receipt success to `COMMITTED` and final revert with matching identity to `FAILED_SAFE`. -- Keep `UNKNOWN` for pending, provider unavailable, RPC unavailable, Graph empty/lagging/unhealthy, identity mismatch, or contradictory evidence. -- Persist every observation with source, retrieval time, block height, health, and sanitized reason. -- Prove repeated reconciliation and duplicate webhook/provider events are idempotent and create zero submissions. +- A composition branch replaces simulators with reviewed B and C package entry points. +- Root lint, type, unit, integration, contract, build, migration, concurrency, restart, and failure checks pass. +- The complete `.agent/TEST_MATRIX.md` records durable final state and external settlement count. +- One real allowed Arc Testnet payment commits exactly once through Privy. +- Wrong-scope and above-cap cases produce zero settlement. +- A lost-response scenario reaches `UNKNOWN` and reconciles to the original transaction without a duplicate. +- Live Graph evidence is shown with `_meta`, deployment, indexed block, lag, and health. +- OpenAPI and recovery-view semantics are frozen for frontend. -### M3 — Failure and operational hardening (days 9–12) +### P5 — frontend acceptance -#### A3 — Restart-safe orchestration and auditability (Person A; blockers: A2 only) +- A05, B05, and C05 compose against the frozen API. +- Browser tests cover create, replay, conflict, denial, committed, `UNKNOWN`, reconciliation, Graph lag/error, and service-unavailable states. +- No force-pay or unguarded settlement action exists. +- Accessibility smoke, responsive layout, lint, type, build, and no-secret checks pass. -What it delivers: the API/worker system recovers after process/database interruptions, exposes useful safe telemetry, and has a deterministic safe-disable path. +### P6 — release candidate -Acceptance: +- A06, B06, and C06 evidence bundles compose into one repeatable testnet demo. +- Sponsor qualification cites working code, tests, live evidence, network, and limitations. +- Safe-disable and recovery runbooks work without manual database surgery. +- Exact candidate tree passes repository checks and mandatory independent review gates before human merge. -- Restart after intent creation, job claim, `SUBMITTING` persistence, and adapter return; invariant holds at every point. -- Stale/orphaned work becomes reconciliation work, not a new submission lease. -- Structured logs carry Business Intent/Attempt IDs and state transitions but redact payload purpose as configured and never include credentials, authorization signatures, raw provider bodies, or private wallet material. -- Metrics cover state counts, transition failures, queue lag, UNKNOWN age, reconciliation outcomes, policy denials, and duplicate/conflict counts. -- A kill switch stops new submissions while status and reconciliation reads remain available. +## 13. Test ownership -#### B3 — Provider ambiguity and policy hardening (Person B; blockers: B2 only) +| Required case | Producer | Independent local proof | Project-gate proof | +| --- | --- | --- | --- | +| Normal job | A | Domain fake settlement counter | P4 real adapter | +| Same request twice | A | HTTP + PostgreSQL | P4 composed worker | +| Conflicting payload, same ID | A | HTTP + PostgreSQL | P4 recovery view | +| 10 sequential retries | A | Worker + fake port | P4 adapter call count | +| 10 parallel workers | A | Real PostgreSQL concurrency | P4 composed worker | +| Crash before submission | A | Worker kill point | P4 zero external settlement | +| Crash after possible submission | B | Adapter fault fixture | P4 durable `UNKNOWN` | +| Lost payment response | B | Proxy/fixture | P4 original transaction reconciled | +| Graph delay/absence/error | C | Graph simulator | P4 no submission grant | +| Privy denial/above cap | B | Policy fixture/live-ready harness | P4 zero settlement | +| Service restart | A | Process orchestration | P4 evidence durability | +| Downstream failure after payment | A | Supplier fake | P4 original receipt retained | +| Two agent instances | A | Two processes + fake counter | P4 single settlement history | -What it delivers: provider/RPC outcomes are conservatively classified across realistic failures and the policy remains effective after restart/config changes. +## 14. Frontend-last rule -Acceptance: +No production frontend implementation begins before Gate P4. Prior to P4, coders may only define JSON fixtures, OpenAPI examples, and non-production mock-server behavior needed to test backend contracts. They may not build screens, components, styling, or browser flows. -- Inject DNS failure, connection refusal, timeout before response, truncated response, 429/5xx, malformed payload, lost success response, pending/evicted transaction, final revert, and mismatched receipt. -- Only documented, proven pre-broadcast failures become `DEFINITELY_NOT_SUBMITTED`; every doubtful result becomes `POSSIBLY_SUBMITTED`. -- Reusing the persisted Privy idempotency key and identical body is tested; its 24-hour limit is documented and never treated as permanent protection. -- Policy fingerprint/ID and expected restrictions are checked at readiness; mismatch fails closed. -- If webhooks are available, signature verification and duplicate/out-of-order delivery tests pass; otherwise polling remains complete and webhooks stay disabled. +After P4, the three frontend packets remain independent: -#### C3 — Indexer lag, contradiction, and chaos evidence (Person C; blockers: C2 only) +- A05 owns application shell, create/replay/conflict, and authoritative status. +- B05 owns policy, authorization, transaction, and explorer details. +- C05 owns recovery timeline, evidence provenance, Graph freshness, and escalation. -What it delivers: recovery remains safe when The Graph or other evidence sources are delayed, empty, unhealthy, inconsistent, or unavailable. +Each slice is built against the frozen mock server. Final composition is a project gate, not a packet closure requirement. -Acceptance: +## 15. Branch and merge strategy -- Delay and empty The Graph results, set `hasIndexingErrors`, trail chain head, remove `_meta`, fail the query, and return duplicate/out-of-order events; none unlock a payment. -- Inject crash/lost response after possible submission and show the record remains `UNKNOWN` until authoritative evidence resolves it. -- Verify recovery evidence survives service restart and can be replayed for audit without provider secrets. -- Define UNKNOWN-age alerts and a human escalation runbook; the runbook never tells an operator to “just retry.” -- Produce a single command that runs the cross-source fixture matrix against the reconciliation package. +- One packet equals one short-lived branch and focused PR, for example `milestone/a01-foundation-contracts`. +- Branch from the recorded implementation-base SHA. A coder’s next branch may start from their own previous approved packet without waiting for unrelated lanes. +- Never mix two owners’ directories in one packet PR. +- Contract changes use expand-migrate-contract: add new form, retain old form, migrate consumers independently, then remove old form in a separate task. +- Coder A owns root composition and resolves shared/root conflicts. B and C never edit root files simply to make local tooling work; they use package-local commands. +- Each implementation change follows `.agent/IMPLEMENTATION_LOOP.md`. Agents do not merge PRs. -M3 exit: each owner passes their package suite and provides a versioned artifact plus fixtures. No cross-track package implementation is required to reach this exit. +## 16. Human-only external configuration -### M4 — Integrated backend and live testnet proof (days 13–15) +Coder B produces a repeatable setup guide or wizard, but a human performs Privy application/wallet/key-quorum/policy creation, Arc testnet funding, Graph Studio credential entry, and CI-secret configuration. -This is the first cross-track convergence. Each person prepares against simulators immediately; only the final acceptance run waits for all three M3 artifacts. +- Secret input is hidden and written only to ignored runtime files or approved secret stores. +- Public network, contract, deployment, and policy identifiers are separated from secrets. +- Policy replacement, ownership change, funding, deployment, or other external mutation requires explicit confirmation. +- Offline fixtures keep all coder packets closable when credentials or services are unavailable. +- Agents never paste secrets into context records, reviews, logs, fixtures, or PRs. -#### A4 — Composition and migration integration (Person A) +## 17. Observability and operations -- Wire production ports without importing provider details into the domain package. -- Run migrations from an empty database and from the previous schema; verify rollback/safe-disable behavior. -- Validate OpenAPI, generated contract fixtures, root lint/type/test/build, and service readiness. -- Own conflict resolution only in shared/root files; provider owners resolve their packages. +- Correlation fields: Business Intent ID, Attempt ID, settlement version, Privy reference/transaction ID, Arc transaction hash, and Graph deployment/indexed block. +- Never log signatures, credentials, private keys, raw authorization bodies, or private wallet material. +- Metrics: intent states, oldest/count `UNKNOWN`, transition conflicts, queue lag, reconciliation outcomes, policy denials, provider/RPC errors, Graph lag/health, duplicate and conflict counts. +- Safe disable stops new submission ownership while preserving status, evidence ingestion, and reconciliation reads. +- Operators inspect durable identity and evidence. There is no generic retry or force-pay button. -#### B4 — Live authorization/settlement evidence (Person B) +## 18. Risk controls -- Run one allowed Arc Testnet transfer through the integrated worker. -- Run policy-denied and above-cap intents and prove zero settlement. -- Capture sanitized transaction ID/hash, receipt, expected Transfer log, chain, policy identity, and explorer link for demo evidence. -- Trace an intentionally lost local response into `UNKNOWN` without permitting a second transaction. +| Risk | Fail-closed mitigation | Owner | +| --- | --- | --- | +| Privy idempotency expires | PostgreSQL uniqueness remains authoritative; reuse stored key/body only as supplemental guard | A/B | +| SDK or policy syntax changes | B01 pins after compatibility proof; readiness validates policy identity and network | B | +| ERC-20/native precision confusion | Six-decimal ERC-20 is the only settlement amount; native balance is gas only | B/C | +| Lost response after broadcast | Persist identity first, enter `UNKNOWN`, reconcile, forbid another payment | All | +| Pending/evicted Arc transaction | Hold `UNKNOWN`; no automatic replacement in v1 | B/C | +| Graph lag/error/empty result | Surface freshness and health; never infer non-payment | C | +| Queue redelivery | Domain CAS/constraints plus single-attempt submission task | A | +| Shared-file conflicts | Exclusive path ownership and A-only root composition | A | +| Credentials unavailable | Offline contract packs and simulators remain sufficient for packet closure | B | +| Schedule pressure | Cut webhooks, rolling policy support, visual polish, and optional telemetry before safety | All | + +## 19. Definition of done for every packet + +- Scope, non-goals, consumed contract version, and acceptance criteria are explicit. +- The smallest public-seam test is written first and passes with the implementation. +- Package-local format, lint, type, test, and build commands pass where present. +- Payment/retry work asserts durable state and external settlement count. +- Boundary validation, integer money, redaction, testnet restriction, and safe-disable impact are covered. +- Contract pack, fixtures, simulator, docs, and `.env.example` are updated when applicable, without secrets. +- No unrelated owner path or shared root file is changed. +- The packet handoff lists exact artifact/version, commands, evidence, residual risks, and next same-owner packet. +- Repository FreePi/CI/human-review policy is satisfied. Agents never merge. + +## 20. Packet-to-outcome traceability + +| Packet | Primary product outcome | Principal proof | +| --- | --- | --- | +| A01 | Stable public seams and deterministic local development | Contract/schema drift and simulator tests | +| A02 | Durable create, replay, conflict, and status behavior | Real PostgreSQL API tests | +| A03 | One submission owner under redelivery/concurrency | Ten-worker/two-process counter proof | +| A04 | Restart-safe, operable backend composition | Restart matrix, safe disable, simulator root suite | +| A05 | Safe intent creation and authoritative status UI | Frozen-mock browser/accessibility tests | +| A06 | Repeatable invariant and operations demo | Clean bootstrap plus scenario result table | +| B01 | Known-compatible provider/network boundary | SDK spike and fail-closed readiness tests | +| B02 | Exact request/policy/receipt semantics | Golden calldata, deny matrix, receipt corpus | +| B03 | Testnet-capable policy-constrained settlement | Offline harness plus optional sanitized live proof | +| B04 | Conservative handling of provider ambiguity | Fault taxonomy and lookup contract suite | +| B05 | Safe authorization/transaction UI | Fixture-driven component and redaction tests | +| B06 | Verifiable Privy/Arc sponsor evidence | Policy denial and real transfer evidence bundle | +| C01 | Correct Arc transfer indexing and visible freshness | Mapping and Graph-health fixture tests | +| C02 | Deterministic zero-submit reconciliation | Complete evidence/decision matrix | +| C03 | Safety under loss, lag, contradiction, and restart | Seeded failure-injection suite | +| C04 | Recovery service ready for real adapter replacement | Simulator composition and matrix report | +| C05 | Accurate recovery/index UI | Degraded-evidence component tests | +| C06 | Verifiable Graph/recovery sponsor evidence | Live health, degraded demo, qualification report | + +Every success criterion in Section 3 has at least two independent proof surfaces: a producer packet and a later project-gate verification. Packet closure establishes the producer proof; it never claims final integrated behavior by itself. + +## 21. Execution environments -#### C4 — Integrated reconciliation and matrix (Person C) +### Offline contract mode -- Reconcile the lost-response scenario to the original final transaction using durable/Privy/Arc evidence. -- Demonstrate live Subgraph history with `_meta`, then simulate lag/empty/error and show safe behavior. -- Run the full `.agent/TEST_MATRIX.md` suite and publish a sanitized results table with durable state and external settlement count. -- Verify alerts and recovery-view output distinguish authoritative and indexed evidence. +Purpose: default mode for every coder packet. -M4 exit criteria: +- Uses synthetic, versioned, schema-checked fixtures only. +- Requires no Privy, Arc, Graph, or secret configuration. +- Runs package-local checks and deterministic simulators. +- Is sufficient to close A01–A04, B01–B04, and C01–C04. +- Cannot support sponsor qualification or real-settlement claims. -- All lint, static analysis, type, unit, integration, contract, build, migration, and focused failure-injection checks pass from the repository root. -- Every required test-matrix row records stable ID, final durable state, and external settlement count. -- Real testnet happy path has exactly one committed settlement; denial paths have zero; ambiguous path has no duplicate. -- Backend API/OpenAPI and recovery semantics are frozen for the frontend. Breaking changes after this point use expand-migrate-contract. +### Local integration mode -### M5 — Frontend, last (days 16–18) +Purpose: compose reviewed packages with PostgreSQL and local services before external effects. -Frontend work starts only after M4 passes. All three slices use the frozen OpenAPI and mock server, so component work remains parallel. +- Uses real PostgreSQL and Graphile Worker. +- Replaces provider/Graph network access with simulators. +- Runs migrations, API/worker orchestration, concurrency, restart, failure, and recovery suites. +- Remains the fallback when external providers are unavailable. -#### F-A — Intent shell and status (Person A) +### Testnet evidence mode + +Purpose: Gate P4 and P6 live proof. -- App shell, service-auth handoff suitable for the demo environment, create-intent form, exact atomic-amount parsing/formatting, and status polling. -- Show replay and same-ID conflict clearly; never generate a new Business Intent ID on a retry unless the user starts a genuinely new obligation. -- Display only USDC, Arc Testnet, and six payment decimals; keep native gas details separate. +- Requires human-approved Privy/Arc/Graph configuration in ignored/approved secret stores. +- Checks Arc chain/token/policy/deployment identities before running. +- Limits settlement to an approved recipient and cap. +- Produces sanitized public identifiers and result tables only. +- Stops new submission work on configuration mismatch or doubt. -#### F-B — Authorization and settlement details (Person B) +### Frontend mock mode -- Policy scope summary, authorization denied state, submission/pending/final state, sanitized transaction details, and Arc explorer link. -- No bypass button and no “force pay” action. `UNKNOWN` disables new settlement submission. -- Do not show a confirmation counter: Arc is pending or final. +Purpose: independently close A05/B05/C05. -#### F-C — Recovery timeline and indexed history (Person C) +- Uses the P4-frozen OpenAPI and sanitized response fixtures. +- Simulates every authoritative, provider, and Graph state. +- Contains no provider credentials or direct settlement capability. +- Must behave identically to production UI for state labeling and disabled actions. -- Attempt/reconciliation timeline, authoritative local state, Privy/Arc evidence, Graph observations, indexed-through block/time, lag, and health. -- Empty Graph data is labeled “not observed through block N,” never “not paid.” -- UNKNOWN state provides safe explanation/escalation, not a retry shortcut. +## 22. Gate P4 integration procedure -M5 exit criteria: +P4 is deliberately procedural so convergence does not turn into open-ended shared development. -- Browser tests cover create, identical replay, conflict, denial, committed, UNKNOWN, reconciliation, Graph lag/error, and service-unavailable paths. -- Accessibility smoke tests, responsive layout, lint/type/build, and no-secret/source-map checks pass. -- The UI cannot invoke an unguarded settlement path. +1. Record exact reviewed A04, B04, and C04 package versions and tree SHAs. +2. Coder A creates the single composition branch from the approved integration base. +3. Replace the settlement simulator with B04’s public package entry point; run contract compatibility before any live call. +4. Replace the recovery/index simulators with C04 public entry points; run command/evidence compatibility. +5. Run offline root checks first. A contract mismatch stops composition and opens one owner-specific compatibility ticket. +6. Run empty and upgrade migrations, API/worker boot, readiness, and safe-disable checks. +7. Run the complete local failure matrix with real packages but simulated external services. +8. A human enables testnet evidence mode and confirms network, token, wallet, policy, recipient, cap, funding, and Graph deployment. +9. Execute one allowed intent and bind durable identity, Privy identity, Arc receipt/Transfer, and indexed observation. +10. Execute wrong-scope and above-cap denials; confirm zero settlements. +11. Inject a lost local response after possible broadcast; confirm durable `UNKNOWN`, zero replacement transaction, and reconciliation to original evidence. +12. Simulate empty, lagging, unhealthy, unavailable, and contradictory Graph results; confirm no permission change. +13. Publish a sanitized Gate P4 manifest and freeze OpenAPI/recovery-view semantics. -### M6 — Demo qualification and release candidate (days 19–20) +P4 failures never produce ad hoc edits by multiple coders on the composition branch. The owning coder fixes their package in a focused branch, republishes a reviewed version, and A updates only the version slot. -#### Person A — Invariant and operational demo +## 23. Asynchronous merge-conflict prevention -- Script duplicate requests, 10 parallel workers, restart, lost response, and downstream failure; show durable states and settlement count. -- Verify clean database bootstrap, safe-disable switch, logs/metrics, README, architecture diagram, and operator runbook. +### Path-level controls -#### Person B — Privy and Arc evidence +- A owns root package manager files, shared compiler/lint/test configuration, OpenAPI, migrations, API, worker, contracts, and domain/storage packages. +- B owns only provider/chain adapter packages, provider fixtures, and human provider setup docs. +- C owns only reconciliation/Graph/failure packages, Subgraph files, and recovery docs. +- Frontend composition reserves one shell/route registry editor; B/C expose components through documented entry points instead of editing the registry concurrently. -- Demonstrate policy-constrained corporate wallet execution, one real authorized USDC transfer on Arc Testnet, and zero-settlement denials. -- Record sanitized policy scope, transaction/receipt/Transfer proof, network, explorer URL, and limitations. +### Commit controls -#### Person C — The Graph and recovery evidence +- One small task normally maps to one commit; do not combine unrelated numbered tasks merely to reduce PR count. +- Generated files stay in the same commit as their source and drift check. +- Formatting-only repo-wide rewrites are separate, human-scheduled changes, never hidden in a packet. +- A packet branch contains no merge from another active packet branch. Rebase/merge decisions follow human repository policy. -- Demonstrate live indexed Arc data in the recovery view and the same flow under delayed/empty/unhealthy indexed data. -- Run sponsor qualification against working code/tests/demo evidence and report each sponsor `QUALIFIED`, `NOT QUALIFIED`, or `NOT VERIFIED`; never promote missing evidence. +### Contract controls -Release-candidate exit: +- Published fixture/schema digests are immutable. +- Consumers pin a digest/version rather than a moving branch. +- New optional fields have deterministic default handling that fails closed. +- New enum variants are rejected until explicitly supported. +- Removal/deprecation never occurs in the same wave as introduction. -- Full test matrix and root checks pass on the exact candidate content. -- Secret scan and intended-file review pass; `.env*`, credentials, wallet material, and authorization responses are absent from review inputs. -- Each implementation change follows `.agent/IMPLEMENTATION_LOOP.md`: local checks, a fresh FreePi Gate A, draft PR to `develop`, green required CI, a separate fresh Gate B, then human review. Agents never merge. -- Demo can be reset and repeated using testnet-only funds without manual database surgery. +## 24. Decision and escalation policy -## 9. Test ownership matrix +Continue asynchronously with a documented conservative assumption for ordinary implementation details. Stop and request a human/product decision only when the choice could change: -| Required case | Primary owner | Independent harness | Integrated verifier | -| --- | --- | --- | --- | -| Normal job | A | Fake settlement counter | B | -| Same request twice / conflicting payload | A | HTTP + PostgreSQL | C observes recovery output | -| 10 sequential retries | A | Worker + fake port | B validates one adapter call | -| 10 parallel workers | A | Real PostgreSQL concurrency | C captures evidence timeline | -| Crash before submission | A | Worker kill point | B proves zero call | -| Crash after possible submission | B | Adapter fault point | C reconciles; A verifies state | -| Lost payment response | B | Proxy/fixture fault | C resolves original transaction | -| Graph delay or absence | C | Graph simulator | A verifies no submission grant | -| Privy denial / above policy | B | Policy testnet harness | A verifies zero settlement | -| Service restart | A | Process orchestration | C verifies evidence durability | -| Downstream failure after payment | A | Supplier fake | B verifies original receipt retained | -| Two agent instances | A | Two workers/processes | C verifies one settlement history | +- the one-intent/at-most-one-settlement invariant; +- stable Business Intent identity or payload-conflict semantics; +- monetary precision or canonical amount representation; +- which state grants submission ownership; +- when `UNKNOWN` may transition to `FAILED_SAFE`; +- Privy policy scope or bypass availability; +- Arc network/token identity; +- The Graph’s non-authoritative role; +- use of non-testnet funds or irreversible external configuration; +- public API breaking compatibility after P4. -The primary owner builds the failure fixture and focused proof. Integrated verification is a Milestone 4 responsibility, not a prerequisite for the owner to finish M1–M3. +An escalation record contains the exact decision, safest default, affected contract/version, options, security impact, and owner. While it is unresolved, unaffected packets continue and the affected boundary fails closed. -## 10. Branching, review, and merge train +## 25. Schedule control and scope-cut order -- Do not implement product code on `agents-setup`, `develop`, or `main`. Once this planning/infrastructure change is human-merged to `develop`, create short-lived `milestone/a-*`, `milestone/b-*`, and `milestone/c-*` branches from the same `develop` SHA. -- One branch/PR delivers one task above. Within M1–M3, each branch is blocked only by the prior branch in the same lettered track. -- Merge independent package PRs before root composition. If two changes touch a shared contract, use expand-migrate-contract: add the new form, migrate all consumers in independent PRs, then remove the old form. -- Only Person A edits root composition files during M4. Persons B/C supply reviewed package commits and fixtures, preventing three-way conflicts. -- Every PR lists exact blockers, acceptance evidence, selected test-matrix cases, invariant impact, safe-disable strategy, and both required review gates. -- A human controls merge order and performs every merge. +The 20-day horizon is a forecast. Re-estimate at P1 and after any provider compatibility failure. Never change acceptance evidence silently to preserve dates. -## 11. Human-only configuration plan +If time is constrained, cut in this order: -Person B owns a repeatable interactive setup wizard after B1 fixes the variable contract. It must guide a human through Privy application/wallet/key-quorum/policy creation, Arc testnet funding, The Graph Studio deployment credentials, and CI secret entry. It must: +1. Optional Privy webhooks; retain complete polling. +2. Rolling/multiple policy support; retain one explicit policy. +3. Nonessential dashboard panels and telemetry dimensions; retain safety alerts. +4. Visual animation, theming, and secondary responsive polish; retain accessible core flows. +5. Extra demo narratives; retain invariant, authorization, settlement, `UNKNOWN`, and Graph-degradation proof. -- Open current official URLs before each instruction. -- Capture secrets with hidden input and write them only to ignored `.env` or approved CI secrets. -- Keep public chain/contract/deployment identifiers in non-secret variables. -- Confirm before policy replacement, wallet ownership change, funding, deployment, or any irreversible action. -- Be statically validated but never run end to end by an agent without the human. +Never cut: -The backend must still boot in fake/local mode with no third-party credentials, so configuration work never blocks Persons A or C. +- durable constraints and atomic submission ownership; +- ambiguity classification and reconciliation; +- denial/zero-settlement proof; +- concurrency, restart, and lost-response tests; +- exact Arc receipt/Transfer verification; +- Graph freshness/health labeling and non-authority; +- secret/redaction checks; +- independent review and human merge controls. -## 12. Observability and safe operation +## 26. Evidence manifest format -- Correlation keys: Business Intent ID, Attempt ID, settlement version, Privy reference/transaction ID, Arc transaction hash, and Graph deployment/indexed block. Never log authorization signatures, credentials, private keys, or raw sensitive payloads. -- Alerts: oldest UNKNOWN age, count of UNKNOWN intents, repeated reconciliation failures, Graph block lag/health, policy denials, provider/RPC failure rate, queue lag, and state-transition conflicts. -- Safe disable: stop accepting/claiming new settlement submissions while keeping GET status, evidence ingestion, and reconciliation reads operational. -- Manual escalation: operators inspect durable request identity and evidence; there is no generic retry button. Any future override requires a separate audited design and is outside this plan. +Every packet and project gate publishes a concise Markdown or JSON manifest with: -## 13. Risks and mitigations +```text +artifact_id: +artifact_version: +source_commit: +source_tree: +contract_versions: +environment: offline | local-integration | testnet | frontend-mock +commands: +acceptance: +external_effect_count: +secrets_review: PASS | FAIL +known_gaps: +next_owner_packet: +``` -| Risk | Mitigation / fail-closed response | Owner | -| --- | --- | --- | -| Privy idempotency expires after 24 hours | Durable OneShot constraint remains authoritative; reuse stored key/body only as supplemental protection | A/B | -| SDK or policy syntax changes | Pin after B1 compatibility test; readiness verifies policy ID/fingerprint and network; deny on mismatch | B | -| Arc native/ERC-20 precision confusion or double counting | Settlement uses six-decimal ERC-20 only; native balance is gas; verify one canonical Transfer identity | B/C | -| Lost response or process crash after broadcast | Persist request identity before call, enter UNKNOWN, reconcile, forbid new nonce/payment | All | -| Arc transaction pending/evicted with no receipt | Hold UNKNOWN; no automatic replacement in v1; escalate after threshold | B/C | -| Graph lag, error, endpoint version drift, or empty result | Query `_meta`, compare chain head, pin deployment for demo, label stale/unhealthy, never authorize from absence | C | -| Queue redelivery | One queue attempt for submission, domain CAS/unique constraints, idempotent reconciliation | A | -| Shared-file merge conflicts | File ownership plus independent package commands; root composition owned by A | A | -| Credential/setup delays | Fakes unblock all tracks; human wizard and live setup occur in B2, before M4 | B | -| Schedule pressure | Preserve safety acceptance; cut optional webhooks, rolling policies, visual polish, and nonessential telemetry first | All | - -## 14. Definition of done for every implementation task - -- Outcome and non-goals match the task above; no hidden follow-up is required for claimed behavior. -- Public-seam test is written red first, then the smallest vertical behavior is implemented; tests avoid private implementation coupling. -- Relevant unit, contract, integration, concurrency, failure-injection, migration, lint, type, and build checks pass. -- Durable state and external settlement count are asserted where money or retries are involved. -- Security boundaries, input validation, integer money, logging redaction, testnet restriction, and safe-disable behavior are reviewed. -- Documentation, OpenAPI/fixtures, runbooks, and `.env.example` are updated without secrets. -- The branch/diff is focused and passes the repository's FreePi/CI/human-review policy. No agent merges. - -## 15. First implementation actions after plan approval - -1. Human merges the planning/agent-infrastructure change to `develop`; record the exact base SHA. -2. All three people complete M0 together and create their independent branches/worktrees. -3. Person A starts A1; Person B starts B1; Person C starts C1 simultaneously. -4. Hold one 15-minute daily contract check limited to proposed breaking changes, UNKNOWN classification, and risks. Status reporting must not become an approval dependency. -5. At M1 exit, re-estimate the calendar from evidence while preserving M2–M6 acceptance criteria and the rule that frontend remains last. +Successful command logs are summarized, not pasted wholesale. Failure logs retain only the minimum sanitized evidence needed for diagnosis. External transaction and deployment identifiers are public testnet evidence only after redaction review. + +## 27. Final readiness audit + +Before Gate P6 can pass, confirm: + +- Exact source/tree identities are recorded for all composed artifacts. +- The implementation base and every contract-pack version are immutable and traceable. +- Root install, format, lint, type, unit, integration, contract, build, migration, browser, and policy checks pass. +- Every applicable test-matrix row records stable intent, durable state, and external settlement count. +- Allowed testnet flow has exactly one committed settlement. +- Denial and invalid-scope flows have zero settlement. +- Lost-response flow has no replacement and reconciles to the original transaction or safely remains `UNKNOWN`. +- Restart and two-agent scenarios preserve the invariant. +- Graph empty/lag/error/unavailable states never alter settlement permission. +- Safe disable stops new submissions while status and recovery reads continue. +- UI has no direct/bypass/force-pay action and labels authority/freshness correctly. +- Demo/reset instructions require no unsafe database surgery or external-history rewrite. +- Evidence, repository, logs, screenshots, fixtures, source maps, and reviews contain no secrets. +- Privy, Arc, and The Graph claims use the qualification standard and cite live evidence or remain `NOT VERIFIED`. +- Mandatory FreePi gates and required CI apply to the exact candidate tree/head. +- A human performs the final review and merge. + +## 28. Kickoff sequence + +1. Human approves this plan and the frozen contract pack. +2. Record the implementation-base full SHA. +3. A, B, and C create independent worktrees and start A01, B01, and C01 simultaneously. +4. Each coder closes and advances through their own lane without waiting for global milestone closure. +5. Run project gates asynchronously when all required artifacts happen to be available; failures create focused owner tickets and do not halt unaffected work. +6. Do not start A05, B05, or C05 until P4 passes. +7. Re-estimate after P1 using measured friction, preserving all safety criteria.