diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1ac84c363..42421b6b0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ concurrency: group: ci-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true -# Per-push gate: the web app + the TS FORGE_RULES_V1 conformance suite (the +# Per-push gate: the web app + the TS FORGE_RULES_V2 conformance suite (the # cross-client parity contract). The Rust workspace pulls in the Dash Platform SDK # (a git dependency pinned to an immutable tag in Cargo.toml); building that # dependency tree does not fit a fast per-push job, so Rust is gated by `rust.yml` diff --git a/.github/workflows/mirror-action.yml b/.github/workflows/mirror-action.yml index ee3c8ab82..5b6fda69a 100644 --- a/.github/workflows/mirror-action.yml +++ b/.github/workflows/mirror-action.yml @@ -10,7 +10,7 @@ name: Mirror Action on: workflow_dispatch: schedule: - # Monday midday: well clear of testnet-nightly (06:00), which signs as the same + # Monday midday: well clear of the Devnet Nightly (06:00), which signs as the same # OWNER identity; two jobs signing at once can collide on identity nonces. - cron: "41 12 * * 1" pull_request: @@ -61,7 +61,7 @@ jobs: run: bash action/test.sh # A separate probe job so the live job's CONCLUSION is literally `skipped` when the - # fixture identity is absent (see testnet-nightly.yml for why that matters). + # fixture identity is absent (see nightly.yml for why that matters). fixtures: name: fixture identity configured? if: github.event_name != 'pull_request' @@ -94,7 +94,7 @@ jobs: persist-credentials: false # Pinned modern protoc: Ubuntu's 3.21 breaks the tenderdash proto build - # (testnet-nightly.yml has the details). + # (nightly.yml has the details). - name: Install protoc env: PROTOC_VERSION: '28.3' diff --git a/.github/workflows/testnet-nightly.yml b/.github/workflows/nightly.yml similarity index 58% rename from .github/workflows/testnet-nightly.yml rename to .github/workflows/nightly.yml index 7270fb20e..daa85ee01 100644 --- a/.github/workflows/testnet-nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,34 +1,38 @@ -name: Testnet Nightly +name: Devnet Nightly -# Nightly certification against LIVE Dash Platform testnet. +# Nightly certification against LIVE devnet moutai, where forge-v2 (Platform protocol 14) is +# deployed. Testnet and mainnet still run protocol 13 and have no forge-v2 deployment; +# testnet runs resume here once protocol 14 reaches testnet and forge-v2 is deployed there. # -# The suites this drives are implemented and live in the repo: -# * forge-web/e2e/ — Playwright: read paths, fallback browse, zero-backend, a11y -# * e2e/cli/run.sh — 12 CLI scenarios on devnet moutai (forge-v2): clone/push -# round-trip, non-ff, ref delete, revoked-writer push, non-member -# push, third-party verify, depth+filter, issue lifecycle, PR from -# a fork with a real merge, release asset (SKIPs: no MinIO on the -# runner), star/unstar; plus a testnet v1 read-compat clone +# The suites this drives: +# * forge-web/e2e/ — Playwright on a moutai build: v2 read paths, fallback browse, +# zero-backend, a11y, against the forge-v2 read fixture +# * e2e/cli/run.sh — 11 CLI scenarios on moutai: clone/push round-trip, non-ff, +# ref delete, revoked-writer push, non-member push, third-party +# verify, depth+filter, issue lifecycle, PR from a fork with a +# real merge, release asset (SKIPs: no MinIO on the runner), +# star/unstar # # They split by what they need: -# * READ-ONLY specs need only a network path to testnet DAPI and the read fixture repo -# (seeded by `seed-read-fixture` when the secrets exist; e2e/README.md reserves it), so -# they run unconditionally and their failure fails this workflow. -# * The CLI suite and the write specs need FUNDED fixture identities, which cannot live in -# a fork's PR context. A separate `fixtures` probe job decides whether they run, so when -# the secrets are absent the suite job's conclusion is literally `skipped` rather than a -# green job with everything gated out — a distinction any badge or alert rule can see. +# * The READ-ONLY browser specs need only a network path to moutai DAPI and the read +# fixture (`forge-v2-demo`, seeded by forge-contracts/scripts/seed-v2-fixture.mjs; +# e2e/README.md reserves it), so they run unconditionally and their failure fails this +# workflow. The seed job runs first when the fixture secrets exist; it is idempotent (an +# existing fixture is left alone). +# * The CLI suite needs FUNDED fixture identities, which cannot live in a fork's PR +# context. A separate `fixtures` probe job decides whether it runs, so when the secrets +# are absent the suite job's conclusion is literally `skipped` rather than a green job +# with everything gated out — a distinction any badge or alert rule can see. +# * The browser WRITE specs (v2-writes, v2-auth) spend real devnet funds and v2-auth needs +# the devnet faucet key; they run by hand (`E2E_WRITE=1`, see forge-web/e2e/). # # Fixture identity secrets (e2e/cli/config.sh names the roles): -# FORGE_MOUTAI_IDENTITY_OWNER - owns the forge-v2 e2e-cli repo, adds/removes members -# FORGE_MOUTAI_IDENTITY_COLLAB - added as a writer, then removed (scenario 04) -# FORGE_MOUTAI_IDENTITY_CONTRIB - never a member (scenario 05) -# FORGE_TEST_IDENTITY_CONTRIB - any testnet identity, for the v1 read-compat clone (08) -# FORGE_TEST_IDENTITY_DEPLOYER - testnet: owns the browser specs' read fixture (v1), -# verified by the seed job +# FORGE_MOUTAI_IDENTITY_OWNER - owns the e2e-cli repo and the read fixture's demo repo +# FORGE_MOUTAI_IDENTITY_MAINTAINER - maintainer of the demo repo, owner of forge-v2-empty +# FORGE_MOUTAI_IDENTITY_COLLAB - added as a writer, then removed (scenario 04) +# FORGE_MOUTAI_IDENTITY_CONTRIB - never a member (scenario 05) # Each holds the bridge-format identity JSON that `dg` reads from -# ~/.config/dash-forge/test-identities/devnet-moutai/.identity.json (moutai) or -# ~/.config/dash-forge/test-identities/.identity.json (testnet). +# ~/.config/dash-forge/test-identities/devnet-moutai/.identity.json. on: workflow_dispatch: @@ -36,15 +40,15 @@ on: - cron: "0 6 * * *" concurrency: - group: testnet-nightly + group: devnet-nightly cancel-in-progress: false jobs: web-read-paths: - name: playwright (read-only, live testnet) - # Reads the dedicated read fixture (e2e/README.md), so it waits for the seed job — but - # still runs when that job is skipped (no secrets: the fixture is read as it stands) or - # failed (the specs then say what is wrong with it). + name: playwright (read-only, live devnet moutai) + # Reads the read fixture (e2e/README.md), so it waits for the seed job — but still runs + # when that job is skipped (no secrets: the fixture is read as it stands) or failed (the + # specs then say what is wrong with it). needs: seed-read-fixture if: ${{ !cancelled() }} runs-on: ubuntu-latest @@ -52,6 +56,8 @@ jobs: defaults: run: working-directory: forge-web + env: + E2E_DEVNET: moutai steps: - uses: actions/checkout@v5 - uses: pnpm/action-setup@v5 @@ -64,14 +70,17 @@ jobs: cache-dependency-path: forge-web/pnpm-lock.yaml - run: pnpm install --frozen-lockfile - run: pnpm exec playwright install --with-deps chromium - - run: pnpm build - # auth-write needs a funded identity; everything else is a read against live testnet. + - name: Build for devnet moutai + env: + NEXT_PUBLIC_NETWORK: devnet + NEXT_PUBLIC_DEVNET_NAME: moutai + run: pnpm build # E2E_SKIP_BUILD reuses the `out/` just built — the Playwright webServer would # otherwise run `pnpm build` a second time before serving it. - name: Playwright read-path + a11y specs env: E2E_SKIP_BUILD: '1' - run: pnpm exec playwright test read-paths.spec.ts fallback-browse.spec.ts zero-backend.spec.ts a11y.spec.ts + run: pnpm exec playwright test v2-reads.spec.ts fallback-browse.spec.ts zero-backend.spec.ts a11y.spec.ts - uses: actions/upload-artifact@v6 if: always() with: @@ -88,27 +97,27 @@ jobs: runs-on: ubuntu-latest outputs: present: ${{ steps.probe.outputs.present }} - # The read-fixture seeder signs with DEPLOYER alone. - deployer: ${{ steps.probe.outputs.deployer }} + # The read-fixture seeder signs with all four roles. + seeder: ${{ steps.probe.outputs.seeder }} steps: - name: Probe id: probe env: FORGE_MOUTAI_IDENTITY_OWNER: ${{ secrets.FORGE_MOUTAI_IDENTITY_OWNER }} + FORGE_MOUTAI_IDENTITY_MAINTAINER: ${{ secrets.FORGE_MOUTAI_IDENTITY_MAINTAINER }} FORGE_MOUTAI_IDENTITY_COLLAB: ${{ secrets.FORGE_MOUTAI_IDENTITY_COLLAB }} FORGE_MOUTAI_IDENTITY_CONTRIB: ${{ secrets.FORGE_MOUTAI_IDENTITY_CONTRIB }} - FORGE_TEST_IDENTITY_CONTRIB: ${{ secrets.FORGE_TEST_IDENTITY_CONTRIB }} - FORGE_TEST_IDENTITY_DEPLOYER: ${{ secrets.FORGE_TEST_IDENTITY_DEPLOYER }} run: | - if [ -n "$FORGE_TEST_IDENTITY_DEPLOYER" ]; then - echo "deployer=true" >> "$GITHUB_OUTPUT" + if [ -n "$FORGE_MOUTAI_IDENTITY_OWNER" ] && [ -n "$FORGE_MOUTAI_IDENTITY_MAINTAINER" ] \ + && [ -n "$FORGE_MOUTAI_IDENTITY_COLLAB" ] && [ -n "$FORGE_MOUTAI_IDENTITY_CONTRIB" ]; then + echo "seeder=true" >> "$GITHUB_OUTPUT" else - echo "deployer=false" >> "$GITHUB_OUTPUT" + echo "seeder=false" >> "$GITHUB_OUTPUT" fi missing=() # Report the SECRET names an operator has to create, not internal aliases. for name in FORGE_MOUTAI_IDENTITY_OWNER FORGE_MOUTAI_IDENTITY_COLLAB \ - FORGE_MOUTAI_IDENTITY_CONTRIB FORGE_TEST_IDENTITY_CONTRIB; do + FORGE_MOUTAI_IDENTITY_CONTRIB; do [ -z "${!name}" ] && missing+=("$name") done if [ "${#missing[@]}" -ne 0 ]; then @@ -118,8 +127,8 @@ jobs: echo echo "Missing repository secrets: \`${missing[*]}\`." echo - echo "These identities must exist and be funded (moutai; testnet for 08) for the CLI suite" - echo "to run. The suite job below reports SKIPPED — it is **not** a passing" + echo "These identities must exist and be funded on devnet moutai for the CLI" + echo "suite to run. The suite job below reports SKIPPED — it is **not** a passing" echo "run. See \`e2e/cli/config.sh\` for the role pool and" echo "\`docs/testing/e2e-test-plan.md\` for provisioning." } >> "$GITHUB_STEP_SUMMARY" @@ -128,50 +137,49 @@ jobs: echo "present=true" >> "$GITHUB_OUTPUT" fi - # Make the browser specs' read fixture exist and hold exactly the expected commit. It is - # its own repo, written only by this job, so nothing the CLI suite or an ad-hoc storage run - # stores can reach what the browser reads (e2e/README.md). Idempotent: a no-op once seeded. + # Make sure the browser specs' read fixture exists. It is its own pair of repos, written only + # by this job, so nothing the CLI suite or an ad-hoc storage run stores can reach what the + # browser reads (e2e/README.md). Idempotent: a no-op once the fixture is on chain. seed-read-fixture: name: seed the read fixture needs: fixtures - if: needs.fixtures.outputs.deployer == 'true' + if: needs.fixtures.outputs.seeder == 'true' runs-on: ubuntu-latest - timeout-minutes: 45 - env: - ID_DEPLOYER_JSON: ${{ secrets.FORGE_TEST_IDENTITY_DEPLOYER }} + timeout-minutes: 20 steps: - uses: actions/checkout@v5 - - name: Install protoc - env: - PROTOC_VERSION: '28.3' - run: | - curl -sSLo /tmp/protoc.zip \ - "https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-linux-x86_64.zip" - sudo unzip -q -o /tmp/protoc.zip -d /usr/local bin/protoc 'include/*' - sudo chmod +x /usr/local/bin/protoc - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 + - uses: actions/setup-node@v5 with: - shared-key: e2e-cli - - name: Materialize the DEPLOYER identity + node-version: 22 + cache: npm + cache-dependency-path: forge-contracts/sdk-v2/package-lock.json + - run: npm ci --ignore-scripts + working-directory: forge-contracts/sdk-v2 + # The keys live only in this step's environment, not the job's. + - name: Materialize the fixture identities + env: + ID_OWNER_JSON: ${{ secrets.FORGE_MOUTAI_IDENTITY_OWNER }} + ID_MAINTAINER_JSON: ${{ secrets.FORGE_MOUTAI_IDENTITY_MAINTAINER }} + ID_COLLAB_JSON: ${{ secrets.FORGE_MOUTAI_IDENTITY_COLLAB }} + ID_CONTRIB_JSON: ${{ secrets.FORGE_MOUTAI_IDENTITY_CONTRIB }} run: | - dir="${HOME}/.config/dash-forge/test-identities" + dir="${HOME}/.config/dash-forge/test-identities/devnet-moutai" mkdir -p "$dir" && chmod 700 "$dir" - printf '%s' "$ID_DEPLOYER_JSON" > "$dir/DEPLOYER.identity.json" - # harness_init checks for the whole role set; only DEPLOYER signs here. - for r in COLLAB CONTRIB; do cp "$dir/DEPLOYER.identity.json" "$dir/$r.identity.json"; done + printf '%s' "$ID_OWNER_JSON" > "$dir/OWNER.identity.json" + printf '%s' "$ID_MAINTAINER_JSON" > "$dir/MAINTAINER.identity.json" + printf '%s' "$ID_COLLAB_JSON" > "$dir/COLLAB.identity.json" + printf '%s' "$ID_CONTRIB_JSON" > "$dir/CONTRIB.identity.json" chmod 600 "$dir"/*.identity.json - - name: Build CLI binaries - timeout-minutes: 30 - run: cargo build --locked -p dg -p git-remote-dash - name: Seed - timeout-minutes: 12 - run: bash e2e/cli/seed-read-fixture.sh + timeout-minutes: 15 + run: node forge-contracts/scripts/seed-v2-fixture.mjs --network devnet --devnet-name moutai cli-suite: name: cli e2e (live devnet moutai) - needs: fixtures - if: needs.fixtures.outputs.present == 'true' + # After the seed job: both sign as OWNER, and two signers on one identity at once + # collide on its contract nonce. + needs: [fixtures, seed-read-fixture] + if: ${{ !cancelled() && needs.fixtures.outputs.present == 'true' }} runs-on: ubuntu-latest # checkout + protoc + toolchain + cache (~3 min), build (≤30), suite (≤45). timeout-minutes: 85 @@ -179,7 +187,6 @@ jobs: ID_OWNER_JSON: ${{ secrets.FORGE_MOUTAI_IDENTITY_OWNER }} ID_COLLAB_JSON: ${{ secrets.FORGE_MOUTAI_IDENTITY_COLLAB }} ID_CONTRIB_JSON: ${{ secrets.FORGE_MOUTAI_IDENTITY_CONTRIB }} - ID_TESTNET_JSON: ${{ secrets.FORGE_TEST_IDENTITY_CONTRIB }} steps: - uses: actions/checkout@v5 @@ -210,8 +217,7 @@ jobs: printf '%s' "$ID_OWNER_JSON" > "$dir/devnet-moutai/OWNER.identity.json" printf '%s' "$ID_COLLAB_JSON" > "$dir/devnet-moutai/COLLAB.identity.json" printf '%s' "$ID_CONTRIB_JSON" > "$dir/devnet-moutai/CONTRIB.identity.json" - printf '%s' "$ID_TESTNET_JSON" > "$dir/CONTRIB.identity.json" - chmod 600 "$dir"/*.identity.json "$dir"/devnet-moutai/*.identity.json + chmod 600 "$dir"/devnet-moutai/*.identity.json # Built in its own step so a slow (cache-miss) build cannot eat into the suite's time # budget below; run.sh picks the binaries up from target/debug. diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index c030f84f5..0eb15ad94 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -1,5 +1,11 @@ name: Deploy forge-web to Pages +# The hosted build (forge.dashhq.org) targets devnet moutai: forge-v2 needs Platform +# protocol 14, which only the devnet runs today. The network is a build-time choice +# (NEXT_PUBLIC_NETWORK / NEXT_PUBLIC_DEVNET_NAME); override it with the repository variables +# PAGES_NETWORK / PAGES_DEVNET_NAME (e.g. PAGES_NETWORK=testnet once forge-v2 is deployed +# there) without editing this file. The header badge names the network the build reads. + on: push: branches: [master] @@ -36,7 +42,11 @@ jobs: cache: pnpm cache-dependency-path: forge-web/pnpm-lock.yaml - run: pnpm install --frozen-lockfile - - run: pnpm build + - name: Build (${{ vars.PAGES_NETWORK || 'devnet' }}) + env: + NEXT_PUBLIC_NETWORK: ${{ vars.PAGES_NETWORK || 'devnet' }} + NEXT_PUBLIC_DEVNET_NAME: ${{ (vars.PAGES_NETWORK || 'devnet') == 'devnet' && (vars.PAGES_DEVNET_NAME || 'moutai') || '' }} + run: pnpm build - uses: actions/configure-pages@v5 - uses: actions/upload-pages-artifact@v3 with: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 7d0d8ebec..6808f94ad 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -16,9 +16,8 @@ on: - 'rustfmt.toml' # Compiled into every binary by the crates' build.rs (`--version` stamping). - 'build-support/**' - # Compiled into the binaries, not just test data: forge-core include_str!s - # templates/repo-v1.json and embeds every deployments/*.json (build.rs), and the - # conformance test loads vectors/. + # Compiled into the binaries, not just test data: forge-core embeds every + # deployments/*.json (build.rs), and the conformance test loads vectors/. - 'forge-contracts/**' - '.github/workflows/rust.yml' push: diff --git a/EXECUTION.md b/EXECUTION.md index 44d784874..a7e135cfe 100644 --- a/EXECUTION.md +++ b/EXECUTION.md @@ -1,5 +1,7 @@ # Dash Forge — Execution Tracker +> **Historical.** This is the build log of forge-v1 (a global registry contract plus one contract per repository, with WRITE/MAINTAIN token access control). forge-v1 was removed on 2026-09-26 with no backwards compatibility: the registry, the `repo-v1` template, the token ACLs and the testnet deployments named below no longer exist in the code. The current plan is [docs/roadmap.md](docs/roadmap.md); the current design is [forge-v2](docs/contracts/forge-v2.md). The log below is kept as written. + Session-continuity anchor. Docs in `docs/` are the spec; this file tracks build state. Update every session. > **2026-09-24:** this log records the July build. "Complete" below means *demonstrated on testnet*, not *usable by real users*. Forward planning now lives in [docs/roadmap.md](docs/roadmap.md). diff --git a/Makefile b/Makefile index 2aeee5c58..7ffcc23c5 100644 --- a/Makefile +++ b/Makefile @@ -54,17 +54,18 @@ infra-up: infra-down: docker compose -f $(COMPOSE_FILE) down -v -## e2e: run the CLI end-to-end suite (LIVE devnet moutai, forge-v2; scenario 08 reads a -## testnet v1 repo) against the OWNER-owned e2e-cli repo (created on first run). +## e2e: run the CLI end-to-end suite (LIVE devnet moutai, forge-v2) against the +## OWNER-owned e2e-cli repo (created on first run). ## Builds the binaries if needed, then drives real git push/clone through the ## dash:// helper. See e2e/cli/README-less run.sh header for env knobs ## (RUN_ID, E2E_TIMEOUT, E2E_NO_CLEANUP, subset args). Exits non-zero on any FAIL. e2e: build-rust @bash e2e/cli/run.sh -## e2e-fixture: seed the browser specs' read fixture (idempotent; see e2e/README.md). -e2e-fixture: build-rust - @bash e2e/cli/seed-read-fixture.sh +## e2e-fixture: seed the browser specs' forge-v2 read fixture on DEVNET (idempotent; needs +## `npm ci` in forge-contracts/sdk-v2 and the devnet OWNER/MAINTAINER/COLLAB/CONTRIB fixtures). +e2e-fixture: + @node forge-contracts/scripts/seed-v2-fixture.mjs --network devnet --devnet-name $(DEVNET) ## devnet-identities: mint (or resume) the 9-role identity pool on a devnet, ## funded from the devnet's faucet wallet key, then verify every identity on diff --git a/README.md b/README.md index 06d933ec5..67370c630 100644 --- a/README.md +++ b/README.md @@ -7,15 +7,16 @@ - **No takedowns.** The contracts have no moderation. Nobody can delete your history or ban your identity. - **Plain git.** `git clone dash://…` and `git push` work unchanged, and so does jj. `dg` feels like `gh`. -## Try it (testnet) +## Try it (devnet moutai) -Build the two binaries (Rust and `protoc` 25 or newer; see [BUILDING.md](docs/BUILDING.md)). Create an identity in the [Dash bridge](https://bridge.thepasta.org/?network=testnet), fund it from the bridge's testnet faucet twice (a repository costs ~1.18 tDASH; each request gives 1), and download its key backup. Then, from any git repository, replacing `` with your identity id: +Forge runs on devnet **moutai** today (Platform protocol 14). Build the two binaries (Rust and `protoc` 25 or newer; see [BUILDING.md](docs/BUILDING.md)). Create an identity in the [Dash bridge](https://bridge.thepasta.org/?network=devnet-moutai), fund it from the [moutai faucet](https://faucet.moutai.networks.dash.org) (a repository costs about 0.001 DASH), and download its key backup. Then, from any git repository, replacing `` with your identity id: ```sh cargo install --locked --path crates/dg && cargo install --locked --path crates/git-remote-dash -dg auth login --identity ~/Downloads/dash-identity-.json -export DASH_FORGE_KEY=~/.config/dash-forge/identities/testnet/.identity.json -dg repo create hello # a v1 repository: ~1.18 tDASH (forge-v2 will be ~0.001 DASH) +dg auth login --network devnet --devnet-name moutai --identity ~/Downloads/dash-identity-.json +export DASH_FORGE_KEY=~/.config/dash-forge/identities/devnet-moutai/.identity.json +export DASH_FORGE_NETWORK=devnet DASH_FORGE_DEVNET_NAME=moutai # git-remote-dash reads these +dg repo create hello # ~0.001 DASH: three documents in the shared contracts git remote add forge dash:///hello && git push -u forge main ``` @@ -38,13 +39,15 @@ Prebuilt binaries and a one-line `install.sh` will come with the first tagged re ## Status -| Network | Forge version | State | +| Network | Platform protocol | Forge | |---|---|---| -| **Testnet** | **v1** (legacy): one contract per repository, token access control | Live. Everything in the guides that is not marked coming soon works here. A repository costs ~1.18 tDASH. | -| **Devnet moutai** | **forge-v2**: two shared contracts, membership access control, Platform protocol 14 | Contracts registered. The CLI and web app cannot use them yet; support is landing now. A repository will cost ~0.001 DASH. | -| **Mainnet** | — | Not deployed. forge-v2 will be registered once Platform protocol 14 activates on mainnet. | +| **Devnet moutai** | 14 | **forge-v2** registered: two shared contracts (forge-core, forge-collab) in one contract group, membership access control. `dg`, `git-remote-dash` and the web app at forge.dashhq.org use it. A repository costs about 0.001 DASH. | +| **Testnet** | 13 | Not deployed. forge-v2 is registered once Platform protocol 14 reaches testnet. | +| **Mainnet** | 13 | Not deployed. forge-v2 is registered once Platform protocol 14 activates on mainnet. | -Specified but not built yet, and marked **coming soon** in the guides: prebuilt releases, identity creation in `dg` and in the browser, limited-budget keys, DPNS usernames, forks, opening and merging PRs from the browser, the GitHub Mirror Action, and private repositories. +On a network with no forge-v2 deployment, `dg`, `git-remote-dash` and the web app stop with a "not deployed" error. The first version of Forge (forge-v1: one contract per repository, token access control) ran on testnet until 2026-09-26. It was removed with no backwards compatibility, so v1 repositories can no longer be read. + +Specified but not built yet, and marked **coming soon** in the guides: prebuilt releases, identity creation and limited-budget keys in `dg` (the web app has both), DPNS usernames, opening PRs and merging code from the browser, and private repositories. --- @@ -56,7 +59,7 @@ Original design brief: `../INIT.md`; reconciliation notes: [docs/init-reconcilia | Component | What it is | |---|---| -| **forge protocol** | Data contracts. v1 (testnet): one global registry + a per-repo contract template with WRITE/MAINTAIN token ACLs enforced at consensus. forge-v2 (protocol 14): two shared contracts with membership gates ([forge-v2.md](docs/contracts/forge-v2.md)). | +| **forge protocol** | Data contracts. forge-v2 (Platform protocol 14): two shared contracts, forge-core and forge-collab, in one contract group. Access control is membership documents checked at consensus ([forge-v2.md](docs/contracts/forge-v2.md)). | | **git-remote-dash** | Git remote helper (Rust). `git clone dash:///project` and `git push` just work. jj-compatible. | | **dg** | `gh`-replacement CLI (Rust, same workspace): repos, issues, PRs, releases, collaborator management, storage profiles, cost audit, repack, doctor. | | **forge web** | Static SPA (TypeScript, wasm SDK, in-browser repo materialization) deployable to IPFS. Browsing, commit and PR diffs, issues, and PR timelines (including review verdicts) are built; opening a PR and recording a verdict are not — see [PRD 03](docs/prd/03-web-app.md). | @@ -74,21 +77,22 @@ the pinned Platform tag, and how to develop against a local Platform checkout. [docs/INSTALL.md](docs/INSTALL.md) covers the release pipeline, `install.sh`, checksums and attestations, `cargo binstall` and shell completions (`dg completions `). -**Networks.** Testnet is the default. Pick another network with `--network mainnet`, or -`--network devnet --devnet-name moutai` for a named devnet (`--dapi-addresses` sets its -nodes). The helper reads the same settings from git config (`dash.network`, -`dash.devnetName`, `dash.dapiAddresses`), and the web build reads them from +**Networks.** Testnet is the default network, but only devnet moutai has a forge-v2 +deployment today, so pass `--network devnet --devnet-name moutai` (`dg auth login` records +it as your default; `--dapi-addresses` sets the devnet's nodes). The helper reads the same +settings from `DASH_FORGE_NETWORK` / `DASH_FORGE_DEVNET_NAME` or git config +(`dash.network`, `dash.devnetName`, `dash.dapiAddresses`), and the web build reads them from `NEXT_PUBLIC_NETWORK` and `NEXT_PUBLIC_DEVNET_NAME`. Contract ids come only from -`forge-contracts/deployments/.json`. A network with no deployment (mainnet, until -the runbook is executed) fails with a clear "not deployed" error and never falls back to -testnet ids. See [BUILDING.md § Networks](docs/BUILDING.md#networks). +`forge-contracts/deployments/.json`. A network with no deployment (testnet and +mainnet today) fails with a clear "not deployed" error and never falls back to another +network's ids. See [BUILDING.md § Networks](docs/BUILDING.md#networks). ### Document index 1. [Platform constraints & research findings](docs/research/platform-constraints.md) — verified limits/fees that shape the design. 2. [INIT.md reconciliation](docs/init-reconciliation.md) — what was adopted from the original brief; constraint-forced deviations, flagged for review. -3. [System architecture](docs/architecture.md) — components, contract topology, token ACL, storage backends, data flows, economics. -4. [Data contracts design](docs/contracts/data-contracts.md) — registry + repo-template schemas, token costs, indices. [forge-v2 contracts](docs/contracts/forge-v2.md) — the protocol-14 shared contracts. +3. [System architecture](docs/architecture.md) — components, contract topology, membership access control, storage backends, data flows, economics. +4. [forge-v2 contracts](docs/contracts/forge-v2.md) — the protocol-14 shared contracts: types, gates, client rules, costs, deployment. [Data contracts design](docs/contracts/data-contracts.md) is the historical forge-v1 design (registry + per-repo contracts), no longer implemented. 5. PRDs: - [01 Product overview & personas](docs/prd/01-product-overview.md) - [02 git-remote-dash & dg](docs/prd/02-git-remote-helper-cli.md) @@ -99,10 +103,10 @@ testnet ids. See [BUILDING.md § Networks](docs/BUILDING.md#networks). 6. [Economics & fee minimization](docs/economics.md) — compression pipeline, deposit-vs-burn cost model, repack/refund GC. 7. [Style guide](docs/design/style-guide.md) — visual system + engineering conventions. 8. [Implementation plan](docs/implementation-plan.md) — Phase 0 de-risk gate → mainnet protocol → CLI+relay → web+import → hardening. -9. [E2E & production test plan](docs/testing/e2e-test-plan.md) — testnet identities/funds via bridge.thepasta.org + faucet.thepasta.org; mainnet smoke. -10. [Spike results & Design Freeze #1](docs/research/spike-results.md) — the 9 de-risking spikes (GO verdict). +9. [E2E & production test plan](docs/testing/e2e-test-plan.md) — devnet moutai identities and funds, the nightly suites, mainnet smoke. +10. [Spike results & Design Freeze #1](docs/research/spike-results.md) — the 9 de-risking spikes (GO verdict), run for forge-v1. 11. [Building from source](docs/BUILDING.md) — prerequisites, the pinned Platform SDK tag, local overrides. [Installing prebuilt binaries](docs/INSTALL.md) — install.sh, checksums + attestations, cargo binstall, cutting a release. -12. [Design Freeze #2 (as-built)](docs/design-freeze-2.md) — what implementation established: deviations, discoveries, final decisions. +12. [Design Freeze #2 (as-built)](docs/design-freeze-2.md) — what the forge-v1 implementation established (historical). 13. [Mainnet runbook](docs/mainnet-runbook.md) — the rehearsed (not-yet-executed) mainnet deployment procedure. 14. [Error codes](docs/errors.md) — every `dg` / `git-remote-dash` error code, its exit code and fix. 15. [Product roadmap](docs/roadmap.md) — verified state, owner decisions, phased plan and execution tracker. @@ -110,9 +114,9 @@ testnet ids. See [BUILDING.md § Networks](docs/BUILDING.md#networks). ### Verification -The web app is live at **https://forge.dashhq.org** (GitHub Pages). The CLI end-to-end suite (`e2e/cli/`, 7 scenarios) and the Playwright specs (`forge-web/e2e/`) run nightly against live testnet; see [e2e/README.md](e2e/README.md). +The web app is live at **https://forge.dashhq.org** (GitHub Pages), built for devnet moutai; its header badge says "devnet". The CLI end-to-end suite (`e2e/cli/`) and the Playwright specs (`forge-web/e2e/`) run nightly against moutai ("Devnet Nightly"); see [e2e/README.md](e2e/README.md). -Proven end-to-end on testnet: `git clone dash://…` / `git push` byte-identical round-trip; frozen-collaborator push rejected at consensus; third-party "no trust in any server" verification; browser app rendering live proof-verified data with the trust panel; CLI↔web parity via the shared conformance vectors. See [design-freeze-2.md](docs/design-freeze-2.md) for as-built decisions and [mainnet-runbook.md](docs/mainnet-runbook.md) for the (rehearsed, not-yet-executed) mainnet deployment. +Proven end-to-end on moutai: `git clone dash://…` / `git push` byte-identical round-trip; a revoked writer's push and a non-member's push rejected at consensus; third-party "no trust in any server" verification; issue and PR lifecycles, including a PR from a fork with a real merge; the browser app rendering proof-verified data with the trust panel; CLI↔web parity via the shared conformance vectors. See [forge-v2.md](docs/contracts/forge-v2.md) for the contract design and [mainnet-runbook.md](docs/mainnet-runbook.md) for the (not-yet-executed) mainnet deployment. Components (all under this repo): `forge-contracts` · `forge-core` (Rust lib) · `git-remote-dash` · `dg` (CLI) · `forge-relay` · `forge-import` · `forge-web`. diff --git a/crates/dg/src/auth.rs b/crates/dg/src/auth.rs index 97c48cf0c..f05d317a7 100644 --- a/crates/dg/src/auth.rs +++ b/crates/dg/src/auth.rs @@ -58,18 +58,9 @@ async fn login(ctx: &Ctx) -> Result<()> { // only when it differs from the deployment file's: config outranks that file, so // copying the file's list here would pin it past a devnet reset that updates the file. let mut config = Config::load().unwrap_or_default(); - let previous_network = config - .network_settings() - .resolve() - .ok() - .map(|t| t.network.key()); config.network = Some(ctx.network().kind().to_string()); config.devnet_name = ctx.network().devnet_name().map(str::to_string); config.dapi_addresses = explicit_dapi_addresses(ctx.network()); - // A registry override belongs to the network it was set for. - if previous_network.as_deref() != Some(network.as_str()) { - config.registry_contract_id = None; - } config.default_identity = Some(dest.to_string_lossy().to_string()); config.default_identity_id = Some(bridge.identity_id.clone()); config.save()?; diff --git a/crates/dg/src/collab.rs b/crates/dg/src/collab.rs index 343808030..aa48fc571 100644 --- a/crates/dg/src/collab.rs +++ b/crates/dg/src/collab.rs @@ -2,15 +2,12 @@ //! //! On forge-v2 a member is a `writer` or `maintainer` document the repo owner creates //! (add) or deletes (remove); consensus refuses the removed member's next write at once. -//! There is no suspend: remove and re-add instead. v1 repositories are read only; their -//! token-based collaborator list can still be listed. +//! There is no suspend: remove and re-add instead. use anyhow::{Context, Result}; use serde_json::json; use forge_core::members::{doc_type as role_name, MemberReader, MemberService}; -use forge_core::tokens::TokenService; -use forge_core::user_error::{codes, UserError}; use crate::common::{resolve, RepoRef}; use crate::context::Ctx; @@ -20,14 +17,6 @@ use crate::{CollabCommand, RoleArg}; pub async fn run(ctx: &Ctx, cmd: &CollabCommand) -> Result<()> { match cmd { CollabCommand::Add { repo, member, role } => add(ctx, repo, member, *role).await, - CollabCommand::Suspend { .. } | CollabCommand::Unsuspend { .. } => Err(UserError::new( - codes::NOT_IMPLEMENTED, - "suspend/unsuspend are not supported on forge-v2", - ) - .cause("forge-v2 has no freeze: membership is a document the owner creates or deletes") - .fix("`dg collab remove / ` revokes access immediately") - .fix("`dg collab add / --role writer` restores it") - .into()), CollabCommand::Remove { repo, member, role } => remove(ctx, repo, member, *role).await, CollabCommand::List { repo } => list(ctx, repo).await, } @@ -114,42 +103,6 @@ async fn list(ctx: &Ctx, repo: &str) -> Result<()> { let (client, _bridge, identity) = ctx.connect_with_identity().await?; let handle = resolve(&client, &identity, &repo_ref).await?; - if let Ok(contract_id) = handle.v1_contract_id() { - // v1 (read only): the token balances are the collaborator list. - let collaborators = TokenService::new(&client) - .list_collaborators(contract_id) - .await - .context("list_collaborators")?; - let rows: Vec<_> = collaborators - .iter() - .map(|c| { - json!({ - "identityId": c.identity_id, - "write": c.holdings.write, - "writeFrozen": c.holdings.write_frozen, - "maintain": c.holdings.maintain, - "maintainFrozen": c.holdings.maintain_frozen, - }) - }) - .collect(); - ctx.emit( - json!({ "generation": "v1", "count": rows.len(), "collaborators": rows }), - || { - println!( - "{} collaborator(s) (v1 repo, read only):", - collaborators.len() - ); - for c in &collaborators { - println!( - " {} write={} maintain={}", - c.identity_id, c.holdings.write, c.holdings.maintain - ); - } - }, - ); - return Ok(()); - } - let members = MemberReader::new(&client) .list(&handle) .await @@ -165,14 +118,11 @@ async fn list(ctx: &Ctx, repo: &str) -> Result<()> { }) }) .collect(); - ctx.emit( - json!({ "generation": "v2", "count": rows.len(), "members": rows }), - || { - println!("{} member(s) of {}:", members.len(), handle.display()); - for m in &members { - println!(" {} {}", m.identity_id, role_name(m.role)); - } - }, - ); + ctx.emit(json!({ "count": rows.len(), "members": rows }), || { + println!("{} member(s) of {}:", members.len(), handle.display()); + for m in &members { + println!(" {} {}", m.identity_id, role_name(m.role)); + } + }); Ok(()) } diff --git a/crates/dg/src/common.rs b/crates/dg/src/common.rs index c233b1ef3..850b06611 100644 --- a/crates/dg/src/common.rs +++ b/crates/dg/src/common.rs @@ -52,10 +52,10 @@ impl RepoRef { self.owner.as_deref().unwrap_or(default_owner) } - /// The repo id, when the reference is a bare base58 id (a forge-v2 repo id or a v1 - /// repo contract id, as `dash://` takes). Repo names are lowercase, so a base58 - /// id — which mixes cases — can never be mistaken for one. - pub fn contract_id(&self) -> Option<&str> { + /// The repo id, when the reference is a bare base58 id (a forge-v2 repo document id, as + /// `dash://` takes). Repo names are lowercase, so a base58 id — which mixes cases — + /// can never be mistaken for one. + pub fn repo_id(&self) -> Option<&str> { (self.owner.is_none() && looks_like_identity_id(&self.name) && self.name.chars().any(|c| c.is_ascii_uppercase())) @@ -70,7 +70,7 @@ fn invalid_ref(input: &str, why: &str) -> anyhow::Error { format!("invalid repository reference {input:?}"), ) .cause(why) - .fix("use `/`, e.g. `8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB/project`, a bare `` for your own repositories, or the repo's contract id") + .fix("use `/`, e.g. `8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB/project`, a bare `` for your own repositories, or the repo's id") .into() } @@ -82,14 +82,13 @@ fn looks_like_identity_id(s: &str) -> bool { .all(|c| c.is_ascii_alphanumeric() && !matches!(c, '0' | 'O' | 'I' | 'l')) } -/// Resolve a [`RepoRef`]: a bare id as a forge-v2 repo id or a v1 contract id; otherwise -/// `owner/name` as a forge-v2 repo, falling back to a (read-only) v1 registry listing. +/// Resolve a [`RepoRef`]: a bare id as a repo document id; otherwise `owner/name`. pub async fn resolve( client: &PlatformClient, identity: &LoadedIdentity, repo_ref: &RepoRef, ) -> Result { - if let Some(id) = repo_ref.contract_id() { + if let Some(id) = repo_ref.repo_id() { return forge_core::resolve::resolve_id(client, id) .await .with_context(|| format!("resolving repo {id}")); @@ -128,13 +127,6 @@ impl Session { }) } - /// [`Self::open`], refusing a (read-only) v1 repository before anything is signed. - pub async fn open_v2(ctx: &crate::context::Ctx, repo: &str) -> Result { - let s = Self::open(ctx, repo).await?; - s.repo.require_v2()?; - Ok(s) - } - /// The forge-v2 collaboration service, signing as this session's identity. pub fn collab(&self) -> forge_core::collab::v2::Collab<'_> { forge_core::collab::v2::Collab::new(&self.client, &self.identity, &self.bridge) @@ -180,9 +172,9 @@ mod tests { #[test] fn parses_owner_slash_name() { - let r = RepoRef::parse(&format!("{ID}/m1-75299")).unwrap(); + let r = RepoRef::parse(&format!("{ID}/my-repo")).unwrap(); assert_eq!(r.owner.as_deref(), Some(ID)); - assert_eq!(r.name, "m1-75299"); + assert_eq!(r.name, "my-repo"); } #[test] @@ -196,12 +188,10 @@ mod tests { #[test] fn a_bare_contract_id_is_a_contract_reference() { let r = RepoRef::parse(ID).unwrap(); - assert_eq!(r.contract_id(), Some(ID)); - assert_eq!(RepoRef::parse("my-repo").unwrap().contract_id(), None); + assert_eq!(r.repo_id(), Some(ID)); + assert_eq!(RepoRef::parse("my-repo").unwrap().repo_id(), None); assert_eq!( - RepoRef::parse(&format!("{ID}/my-repo")) - .unwrap() - .contract_id(), + RepoRef::parse(&format!("{ID}/my-repo")).unwrap().repo_id(), None ); } diff --git a/crates/dg/src/config.rs b/crates/dg/src/config.rs index 9c7df2fb2..329f1a2b4 100644 --- a/crates/dg/src/config.rs +++ b/crates/dg/src/config.rs @@ -8,7 +8,6 @@ //! network = "devnet" # testnet | mainnet | devnet //! devnet_name = "moutai" # devnet only //! dapi_addresses = "68.67.122.254,68.67.122.207" # devnet only; default: deployments file -//! registry_contract_id = "…" # optional override of deployments/.json //! ``` use std::path::{Path, PathBuf}; @@ -28,10 +27,6 @@ pub struct Config { /// Comma-separated devnet DAPI addresses. Overridden by `--dapi-addresses`. #[serde(skip_serializing_if = "Option::is_none")] pub dapi_addresses: Option, - /// Registry contract id override for `network` (default: the embedded - /// `forge-contracts/deployments/.json`). - #[serde(skip_serializing_if = "Option::is_none")] - pub registry_contract_id: Option, /// Absolute path to the default identity file. Overridden by `--identity` / `DASH_FORGE_KEY`. #[serde(skip_serializing_if = "Option::is_none")] pub default_identity: Option, @@ -66,9 +61,6 @@ impl Config { devnet_name: self.devnet_name.clone(), dapi_addresses: self.dapi_addresses.clone(), quorum_base_url: None, - registry: self.registry_contract_id.clone().map(|id| { - forge_core::network::Registry::override_from(id, "config registry_contract_id") - }), } } @@ -154,16 +146,18 @@ mod tests { fn devnet_config_parses_into_a_network_layer() { let cfg: Config = toml::from_str( "network = \"devnet\"\ndevnet_name = \"moutai\"\n\ - dapi_addresses = \"10.0.0.1\"\nregistry_contract_id = \"REG\"\n", + dapi_addresses = \"10.0.0.1\"\n", ) .unwrap(); let target = cfg.network_settings().resolve().unwrap(); assert_eq!(target.network.key(), "devnet-moutai"); - let registry = target.require_registry().unwrap(); - assert_eq!(registry.contract_id, "REG"); - assert_eq!( - registry.source.to_string(), - "override (config registry_contract_id)" - ); + assert!(target.require_v2().is_ok()); + } + + #[test] + fn an_old_registry_key_is_ignored() { + let cfg: Config = + toml::from_str("network = \"testnet\"\nregistry_contract_id = \"REG\"\n").unwrap(); + assert_eq!(cfg.network.as_deref(), Some("testnet")); } } diff --git a/crates/dg/src/context.rs b/crates/dg/src/context.rs index e73eb0bd5..27136fc48 100644 --- a/crates/dg/src/context.rs +++ b/crates/dg/src/context.rs @@ -21,7 +21,7 @@ pub struct Ctx { pub json: bool, /// Skip confirmation prompts (automation / CI). pub yes: bool, - /// The resolved network and the registry to use on it. + /// The resolved network and the forge-v2 contracts deployed on it. pub target: NetworkTarget, /// The resolved identity file path (from `--identity` / `DASH_FORGE_KEY` / config), if any. pub identity_path: Option, @@ -31,7 +31,7 @@ pub struct Ctx { /// /// Precedence, field by field: flags (`--network` / `--devnet-name` / `--dapi-addresses`) > /// config file > environment (`DASH_FORGE_NETWORK`, `DASH_FORGE_DEVNET_NAME`, -/// `DASH_FORGE_DAPI_ADDRESSES`, `FORGE_REGISTRY_CONTRACT_ID`) > the embedded +/// `DASH_FORGE_DAPI_ADDRESSES`) > the embedded /// `forge-contracts/deployments/.json` > testnet. A lower layer that names a /// different network contributes nothing network-specific (see `NetworkSettings::overlay`). fn resolve_target( @@ -191,7 +191,6 @@ impl Ctx { #[cfg(test)] mod tests { use super::*; - use forge_core::network::{ContractSource, Registry}; fn config(network: &str) -> Config { Config { @@ -225,44 +224,4 @@ mod tests { let t = resolve_target(flags, &config("testnet"), NetworkSettings::default()).unwrap(); assert_eq!(t.network.key(), "devnet-moutai"); } - - #[test] - fn env_registry_override_beats_the_deployment_but_not_config() { - let env = NetworkSettings { - registry: Some(Registry::override_from( - "ENVREG", - "env FORGE_REGISTRY_CONTRACT_ID", - )), - ..Default::default() - }; - let t = - resolve_target(NetworkSettings::default(), &Config::default(), env.clone()).unwrap(); - assert_eq!(t.require_registry().unwrap().contract_id, "ENVREG"); - - let cfg = Config { - registry_contract_id: Some("CFGREG".into()), - ..Default::default() - }; - let t = resolve_target(NetworkSettings::default(), &cfg, env).unwrap(); - assert_eq!(t.require_registry().unwrap().contract_id, "CFGREG"); - } - - #[test] - fn a_configured_testnet_registry_does_not_follow_network_mainnet() { - let cfg = Config { - network: Some("testnet".into()), - registry_contract_id: Some("TESTREG".into()), - ..Default::default() - }; - let flags = NetworkSettings::from_flags(Some("mainnet".into()), None, None); - let t = resolve_target(flags, &cfg, NetworkSettings::default()).unwrap(); - assert_eq!(t.network, Network::Mainnet); - assert!( - t.registry.is_none() - || matches!( - t.registry.as_ref().unwrap().source, - ContractSource::Deployment(_) - ) - ); - } } diff --git a/crates/dg/src/cost.rs b/crates/dg/src/cost.rs index 4d54f98b1..2fda490b5 100644 --- a/crates/dg/src/cost.rs +++ b/crates/dg/src/cost.rs @@ -114,7 +114,6 @@ async fn audit(ctx: &Ctx, repo: Option<&str>) -> Result<()> { json!({ "mode": "repo_storage_tally", "repoId": handle.id(), - "generation": handle.generation(), "packCount": manifests.len(), "packBytes": total_bytes, "depositLocked": cost_json(deposit_locked, price), @@ -126,9 +125,7 @@ async fn audit(ctx: &Ctx, repo: Option<&str>) -> Result<()> { manifests.len() ); println!(" deposit locked: {}", cost_line(deposit_locked, price)); - if !handle.is_v1() { - println!(" (forge-v2 packs are permanent: the deposit is not refundable)"); - } + println!(" (packs are permanent: the deposit is not refundable)"); }, ); Ok(()) diff --git a/crates/dg/src/doctor.rs b/crates/dg/src/doctor.rs index f35695f96..a6595aaa6 100644 --- a/crates/dg/src/doctor.rs +++ b/crates/dg/src/doctor.rs @@ -19,12 +19,11 @@ use std::process::Command; use anyhow::Result; use serde_json::{json, Value}; -use forge_core::network::{self, ContractSource, NetworkSettings, NetworkTarget}; +use forge_core::network::{NetworkSettings, NetworkTarget}; use forge_core::platform::{Network, PlatformClient}; use forge_core::storage::cors::probe_preflight; use forge_core::storage::policy::git_config_scoped; use forge_core::storage::{Profile, StoragePolicy, StorageProfiles}; -use forge_core::tokens::TOKEN_HISTORY_CONTRACT_ID; use forge_core::user_error::{codes, redact, UserError}; use crate::config::{config_dir, config_path, Config}; @@ -259,11 +258,6 @@ struct Counts { /// The whole report as JSON. fn report_json(ctx: &Ctx, sections: &[Section], applied: &[Value], counts: &Counts) -> Value { - let registry = ctx - .target - .registry - .as_ref() - .map(|r| json!({ "contractId": r.contract_id, "source": r.source.to_string() })); let sections_json: Vec = sections .iter() .map(|s| { @@ -283,7 +277,6 @@ fn report_json(ctx: &Ctx, sections: &[Section], applied: &[Value], counts: &Coun json!({ "ok": counts.failed == 0, "network": ctx.network_label(), - "registry": registry, "forgeV2": ctx.target.v2.as_ref().map(|ids| json!({ "core": ids.core, "collab": ids.collab, @@ -487,27 +480,15 @@ async fn check_identity(ctx: &Ctx) -> Vec { if !forge_core::keystore::is_inline_key(&path) { out.push(file_mode_check(&path)); } - out.push( - match ( - bridge.doc_op_key().is_ok(), - bridge.token_admin_key().is_ok(), - ) { - (true, true) => Check::ok( - "keys", - "HIGH/CRITICAL auth key for writes; CRITICAL for token admin", - ), - (true, false) => Check::warn( - "keys", - "writes OK; no CRITICAL key, so `dg repo create` and `dg collab` cannot sign", - "use the identity export that includes the CRITICAL AUTHENTICATION key for those", - ), - (false, _) => Check::fail( - "keys", - "no HIGH or CRITICAL AUTHENTICATION key: nothing can be signed", - "export the identity again from the bridge (it includes the auth keys)", - ), - }, - ); + out.push(if bridge.doc_op_key().is_ok() { + Check::ok("keys", "HIGH/CRITICAL auth key for writes") + } else { + Check::fail( + "keys", + "no HIGH or CRITICAL AUTHENTICATION key: nothing can be signed", + "export the identity again from the bridge (it includes the auth keys)", + ) + }); out.push(match ctx.connect().await { Err(_) => Check::warn( "balance", @@ -638,11 +619,11 @@ async fn check_network(ctx: &Ctx) -> Vec { }; let mut out = vec![Check::ok("target", target)]; - // DAPI + proof verification: fetch the registry contract, or — with no registry on this - // network (the contracts row fails for that) — the TokenHistory system contract. - let (what, contract_id) = match &ctx.target.registry { - Some(r) => ("registry contract", r.contract_id.as_str()), - None => ("TokenHistory system contract", TOKEN_HISTORY_CONTRACT_ID), + // DAPI + proof verification: fetch forge-core, or — with no forge-v2 on this network + // (the contracts row fails for that) — the DPNS system contract. + let (what, contract_id) = match &ctx.target.v2 { + Some(ids) => ("forge-core contract", ids.core.as_str()), + None => ("DPNS system contract", DPNS_CONTRACT_ID), }; let client = match ctx.connect().await { Ok(c) => c, @@ -683,14 +664,17 @@ async fn check_network(ctx: &Ctx) -> Vec { out } +/// The DPNS system contract: its id is fixed by rs-dpp and identical on every network. +const DPNS_CONTRACT_ID: &str = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec"; + /// The forge-v2 contracts recorded for this network: both must fetch with a verified proof /// and both must be enrolled, as whole contracts, in the recorded contract group. A network -/// with no forge-v2 deployment passes with a note — v1 is the live data plane there. +/// with no forge-v2 deployment is reported by the contracts row, so this one only notes it. async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Check { let Some(ids) = &target.v2 else { return Check::ok( "forge-v2", - format!("not deployed on {} (v1 repos only)", target.network.key()), + format!("not deployed on {} (see contracts)", target.network.key()), ); }; let mut problems = Vec::new(); @@ -725,42 +709,29 @@ async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Chec Check::fail( "forge-v2", problems.join("; "), - "the network may not run protocol 14 yet, or the deployment record is stale; v1 repos still work", + "the network may not run protocol 14 yet, or the deployment record is stale", ) } } -/// The registry id this invocation will use and where it came from. A network with no -/// deployment fails here with the same actionable message the commands give. +/// The forge-v2 contracts this invocation will use and where they came from. A network with +/// no deployment fails here with the same actionable message the commands give. fn check_contracts(target: &NetworkTarget) -> Check { - let embedded = network::deployed_registry(&target.network); - match (target.require_registry(), embedded) { - (Ok(r), Ok(embedded)) => { - // An override that differs from a real deployment is legitimate (a private - // registry) but worth surfacing, since it changes which repos resolve. - let note = match (&r.source, embedded) { - (ContractSource::Override(_), Some(d)) if d.contract_id != r.contract_id => { - format!("; overrides {} from {}", d.contract_id, d.source) - } - _ => String::new(), - }; - let v2 = target - .v2 - .as_ref() - .map(|v| format!(", forge-v2 core={} collab={}", v.core, v.collab)) - .unwrap_or_default(); - Check::ok( - "registry", - format!( - "registry={} (source: {}{note}), tokenHistory={TOKEN_HISTORY_CONTRACT_ID}{v2}", - r.contract_id, r.source - ), - ) - } - (Err(e), _) | (_, Err(e)) => Check::fail( - "registry", + match target.require_v2() { + Ok(ids) => Check::ok( + "forge-v2", + format!( + "core={} collab={} group={} (source: forge-contracts/deployments/{}.json)", + ids.core, + ids.collab, + ids.group, + target.network.key() + ), + ), + Err(e) => Check::fail( + "forge-v2", e.to_string(), - "use a network with a deployment (`--network testnet`), or set `registry_contract_id` in config.toml", + "use a network with a deployment: `--network devnet --devnet-name moutai`", ), } } @@ -986,49 +957,31 @@ fn in_git_repo() -> bool { #[cfg(test)] mod tests { use super::*; - use forge_core::network::Registry; #[test] fn contracts_check_reports_the_deployment_file_as_the_source() { - let target = NetworkSettings::default().resolve().unwrap(); - let c = check_contracts(&target); - assert_eq!(c.status, Status::Ok, "{}", c.detail); - assert!( - c.detail - .contains("source: forge-contracts/deployments/testnet.json"), - "{}", - c.detail - ); - } - - #[test] - fn contracts_check_names_an_override_and_what_it_replaces() { let target = NetworkSettings { - registry: Some(Registry::override_from( - "PRIVATE", - "env FORGE_REGISTRY_CONTRACT_ID", - )), + network: Some("devnet".into()), + devnet_name: Some("moutai".into()), ..Default::default() } .resolve() .unwrap(); let c = check_contracts(&target); - assert_eq!(c.status, Status::Ok); - assert!(c.detail.contains("registry=PRIVATE"), "{}", c.detail); + assert_eq!(c.status, Status::Ok, "{}", c.detail); assert!( c.detail - .contains("override (env FORGE_REGISTRY_CONTRACT_ID)"), + .contains("source: forge-contracts/deployments/devnet-moutai.json"), "{}", c.detail ); - assert!(c.detail.contains("overrides "), "{}", c.detail); } #[test] fn contracts_check_fails_clearly_on_an_undeployed_devnet() { let target = NetworkSettings { network: Some("devnet".into()), - devnet_name: Some("moutai".into()), + devnet_name: Some("paloma".into()), ..Default::default() } .resolve() @@ -1037,7 +990,7 @@ mod tests { assert_eq!(c.status, Status::Fail); assert!( c.detail - .contains("no Dash Forge registry is deployed on devnet-moutai yet"), + .contains("forge-v2 isn't deployed on devnet-paloma yet"), "{}", c.detail ); diff --git a/crates/dg/src/errors.rs b/crates/dg/src/errors.rs index 5685e5ab5..de7db0955 100644 --- a/crates/dg/src/errors.rs +++ b/crates/dg/src/errors.rs @@ -148,8 +148,6 @@ pub fn context_for(cmd: &Command) -> (Option<&'static str>, Option<&str>) { ("label not changed", Some(repo)) } Command::Collab(C::Add { repo, .. }) => ("collaborator not added", Some(repo)), - Command::Collab(C::Suspend { repo, .. }) => ("collaborator not suspended", Some(repo)), - Command::Collab(C::Unsuspend { repo, .. }) => ("collaborator not unsuspended", Some(repo)), Command::Collab(C::Remove { repo, .. }) => ("collaborator not removed", Some(repo)), Command::Collab(C::List { repo }) => ("could not list collaborators", Some(repo)), Command::Cost(CostCommand::Estimate { .. }) => ("no estimate", None), @@ -221,7 +219,11 @@ mod tests { fn every_error_path_exits_non_zero() { let e = anyhow::anyhow!("something odd"); assert_eq!(report(true, &e, &ErrorContext::default()), 1); - let core: anyhow::Error = forge_core::Error::TokenFrozen.into(); + let core: anyhow::Error = forge_core::Error::NotAMember { + document_type: "refUpdate".into(), + detail: "40120".into(), + } + .into(); assert_eq!(report(true, &core, &ErrorContext::default()), 6); } } diff --git a/crates/dg/src/issue.rs b/crates/dg/src/issue.rs index dcf76bb61..37310b6f0 100644 --- a/crates/dg/src/issue.rs +++ b/crates/dg/src/issue.rs @@ -3,14 +3,12 @@ //! forge-v2 repositories go through [`forge_core::collab::v2::Collab`]: issues are numbered //! by the `forge-v2.md` §6 rule, a create is journaled so a re-run resumes it, and close / //! reopen pick their gate automatically (a member's `event`, else the author's -//! `authorEvent`). v1 repositories are read only: `list` and `view` still read them, every -//! write is refused (E605) before anything is signed. +//! `authorEvent`). -use anyhow::{Context, Result}; +use anyhow::Result; use serde_json::json; use forge_core::collab::v2::{Collab, Target}; -use forge_core::collab::IssueService; use forge_core::create::default_journal_dir; use forge_core::rules::{EventKind, IssueState}; @@ -54,29 +52,17 @@ fn labels_of(state: &IssueState) -> String { async fn list(ctx: &Ctx, repo: &str, state: StateArg, limit: u32) -> Result<()> { let s = Session::open(ctx, repo).await?; + let collab = Collab::reader(&s.client); + let page = collab.list_issues(&s.repo, limit).await?; + let (hidden, more) = (page.hidden, page.more); // (number, title, author, state) - let (rows, hidden, more): (Vec, usize, bool) = if s.repo.is_v1() { - let issues = IssueService::new(&s.client, &s.identity, &s.bridge) - .list_issues(s.repo.v1_contract_id()?, state.into(), limit, None) - .await - .context("list_issues")?; - let rows = issues - .into_iter() - .map(|iw| (iw.issue.number, iw.issue.title, iw.issue.author, iw.state)) - .collect(); - (rows, 0, false) - } else { - let collab = Collab::reader(&s.client); - let page = collab.list_issues(&s.repo, limit).await?; - let mut rows = Vec::new(); - for issue in page.rows { - let st = collab.issue_state(&s.repo, &issue).await?; - if state.matches(st.open) { - rows.push((u64::from(issue.number), issue.title, issue.author, st)); - } + let mut rows: Vec = Vec::new(); + for issue in page.rows { + let st = collab.issue_state(&s.repo, &issue).await?; + if state.matches(st.open) { + rows.push((u64::from(issue.number), issue.title, issue.author, st)); } - (rows, page.hidden, page.more) - }; + } let json_rows: Vec<_> = rows .iter() @@ -120,44 +106,21 @@ async fn list(ctx: &Ctx, repo: &str, state: StateArg, limit: u32) -> Result<()> async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { let s = Session::open(ctx, repo).await?; - // (id, title, body, author, state, comments [(author, body)]) - let (id, title, body, author, state, comments) = if s.repo.is_v1() { - let iw = IssueService::new(&s.client, &s.identity, &s.bridge) - .issue_state(s.repo.v1_contract_id()?, number) - .await - .context("issue_state")? - .ok_or_else(|| not_found(repo, number))?; - let i = iw.issue; - ( - i.document_id, - i.title, - i.body, - i.author, - iw.state, - Vec::new(), - ) - } else { - let collab = Collab::reader(&s.client); - let view = collab - .issue_view(&s.repo, number_arg(number)?) - .await? - .ok_or_else(|| not_found(repo, number))?; - let comments = collab - .comments(&s.repo, &view.issue.document_id) - .await? - .into_iter() - .map(|c| (c.author, c.body)) - .collect::>(); - let i = view.issue; - ( - i.document_id, - i.title, - i.body, - i.author, - view.state, - comments, - ) - }; + let collab = Collab::reader(&s.client); + let view = collab + .issue_view(&s.repo, number_arg(number)?) + .await? + .ok_or_else(|| not_found(repo, number))?; + // [(author, body)] + let comments = collab + .comments(&s.repo, &view.issue.document_id) + .await? + .into_iter() + .map(|c| (c.author, c.body)) + .collect::>(); + let state = view.state; + let i = view.issue; + let (id, title, body, author) = (i.document_id, i.title, i.body, i.author); ctx.emit( json!({ @@ -188,7 +151,7 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { } async fn create(ctx: &Ctx, repo: &str, title: &str, body: &str) -> Result<()> { - let s = Session::open_v2(ctx, repo).await?; + let s = Session::open(ctx, repo).await?; ctx.confirm_or_cancel(&format!( "Open issue {title:?} in {}? (one small document, ~0.0001 DASH)", s.repo.display() @@ -237,7 +200,7 @@ async fn target(s: &Session, repo: &str, number: u64) -> Result { } async fn comment(ctx: &Ctx, repo: &str, number: u64, body: &str) -> Result<()> { - let s = Session::open_v2(ctx, repo).await?; + let s = Session::open(ctx, repo).await?; let target = target(&s, repo, number).await?; ctx.confirm_or_cancel(&format!("Comment on issue #{number}? (one small document)"))?; let id = s @@ -252,7 +215,7 @@ async fn comment(ctx: &Ctx, repo: &str, number: u64, body: &str) -> Result<()> { } async fn set_open(ctx: &Ctx, repo: &str, number: u64, close: bool) -> Result<()> { - let s = Session::open_v2(ctx, repo).await?; + let s = Session::open(ctx, repo).await?; let target = target(&s, repo, number).await?; let (verb, prompt) = if close { ("close", "Close") @@ -303,7 +266,7 @@ async fn label( )) } }; - let s = Session::open_v2(ctx, repo).await?; + let s = Session::open(ctx, repo).await?; let target = target(&s, repo, number).await?; ctx.confirm_or_cancel(&format!( "Label issue #{number} ({value})? (one small document; members only)" diff --git a/crates/dg/src/label.rs b/crates/dg/src/label.rs index ee87ef526..563f7a069 100644 --- a/crates/dg/src/label.rs +++ b/crates/dg/src/label.rs @@ -2,11 +2,10 @@ //! newest definition per name wins). Applying a label to an issue or PR is //! `dg issue label` (a member `event`). -use anyhow::{Context, Result}; +use anyhow::Result; use serde_json::json; use forge_core::collab::v2::Collab; -use forge_core::collab::LabelService; use crate::common::Session; use crate::context::Ctx; @@ -28,14 +27,7 @@ pub async fn run(ctx: &Ctx, cmd: &LabelCommand) -> Result<()> { async fn list(ctx: &Ctx, repo: &str, all: bool) -> Result<()> { let s = Session::open(ctx, repo).await?; - let labels = if s.repo.is_v1() { - LabelService::new(&s.client, &s.identity, &s.bridge) - .list_labels(s.repo.v1_contract_id()?) - .await - .context("list_labels")? - } else { - Collab::reader(&s.client).labels(&s.repo).await? - }; + let labels = Collab::reader(&s.client).labels(&s.repo).await?; let shown: Vec<_> = labels.iter().filter(|l| all || !l.retired).collect(); ctx.emit( json!({ @@ -68,7 +60,7 @@ async fn define( description: &str, retired: bool, ) -> Result<()> { - let s = Session::open_v2(ctx, repo).await?; + let s = Session::open(ctx, repo).await?; let verb = if retired { "Retire" } else { "Define" }; ctx.confirm_or_cancel(&format!( "{verb} label {name:?} in {}? (one small document; members only)", diff --git a/crates/dg/src/main.rs b/crates/dg/src/main.rs index 876e2fa2f..e8fdcbc4b 100644 --- a/crates/dg/src/main.rs +++ b/crates/dg/src/main.rs @@ -114,7 +114,7 @@ pub enum Command { /// Label definitions (apply one with `dg issue label`). #[command(subcommand)] Label(LabelCommand), - /// Collaborator (token) management. + /// Repository members (writers and maintainers). #[command(subcommand)] Collab(CollabCommand), /// Cost estimates and spend audits. @@ -539,28 +539,6 @@ pub enum CollabCommand { #[arg(long, value_enum, default_value = "writer")] role: RoleArg, }, - /// Not supported on forge-v2 (remove revokes access immediately). - #[command(hide = true)] - Suspend { - /// The repository (`owner/name`). - repo: String, - /// The collaborator identity id (base58). - member: String, - /// The role to suspend. - #[arg(long, value_enum, default_value = "writer")] - role: RoleArg, - }, - /// Not supported on forge-v2 (add restores access). - #[command(hide = true)] - Unsuspend { - /// The repository (`owner/name`). - repo: String, - /// The collaborator identity id (base58). - member: String, - /// The role to unsuspend. - #[arg(long, value_enum, default_value = "writer")] - role: RoleArg, - }, /// Remove a member (the owner deletes their document; their next push is refused). Remove { /// The repository (`owner/name`). @@ -803,16 +781,6 @@ impl StateArg { } } -impl From for forge_core::collab::StateFilter { - fn from(s: StateArg) -> Self { - match s { - StateArg::All => Self::All, - StateArg::Open => Self::Open, - StateArg::Closed => Self::Closed, - } - } -} - /// PR review verdict. #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] pub enum VerdictArg { @@ -1091,19 +1059,6 @@ mod tests { } } - #[test] - fn parses_collab_unsuspend() { - let cli = Cli::parse_from(["dg", "collab", "unsuspend", "o/r", "member123"]); - match cli.command { - Command::Collab(CollabCommand::Unsuspend { repo, member, role }) => { - assert_eq!(repo, "o/r"); - assert_eq!(member, "member123"); - assert!(matches!(role, RoleArg::Writer)); // default role - } - _ => panic!("expected collab unsuspend"), - } - } - #[test] fn cli_definition_is_consistent() { Cli::command().debug_assert(); diff --git a/crates/dg/src/maint.rs b/crates/dg/src/maint.rs index ab3fc5ba4..a80b0b095 100644 --- a/crates/dg/src/maint.rs +++ b/crates/dg/src/maint.rs @@ -35,7 +35,6 @@ pub async fn repack( let repo_ref = RepoRef::parse(repo)?; let (client, bridge, identity) = ctx.connect_with_identity().await?; let handle = resolve(&client, &identity, &repo_ref).await?; - handle.require_v2()?; let svc = RepoService::new(&client, &identity, &bridge); let price = dash_usd_price(); @@ -162,7 +161,6 @@ pub async fn reseed( }; let target_label = profile.unwrap_or_else(|| to.map_or("external", Backend::label)); - handle.require_v2()?; if !ctx.confirm(&format!( "Reseed {} packs to {target_label}? (re-uploads pack bytes for availability)", handle.display() diff --git a/crates/dg/src/pr.rs b/crates/dg/src/pr.rs index fcfaf0b26..b9a66f2c1 100644 --- a/crates/dg/src/pr.rs +++ b/crates/dg/src/pr.rs @@ -1,4 +1,4 @@ -//! `dg pr` — pull requests on forge-v2 (v1 repositories are read only). +//! `dg pr` — pull requests on forge-v2. //! //! * `create` opens a `patch` in the target repo pointing at the repo that holds the head //! commit (`sourceRepoId`): the target itself, or a fork. With no flags it uses the @@ -19,8 +19,8 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use serde_json::json; -use forge_core::collab::v2::{Collab, PatchInput, PatchView, V2Patch}; -use forge_core::collab::{PullRequest, PullRequestService, Verdict}; +use forge_core::collab::v2::{Collab, Patch, PatchInput, PatchView}; +use forge_core::collab::Verdict; use forge_core::create::default_journal_dir; use forge_core::rules::v2::Role; use forge_core::rules::EventKind; @@ -96,7 +96,7 @@ fn not_found(repo: &str, number: u64) -> anyhow::Error { } /// The v2 PR `number` of `handle`, or E102. -async fn patch(collab: &Collab<'_>, handle: &Repo, repo: &str, number: u64) -> Result { +async fn patch(collab: &Collab<'_>, handle: &Repo, repo: &str, number: u64) -> Result { collab .patch(handle, number_arg(number)?) .await? @@ -118,9 +118,9 @@ fn state_label(v: &PatchView) -> &'static str { // --------------------------------------------------------------------------- async fn create(ctx: &Ctx, args: &crate::PrCreateArgs) -> Result<()> { - let s = Session::open_v2(ctx, &args.repo).await?; + let s = Session::open(ctx, &args.repo).await?; let handle = &s.repo; - let forge = handle.require_v2()?; + let forge = handle.forge(); let cwd = std::env::current_dir().context("reading the current directory")?; // Where the branch may live: --head-repo, else the signer's forks of the target, then the @@ -230,7 +230,6 @@ async fn resolve_head( }; let mut found = None; for repo in &candidates { - repo.require_v2()?; let refs = svc.read_refs(repo).await?; if let Some(tip) = refs .iter() @@ -287,24 +286,6 @@ async fn resolve_head( async fn list(ctx: &Ctx, repo: &str, limit: u32, state: crate::StateArg) -> Result<()> { let s = Session::open(ctx, repo).await?; let handle = &s.repo; - if handle.is_v1() { - let prs = PullRequestService::new(&s.client, &s.identity, &s.bridge) - .list_prs(handle.v1_contract_id()?, limit, None) - .await - .context("list_prs")?; - let rows: Vec<_> = prs.iter().map(v1_row).collect(); - ctx.emit(json!({ "count": rows.len(), "prs": rows }), || { - for p in &prs { - println!( - "#{:<4} {} ({})", - p.number, - safe(&p.title), - short(&p.head_oid) - ); - } - }); - return Ok(()); - } let collab = Collab::reader(&s.client); let page = collab.list_patches(handle, limit).await?; let (hidden, more) = (page.hidden, page.more); @@ -370,40 +351,9 @@ async fn list(ctx: &Ctx, repo: &str, limit: u32, state: crate::StateArg) -> Resu Ok(()) } -fn v1_row(p: &PullRequest) -> serde_json::Value { - json!({ - "number": p.number, - "title": p.title, - "author": p.author, - "baseRef": p.base_ref_name, - "headOid": p.head_oid, - "sourceContractId": p.source_contract_id, - }) -} - -fn view_v1(ctx: &Ctx, pw: &forge_core::collab::PullRequestWithState) { - let mut row = v1_row(&pw.pr); - row["body"] = json!(pw.pr.body); - row["state"] = serde_json::to_value(&pw.state).unwrap_or_default(); - ctx.emit(row, || { - println!("#{} {}", pw.pr.number, safe(&pw.pr.title)); - println!("base: {} head: {}", pw.pr.base_ref_name, pw.pr.head_oid); - println!("(v1 repository, read only)"); - }); -} - async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { let s = Session::open(ctx, repo).await?; let (client, handle) = (&s.client, &s.repo); - if handle.is_v1() { - let pw = PullRequestService::new(client, &s.identity, &s.bridge) - .pr_state(handle.v1_contract_id()?, number, None) - .await - .context("pr_state")? - .ok_or_else(|| not_found(repo, number))?; - view_v1(ctx, &pw); - return Ok(()); - } let collab = Collab::reader(client); let p = patch(&collab, handle, repo, number).await?; let v = collab.patch_view(handle, p).await?; @@ -497,7 +447,7 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> { // --------------------------------------------------------------------------- async fn review(ctx: &Ctx, repo: &str, number: u64, verdict: VerdictArg, body: &str) -> Result<()> { - let s = Session::open_v2(ctx, repo).await?; + let s = Session::open(ctx, repo).await?; let (handle, collab) = (&s.repo, s.collab()); let p = patch(&collab, handle, repo, number).await?; let v = Verdict::from_code(verdict.code()); @@ -531,7 +481,7 @@ async fn review(ctx: &Ctx, repo: &str, number: u64, verdict: VerdictArg, body: & } async fn set_open(ctx: &Ctx, repo: &str, number: u64, close: bool) -> Result<()> { - let s = Session::open_v2(ctx, repo).await?; + let s = Session::open(ctx, repo).await?; let collab = s.collab(); let p = patch(&collab, &s.repo, repo, number).await?; let verb = if close { "Close" } else { "Reopen" }; @@ -583,7 +533,7 @@ async fn merge( event_only: bool, merge_oid: Option<&str>, ) -> Result<()> { - let s = Session::open_v2(ctx, repo).await?; + let s = Session::open(ctx, repo).await?; let (handle, collab) = (&s.repo, s.collab()); let p = patch(&collab, handle, repo, number).await?; let view = collab.patch_view(handle, p).await?; @@ -1020,7 +970,7 @@ fn push_to(dir: &Path, argv: &[String], env: &[(String, String)]) -> Result<()> // --------------------------------------------------------------------------- /// Where a PR's pieces are: the source repo id, the head oid, the base ref, and the target -/// repo's id (v2), or the v1 equivalents. +/// repo's id. struct Located { source: String, head: String, @@ -1031,16 +981,8 @@ struct Located { async fn locate(ctx: &Ctx, repo: &str, number: u64) -> Result { let s = Session::open(ctx, repo).await?; let target = s.repo.id().to_string(); - let (source, head, base_ref) = if s.repo.is_v1() { - let pr = PullRequestService::new(&s.client, &s.identity, &s.bridge) - .get_pr(s.repo.v1_contract_id()?, number) - .await? - .ok_or_else(|| not_found(repo, number))?; - (pr.source_contract_id, pr.head_oid, pr.base_ref_name) - } else { - let p = patch(&Collab::reader(&s.client), &s.repo, repo, number).await?; - (p.source_repo_id, p.head_oid, p.base_ref_name) - }; + let p = patch(&Collab::reader(&s.client), &s.repo, repo, number).await?; + let (source, head, base_ref) = (p.source_repo_id, p.head_oid, p.base_ref_name); // Every field came from a document anyone could have written: check the shapes before // any of them reaches git. if !git::is_oid(&head) { diff --git a/crates/dg/src/release.rs b/crates/dg/src/release.rs index 4d6a2e600..59164ed36 100644 --- a/crates/dg/src/release.rs +++ b/crates/dg/src/release.rs @@ -14,7 +14,7 @@ use serde_json::json; use forge_core::backends::PackMeta; use forge_core::collab::v2::Collab; -use forge_core::collab::{Release, ReleaseAsset, ReleaseInput, ReleaseService}; +use forge_core::collab::{Release, ReleaseAsset, ReleaseInput}; use forge_core::rules::v2::Role; use forge_core::storage::policy::git_config_scoped; use forge_core::storage::{ @@ -109,7 +109,7 @@ async fn upload_asset( } async fn create(ctx: &Ctx, args: &ReleaseCreateArgs) -> Result<()> { - let s = Session::open_v2(ctx, &args.repo).await?; + let s = Session::open(ctx, &args.repo).await?; let collab = s.collab(); let tag = &args.tag; // Maintainer-only at consensus: find out before uploading anything. @@ -200,13 +200,6 @@ fn asset_json(a: &ReleaseAsset) -> serde_json::Value { /// The releases of `repo` (newest per tag, newest first) and the superseded revisions. async fn read_releases(ctx: &Ctx, repo: &str) -> Result<(Vec, Vec)> { let s = Session::open(ctx, repo).await?; - if s.repo.is_v1() { - let r = ReleaseService::new(&s.client, &s.identity, &s.bridge) - .list_releases(s.repo.v1_contract_id()?) - .await - .context("list_releases")?; - return Ok((r, Vec::new())); - } Ok(Collab::reader(&s.client).releases(&s.repo).await?) } diff --git a/crates/dg/src/repo.rs b/crates/dg/src/repo.rs index 00f281386..aa46c61cf 100644 --- a/crates/dg/src/repo.rs +++ b/crates/dg/src/repo.rs @@ -4,8 +4,7 @@ //! New repositories are forge-v2: a `repo` document plus the owner's `maintainer` //! membership and an initial `config` in the network's shared forge-core contract, written //! by one resumable session (`forge_core::create`). A fork is the same plus `forkOf`, the -//! parent's packs recorded by reference and its refs copied (`forge_core::fork`). v1 -//! repositories (one contract each) remain viewable and cloneable but are read only. +//! parent's packs recorded by reference and its refs copied (`forge_core::fork`). //! Repositories cannot be deleted. use std::collections::{BTreeMap, BTreeSet}; @@ -17,7 +16,6 @@ use forge_core::create::{create_repo, default_journal_dir, CreateRepoOpts, StepO use forge_core::members::MemberReader; use forge_core::repo::RepoService; use forge_core::resolve::{list_owned, repo_slug}; -use forge_core::tokens::TokenService; use crate::common::{resolve, RepoRef, Session}; use crate::context::Ctx; @@ -148,7 +146,7 @@ async fn fork(ctx: &Ctx, repo: &str, name: Option<&str>) -> Result<()> { bridge, identity, repo: parent, - } = Session::open_v2(ctx, repo).await?; + } = Session::open(ctx, repo).await?; let slug = repo_slug(name.unwrap_or(parent.name()))?; if parent.owner_id() == identity.id() && slug == parent.name() { return Err(crate::errors::usage(format!( @@ -268,7 +266,7 @@ fn report_fork( /// Star or unstar `repo` (forge-collab `star`, `indexOnly`; unstar is the values-carrying /// delete). async fn star(ctx: &Ctx, repo: &str, on: bool) -> Result<()> { - let s = Session::open_v2(ctx, repo).await?; + let s = Session::open(ctx, repo).await?; let handle = &s.repo; let verb = if on { "Star" } else { "Unstar" }; ctx.confirm_or_cancel(&format!( @@ -314,16 +312,10 @@ async fn view(ctx: &Ctx, repo: &str) -> Result<()> { let default_branch = svc.read_default_branch(&handle).await.unwrap_or(None); let refs = svc.read_refs(&handle).await.unwrap_or_default(); let manifests = svc.read_pack_manifests(&handle).await.unwrap_or_default(); - let members = match handle.v1_contract_id() { - Ok(contract) => TokenService::new(&client) - .list_collaborators(contract) - .await - .map_or(0, |c| c.len()), - Err(_) => MemberReader::new(&client) - .list(&handle) - .await - .map_or(0, |m| m.len()), - }; + let members = MemberReader::new(&client) + .list(&handle) + .await + .map_or(0, |m| m.len()); let refs_json: Vec<_> = refs .iter() @@ -335,11 +327,9 @@ async fn view(ctx: &Ctx, repo: &str) -> Result<()> { ctx.emit( json!({ - "generation": handle.generation(), "repoId": handle.id(), "ownerId": handle.owner_id(), "name": handle.name(), - "readOnly": handle.is_v1(), "defaultBranch": default_branch, "refs": refs_json, "packCount": manifests.len(), @@ -349,11 +339,6 @@ async fn view(ctx: &Ctx, repo: &str) -> Result<()> { }), || { println!("{}", handle.display()); - println!( - " generation: {}{}", - handle.generation(), - if handle.is_v1() { " (read only)" } else { "" } - ); println!(" id: {}", handle.id()); println!( " default branch: {}", @@ -384,7 +369,7 @@ fn ref_state_short(state: &forge_core::rules::RefState) -> String { } } -/// List an owner's repositories: forge-v2 repos, then v1 registry listings. +/// List an owner's repositories. async fn list(ctx: &Ctx, owner: Option<&str>) -> Result<()> { let (client, _bridge, identity) = ctx.connect_with_identity().await?; let owner_id = owner.map_or_else(|| identity.id(), str::to_string); @@ -396,7 +381,6 @@ async fn list(ctx: &Ctx, owner: Option<&str>) -> Result<()> { .map(|r| { json!({ "name": r.repo.name(), - "generation": r.repo.generation(), "repoId": r.repo.id(), "description": r.description, }) @@ -407,12 +391,7 @@ async fn list(ctx: &Ctx, owner: Option<&str>) -> Result<()> { || { println!("{} repo(s) for {owner_id}:", repos.len()); for r in &repos { - println!( - " {} [{}] {}", - r.repo.name(), - r.repo.generation(), - r.description - ); + println!(" {} {}", r.repo.name(), r.description); } }, ); @@ -424,7 +403,6 @@ async fn backend_set(ctx: &Ctx, repo: &str, mode: u8, label: &str) -> Result<()> let repo_ref = RepoRef::parse(repo)?; let (client, bridge, identity) = ctx.connect_with_identity().await?; let handle = resolve(&client, &identity, &repo_ref).await?; - handle.require_v2()?; if !ctx.confirm(&format!( "Set backend of {} to {label}? (a small config write)", diff --git a/crates/dg/src/webhook.rs b/crates/dg/src/webhook.rs index 026f3d414..fc084684b 100644 --- a/crates/dg/src/webhook.rs +++ b/crates/dg/src/webhook.rs @@ -201,7 +201,6 @@ async fn list(ctx: &Ctx, repo: &str) -> Result<()> { let repo_ref = RepoRef::parse(repo)?; let (client, _bridge, identity) = ctx.connect_with_identity().await?; let handle = resolve(&client, &identity, &repo_ref).await?; - handle.require_v2()?; let hooks = newest_per_hook( WebhookReader::new(&client) .for_repo(handle.id()) diff --git a/crates/forge-core/Cargo.toml b/crates/forge-core/Cargo.toml index 086813ff8..6150eef9a 100644 --- a/crates/forge-core/Cargo.toml +++ b/crates/forge-core/Cargo.toml @@ -41,7 +41,7 @@ getrandom = "0.2" reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "multipart"] } async-trait = "0.1" futures = "0.3" -# `time` only — the bounded read-after-write verify polls (tokens.rs) sleep between +# `time` only — the bounded read-after-write verify polls sleep between # re-reads on the caller's tokio runtime (the SDK's broadcast_and_wait already needs one). tokio = { workspace = true, features = ["time"] } diff --git a/crates/forge-core/src/backends/live_tests.rs b/crates/forge-core/src/backends/live_tests.rs index ba476d49e..c6797e15c 100644 --- a/crates/forge-core/src/backends/live_tests.rs +++ b/crates/forge-core/src/backends/live_tests.rs @@ -475,52 +475,3 @@ async fn replicate_to_minio_and_kubo_then_read_back() { assert_eq!(err.confirmed[0].target, "minio"); assert!(err.to_string().contains("dead:"), "{err}"); } - -/// LIVE platform-backend write (`chunk` docs via the WriteEngine). Ignored by default: it -/// needs a testnet connection, a `chunk`-capable contract and a funded, WRITE-token'd -/// identity. Run explicitly once the fixtures are in place: -/// -/// ```text -/// FORGE_TESTNET_IDENTITY= \ -/// FORGE_TESTNET_KEYSTORE= \ -/// FORGE_TESTNET_CONTRACT=9hqcGGpuvN86bkbVUQNL99V1Qd5D9pgKjQd5xEXDv8EP \ -/// cargo test -p forge-core -- --ignored platform_backend_live_put -/// ``` -/// -/// The chunk encode/decode + reassembly path this exercises is already covered offline by -/// the `platform` submodule's unit tests; this proves the on-chain pipelined write. -#[tokio::test] -#[ignore = "needs testnet + funded identity + chunk contract; see doc comment"] -async fn platform_backend_live_put() { - use crate::backends::PlatformBackend; - use crate::keystore::BridgeIdentity; - use crate::platform::{Network, PlatformClient, WriteEngine}; - - let identity_id = std::env::var("FORGE_TESTNET_IDENTITY").expect("FORGE_TESTNET_IDENTITY"); - let keystore_path = std::env::var("FORGE_TESTNET_KEYSTORE").expect("FORGE_TESTNET_KEYSTORE"); - let contract_id = std::env::var("FORGE_TESTNET_CONTRACT").expect("FORGE_TESTNET_CONTRACT"); - - let client = PlatformClient::connect_network(Network::Testnet) - .await - .unwrap(); - let contract = client.fetch_contract(&contract_id).await.unwrap(); - let identity = client.fetch_identity(&identity_id).await.unwrap(); - let bridge = BridgeIdentity::load_from_file(&keystore_path).unwrap(); - let key = bridge.doc_op_key().unwrap(); - let engine = WriteEngine::new(&client, &identity, key).unwrap(); - - // The S0.1 throwaway contract is its own scope (a v1-shaped chunk type, no `repoId`). - let scope = crate::scope::DocScope { - contract_id: contract_id.clone(), - repo_id: None, - }; - let backend = PlatformBackend::new(&engine, &contract, &scope, identity_id.clone()); - // A SMALL payload → a few chunk docs. - let data: Vec = (0..20_000u32) - .map(|i| u8::try_from(i % 251).unwrap()) - .collect(); - let meta = PackMeta::for_bytes(&data); - let uris = backend.put(&data, &meta).await.expect("platform chunk put"); - assert_eq!(uris.len(), 1); - assert_eq!(uris[0].scheme(), Some("platform")); -} diff --git a/crates/forge-core/src/backends/platform.rs b/crates/forge-core/src/backends/platform.rs index 138f18717..3029355a3 100644 --- a/crates/forge-core/src/backends/platform.rs +++ b/crates/forge-core/src/backends/platform.rs @@ -8,7 +8,7 @@ //! Read-back is by `(packHash, seq)` range. //! //! Read-back ([`PlatformBackend::get`]) reads one uploader's chunks by -//! `(packHash, seq)` (with `repoId` and the uploader on forge-v2, see +//! `(repoId, uploader, packHash, seq)` (see //! [`crate::scope::DocScope::chunk_filters`]) and reassembles them with the pure //! [`crate::pack::join`]. The chunk encode/decode is covered offline; the write path by the //! `#[ignore]`d live tests. @@ -103,39 +103,31 @@ pub fn chunk_documents( .collect() } -/// A parsed `platform://` locator: where the chunks live, whose they are, and which pack. +/// A parsed `platform://///` locator: where the chunks live, +/// whose they are, and which pack. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PlatformLocator { - /// The contract holding the chunks: forge-core (v2) or the repo contract (v1). + /// The contract holding the chunks (forge-core). pub contract: String, - /// The repo whose scope holds the chunks (v2 only). A fork's manifest names its - /// parent's chunks this way, so the fork re-uploads nothing. - pub repo: Option, - /// The uploader whose copy the chunks are. forge-v2 locators name it (a v2 chunk's key - /// includes `$ownerId`); v1 ones do not, the repo contract being the whole scope. - pub owner: Option, + /// The repo whose scope holds the chunks. A fork's manifest names its parent's chunks + /// this way, so the fork re-uploads nothing. + pub repo: String, + /// The uploader whose copy the chunks are (a chunk's key includes `$ownerId`). + pub owner: String, /// The pack hash. pub pack_hash: [u8; 32], } impl PlatformLocator { - /// Parse `platform:///` (v1) or - /// `platform://///` (v2). + /// Parse `platform://///`. pub fn parse(uri: &Uri) -> Result { let rest = uri .rest() .filter(|_| uri.scheme() == Some(PLATFORM_SCHEME)) .ok_or_else(|| Error::Config(format!("not a platform locator: {uri}")))?; let parts: Vec<&str> = rest.split('/').collect(); - let (contract, repo, owner, hex_hash) = match parts.as_slice() { - [contract, hash] => (*contract, None, None, *hash), - [core, repo, owner, hash] => ( - *core, - Some((*repo).to_string()), - Some((*owner).to_string()), - *hash, - ), - _ => return Err(Error::Config(format!("malformed platform locator: {uri}"))), + let [contract, repo, owner, hex_hash] = parts.as_slice() else { + return Err(Error::Config(format!("malformed platform locator: {uri}"))); }; let raw = hex::decode(hex_hash) .map_err(|e| Error::Config(format!("platform locator packHash not hex: {e}")))?; @@ -143,9 +135,9 @@ impl PlatformLocator { .try_into() .map_err(|_| Error::Config("platform locator packHash is not 32 bytes".into()))?; Ok(Self { - contract: contract.to_string(), - repo, - owner, + contract: (*contract).to_string(), + repo: (*repo).to_string(), + owner: (*owner).to_string(), pack_hash, }) } @@ -154,11 +146,7 @@ impl PlatformLocator { pub fn scope(&self) -> Result { Ok(DocScope { contract_id: self.contract.clone(), - repo_id: self - .repo - .as_deref() - .map(crate::platform::decode_identifier) - .transpose()?, + repo_id: crate::platform::decode_identifier(&self.repo)?, }) } } @@ -172,7 +160,7 @@ pub struct PlatformBackend<'a> { engine: &'a WriteEngine<'a>, contract: &'a LoadedContract, scope: &'a DocScope, - /// The identity the engine writes as (a v2 chunk's key includes its uploader). + /// The identity the engine writes as (a chunk's key includes its uploader). writer: String, } @@ -197,15 +185,12 @@ impl<'a> PlatformBackend<'a> { Uri(self.scope.locator(&self.writer, pack_hash)) } - /// The scope a locator's chunks are read from: this backend's own, or on forge-v2 - /// another repo's in the same contract (a fork's manifest names its parent's chunks, - /// which chunk reads can address because the chunk key is `(repoId, uploader, pack, - /// seq)`). A locator into another contract is refused: this backend holds one contract. - /// Pointing at other chunks is harmless: the bytes are verified against the pack hash. + /// The scope a locator's chunks are read from: this backend's own, or another repo's in + /// the same contract (a fork's manifest names its parent's chunks, which chunk reads can + /// address because the chunk key is `(repoId, uploader, pack, seq)`). A locator into + /// another contract is refused: this backend holds one contract. Pointing at other + /// chunks is harmless: the bytes are verified against the pack hash. fn read_scope(&self, loc: &PlatformLocator) -> Result { - if loc.repo.is_none() || !self.scope.is_v2() { - return Ok(self.scope.clone()); - } let scope = loc.scope()?; if scope.contract_id != self.scope.contract_id { return Err(Error::Config(format!( @@ -217,7 +202,7 @@ impl<'a> PlatformBackend<'a> { } /// Read every `chunk` document of `owner`'s copy of `pack_hash` (complete, `seq` - /// ordered) and decode each to a [`Chunk`]. `owner` is required on forge-v2. + /// ordered) and decode each to a [`Chunk`]. async fn read_chunks(&self, loc: &PlatformLocator) -> Result> { let scope = self.read_scope(loc)?; let docs = self @@ -226,7 +211,7 @@ impl<'a> PlatformBackend<'a> { .query_all_documents( self.contract, CHUNK_DOC_TYPE, - &scope.chunk_filters(loc.owner.as_deref(), loc.pack_hash)?, + &scope.chunk_filters(&loc.owner, loc.pack_hash)?, &[QueryOrder::asc(FIELD_SEQ)], ) .await?; @@ -331,7 +316,7 @@ impl PackBackend for PlatformBackend<'_> { CHUNK_DOC_TYPE, &self .read_scope(&loc)? - .chunk_filters(loc.owner.as_deref(), loc.pack_hash)?, + .chunk_filters(&loc.owner, loc.pack_hash)?, &[QueryOrder::asc(FIELD_SEQ)], 1, None, @@ -431,15 +416,14 @@ mod tests { } #[test] - fn locators_parse_in_both_generations() { + fn locators_parse() { let h = "cd".repeat(32); - let v1 = PlatformLocator::parse(&Uri(format!("platform://C/{h}"))).unwrap(); - assert_eq!(v1.owner, None); - assert_eq!(v1.pack_hash, [0xcd; 32]); - let v2 = PlatformLocator::parse(&Uri(format!("platform://C/R/OWNER/{h}"))).unwrap(); - assert_eq!(v2.owner.as_deref(), Some("OWNER")); - assert_eq!((v2.contract.as_str(), v2.repo.as_deref()), ("C", Some("R"))); - assert_eq!((v1.contract.as_str(), v1.repo.as_deref()), ("C", None)); + let loc = PlatformLocator::parse(&Uri(format!("platform://C/R/OWNER/{h}"))).unwrap(); + assert_eq!(loc.owner, "OWNER"); + assert_eq!(loc.pack_hash, [0xcd; 32]); + assert_eq!((loc.contract.as_str(), loc.repo.as_str()), ("C", "R")); + // The per-repo-contract form (`platform:///`) is not a locator. + assert!(PlatformLocator::parse(&Uri(format!("platform://C/{h}"))).is_err()); assert!(PlatformLocator::parse(&Uri(format!("platform://C/R/{h}"))).is_err()); assert!(PlatformLocator::parse(&Uri(format!("https://C/{h}"))).is_err()); } diff --git a/crates/forge-core/src/collab/mod.rs b/crates/forge-core/src/collab/mod.rs index d328c14fe..6d4075bdb 100644 --- a/crates/forge-core/src/collab/mod.rs +++ b/crates/forge-core/src/collab/mod.rs @@ -1,59 +1,23 @@ -//! Collaboration services — issues, pull requests, reviews, releases, labels, and the -//! registry social graph (stars / follows). +//! Collaboration types and document codecs shared by the forge-collab services. //! -//! These are the document-write + fold-read APIs the `dg` CLI and forge-web drive on top -//! of a repo contract (issues/PRs/comments/events/reviews/releases/labels) and the global -//! registry contract (stars/follows). Everything SDK-shaped is reached through -//! [`crate::platform`]; state resolution (issue/PR open-vs-closed, actor authorization) is -//! delegated to [`crate::rules`] — this module only fetches the raw documents and hands -//! them in (data-contracts §4). -//! -//! * [`IssueService`] — un-gated issue create (optimistic `number` = max+1 with -//! unique-index retry), comment, append-only `event` log (close/reopen/label/assign), -//! and state via [`crate::rules::fold_issue_state`]. -//! * [`PullRequestService`] — `patch` create pointing at a fork contract, review verdicts, -//! merge events, and state via [`crate::rules::fold_pr_state`]. -//! * [`ReleaseService`] / [`LabelService`] — MAINTAIN-gated, append-only newest-wins. -//! * [`SocialService`] — registry star / unstar / follow / unfollow + O(1) count-tree -//! totals. -//! -//! These address v1 repositories (one contract each), which are read only now. forge-v2 -//! repositories are served by [`v2::Collab`]. +//! [`v2::Collab`] is the service: issues, pull requests, comments, reviews, events, releases, +//! labels, stars and follows on a forge-v2 repository. This module holds what it and the +//! importer share: the release and label shapes, importer provenance ([`Imported`]), the +//! stored numeric event kinds, and the text-length checks run before anything is signed. pub mod v2; use std::collections::BTreeMap; -use crate::backends::sha256; use crate::error::{Error, Result}; use crate::keystore::BridgeIdentity; -use crate::platform::{ - self, FieldValue, LoadedContract, LoadedIdentity, PlatformClient, QueryFilter, QueryOrder, - WriteEngine, -}; -use crate::rules::{self, AuthzResolver, Event, EventKind, IssueState, PrState}; +use crate::platform::{self, FieldValue, LoadedIdentity, PlatformClient, WriteEngine}; +use crate::rules::EventKind; // The verdict mapping is a cross-client rule (both ports render a PR's review history // from it), so it lives in `rules` with the other shared mappings and is re-exported here // for the service API that returns it. pub use crate::rules::Verdict; -use crate::tokens::TokenService; - -// Repo-contract document types. -const DOC_ISSUE: &str = "issue"; -const DOC_PATCH: &str = "patch"; -const DOC_COMMENT: &str = "comment"; -const DOC_EVENT: &str = "event"; -const DOC_REVIEW: &str = "review"; -const DOC_LABEL: &str = "label"; -const DOC_RELEASE: &str = "release"; -// Registry-contract document types. -const DOC_STAR: &str = "star"; -const DOC_FOLLOW: &str = "follow"; - -/// Max attempts to allocate an optimistic `number` before giving up (each retry bumps the -/// number past the collision the previous attempt hit). -const MAX_NUMBER_ATTEMPTS: u32 = 8; /// The page size a caller-supplied `limit` of 0 means: "one page of the server default". /// Drive's own default and maximum are both 100 rows. @@ -61,7 +25,7 @@ pub(crate) const DEFAULT_PAGE: u32 = 100; /// Build a HIGH-key document write/delete engine over `client` for `identity`. /// -/// Document create/delete accept a HIGH auth key (S0.7); only token admin needs CRITICAL. +/// Document create/delete accept a HIGH auth key (S0.7), falling back to CRITICAL. pub(crate) fn doc_engine<'a>( client: &'a PlatformClient, identity: &'a LoadedIdentity, @@ -102,7 +66,7 @@ pub(crate) fn check_text( } /// Importer provenance (the `imported` object on `issue` / `patch` / `comment` / `review` -/// documents, data-contracts §2.3): the original author login, the original creation time +/// documents, forge-v2.md §2): the original author login, the original creation time /// (unix seconds), and the source URL. Recorded because Platform `$createdAt` is consensus /// time, not the original artifact's time — clients render this provenance for migrated /// docs and (via the gist-claim flow, PRD 06) can later attribute a placeholder `author` @@ -147,7 +111,7 @@ pub(crate) fn insert_imported( Ok(()) } -/// Map a [`crate::rules::EventKind`] to its stored numeric `kind` (data-contracts §2.3). +/// Map a [`crate::rules::EventKind`] to its stored numeric `kind` (forge-v2.md §3). pub(crate) fn event_kind_to_u64(kind: EventKind) -> u64 { match kind { EventKind::Close => 1, @@ -180,73 +144,7 @@ pub(crate) fn u64_to_event_kind(kind: u64) -> Option { }) } -/// The next optimistic `number` for a numbered type (`issue` / `patch`): newest number + 1, -/// or 1 for the first. A concurrent create can still collide on the unique `number` index — -/// the caller retries, incrementing. -async fn next_number( - client: &PlatformClient, - contract: &LoadedContract, - doc_type: &str, -) -> Result { - let docs = client - .query_documents( - contract, - doc_type, - &[], - &[QueryOrder::desc("number")], - 1, - None, - ) - .await?; - Ok(docs - .into_iter() - .next() - .and_then(|d| d.field_u64("number")) - .map_or(1, |n| n + 1)) -} - -// =========================================================================== -// Issues -// =========================================================================== - -/// An issue document, flattened. -#[derive(Debug, Clone)] -pub struct Issue { - /// The issue number (unique within the repo). - pub number: u64, - /// Document `$id`. - pub document_id: String, - /// Author `$ownerId` (base58). - pub author: String, - /// Title. - pub title: String, - /// Body (may be empty). - pub body: String, - /// Consensus `$createdAt` (ms). - pub created_at: u64, -} - -/// An issue with its resolved [`crate::rules::IssueState`] (open/closed + labels/assignees). -#[derive(Debug, Clone)] -pub struct IssueWithState { - /// The issue document. - pub issue: Issue, - /// The event-fold state. - pub state: IssueState, -} - -/// Filter for [`IssueService::list_issues`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum StateFilter { - /// Every issue. - All, - /// Only open issues. - Open, - /// Only closed issues. - Closed, -} - -/// Optional review/inline anchor for a [`IssueService::comment`]. +/// Optional review/inline anchor for a [`v2::Collab::comment`]. #[derive(Debug, Clone, Default)] pub struct CommentAnchor { /// Parent comment `$id` (a threaded reply). @@ -261,854 +159,11 @@ pub struct CommentAnchor { pub side: Option, } -/// The issue service, bound to one acting identity and its keys. -pub struct IssueService<'a> { - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, -} - -impl<'a> IssueService<'a> { - /// Bind the service. - pub fn new( - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, - ) -> Self { - Self { - client, - identity, - bridge, - } - } - - /// Create an issue (un-gated — §2.2). `number` is optimistically `max+1`, retried on a - /// unique-index collision (a concurrent create took the number). Returns the [`Issue`]. - pub async fn create_issue( - &self, - repo_contract_id: &str, - title: &str, - body: &str, - ) -> Result { - self.create_issue_imported(repo_contract_id, title, body, None) - .await - } - - /// Create an issue carrying importer [`Imported`] provenance (PRD 06). Identical to - /// [`IssueService::create_issue`] but records the original author / creation time / URL - /// in the doc's `imported` object. `imported = None` is exactly [`create_issue`]. - pub async fn create_issue_imported( - &self, - repo_contract_id: &str, - title: &str, - body: &str, - imported: Option<&Imported>, - ) -> Result { - check_len("issue title", title, 256)?; - check_len("issue body", body, 5120)?; - let contract = self.client.fetch_contract(repo_contract_id).await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - - let mut number = next_number(self.client, &contract, DOC_ISSUE).await?; - for _ in 0..MAX_NUMBER_ATTEMPTS { - let mut props = BTreeMap::new(); - props.insert("number".to_string(), FieldValue::integer(number)); - props.insert("title".to_string(), FieldValue::text(title)); - if !body.is_empty() { - props.insert("body".to_string(), FieldValue::text(body)); - } - insert_imported(&mut props, imported)?; - match engine.create_document(&contract, DOC_ISSUE, props).await { - Ok(document_id) => { - return Ok(Issue { - number, - document_id, - author: self.identity.id(), - title: title.to_string(), - body: body.to_string(), - created_at: 0, - }); - } - // Every collision retries with the next number; only after exhausting all - // attempts do we surface the friendly "exhausted" error (the final-attempt - // duplicate must not leak the raw DuplicateUniqueIndex). - Err(Error::DuplicateUniqueIndex(_)) => { - number += 1; - tracing::warn!(number, "issue number collision; retrying with next number"); - } - Err(e) => return Err(e), - } - } - Err(Error::Platform( - "exhausted issue-number allocation attempts".into(), - )) - } - - /// Fetch a single issue by number. - pub async fn get_issue(&self, repo_contract_id: &str, number: u64) -> Result> { - let contract = self.client.fetch_contract(repo_contract_id).await?; - let docs = self - .client - .query_documents( - &contract, - DOC_ISSUE, - &[QueryFilter::eq("number", FieldValue::integer(number))], - &[], - 1, - None, - ) - .await?; - Ok(docs.into_iter().next().map(|d| issue_from_doc(&d))) - } - - /// List issues, newest first, folding each one's `event` log into its state and - /// filtering by `filter`. `limit` (0 = server default ~100) and `start_after` (a base58 - /// issue `$id`) paginate the underlying `issue` query — the state fold runs per page. - /// A `start_after` page is served from a complete ascending read (see - /// `PlatformClient::query_documents`), because protocol 13 cannot prove a descending page - /// after a cursor under the 4.2 verifier. - pub async fn list_issues( - &self, - repo_contract_id: &str, - filter: StateFilter, - limit: u32, - start_after: Option<&str>, - ) -> Result> { - let contract = self.client.fetch_contract(repo_contract_id).await?; - // `0` is the CLI's documented "server default page", not a request for - // everything and not a request for one row. `query_documents` now rejects 0 - // outright (it used to mean "unset", which Drive filled with 100 — the silent - // truncation this whole change is about), so spell the page size out. - let limit = if limit == 0 { DEFAULT_PAGE } else { limit }; - let docs = self - .client - .query_documents( - &contract, - DOC_ISSUE, - &[], - &[QueryOrder::desc("$createdAt")], - limit, - start_after, - ) - .await?; - - // One AuthzResolver for the page (token history is repo-wide, not per-issue). - let authz = self.authz(repo_contract_id).await?; - - let mut out = Vec::new(); - for d in &docs { - let issue = issue_from_doc(d); - let events = self.fetch_events(&contract, &issue.document_id).await?; - let state = rules::fold_issue_state(&events, &issue.author, &authz); - let keep = match filter { - StateFilter::All => true, - StateFilter::Open => state.open, - StateFilter::Closed => !state.open, - }; - if keep { - out.push(IssueWithState { issue, state }); - } - } - Ok(out) - } - - /// Post a comment on an issue/PR (`target_id` = its base58 `$id`). Un-gated. Returns the - /// comment document id. - pub async fn comment( - &self, - repo_contract_id: &str, - target_id: &str, - body: &str, - anchor: Option<&CommentAnchor>, - ) -> Result { - self.comment_imported(repo_contract_id, target_id, body, anchor, None) - .await - } - - /// Post a comment carrying importer [`Imported`] provenance (PRD 06). `imported = None` - /// is exactly [`IssueService::comment`]. - pub async fn comment_imported( - &self, - repo_contract_id: &str, - target_id: &str, - body: &str, - anchor: Option<&CommentAnchor>, - imported: Option<&Imported>, - ) -> Result { - check_len("comment body", body, 5120)?; - let contract = self.client.fetch_contract(repo_contract_id).await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - - let mut props = BTreeMap::new(); - insert_imported(&mut props, imported)?; - props.insert( - "targetId".to_string(), - FieldValue::identifier(platform::decode_identifier(target_id)?), - ); - props.insert("body".to_string(), FieldValue::text(body)); - if let Some(a) = anchor { - if let Some(reply_to) = &a.reply_to { - props.insert( - "replyTo".to_string(), - FieldValue::identifier(platform::decode_identifier(reply_to)?), - ); - } - if let Some(oid) = &a.commit_oid { - props.insert("commitOid".to_string(), FieldValue::bytes(oid.clone())); - } - if let Some(path) = &a.path { - props.insert("path".to_string(), FieldValue::text(path)); - } - if let Some(line) = a.line { - props.insert("line".to_string(), FieldValue::integer(line)); - } - if let Some(side) = a.side { - props.insert("side".to_string(), FieldValue::integer(side)); - } - } - engine.create_document(&contract, DOC_COMMENT, props).await - } - - /// Append an `event` to the append-only state log (close/reopen/label/assign/…). The - /// event is authoritative only if the fold deems the actor authorized as-of its - /// `$createdAt` (§4) — a stranger's event lands on-chain but is inert. Returns the - /// event document id. - pub async fn add_event( - &self, - repo_contract_id: &str, - target_id: &str, - kind: EventKind, - value: Option<&str>, - oid: Option<&[u8]>, - ) -> Result { - // Injection defense (write-side, mirrors repo.rs's refUpdate guard): a `Retarget` - // event's `value` is a base ref name written into un-gated event data, so a - // token-less identity could plant a newline/NUL/leading-dash name that spoofs a - // ref-advertisement line once a client renders it. Reject illegal names up front. - if matches!(kind, EventKind::Retarget) { - match value { - Some(v) if rules::is_legal_ref_name(v) => {} - _ => { - return Err(Error::Config(format!( - "illegal retarget base ref name {value:?}: must be non-empty, no \ - leading '-', no whitespace/control characters" - ))) - } - } - } - let contract = self.client.fetch_contract(repo_contract_id).await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - post_event(&engine, &contract, target_id, kind, value, oid).await - } - - /// Convenience: close an issue/PR. - pub async fn close(&self, repo_contract_id: &str, target_id: &str) -> Result { - self.add_event(repo_contract_id, target_id, EventKind::Close, None, None) - .await - } - - /// Convenience: reopen an issue/PR. - pub async fn reopen(&self, repo_contract_id: &str, target_id: &str) -> Result { - self.add_event(repo_contract_id, target_id, EventKind::Reopen, None, None) - .await - } - - /// The O(1) total issue count (`documentsCountable` primary tree, §3). - pub async fn issue_count(&self, repo_contract_id: &str) -> Result { - let contract = self.client.fetch_contract(repo_contract_id).await?; - self.client.count_documents(&contract, DOC_ISSUE, &[]).await - } - - /// Resolve one issue's state (fetch + fold), or `None` if the issue does not exist. - pub async fn issue_state( - &self, - repo_contract_id: &str, - number: u64, - ) -> Result> { - let Some(issue) = self.get_issue(repo_contract_id, number).await? else { - return Ok(None); - }; - let contract = self.client.fetch_contract(repo_contract_id).await?; - let events = self.fetch_events(&contract, &issue.document_id).await?; - let authz = self.authz(repo_contract_id).await?; - let state = rules::fold_issue_state(&events, &issue.author, &authz); - Ok(Some(IssueWithState { issue, state })) - } - - // --- internal --- - - /// Build the as-of-time authorization resolver from the repo's token history. - async fn authz(&self, repo_contract_id: &str) -> Result { - let records = TokenService::new(self.client) - .token_history(repo_contract_id) - .await?; - Ok(AuthzResolver::new(records)) - } - - /// Fetch every `event` for a target, flattened to [`crate::rules::Event`]. - async fn fetch_events(&self, contract: &LoadedContract, target_id: &str) -> Result> { - fetch_events(self.client, contract, target_id).await - } -} - -/// Build an [`Issue`] from a fetched document. -fn issue_from_doc(d: &platform::FetchedDocument) -> Issue { - Issue { - number: d.field_u64("number").unwrap_or_default(), - document_id: d.id.clone(), - author: d.owner_id.clone(), - title: d.field_str("title").unwrap_or_default(), - body: d.field_str("body").unwrap_or_default(), - created_at: d.created_at.unwrap_or(0), - } -} - -/// Fetch every `event` for `target_id` (base58) in `contract`, as [`crate::rules::Event`]s. -async fn fetch_events( - client: &PlatformClient, - contract: &LoadedContract, - target_id: &str, -) -> Result> { - let target_bytes = platform::decode_identifier(target_id)?; - // Paginate to exhaustion: event create is UN-GATED, so a stranger can post >100 - // throwaway events to bury real close/merge/label events past the ≤100-row page cap - // and freeze the folded state forever. Every event must reach the fold. - let docs = client - .query_all_documents( - contract, - DOC_EVENT, - &[QueryFilter::eq( - "targetId", - FieldValue::identifier(target_bytes), - )], - &[QueryOrder::asc("$createdAt")], - ) - .await?; - let mut events = Vec::new(); - for d in &docs { - let Some(kind) = d.field_u64("kind").and_then(u64_to_event_kind) else { - continue; - }; - events.push(Event { - id: d.id.clone(), - target_id: target_id.to_string(), - kind, - actor: d.owner_id.clone(), - value: d.field_str("value"), - oid: d.field_hex("oid"), - created_at: d.created_at.unwrap_or(0), - }); - } - Ok(events) -} - -/// Post an `event` document (shared by issue + PR services). -async fn post_event( - engine: &WriteEngine<'_>, - contract: &LoadedContract, - target_id: &str, - kind: EventKind, - value: Option<&str>, - oid: Option<&[u8]>, -) -> Result { - let mut props = BTreeMap::new(); - props.insert( - "targetId".to_string(), - FieldValue::identifier(platform::decode_identifier(target_id)?), - ); - props.insert( - "kind".to_string(), - FieldValue::integer(event_kind_to_u64(kind)), - ); - if let Some(v) = value { - props.insert("value".to_string(), FieldValue::text(v)); - } - if let Some(o) = oid { - props.insert("oid".to_string(), FieldValue::bytes(o.to_vec())); - } - engine.create_document(contract, DOC_EVENT, props).await -} - -// =========================================================================== -// Pull requests -// =========================================================================== - -/// Input for [`PullRequestService::create_pr`]. -#[derive(Debug, Clone)] -pub struct PullRequestInput { - /// PR title. - pub title: String, - /// PR body. - pub body: String, - /// Base ref name in the target repo, e.g. `refs/heads/main`. - pub base_ref_name: String, - /// The fork listing `$id` (registry), if known. - pub source_listing_id: Option, - /// The fork **contract** id (base58) — where the PR's objects live. - pub source_contract_id: String, - /// The source ref name in the fork, e.g. `refs/heads/feature`. - pub source_ref_name: Option, - /// Head commit oid (the PR tip). - pub head_oid: Vec, - /// `patchManifest` hash in the fork contract (32 bytes), if published. - pub patch_manifest_hash: Option<[u8; 32]>, -} - -/// A pull-request (`patch`) document, flattened. -#[derive(Debug, Clone)] -pub struct PullRequest { - /// PR number (unique within the repo; independent of issue numbering). - pub number: u64, - /// Document `$id`. - pub document_id: String, - /// Author `$ownerId` (base58). - pub author: String, - /// Title. - pub title: String, - /// Body. - pub body: String, - /// Base ref name. - pub base_ref_name: String, - /// Head oid (hex). - pub head_oid: String, - /// The **source** repo contract id (base58) — where the PR's objects actually live. - /// - /// Read back because a reviewer cannot fetch a PR without it: a `dash://` URL is - /// `/`, and this is the only pointer the patch carries to the repo that - /// holds the head commit. Empty only for a malformed document. - pub source_contract_id: String, - /// The source repo's registry `repoListing` `$id`, when the author recorded one. - /// - /// Optional extra provenance. A bare contract id IS fetchable — `dash://` - /// resolves straight from the contract — so nothing depends on this being present. - pub source_listing_id: Option, - /// The branch the PR was opened from, in the source repo. - pub source_ref_name: Option, - /// `patchManifest` hash in the source contract (hex), when the author published one. - pub patch_manifest_hash: Option, - /// Consensus `$createdAt` (ms). - pub created_at: u64, -} - -/// A `review` document, flattened. -#[derive(Debug, Clone)] -pub struct Review { - /// Document `$id`. - pub document_id: String, - /// Reviewer `$ownerId` (base58). - pub reviewer: String, - /// The verdict. - pub verdict: Verdict, - /// The commit the review was made against (hex). - pub commit_oid: String, - /// Review body. - pub body: String, - /// Consensus `$createdAt` (ms). - pub created_at: u64, -} - -/// A PR with its resolved [`crate::rules::PrState`]. -#[derive(Debug, Clone)] -pub struct PullRequestWithState { - /// The PR document. - pub pr: PullRequest, - /// The event-fold state. - pub state: PrState, -} - -/// The pull-request service. -pub struct PullRequestService<'a> { - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, -} - -impl<'a> PullRequestService<'a> { - /// Bind the service. - pub fn new( - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, - ) -> Self { - Self { - client, - identity, - bridge, - } - } - - /// Create a `patch` (PR) in the **base** repo, un-gated, pointing at the fork contract - /// (§2.3, §5.5). `number` is optimistic `max+1` with unique-index retry. - pub async fn create_pr( - &self, - repo_contract_id: &str, - input: &PullRequestInput, - ) -> Result { - self.create_pr_imported(repo_contract_id, input, None).await - } - - /// Create a `patch` (PR) carrying importer [`Imported`] provenance (PRD 06). This is the - /// path forge-import uses for both open PRs and closed-PR archived metadata (title/diff/ - /// state, not full packs — §06). `imported = None` is exactly [`create_pr`]. - pub async fn create_pr_imported( - &self, - repo_contract_id: &str, - input: &PullRequestInput, - imported: Option<&Imported>, - ) -> Result { - check_len("PR title", &input.title, 256)?; - check_len("PR body", &input.body, 5120)?; - // Injection defense (write-side, mirrors repo.rs's refUpdate guard): base/source - // ref names are written into un-gated patch data, so an illegal name (newline/NUL/ - // leading-dash) could spoof a ref-advertisement line when rendered. Reject up front. - if !rules::is_legal_ref_name(&input.base_ref_name) { - return Err(Error::Config(format!( - "illegal PR base ref name {:?}: must be non-empty, no leading '-', no \ - whitespace/control characters", - input.base_ref_name - ))); - } - if let Some(source_ref) = &input.source_ref_name { - if !rules::is_legal_ref_name(source_ref) { - return Err(Error::Config(format!( - "illegal PR source ref name {source_ref:?}: must be non-empty, no leading \ - '-', no whitespace/control characters" - ))); - } - } - let contract = self.client.fetch_contract(repo_contract_id).await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - - let base_ref_hash = sha256(input.base_ref_name.as_bytes()); - let source_contract = platform::decode_identifier(&input.source_contract_id)?; - - let mut number = next_number(self.client, &contract, DOC_PATCH).await?; - for _ in 0..MAX_NUMBER_ATTEMPTS { - let mut props = BTreeMap::new(); - props.insert("number".to_string(), FieldValue::integer(number)); - props.insert("title".to_string(), FieldValue::text(&input.title)); - if !input.body.is_empty() { - props.insert("body".to_string(), FieldValue::text(&input.body)); - } - props.insert( - "baseRefNameHash".to_string(), - FieldValue::bytes32(base_ref_hash), - ); - props.insert( - "baseRefName".to_string(), - FieldValue::text(&input.base_ref_name), - ); - props.insert( - "sourceContractId".to_string(), - FieldValue::identifier(source_contract), - ); - if let Some(listing) = &input.source_listing_id { - props.insert( - "sourceListingId".to_string(), - FieldValue::identifier(platform::decode_identifier(listing)?), - ); - } - if let Some(source_ref) = &input.source_ref_name { - props.insert( - "sourceRefNameHash".to_string(), - FieldValue::bytes32(sha256(source_ref.as_bytes())), - ); - props.insert("sourceRefName".to_string(), FieldValue::text(source_ref)); - } - props.insert( - "headOid".to_string(), - FieldValue::bytes(input.head_oid.clone()), - ); - if let Some(manifest) = input.patch_manifest_hash { - props.insert( - "patchManifestHash".to_string(), - FieldValue::bytes32(manifest), - ); - } - insert_imported(&mut props, imported)?; - - match engine.create_document(&contract, DOC_PATCH, props).await { - Ok(document_id) => { - return Ok(PullRequest { - number, - document_id, - author: self.identity.id(), - title: input.title.clone(), - body: input.body.clone(), - base_ref_name: input.base_ref_name.clone(), - head_oid: hex::encode(&input.head_oid), - source_contract_id: input.source_contract_id.clone(), - source_listing_id: input.source_listing_id.clone(), - source_ref_name: input.source_ref_name.clone(), - patch_manifest_hash: input.patch_manifest_hash.map(hex::encode), - created_at: 0, - }); - } - Err(Error::DuplicateUniqueIndex(_)) => { - number += 1; - tracing::warn!(number, "PR number collision; retrying with next number"); - } - Err(e) => return Err(e), - } - } - Err(Error::Platform( - "exhausted PR-number allocation attempts".into(), - )) - } - - /// Fetch a single PR by number. - pub async fn get_pr(&self, repo_contract_id: &str, number: u64) -> Result> { - let contract = self.client.fetch_contract(repo_contract_id).await?; - let docs = self - .client - .query_documents( - &contract, - DOC_PATCH, - &[QueryFilter::eq("number", FieldValue::integer(number))], - &[], - 1, - None, - ) - .await?; - Ok(docs.into_iter().next().map(|d| pr_from_doc(&d))) - } - - /// List PRs, newest first (no state fold — cheap listing). - pub async fn list_prs( - &self, - repo_contract_id: &str, - limit: u32, - start_after: Option<&str>, - ) -> Result> { - let contract = self.client.fetch_contract(repo_contract_id).await?; - // `0` is the CLI's documented "server default page", not a request for - // everything and not a request for one row. `query_documents` now rejects 0 - // outright (it used to mean "unset", which Drive filled with 100 — the silent - // truncation this whole change is about), so spell the page size out. - let limit = if limit == 0 { DEFAULT_PAGE } else { limit }; - let docs = self - .client - .query_documents( - &contract, - DOC_PATCH, - &[], - &[QueryOrder::desc("$createdAt")], - limit, - start_after, - ) - .await?; - Ok(docs.iter().map(pr_from_doc).collect()) - } - - /// Resolve one PR's [`crate::rules::PrState`] by folding its `event` log. - /// - /// ## Merge reachability (monotonic) - /// - /// `fold_pr_state` validates a `merge` event by `is_ancestor(merge_oid, base_tip)`. - /// forge-core has no commit graph, so a naive reflexive `|a,b| a==b` stand-in is - /// **wrong and non-monotonic**: it only accepts the merge while `base_tip == merge_oid`, - /// so the instant any later commit advances the base ref the merge event is rejected and - /// `merged` flips permanently back to `open`. Instead we approximate reachability with - /// the **set of every oid that was ever a tip of the base ref** (walked from the base - /// `refUpdate`/`protectedRefUpdate` history). That set only grows, so a merge whose oid - /// was ever a valid base tip stays merged forever — the correct on-platform monotonic - /// approximation. (A full git-backed ancestry predicate is strictly better but needs an - /// object store; the historical-tips set is sound for the merged/open decision.) - /// - /// `base_tip` (hex) may be supplied by a caller that has resolved the current tip; when - /// `None` the newest historical tip is used so the merge arm can fire. - pub async fn pr_state( - &self, - repo_contract_id: &str, - number: u64, - base_tip: Option<&str>, - ) -> Result> { - let Some(pr) = self.get_pr(repo_contract_id, number).await? else { - return Ok(None); - }; - let contract = self.client.fetch_contract(repo_contract_id).await?; - let events = fetch_events(self.client, &contract, &pr.document_id).await?; - let records = TokenService::new(self.client) - .token_history(repo_contract_id) - .await?; - let authz = AuthzResolver::new(records); - - let (historical_tips, newest_tip) = - self.base_ref_tips(&contract, &pr.base_ref_name).await?; - let effective_base_tip = base_tip.map(str::to_string).or(newest_tip); - let state = rules::fold_pr_state( - &events, - &pr.author, - &authz, - effective_base_tip.as_deref(), - |oid, _tip| historical_tips.contains(oid), - ); - Ok(Some(PullRequestWithState { pr, state })) - } - - /// Every oid `base_ref_name` has validly pointed at (the monotonic merge-reachability - /// set) plus the newest such tip ([`rules::merge_base_tips`]): the ref's full `refUpdate` + - /// `protectedRefUpdate` history — an equality read on one `refNameHash`, so its cost is this - /// ref's pushes, not the repo's — folded with the repo's config timeline, so a plain - /// `refUpdate` on a protected branch (inert, §4) never makes a merge count. - async fn base_ref_tips( - &self, - contract: &LoadedContract, - base_ref_name: &str, - ) -> Result<(std::collections::BTreeSet, Option)> { - // Issues and PRs still live in v1 repo contracts: the contract is the whole scope. - let scope = crate::scope::DocScope { - contract_id: contract.id(), - repo_id: None, - }; - let base = - crate::refs::read_merge_base(self.client, contract, &scope, base_ref_name).await?; - // v1 folds against the newest valid tip, deletions ignored, as it always has. - Ok((base.historical.into_iter().collect(), base.tip)) - } - - /// Post a `review` verdict on a PR (`1` approve, `2` request-changes, `3` comment). - pub async fn review( - &self, - repo_contract_id: &str, - patch_id: &str, - verdict: u64, - commit_oid: &[u8], - body: &str, - ) -> Result { - self.review_imported(repo_contract_id, patch_id, verdict, commit_oid, body, None) - .await - } - - /// Post a `review` verdict carrying importer [`Imported`] provenance (PRD 06). - /// `imported = None` is exactly [`PullRequestService::review`]. - pub async fn review_imported( - &self, - repo_contract_id: &str, - patch_id: &str, - verdict: u64, - commit_oid: &[u8], - body: &str, - imported: Option<&Imported>, - ) -> Result { - check_len("review body", body, 5120)?; - let contract = self.client.fetch_contract(repo_contract_id).await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - let mut props = BTreeMap::new(); - insert_imported(&mut props, imported)?; - props.insert( - "patchId".to_string(), - FieldValue::identifier(platform::decode_identifier(patch_id)?), - ); - props.insert("verdict".to_string(), FieldValue::integer(verdict)); - props.insert( - "commitOid".to_string(), - FieldValue::bytes(commit_oid.to_vec()), - ); - if !body.is_empty() { - props.insert("body".to_string(), FieldValue::text(body)); - } - engine.create_document(&contract, DOC_REVIEW, props).await - } - - /// Every `review` on a patch, oldest first. - /// - /// Reviews were write-only until this existed: `dg pr review --verdict request-changes` - /// created a document that no command, reader or view ever queried, so "changes - /// requested" was a paid-for record that was invisible to everyone — including the - /// contributor it was addressed to. Uses the `(patchId asc, $createdAt asc)` index and - /// pages to exhaustion, because a verdict buried past row 100 is exactly the one that - /// matters (`review` is un-gated, so anyone may append). - pub async fn list_reviews( - &self, - repo_contract_id: &str, - patch_id: &str, - ) -> Result> { - let contract = self.client.fetch_contract(repo_contract_id).await?; - let docs = self - .client - .query_all_documents( - &contract, - DOC_REVIEW, - &[QueryFilter::eq( - "patchId", - FieldValue::identifier(platform::decode_identifier(patch_id)?), - )], - &[QueryOrder::asc("patchId"), QueryOrder::asc("$createdAt")], - ) - .await?; - Ok(docs.iter().map(review_from_doc).collect()) - } - - /// Post a `merge` event with the merge-commit `oid` (the actual git merge is done by the - /// caller). Authoritative only if the fold accepts it (holder + reachable oid, §4). - pub async fn merge_event( - &self, - repo_contract_id: &str, - target_id: &str, - merge_oid: &[u8], - ) -> Result { - let contract = self.client.fetch_contract(repo_contract_id).await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - post_event( - &engine, - &contract, - target_id, - EventKind::Merge, - None, - Some(merge_oid), - ) - .await - } - - /// The O(1) total PR count (`documentsCountable` primary tree, §3). - pub async fn pr_count(&self, repo_contract_id: &str) -> Result { - let contract = self.client.fetch_contract(repo_contract_id).await?; - self.client.count_documents(&contract, DOC_PATCH, &[]).await - } -} - -/// Build a [`PullRequest`] from a fetched document. -fn pr_from_doc(d: &platform::FetchedDocument) -> PullRequest { - PullRequest { - number: d.field_u64("number").unwrap_or_default(), - document_id: d.id.clone(), - author: d.owner_id.clone(), - title: d.field_str("title").unwrap_or_default(), - body: d.field_str("body").unwrap_or_default(), - base_ref_name: d.field_str("baseRefName").unwrap_or_default(), - head_oid: d.field_hex("headOid").unwrap_or_default(), - // `sourceContractId` / `sourceListingId` are identifier byteArrays; base58 is the - // form every Platform contract/document API takes. - source_contract_id: d - .field_bytes32("sourceContractId") - .map(platform::encode_identifier) - .unwrap_or_default(), - source_listing_id: d - .field_bytes32("sourceListingId") - .map(platform::encode_identifier), - source_ref_name: d.field_str("sourceRefName"), - patch_manifest_hash: d.field_hex("patchManifestHash"), - created_at: d.created_at.unwrap_or(0), - } -} - -fn review_from_doc(d: &platform::FetchedDocument) -> Review { - Review { - document_id: d.id.clone(), - reviewer: d.owner_id.clone(), - verdict: Verdict::from_code(d.field_u64("verdict").unwrap_or_default()), - commit_oid: d.field_hex("commitOid").unwrap_or_default(), - body: d.field_str("body").unwrap_or_default(), - created_at: d.created_at.unwrap_or(0), - } -} - // =========================================================================== // Releases // =========================================================================== -/// A release asset (serialized into the `assets` JSON-string field, §0/§2.3): +/// A release asset (serialized into the `assets` JSON-string field): /// `{name, sha256, sizeBytes, uris}` (`size_bytes`, written by earlier clients, still reads). #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -1129,7 +184,7 @@ pub struct ReleaseAsset { pub uri: Option, } -/// Input for [`ReleaseService::create_release`]. +/// Input for [`v2::Collab::create_release`]. #[derive(Debug, Clone)] pub struct ReleaseInput { /// Tag name (the logical key; newest doc per tag wins). @@ -1166,102 +221,6 @@ pub struct Release { pub created_at: u64, } -/// The release service (MAINTAIN-gated create; the owner holds MAINTAIN via `baseSupply`). -pub struct ReleaseService<'a> { - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, -} - -impl<'a> ReleaseService<'a> { - /// Bind the service. - pub fn new( - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, - ) -> Self { - Self { - client, - identity, - bridge, - } - } - - /// Create (or supersede) a release for a tag. MAINTAIN-gated; append-only newest-wins - /// (an edit / yank is a fresh doc, never a mutation of the old one, §2.2). Returns the - /// document id. - pub async fn create_release( - &self, - repo_contract_id: &str, - input: &ReleaseInput, - ) -> Result { - check_len("release tagName", &input.tag_name, 63)?; - check_len("release name", &input.name, 120)?; - check_len("release notes", &input.notes, 5120)?; - let contract = self.client.fetch_contract(repo_contract_id).await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - let mut props = BTreeMap::new(); - props.insert("tagName".to_string(), FieldValue::text(&input.tag_name)); - if !input.name.is_empty() { - props.insert("name".to_string(), FieldValue::text(&input.name)); - } - if !input.notes.is_empty() { - props.insert("notes".to_string(), FieldValue::text(&input.notes)); - } - props.insert("yanked".to_string(), FieldValue::boolean(input.yanked)); - if !input.assets.is_empty() { - let json = serde_json::to_string(&input.assets) - .map_err(|e| Error::Config(format!("serializing release assets: {e}")))?; - props.insert("assets".to_string(), FieldValue::text(json)); - } - engine.create_document(&contract, DOC_RELEASE, props).await - } - - /// List releases, newest doc per `tagName` (newest-wins supersede resolution, §2.2), - /// ordered newest first. - /// - /// Read to exhaustion: this is a newest-wins fold over an append-only type, so a capped - /// read does not surface a stale value — it drops the row entirely. A tag whose only - /// revision is older than the newest page simply disappears from the listing, and - /// because every surviving entry still looks current there is no signal that anything - /// was lost. - pub async fn list_releases(&self, repo_contract_id: &str) -> Result> { - let contract = self.client.fetch_contract(repo_contract_id).await?; - let docs = self - .client - .query_all_documents( - &contract, - DOC_RELEASE, - &[], - &[QueryOrder::desc("$createdAt")], - ) - .await?; - - // Keep the newest doc per tag ((createdAt, id) total order; docs already desc). - let mut newest: BTreeMap = BTreeMap::new(); - for d in &docs { - let release = release_from_doc(d); - newest - .entry(release.tag_name.clone()) - .and_modify(|existing| { - if (release.created_at, &release.document_id) - > (existing.created_at, &existing.document_id) - { - *existing = release.clone(); - } - }) - .or_insert(release); - } - let mut out: Vec = newest.into_values().collect(); - out.sort_by(|a, b| { - b.created_at - .cmp(&a.created_at) - .then_with(|| b.document_id.cmp(&a.document_id)) - }); - Ok(out) - } -} - /// Build a [`Release`] from a fetched document. pub(crate) fn release_from_doc(d: &platform::FetchedDocument) -> Release { let assets = d @@ -1317,82 +276,6 @@ pub struct Label { pub created_at: u64, } -/// The label service (MAINTAIN-gated create; append-only newest-wins). -pub struct LabelService<'a> { - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, -} - -impl<'a> LabelService<'a> { - /// Bind the service. - pub fn new( - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, - ) -> Self { - Self { - client, - identity, - bridge, - } - } - - /// Create (or supersede) a label. MAINTAIN-gated; newest doc per `name` wins. Returns - /// the document id. - pub async fn create_label( - &self, - repo_contract_id: &str, - name: &str, - color: &str, - description: &str, - retired: bool, - ) -> Result { - check_len("label name", name, 30)?; - check_len("label color", color, 7)?; - check_len("label description", description, 200)?; - let contract = self.client.fetch_contract(repo_contract_id).await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - let mut props = BTreeMap::new(); - props.insert("name".to_string(), FieldValue::text(name)); - if !color.is_empty() { - props.insert("color".to_string(), FieldValue::text(color)); - } - if !description.is_empty() { - props.insert("description".to_string(), FieldValue::text(description)); - } - props.insert("retired".to_string(), FieldValue::boolean(retired)); - engine.create_document(&contract, DOC_LABEL, props).await - } - - /// List labels, newest doc per `name` (newest-wins), skipping none — the `retired` flag - /// is carried so callers can hide retired labels. - pub async fn list_labels(&self, repo_contract_id: &str) -> Result> { - let contract = self.client.fetch_contract(repo_contract_id).await?; - // Complete for the same reason as `list_releases`: a newest-wins fold over a capped - // read silently omits labels rather than showing them stale. - let docs = self - .client - .query_all_documents(&contract, DOC_LABEL, &[], &[QueryOrder::desc("$createdAt")]) - .await?; - let mut newest: BTreeMap = BTreeMap::new(); - for d in &docs { - let label = label_from_doc(d); - newest - .entry(label.name.clone()) - .and_modify(|existing| { - if (label.created_at, &label.document_id) - > (existing.created_at, &existing.document_id) - { - *existing = label.clone(); - } - }) - .or_insert(label); - } - Ok(newest.into_values().collect()) - } -} - /// Build a [`Label`] from a fetched document. pub(crate) fn label_from_doc(d: &platform::FetchedDocument) -> Label { Label { @@ -1405,276 +288,6 @@ pub(crate) fn label_from_doc(d: &platform::FetchedDocument) -> Label { } } -// =========================================================================== -// Social graph (registry) -// =========================================================================== - -/// The registry social service (stars / follows) over the global registry contract of the -/// client's network ([`PlatformClient::fetch_registry`]). -pub struct SocialService<'a> { - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, -} - -impl<'a> SocialService<'a> { - /// Bind the service to `client` (and so to its network's registry), the acting - /// `identity`, and its `bridge` key material. - pub fn new( - client: &'a PlatformClient, - identity: &'a LoadedIdentity, - bridge: &'a BridgeIdentity, - ) -> Self { - Self { - client, - identity, - bridge, - } - } - - /// Star a repo listing (`listing_id` = the `repoListing` `$id`, base58). Returns the - /// star document id. - /// - /// Idempotent: a re-star collides on the unique `($ownerId, listingId)` index; that - /// [`Error::DuplicateUniqueIndex`] is caught and the caller's existing star id is - /// returned instead of an error (mirroring [`crate::tokens::TokenService::grant`]). - pub async fn star(&self, listing_id: &str) -> Result { - let registry = self.client.fetch_registry().await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - let mut props = BTreeMap::new(); - props.insert( - "listingId".to_string(), - FieldValue::identifier(platform::decode_identifier(listing_id)?), - ); - match engine.create_document(®istry, DOC_STAR, props).await { - Ok(id) => Ok(id), - Err(Error::DuplicateUniqueIndex(_)) => { - // Already starred — resolve and return the existing star id. - self.find_own(®istry, DOC_STAR, "listingId", listing_id) - .await? - .ok_or_else(|| { - Error::Platform("star collided but no existing star found".into()) - }) - } - Err(e) => Err(e), - } - } - - /// Unstar (delete the caller's own `star` for `listing_id`). No-op if not starred. - /// - /// Resolves the star via the caller's own `star($ownerId, …)` index and filters by - /// `listingId` client-side. (A two-clause `($ownerId, listingId)` query collides with - /// the countable `listing` index and fails proof verification on the deployed registry - /// — "wrong element type" — so the single-field owner query is used instead.) - pub async fn unstar(&self, listing_id: &str) -> Result<()> { - let registry = self.client.fetch_registry().await?; - let Some(doc) = self - .find_own(®istry, DOC_STAR, "listingId", listing_id) - .await? - else { - return Ok(()); - }; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - engine.delete_document(®istry, DOC_STAR, &doc).await - } - - /// The star count for a listing (`star(listingId)`, §3). - /// - /// Prefers the O(1) count-tree; falls back to a paginated row count when the deployed - /// registry's `listing` index is a compound `(listingId, $createdAt)` countable index - /// (the SDK count-proof helper requires the where-clause fields to *exactly* match a - /// countable index's properties, so a single-field `listingId` count is rejected until - /// the registry carries a single-property `(listingId)` countable index — a - /// data-contract reconciliation item). - pub async fn star_count(&self, listing_id: &str) -> Result { - self.social_count( - DOC_STAR, - QueryFilter::eq( - "listingId", - FieldValue::identifier(platform::decode_identifier(listing_id)?), - ), - ) - .await - } - - /// The identities (base58 `$ownerId`) that starred a listing, newest first. - pub async fn list_stars( - &self, - listing_id: &str, - limit: u32, - start_after: Option<&str>, - ) -> Result> { - // `0` is the CLI's documented "server default page", not a request for - // everything and not a request for one row. `query_documents` now rejects 0 - // outright (it used to mean "unset", which Drive filled with 100 — the silent - // truncation this whole change is about), so spell the page size out. - let limit = if limit == 0 { DEFAULT_PAGE } else { limit }; - let registry = self.client.fetch_registry().await?; - let docs = self - .client - .query_documents( - ®istry, - DOC_STAR, - &[QueryFilter::eq( - "listingId", - FieldValue::identifier(platform::decode_identifier(listing_id)?), - )], - &[QueryOrder::desc("$createdAt")], - limit, - start_after, - ) - .await?; - Ok(docs.into_iter().map(|d| d.owner_id).collect()) - } - - /// Follow an identity (`identity_id`, base58). Returns the follow document id. - pub async fn follow(&self, identity_id: &str) -> Result { - let registry = self.client.fetch_registry().await?; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - let mut props = BTreeMap::new(); - props.insert( - "identityId".to_string(), - FieldValue::identifier(platform::decode_identifier(identity_id)?), - ); - engine.create_document(®istry, DOC_FOLLOW, props).await - } - - /// Unfollow (delete the caller's own `follow` of `identity_id`). No-op if not following. - /// Same single-field owner-query strategy as [`SocialService::unstar`]. - pub async fn unfollow(&self, identity_id: &str) -> Result<()> { - let registry = self.client.fetch_registry().await?; - let Some(doc) = self - .find_own(®istry, DOC_FOLLOW, "identityId", identity_id) - .await? - else { - return Ok(()); - }; - let engine = doc_engine(self.client, self.identity, self.bridge)?; - engine.delete_document(®istry, DOC_FOLLOW, &doc).await - } - - /// Find the caller's own `doc_type` document whose identifier field `target_field` - /// equals `target` (base58), by paging the caller's `$ownerId`-scoped documents and - /// filtering client-side. Returns the document `$id`, if any. - async fn find_own( - &self, - registry: &LoadedContract, - doc_type: &str, - target_field: &str, - target: &str, - ) -> Result> { - let target_bytes = platform::decode_identifier(target)?; - let mut start_after: Option = None; - loop { - let page = self - .client - .query_documents( - registry, - doc_type, - &[QueryFilter::eq( - "$ownerId", - FieldValue::identifier(platform::decode_identifier(&self.identity.id())?), - )], - &[QueryOrder::asc("$createdAt")], - 100, - start_after.as_deref(), - ) - .await?; - let n = page.len(); - if let Some(found) = page - .iter() - .find(|d| d.field_bytes(target_field).as_deref() == Some(target_bytes.as_slice())) - { - return Ok(Some(found.id.clone())); - } - if n < 100 { - return Ok(None); - } - start_after = page.last().map(|d| d.id.clone()); - } - } - - /// The follower count of an identity (`follow(identityId)`, §3). Count-tree with a - /// paginated fallback (see [`SocialService::star_count`]). - pub async fn follower_count(&self, identity_id: &str) -> Result { - self.social_count( - DOC_FOLLOW, - QueryFilter::eq( - "identityId", - FieldValue::identifier(platform::decode_identifier(identity_id)?), - ), - ) - .await - } - - /// The following count of an identity (`follow($ownerId)`, §3). Count-tree with a - /// paginated fallback (see [`SocialService::star_count`]). - pub async fn following_count(&self, owner_id: &str) -> Result { - self.social_count( - DOC_FOLLOW, - QueryFilter::eq( - "$ownerId", - FieldValue::identifier(platform::decode_identifier(owner_id)?), - ), - ) - .await - } - - /// Count `doc_type` documents matching `filter`: try the O(1) count-tree, and on the - /// registry's compound-countable-index rejection fall back to a paginated row count. - async fn social_count(&self, doc_type: &str, filter: QueryFilter) -> Result { - let registry = self.client.fetch_registry().await?; - match self - .client - .count_documents(®istry, doc_type, std::slice::from_ref(&filter)) - .await - { - Ok(n) => Ok(n), - Err(Error::Platform(msg)) if msg.contains("countable") => { - tracing::warn!( - doc_type, - "count-tree unavailable (compound countable index on the deployed \ - registry); falling back to a paginated row count" - ); - self.count_rows(®istry, doc_type, &filter).await - } - Err(e) => Err(e), - } - } - - /// Count matching documents by paging through them (the fallback when the count-tree - /// index shape is not servable). Bounded by the real row count. - async fn count_rows( - &self, - registry: &LoadedContract, - doc_type: &str, - filter: &QueryFilter, - ) -> Result { - let mut total: u64 = 0; - let mut start_after: Option = None; - loop { - let page = self - .client - .query_documents( - registry, - doc_type, - std::slice::from_ref(filter), - &[QueryOrder::asc("$createdAt")], - 100, - start_after.as_deref(), - ) - .await?; - let n = page.len(); - total += n as u64; - if n < 100 { - break; - } - start_after = page.last().map(|d| d.id.clone()); - } - Ok(total) - } -} - #[cfg(test)] mod tests { use super::{event_kind_to_u64, u64_to_event_kind, Verdict}; diff --git a/crates/forge-core/src/collab/v2.rs b/crates/forge-core/src/collab/v2.rs index 32666d703..7deb5b3d8 100644 --- a/crates/forge-core/src/collab/v2.rs +++ b/crates/forge-core/src/collab/v2.rs @@ -16,9 +16,6 @@ //! number by the §6 rule and are resumable: the signed create is journaled before it is //! broadcast, so re-running an interrupted create re-broadcasts the same bytes instead of //! opening a second issue. -//! -//! v1 repositories are read by the services in the parent module and refused here -//! ([`crate::Error::V1ReadOnly`]). use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; @@ -127,7 +124,7 @@ pub struct Target { /// An `issue` document, flattened. #[derive(Debug, Clone)] -pub struct V2Issue { +pub struct Issue { /// The issue number. pub number: u32, /// Document `$id`. @@ -144,7 +141,7 @@ pub struct V2Issue { pub imported: Option, } -impl V2Issue { +impl Issue { /// This issue as an event / comment target. pub fn target(&self) -> Target { Target { @@ -158,7 +155,7 @@ impl V2Issue { /// A `patch` (pull request) document, flattened. #[derive(Debug, Clone)] -pub struct V2Patch { +pub struct Patch { /// The PR number (independent of issue numbers). pub number: u32, /// Document `$id`. @@ -185,7 +182,7 @@ pub struct V2Patch { pub imported: Option, } -impl V2Patch { +impl Patch { /// This PR as an event / comment target. pub fn target(&self) -> Target { Target { @@ -218,7 +215,7 @@ pub struct PatchInput { /// A `comment`, flattened. #[derive(Debug, Clone)] -pub struct V2Comment { +pub struct Comment { /// Document `$id`. pub document_id: String, /// Author. @@ -233,7 +230,7 @@ pub struct V2Comment { /// A `review`, flattened. #[derive(Debug, Clone)] -pub struct V2Review { +pub struct Review { /// Document `$id`. pub document_id: String, /// Reviewer (`$ownerId`). @@ -284,7 +281,7 @@ impl Listed { #[derive(Debug, Clone)] pub struct IssueView { /// The issue. - pub issue: V2Issue, + pub issue: Issue, /// Open/closed, labels, assignees. pub state: IssueState, } @@ -293,7 +290,7 @@ pub struct IssueView { #[derive(Debug, Clone)] pub struct PatchView { /// The PR. - pub patch: V2Patch, + pub patch: Patch, /// Open/closed/merged, labels, draft. pub state: PrState, /// The base ref's current tip (hex), when it has one. @@ -376,9 +373,9 @@ fn number_of(d: &FetchedDocument) -> u32 { .unwrap_or_default() } -/// A fetched `issue` as a [`V2Issue`]. -pub fn issue_from_doc(d: &FetchedDocument) -> V2Issue { - V2Issue { +/// A fetched `issue` as a [`Issue`]. +pub fn issue_from_doc(d: &FetchedDocument) -> Issue { + Issue { number: number_of(d), document_id: d.id.clone(), author: d.owner_id.clone(), @@ -389,9 +386,9 @@ pub fn issue_from_doc(d: &FetchedDocument) -> V2Issue { } } -/// A fetched `patch` as a [`V2Patch`]. -pub fn patch_from_doc(d: &FetchedDocument) -> V2Patch { - V2Patch { +/// A fetched `patch` as a [`Patch`]. +pub fn patch_from_doc(d: &FetchedDocument) -> Patch { + Patch { number: number_of(d), document_id: d.id.clone(), author: d.owner_id.clone(), @@ -410,8 +407,8 @@ pub fn patch_from_doc(d: &FetchedDocument) -> V2Patch { } } -fn comment_from_doc(d: &FetchedDocument) -> V2Comment { - V2Comment { +fn comment_from_doc(d: &FetchedDocument) -> Comment { + Comment { document_id: d.id.clone(), author: d.owner_id.clone(), body: d.field_str("body").unwrap_or_default(), @@ -420,8 +417,8 @@ fn comment_from_doc(d: &FetchedDocument) -> V2Comment { } } -fn review_from_doc(d: &FetchedDocument) -> V2Review { - V2Review { +fn review_from_doc(d: &FetchedDocument) -> Review { + Review { document_id: d.id.clone(), reviewer: d.owner_id.clone(), verdict: Verdict::from_code(d.field_u64("verdict").unwrap_or_default()), @@ -718,11 +715,10 @@ impl<'a> Collab<'a> { doc_engine(self.client, identity, bridge) } - /// The forge-v2 contracts of `repo`, refusing v1 and private repos. + /// The forge-v2 contracts of `repo`, refusing private repos. fn forge(repo: &RepoRef) -> Result<&ForgeIds> { - let forge = repo.require_v2()?; repo.require_readable()?; - Ok(forge) + Ok(repo.forge()) } async fn collab_contract(&self, repo: &RepoRef) -> Result { @@ -752,10 +748,7 @@ impl<'a> Collab<'a> { } fn visibility(repo: &RepoRef) -> Visibility { - match repo { - RepoRef::V2 { visibility, .. } => *visibility, - RepoRef::V1 { .. } => Visibility::Public, - } + repo.visibility } /// Create one document of `repo` (its `repoId` added) in `contract`, as the signer. @@ -836,7 +829,7 @@ impl<'a> Collab<'a> { } /// Issue `number` of `repo`, if it exists and is well-formed. - pub async fn issue(&self, repo: &RepoRef, number: u32) -> Result> { + pub async fn issue(&self, repo: &RepoRef, number: u32) -> Result> { Ok(self .target_doc(repo, TargetKind::Issue, number) .await? @@ -845,7 +838,7 @@ impl<'a> Collab<'a> { } /// Pull request `number` of `repo`, if it exists and is well-formed. - pub async fn patch(&self, repo: &RepoRef, number: u32) -> Result> { + pub async fn patch(&self, repo: &RepoRef, number: u32) -> Result> { Ok(self .target_doc(repo, TargetKind::Patch, number) .await? @@ -896,7 +889,7 @@ impl<'a> Collab<'a> { } /// The newest `limit` issues (0 = one page of 100), newest first. - pub async fn list_issues(&self, repo: &RepoRef, limit: u32) -> Result> { + pub async fn list_issues(&self, repo: &RepoRef, limit: u32) -> Result> { Ok(self .newest(repo, TargetKind::Issue, limit) .await? @@ -904,7 +897,7 @@ impl<'a> Collab<'a> { } /// The newest `limit` pull requests (0 = one page of 100), newest first. - pub async fn list_patches(&self, repo: &RepoRef, limit: u32) -> Result> { + pub async fn list_patches(&self, repo: &RepoRef, limit: u32) -> Result> { Ok(self .newest(repo, TargetKind::Patch, limit) .await? @@ -917,7 +910,7 @@ impl<'a> Collab<'a> { &self, forge: &ForgeIds, source_repo_id: &str, - ) -> Result> { + ) -> Result> { let collab = self.client.fetch_contract(&forge.collab).await?; let docs = self .client @@ -974,7 +967,7 @@ impl<'a> Collab<'a> { } /// Every well-formed comment on a target, oldest first. - pub async fn comments(&self, repo: &RepoRef, target_id: &str) -> Result> { + pub async fn comments(&self, repo: &RepoRef, target_id: &str) -> Result> { let collab = self.collab_contract(repo).await?; Ok(self .by_target(&collab, DOC_COMMENT, "targetId", target_id) @@ -986,7 +979,7 @@ impl<'a> Collab<'a> { } /// Every well-formed review on a patch, oldest first. - pub async fn reviews(&self, repo: &RepoRef, patch_id: &str) -> Result> { + pub async fn reviews(&self, repo: &RepoRef, patch_id: &str) -> Result> { let collab = self.collab_contract(repo).await?; Ok(self .by_target(&collab, DOC_REVIEW, "patchId", patch_id) @@ -1000,7 +993,7 @@ impl<'a> Collab<'a> { // --- reads: folded state -------------------------------------------------------- /// An issue's state (§3 fold). - pub async fn issue_state(&self, repo: &RepoRef, issue: &V2Issue) -> Result { + pub async fn issue_state(&self, repo: &RepoRef, issue: &Issue) -> Result { let log = self.target_log(repo, &issue.document_id).await?; Ok(fold_issue_state_v2( &log.events, @@ -1032,7 +1025,7 @@ impl<'a> Collab<'a> { } /// A pull request's state (§3 fold; a merge counts once its oid has been a base tip). - pub async fn patch_view(&self, repo: &RepoRef, patch: V2Patch) -> Result { + pub async fn patch_view(&self, repo: &RepoRef, patch: Patch) -> Result { let log = self.target_log(repo, &patch.document_id).await?; let base = self.base_ref_tips(repo, &patch.base_ref_name).await?; let state = fold_pr_state_v2( @@ -1056,8 +1049,8 @@ impl<'a> Collab<'a> { pub async fn approvals( &self, repo: &RepoRef, - patch: &V2Patch, - ) -> Result<(Approvals, Vec)> { + patch: &Patch, + ) -> Result<(Approvals, Vec)> { let oracle = self.member_oracle(repo).await?; self.approvals_with(repo, patch, &oracle).await } @@ -1073,9 +1066,9 @@ impl<'a> Collab<'a> { pub async fn approvals_with( &self, repo: &RepoRef, - patch: &V2Patch, + patch: &Patch, oracle: &RoleOracle, - ) -> Result<(Approvals, Vec)> { + ) -> Result<(Approvals, Vec)> { let reviews = self.reviews(repo, &patch.document_id).await?; let rule: Vec = reviews .iter() diff --git a/crates/forge-core/src/create.rs b/crates/forge-core/src/create.rs index 9a5cc83a3..615d86537 100644 --- a/crates/forge-core/src/create.rs +++ b/crates/forge-core/src/create.rs @@ -7,7 +7,7 @@ //! (anyone may create one; `(owner, name)` is unique). //! 2. the owner's own `maintainer` document — only the repo's owner may create it, and //! without it the owner could not write the M-gated `config` (or push to a protected -//! ref). This is the v2 form of v1's "the owner is credited both tokens at creation". +//! ref). //! 3. the initial `config` — default branch and storage backend. //! //! **Resumable, never double-paying.** Before each document is broadcast, its signed @@ -32,7 +32,7 @@ use crate::platform::{ self, BroadcastOutcome, FieldValue, LoadedContract, LoadedIdentity, PlatformClient, WriteEngine, WriteIntent, }; -use crate::resolve::{find_v2, repo_slug, DOC_REPO}; +use crate::resolve::{find_named, repo_slug, DOC_REPO}; use crate::rules::v2::{Role, Visibility}; use crate::scope::RepoRef; @@ -316,7 +316,7 @@ pub async fn create_repo( &mut journal, Step::Repo, || async { - Ok(find_v2(client, &forge, owner_bytes, &opts.name) + Ok(find_named(client, &forge, owner_bytes, &opts.name) .await? .map(|r| r.id().to_string())) }, @@ -439,7 +439,7 @@ async fn find_repo_after_create( expected_id: &str, ) -> Result { for attempt in 0..FIND_ATTEMPTS { - if let Some(repo) = find_v2(client, forge, owner, name).await? { + if let Some(repo) = find_named(client, forge, owner, name).await? { if repo.id() != expected_id { return Err(Error::Platform(format!( "repo {name} resolves to {} but this session wrote {expected_id}", diff --git a/crates/forge-core/src/error.rs b/crates/forge-core/src/error.rs index a3c794b2d..bef88460b 100644 --- a/crates/forge-core/src/error.rs +++ b/crates/forge-core/src/error.rs @@ -2,7 +2,7 @@ //! //! Each variant maps to a product-level error class from the PRDs and must, at the //! binary boundary, be rendered as an actionable message (e.g. insufficient credits -//! links to the funding bridge; a frozen token explains the revocation). +//! links to the funding bridge; a missing membership names who can grant it). use thiserror::Error; @@ -22,10 +22,6 @@ pub enum Error { available: u64, }, - /// The identity's WRITE/MAINTAIN token is frozen — access was revoked/suspended. - #[error("token frozen: this identity's write access has been suspended")] - TokenFrozen, - /// A network / consensus operation timed out. /// /// `retryable` distinguishes an idempotent rebroadcast candidate (the signed ST @@ -52,10 +48,6 @@ pub enum Error { reason: String, }, - /// The identity lacks the token/key authorization for the requested write. - #[error("unauthorized: missing the required WRITE or MAINTAIN token")] - Unauthorized, - /// A referenced document, ref, manifest or chunk could not be found. #[error("not found")] NotFound, @@ -95,39 +87,18 @@ pub enum Error { #[error("configuration error: {0}")] Config(String), - /// The selected network has no Dash Forge registry deployment (no id in - /// `forge-contracts/deployments/.json`, and no override). Returned instead of - /// falling back to another network's contract id. - #[error( - "no Dash Forge registry is deployed on {network} yet; see docs/mainnet-runbook.md \ - (or set FORGE_REGISTRY_CONTRACT_ID to a registry you deployed there)" - )] - NotDeployed { - /// The network key (`mainnet`, `devnet-moutai`). - network: String, - }, - /// The selected network has no forge-v2 deployment (no fully registered `v2` record in - /// its deployment file). v2 writes and v2 lookups fail with this; v1 reads still work. + /// its deployment file). Returned instead of falling back to another network's + /// contracts. #[error( "forge-v2 isn't deployed on {network} yet; use --network devnet --devnet-name moutai \ - (existing v1 repos there stay readable)" + (see docs/mainnet-runbook.md)" )] V2NotDeployed { /// The network key (`testnet`, `mainnet`). network: String, }, - /// A write was attempted on a forge-v1 repository. v1 (one contract per repo) is read - /// only now; new writes go to forge-v2. - #[error( - "{repo} is a v1 repo (read-only); run `dg migrate` (coming soon) to move it to forge-v2" - )] - V1ReadOnly { - /// The repo as the user named it (`owner/name` or a contract id). - repo: String, - }, - /// Consensus refused a write because the writer has no membership document the /// document type needs (protocol 14 `ownerRefersTo`, consensus code 40120): not a /// member at all, or a writer where the type is maintainer-only (`protectedRefUpdate`, diff --git a/crates/forge-core/src/fork.rs b/crates/forge-core/src/fork.rs index f40178bb4..90d6f381d 100644 --- a/crates/forge-core/src/fork.rs +++ b/crates/forge-core/src/fork.rs @@ -64,12 +64,8 @@ pub fn fork_manifest( if !MANIFEST_URIS_V2.fits(&uris) { uris.retain(|u| !u.starts_with("s3://")); } - uris.retain(|u| { - MANIFEST_URIS_V2 - .max_item_len - .is_none_or(|max| u.len() <= max) - }); - uris.truncate(MANIFEST_URIS_V2.max_items.unwrap_or(usize::MAX)); + uris.retain(|u| u.len() <= MANIFEST_URIS_V2.max_item_len); + uris.truncate(MANIFEST_URIS_V2.max_items); if uris.is_empty() { return Ok(None); } @@ -171,9 +167,8 @@ pub async fn fork_repo( opts: &CreateRepoOpts, journal_dir: &std::path::Path, ) -> Result { - parent.require_v2()?; parent.require_readable()?; - let forge = parent.require_v2()?; + let forge = parent.forge(); let mut opts = opts.clone(); opts.name = crate::resolve::repo_slug(&opts.name)?; opts.fork_of = Some(platform::decode_identifier(parent.id())?); @@ -182,7 +177,7 @@ pub async fn fork_repo( // A repo of the signer's with this name already exists: continue only if it is a fork // of this parent (an interrupted fork). Anything else would have the parent's manifests // and refs written into an unrelated repository, permanently. - if let Some(existing) = crate::resolve::find_v2( + if let Some(existing) = crate::resolve::find_named( client, forge, platform::decode_identifier(&owner)?, @@ -272,7 +267,7 @@ mod tests { const UPLOADER: &str = "9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD"; fn parent() -> RepoRef { - RepoRef::V2 { + RepoRef { forge: ForgeIds { core: "CORE".into(), collab: "COLLAB".into(), diff --git a/crates/forge-core/src/keystore.rs b/crates/forge-core/src/keystore.rs index 98b87cdb8..9e36fc194 100644 --- a/crates/forge-core/src/keystore.rs +++ b/crates/forge-core/src/keystore.rs @@ -150,8 +150,7 @@ pub fn describe_key_source(source: &Path) -> String { /// Security levels acceptable for signing a document create/delete, in preference /// order. Document ops accept HIGH (spike S0.7); CRITICAL also works and is the -/// fallback when a HIGH key is absent. Token-admin ops (mint/freeze/destroy) require -/// CRITICAL — see [`BridgeIdentity::token_admin_key`]. +/// fallback when a HIGH key is absent. pub const DOC_OP_LEVELS: [&str; 2] = ["HIGH", "CRITICAL"]; impl BridgeIdentity { @@ -243,16 +242,6 @@ impl BridgeIdentity { Error::Config("no HIGH or CRITICAL AUTHENTICATION key in identity file".into()) }) } - - /// Pick the AUTHENTICATION/CRITICAL key required for token-admin operations - /// (mint/freeze/destroy). HIGH is rejected at consensus for these (spike S0.7). - pub fn token_admin_key(&self) -> Result<&IdentityKey> { - self.auth_key("CRITICAL").ok_or_else(|| { - Error::Config( - "no CRITICAL AUTHENTICATION key in identity file (required for token admin)".into(), - ) - }) - } } #[cfg(test)] @@ -335,13 +324,6 @@ mod tests { assert_eq!(key.security_level, "HIGH"); } - #[test] - fn token_admin_key_requires_critical() { - let id = BridgeIdentity::from_json(FIXTURE).unwrap(); - // No CRITICAL key in the fixture — token admin must fail loudly. - assert!(id.token_admin_key().is_err()); - } - #[test] fn load_from_missing_file_is_io_error() { let err = BridgeIdentity::load_from_file("/nonexistent/definitely-not-here.json") @@ -381,7 +363,7 @@ mod tests { assert_eq!(key.id, 5); assert_eq!(key.private_key_wif.expose(), "cFAKEwifDONOTUSE"); assert!( - id.token_admin_key().is_err(), + id.auth_key("CRITICAL").is_none(), "a limited key is never CRITICAL" ); assert!(id.mnemonic.expose().is_empty()); diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index 5bd51438b..8f54410c1 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -10,15 +10,15 @@ //! ref + pack-manifest + chunk read/write) `git-remote-dash` calls. //! - [`refs`] — complete ref-update reads (keyset scan + completeness fallback) shared by //! ref listing and PR base-tip resolution. -//! - [`tokens`] — `TokenService`: the collaborator ACL (grant/suspend/revoke = token -//! mint/freeze/destroy; balances = the on-chain collaborator list). -//! - [`collab`] — issue / PR / review / release / label services + the registry social -//! graph (stars / follows), folding state through [`rules`]. +//! - [`members`] — repository membership: `maintainer` / `writer` documents. +//! - [`collab`] — issues, PRs, reviews, releases, labels, stars and follows on forge-collab, +//! folding state through [`rules`]. //! - [`pack`] — chunk geometry and the pure split/join chunker. //! - [`backends`] — the `PackBackend` trait (`platform | ipfs | s3 | https`). //! - [`storage`] — bring-your-own storage: user profiles, a repo's replication policy, //! the push-side `StorageTarget` fan-out, and the gateway-racing reader. -//! - [`rules`] — `FORGE_RULES_V1`: ref resolution, event folds, protected-pattern matching. +//! - [`rules`] — `FORGE_RULES_V2`: ref resolution, event folds, protected-pattern matching, +//! membership, numbering, approvals and the pack reader rule. //! - [`cost`] — fee constants and the storage-cost estimator. //! - [`keystore`] — bridge-format identity JSON parsing with redacted secrets. //! - [`envelope`] — the `encryptedFor` scheme (`ecdh-secp256k1-aes256-cbc`), matching Platform. @@ -49,7 +49,6 @@ pub mod resolve; pub mod rules; pub mod scope; pub mod storage; -pub mod tokens; pub mod user_error; pub mod webhooks; diff --git a/crates/forge-core/src/members.rs b/crates/forge-core/src/members.rs index 885f41f19..534295a10 100644 --- a/crates/forge-core/src/members.rs +++ b/crates/forge-core/src/members.rs @@ -70,12 +70,12 @@ pub fn oracle(members: &[Member]) -> RoleOracle { ) } -/// `repo`'s document scope and the forge-core contract its membership lives in; refuses v1. +/// `repo`'s document scope and the forge-core contract its membership lives in. async fn core( client: &PlatformClient, repo: &RepoRef, ) -> Result<(crate::scope::DocScope, LoadedContract)> { - let forge = repo.require_v2()?; + let forge = repo.forge(); Ok((repo.scope()?, client.fetch_contract(&forge.core).await?)) } @@ -170,7 +170,6 @@ impl<'a> MemberService<'a> { /// Only the repo owner can grant or revoke (consensus enforces it; this fails first, /// with a message instead of a consensus code). fn require_owner(&self, repo: &RepoRef) -> Result<()> { - repo.require_v2()?; if repo.owner_id() != self.identity.id() { return Err(Error::Config(format!( "only the owner of {} ({}) can change its members", @@ -268,7 +267,7 @@ mod tests { use crate::rules::v2::Visibility; fn repo() -> RepoRef { - RepoRef::V2 { + RepoRef { forge: ForgeIds { core: "C".into(), collab: "L".into(), diff --git a/crates/forge-core/src/network.rs b/crates/forge-core/src/network.rs index dedbbb76a..f070e8daa 100644 --- a/crates/forge-core/src/network.rs +++ b/crates/forge-core/src/network.rs @@ -9,9 +9,9 @@ //! - [`NetworkSettings`] is one layer of user input (CLI flags, a config file, git config, //! the environment). Binaries stack layers with [`NetworkSettings::overlay`] in their own //! precedence order and call [`NetworkSettings::resolve`] once. -//! - A network with no registry deployment resolves with `registry: None`; the first -//! operation that needs the registry fails with [`Error::NotDeployed`] rather than -//! silently talking to another network's contract. +//! - A network with no forge-v2 deployment resolves with `v2: None`; the first operation +//! that needs the contracts fails with [`Error::V2NotDeployed`] rather than silently talking +//! to another network's contracts. //! //! SDK-free: [`crate::platform`] maps [`Network`] onto the SDK's types. @@ -31,8 +31,6 @@ pub const ENV_DEVNET_NAME: &str = "DASH_FORGE_DEVNET_NAME"; pub const ENV_DAPI_ADDRESSES: &str = "DASH_FORGE_DAPI_ADDRESSES"; /// Env var: an explicit quorum service base URL for a devnet. pub const ENV_QUORUM_URL: &str = "DASH_FORGE_QUORUM_URL"; -/// Env var: a registry contract id that overrides the embedded deployment. -pub const ENV_REGISTRY_CONTRACT_ID: &str = "FORGE_REGISTRY_CONTRACT_ID"; /// The DAPI port assumed when an address omits one (the Platform HTTPS gateway). pub const DEFAULT_DAPI_PORT: u16 = 1443; @@ -191,8 +189,6 @@ struct DeploymentFile { dapi_addresses: Option>, #[serde(default)] quorum_base_url: Option, - #[serde(default)] - registry: Option, /// The forge-v2 record `deploy-v2.mjs` read-modify-writes (`forge-contracts/scripts`). #[serde(default)] v2: Option, @@ -203,7 +199,7 @@ struct DeploymentFile { struct ContractRecord { #[serde(default)] contract_id: Option, - /// `registered` once confirmed; `broadcasting` while a deploy is in flight (v2 only). + /// `registered` once confirmed; `broadcasting` while a deploy is in flight. #[serde(default)] status: Option, } @@ -245,7 +241,7 @@ impl DeploymentFile { } impl ContractRecord { - /// The id of a confirmed v2 registration; `None` for a missing or in-flight one. + /// The id of a confirmed registration; `None` for a missing or in-flight one. fn registered_id(&self) -> Option { if self.status.as_deref() != Some("registered") { return None; @@ -281,10 +277,8 @@ pub struct ForgeIds { /// What an embedded deployment file records for one network. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Deployment { - /// The deployment key (`testnet`, `devnet-moutai`). + /// The deployment key (`devnet-moutai`, `mainnet`). pub key: String, - /// The registry contract id, or `None` when the file records none (not deployed here). - pub registry_contract_id: Option, /// DAPI addresses recorded for a devnet (normalized); empty for testnet/mainnet. pub dapi_addresses: Vec, /// A quorum service URL recorded for a devnet. @@ -298,16 +292,6 @@ impl Deployment { pub fn path(&self) -> String { format!("forge-contracts/deployments/{}.json", self.key) } - - /// The registry this file records, sourced to the file; `None` when it records none. - pub fn registry(&self) -> Option { - self.registry_contract_id - .clone() - .map(|contract_id| Registry { - contract_id, - source: ContractSource::Deployment(self.path()), - }) - } } /// The keys of every embedded deployment file, sorted. @@ -332,115 +316,42 @@ pub fn deployment(key: &str) -> Result> { .collect::>()?; Ok(Some(Deployment { key: key.to_string(), - registry_contract_id: file - .registry - .and_then(|r| r.contract_id) - .filter(|s| !s.is_empty()), dapi_addresses, quorum_base_url: file.quorum_base_url.filter(|s| !s.is_empty()), v2: file.v2.as_ref().and_then(V2Record::ids), })) } -// --------------------------------------------------------------------------- -// Registry resolution -// --------------------------------------------------------------------------- - -/// Where a resolved contract id came from (reported by `dg doctor`). -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ContractSource { - /// A user override; the string names where it was set (`env FORGE_REGISTRY_CONTRACT_ID`, - /// `config registry_contract_id`, `git config dash.registryContractId`). - Override(String), - /// The embedded deployment file (its repo-relative path). - Deployment(String), -} - -impl fmt::Display for ContractSource { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ContractSource::Override(origin) => write!(f, "override ({origin})"), - ContractSource::Deployment(path) => f.write_str(path), - } - } -} - -/// The registry contract a client uses, and where its id came from. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Registry { - /// The base58 registry contract id. - pub contract_id: String, - /// Where the id came from. - pub source: ContractSource, -} - -impl Registry { - /// A user-supplied override, labelled with where it was set. - pub fn override_from(contract_id: impl Into, origin: impl Into) -> Self { - Self { - contract_id: contract_id.into(), - source: ContractSource::Override(origin.into()), - } - } -} - -/// The registry for `network` with no user override: the embedded deployment's id, or -/// `None` when nothing is deployed there. -pub fn deployed_registry(network: &Network) -> Result> { - Ok(deployment(&network.key())?.and_then(|d| d.registry())) -} - -/// A network plus the registry resolved for it — what [`crate::platform::PlatformClient`] -/// connects to. +/// A network plus the forge-v2 contracts deployed on it — what +/// [`crate::platform::PlatformClient`] connects to. #[derive(Debug, Clone, PartialEq, Eq)] pub struct NetworkTarget { /// The network. pub network: Network, - /// The registry, or `None` when no registry is deployed on `network` and no override - /// was given (registry operations then fail with [`Error::NotDeployed`]). - pub registry: Option, - /// The forge-v2 contracts the embedded deployment records for `network`, if registered. + /// The forge-v2 contracts the embedded deployment records for `network`, or `None` when + /// none are registered there (repository operations then fail with + /// [`Error::V2NotDeployed`]). pub v2: Option, } impl NetworkTarget { - /// `network` with the registry from `FORGE_REGISTRY_CONTRACT_ID` if set, else the - /// embedded deployment. + /// `network` with the contracts its embedded deployment records. pub fn for_network(network: Network) -> Result { - let recorded = deployment(&network.key())?; - let registry = match NetworkSettings::from_env().registry { - Some(r) => Some(r), - None => recorded.as_ref().and_then(Deployment::registry), - }; - let v2 = recorded.and_then(|d| d.v2); - Ok(Self { - network, - registry, - v2, - }) + let v2 = deployment(&network.key())?.and_then(|d| d.v2); + Ok(Self { network, v2 }) } - /// The registry, or the actionable "not deployed here" error. - pub fn require_registry(&self) -> Result<&Registry> { - self.registry.as_ref().ok_or_else(|| Error::NotDeployed { + /// The forge-v2 contracts, or the actionable "not deployed here" error. + pub fn require_v2(&self) -> Result<&ForgeIds> { + self.v2.as_ref().ok_or_else(|| Error::V2NotDeployed { network: self.network.key(), }) } /// The env vars that hand this exact target to a child process (`git` → - /// git-remote-dash): [`Network::env_vars`] plus `FORGE_REGISTRY_CONTRACT_ID` when the - /// registry is an override (blank otherwise, so an inherited value cannot leak in). + /// git-remote-dash): [`Network::env_vars`]. pub fn env_vars(&self) -> Vec<(&'static str, String)> { - let mut vars = self.network.env_vars(); - let registry = match &self.registry { - Some(Registry { - contract_id, - source: ContractSource::Override(_), - }) => contract_id.clone(), - _ => String::new(), - }; - vars.push((ENV_REGISTRY_CONTRACT_ID, registry)); - vars + self.network.env_vars() } } @@ -456,26 +367,22 @@ pub struct NetworkSettings { pub dapi_addresses: Option, /// Quorum service base URL (devnet only). pub quorum_base_url: Option, - /// Registry contract id override. - pub registry: Option, } /// The env var names, in [`NetworkSettings::from_lookup`] order. -const ENV_KEYS: [&str; 5] = [ +const ENV_KEYS: [&str; 4] = [ ENV_NETWORK, ENV_DEVNET_NAME, ENV_DAPI_ADDRESSES, ENV_QUORUM_URL, - ENV_REGISTRY_CONTRACT_ID, ]; /// The git config keys, in [`NetworkSettings::from_lookup`] order. -const GIT_CONFIG_KEYS: [&str; 5] = [ +const GIT_CONFIG_KEYS: [&str; 4] = [ "dash.network", "dash.devnetName", "dash.dapiAddresses", "dash.quorumUrl", - "dash.registryContractId", ]; /// `Some(trimmed)` for a non-empty value; an empty setting counts as unset, so @@ -504,37 +411,34 @@ impl NetworkSettings { } /// The layer read from `DASH_FORGE_NETWORK`, `DASH_FORGE_DEVNET_NAME`, - /// `DASH_FORGE_DAPI_ADDRESSES`, `DASH_FORGE_QUORUM_URL` and `FORGE_REGISTRY_CONTRACT_ID`. + /// `DASH_FORGE_DAPI_ADDRESSES` and `DASH_FORGE_QUORUM_URL`. pub fn from_env() -> Self { - Self::from_lookup(|k| std::env::var(k).ok(), ENV_KEYS, "env") + Self::from_lookup(|k| std::env::var(k).ok(), ENV_KEYS) } - /// The layer from git config `dash.network`, `dash.devnetName`, `dash.dapiAddresses`, - /// `dash.quorumUrl` and `dash.registryContractId`, read through `get` (which returns - /// the value of a git config key, if set). + /// The layer from git config `dash.network`, `dash.devnetName`, `dash.dapiAddresses` + /// and `dash.quorumUrl`, read through `get` (which returns the value of a git config + /// key, if set). pub fn from_git_config(get: impl Fn(&str) -> Option) -> Self { - Self::from_lookup(get, GIT_CONFIG_KEYS, "git config") + Self::from_lookup(get, GIT_CONFIG_KEYS) } - /// Build a layer from a key lookup. `keys` names network, devnet name, DAPI list, - /// quorum URL and registry id in that order; `origin` labels a registry override. - fn from_lookup(get: impl Fn(&str) -> Option, keys: [&str; 5], origin: &str) -> Self { - let [network, devnet_name, dapi_addresses, quorum_base_url, registry] = keys; + /// Build a layer from a key lookup. `keys` names network, devnet name, DAPI list and + /// quorum URL in that order. + fn from_lookup(get: impl Fn(&str) -> Option, keys: [&str; 4]) -> Self { + let [network, devnet_name, dapi_addresses, quorum_base_url] = keys; Self { network: non_empty(get(network)), devnet_name: non_empty(get(devnet_name)), dapi_addresses: non_empty(get(dapi_addresses)), quorum_base_url: non_empty(get(quorum_base_url)), - registry: non_empty(get(registry)) - .map(|id| Registry::override_from(id, format!("{origin} {registry}"))), } } /// Field-wise: keep each field of `self`, filling unset ones from `lower`. /// /// A lower layer that names a *different* network (kind or devnet name) contributes - /// nothing network-specific: a config file's testnet registry override must not follow - /// `--network mainnet`, and a `moutai` DAPI list must not follow `--devnet-name paloma`. + /// nothing network-specific: a `moutai` DAPI list must not follow `--devnet-name paloma`. #[must_use] pub fn overlay(self, lower: Self) -> Self { let differs = |a: &Option, b: &Option, fold: bool| match (a, b) { @@ -557,14 +461,12 @@ impl NetworkSettings { devnet_name: self.devnet_name.or(lower.devnet_name), dapi_addresses: self.dapi_addresses.or(lower.dapi_addresses), quorum_base_url: self.quorum_base_url.or(lower.quorum_base_url), - registry: self.registry.or(lower.registry), } } /// Resolve to a [`NetworkTarget`]. The kind defaults to testnet, or to devnet when only /// a devnet name was given. A devnet needs a name; its DAPI addresses and quorum URL - /// fall back to `deployments/devnet-.json`. The registry is the override if any - /// layer set one, else the embedded deployment. + /// fall back to `deployments/devnet-.json`, as do the forge-v2 contract ids. pub fn resolve(self) -> Result { let kind = match (&self.network, &self.devnet_name) { (Some(kind), _) => kind.as_str(), @@ -607,15 +509,8 @@ impl NetworkSettings { ))) } }; - let registry = self - .registry - .or_else(|| recorded.as_ref().and_then(Deployment::registry)); let v2 = recorded.and_then(|d| d.v2); - Ok(NetworkTarget { - network, - registry, - v2, - }) + Ok(NetworkTarget { network, v2 }) } } @@ -623,16 +518,21 @@ impl NetworkSettings { mod tests { use super::*; - /// The testnet registry id as read straight from the file on disk — proves the embedded - /// copy is the committed file, without restating the id here. - fn testnet_registry_on_disk() -> String { + /// moutai's forge-v2 ids as read straight from the file on disk: proves the embedded copy + /// is the committed file, without restating the ids here. + fn expected_ids() -> ForgeIds { let path = concat!( env!("CARGO_MANIFEST_DIR"), - "/../../forge-contracts/deployments/testnet.json" + "/../../forge-contracts/deployments/devnet-moutai.json" ); let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); - v["registry"]["contractId"].as_str().unwrap().to_string() + let on_disk = |p: &str| v.pointer(p).unwrap().as_str().unwrap().to_string(); + ForgeIds { + core: on_disk("/v2/forgeCore/contractId"), + collab: on_disk("/v2/forgeCollab/contractId"), + group: on_disk("/v2/contractGroupId"), + } } fn layer(network: &str) -> NetworkSettings { @@ -645,7 +545,6 @@ mod tests { #[test] fn every_embedded_deployment_parses() { let keys: Vec<_> = deployment_keys().collect(); - assert!(keys.contains(&"testnet"), "{keys:?}"); assert!(keys.contains(&"devnet-moutai"), "{keys:?}"); for key in keys { deployment(key).unwrap().expect("listed key has a file"); @@ -653,52 +552,26 @@ mod tests { } #[test] - fn testnet_registry_comes_from_the_deployment_file() { - let t = NetworkSettings::default().resolve().unwrap(); - assert_eq!(t.network, Network::Testnet); - let r = t.require_registry().unwrap(); - assert_eq!(r.contract_id, testnet_registry_on_disk()); - assert_eq!( - r.source, - ContractSource::Deployment("forge-contracts/deployments/testnet.json".into()) - ); - } - - #[test] - fn mainnet_without_a_deployment_is_not_deployed_not_testnet() { - // deployments/mainnet.json records DAPI seeds but no registry until the runbook deploy; - // this becomes vacuous (and should be deleted) once it records one. - if deployment("mainnet") - .unwrap() - .is_some_and(|d| d.registry_contract_id.is_some()) - { - return; + fn a_network_without_a_deployment_is_not_deployed_not_another_networks() { + for net in ["testnet", "mainnet"] { + // Vacuous for a network once its deployment file lands. + if deployment(net).unwrap().is_some() { + continue; + } + let t = layer(net).resolve().unwrap(); + assert_eq!(t.network.key(), net); + assert!(t.v2.is_none()); + let err = t.require_v2().unwrap_err().to_string(); + assert!( + err.contains(&format!("forge-v2 isn't deployed on {net} yet")), + "{err}" + ); } - let t = layer("mainnet").resolve().unwrap(); - assert_eq!(t.network, Network::Mainnet); - assert!(t.registry.is_none()); - let err = t.require_registry().unwrap_err().to_string(); - assert!( - err.contains("no Dash Forge registry is deployed on mainnet yet"), - "{err}" - ); - assert!(err.contains("docs/mainnet-runbook.md"), "{err}"); } #[test] fn moutai_exposes_its_forge_v2_ids_from_the_deployment_file() { - let path = concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../forge-contracts/deployments/devnet-moutai.json" - ); - let v: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); - let on_disk = |p: &str| v.pointer(p).unwrap().as_str().unwrap().to_string(); - let expected = ForgeIds { - core: on_disk("/v2/forgeCore/contractId"), - collab: on_disk("/v2/forgeCollab/contractId"), - group: on_disk("/v2/contractGroupId"), - }; + let expected = expected_ids(); let d = deployment("devnet-moutai").unwrap().unwrap(); assert_eq!(d.v2.as_ref(), Some(&expected)); @@ -713,8 +586,7 @@ mod tests { NetworkTarget::for_network(t.network.clone()).unwrap().v2, Some(expected) ); - // Testnet has no forge-v2 record yet. - assert_eq!(NetworkSettings::default().resolve().unwrap().v2, None); + assert_eq!(t.require_v2().unwrap(), &expected_ids()); } #[test] @@ -772,7 +644,7 @@ mod tests { } #[test] - fn moutai_resolves_addresses_from_its_deployment_and_has_no_registry() { + fn moutai_resolves_addresses_from_its_deployment() { let t = NetworkSettings { network: Some("devnet".into()), devnet_name: Some("moutai".into()), @@ -796,8 +668,6 @@ mod tests { t.network.quorum_base_url(), "https://quorums.moutai.networks.dash.org" ); - let err = t.require_registry().unwrap_err().to_string(); - assert!(err.contains("devnet-moutai"), "{err}"); } #[test] @@ -824,7 +694,7 @@ mod tests { } #[test] - fn unknown_devnet_resolves_with_no_addresses_and_no_registry() { + fn unknown_devnet_resolves_with_no_addresses_and_no_contracts() { let t = NetworkSettings { network: Some("devnet".into()), devnet_name: Some("paloma".into()), @@ -835,7 +705,7 @@ mod tests { assert!( matches!(&t.network, Network::Devnet { dapi_addresses, .. } if dapi_addresses.is_empty()) ); - assert!(t.registry.is_none()); + assert!(t.v2.is_none()); } #[test] @@ -895,13 +765,11 @@ mod tests { network: Some("devnet".into()), devnet_name: Some("moutai".into()), dapi_addresses: Some("10.1.1.1".into()), - registry: Some(Registry::override_from("CFG", "config")), ..Default::default() }; let env = NetworkSettings { dapi_addresses: Some("10.9.9.9".into()), quorum_base_url: Some("https://q.example".into()), - registry: Some(Registry::override_from("ENV", "env")), ..Default::default() }; let merged = flags.overlay(config).overlay(env); @@ -909,22 +777,10 @@ mod tests { assert_eq!(merged.devnet_name.as_deref(), Some("moutai")); assert_eq!(merged.dapi_addresses.as_deref(), Some("10.1.1.1")); assert_eq!(merged.quorum_base_url.as_deref(), Some("https://q.example")); - assert_eq!(merged.registry.as_ref().unwrap().contract_id, "CFG"); } #[test] fn a_layer_for_another_network_contributes_nothing_network_specific() { - // `--network mainnet` must not pick up the config file's testnet registry override. - let flags = layer("mainnet"); - let config = NetworkSettings { - network: Some("testnet".into()), - registry: Some(Registry::override_from("TESTREG", "config")), - ..Default::default() - }; - let merged = flags.overlay(config); - assert_eq!(merged.registry, None); - assert!(merged.resolve().unwrap().registry.is_none()); - // `--devnet-name paloma` must not pick up moutai's configured DAPI list. let flags = NetworkSettings { network: Some("devnet".into()), @@ -942,42 +798,11 @@ mod tests { assert_eq!(merged.dapi_addresses, None); // A layer that names no network is not "another network": it applies. - let merged = layer("mainnet").overlay(NetworkSettings { - registry: Some(Registry::override_from("ANY", "env")), + let merged = layer("devnet").overlay(NetworkSettings { + devnet_name: Some("moutai".into()), ..Default::default() }); - assert_eq!(merged.registry.unwrap().contract_id, "ANY"); - } - - #[test] - fn a_registry_override_beats_the_deployment_file() { - let t = NetworkSettings { - registry: Some(Registry::override_from( - "OVERRIDE", - "env FORGE_REGISTRY_CONTRACT_ID", - )), - ..Default::default() - } - .resolve() - .unwrap(); - let r = t.require_registry().unwrap(); - assert_eq!(r.contract_id, "OVERRIDE"); - assert_eq!( - r.source.to_string(), - "override (env FORGE_REGISTRY_CONTRACT_ID)" - ); - } - - #[test] - fn a_registry_override_makes_mainnet_usable() { - let t = NetworkSettings { - network: Some("mainnet".into()), - registry: Some(Registry::override_from("MAIN", "config")), - ..Default::default() - } - .resolve() - .unwrap(); - assert_eq!(t.require_registry().unwrap().contract_id, "MAIN"); + assert_eq!(merged.devnet_name.as_deref(), Some("moutai")); } #[test] @@ -986,7 +811,7 @@ mod tests { (ENV_NETWORK, "devnet"), (ENV_DEVNET_NAME, ""), (ENV_DAPI_ADDRESSES, " "), - (ENV_REGISTRY_CONTRACT_ID, "REG"), + (ENV_QUORUM_URL, "https://q.example"), ]; let env = NetworkSettings::from_lookup( |k| { @@ -995,18 +820,11 @@ mod tests { .map(|(_, v)| (*v).to_string()) }, ENV_KEYS, - "env", ); assert_eq!(env.network.as_deref(), Some("devnet")); assert_eq!(env.devnet_name, None); assert_eq!(env.dapi_addresses, None); - assert_eq!( - env.registry, - Some(Registry::override_from( - "REG", - "env FORGE_REGISTRY_CONTRACT_ID" - )) - ); + assert_eq!(env.quorum_base_url.as_deref(), Some("https://q.example")); } #[test] @@ -1015,7 +833,6 @@ mod tests { "dash.network" => Some("devnet".into()), "dash.devnetName" => Some("moutai".into()), "dash.dapiAddresses" => Some("10.1.1.1".into()), - "dash.registryContractId" => Some("GITREG".into()), _ => None, }); let t = git.resolve().unwrap(); @@ -1023,10 +840,6 @@ mod tests { assert!( matches!(&t.network, Network::Devnet { dapi_addresses, .. } if dapi_addresses == &["https://10.1.1.1:1443"]) ); - assert_eq!( - t.require_registry().unwrap().source.to_string(), - "override (git config dash.registryContractId)" - ); } #[test] @@ -1043,7 +856,6 @@ mod tests { let child = NetworkSettings::from_lookup( |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| v.clone()), ENV_KEYS, - "env", ) .resolve() .unwrap(); diff --git a/crates/forge-core/src/platform/mod.rs b/crates/forge-core/src/platform/mod.rs index e072ee9db..eabc3c357 100644 --- a/crates/forge-core/src/platform/mod.rs +++ b/crates/forge-core/src/platform/mod.rs @@ -35,7 +35,6 @@ use serde::{Deserialize, Serialize}; use dapi_grpc::platform::v0::get_documents_request::get_documents_request_v0::Start; use dash_sdk::dapi_client::{Address, AddressList, CanRetry}; -use dash_sdk::dpp::balances::credits::TokenAmount; use dash_sdk::dpp::block::extended_epoch_info::ExtendedEpochInfo; use dash_sdk::dpp::consensus::basic::BasicError; use dash_sdk::dpp::consensus::state::state_error::StateError; @@ -43,7 +42,6 @@ use dash_sdk::dpp::consensus::ConsensusError; use dash_sdk::dpp::dashcore::secp256k1::rand::{rngs::StdRng, Rng, SeedableRng}; use dash_sdk::dpp::dashcore::Network as DashcoreNetwork; use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; -use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV1Getters; use dash_sdk::dpp::document::{Document, DocumentV0, DocumentV0Getters, INITIAL_REVISION}; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -56,23 +54,13 @@ use dash_sdk::dpp::state_transition::batch_transition::methods::v0::DocumentsBat use dash_sdk::dpp::state_transition::batch_transition::BatchTransition; use dash_sdk::dpp::state_transition::proof_result::StateTransitionProofResult; use dash_sdk::dpp::state_transition::StateTransition; -use dash_sdk::dpp::tokens::calculate_token_id; -use dash_sdk::dpp::tokens::info::v0::IdentityTokenInfoV0Accessors; -use dash_sdk::dpp::tokens::info::IdentityTokenInfo; -use dash_sdk::dpp::tokens::token_amount_on_contract_token::DocumentActionTokenCost; -use dash_sdk::dpp::tokens::token_payment_info::v0::TokenPaymentInfoV0; -use dash_sdk::dpp::tokens::token_payment_info::TokenPaymentInfo; use dash_sdk::drive::query::{OrderClause, SelectProjection, WhereClause, WhereOperator}; use dash_sdk::platform::contract_groups::ContractGroupMembershipsForContract; use dash_sdk::platform::documents::document_query::DocumentQuery; use dash_sdk::platform::fetch_current_no_parameters::FetchCurrent; -use dash_sdk::platform::tokens::identity_token_balances::IdentitiesTokenBalancesQuery; -use dash_sdk::platform::tokens::token_info::IdentitiesTokenInfosQuery; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::{DataContract, Fetch, FetchMany, Identifier, Identity, IdentityPublicKey}; use dash_sdk::{RequestSettings, Sdk, SdkBuilder}; -use drive_proof_verifier::types::identity_token_balance::IdentitiesTokenBalances; -use drive_proof_verifier::types::token_info::IdentitiesTokenInfos; use drive_proof_verifier::DocumentCount; use rs_sdk_trusted_context_provider::TrustedHttpContextProvider; use simple_signer::single_key_signer::SingleKeySigner; @@ -126,7 +114,7 @@ const DAPI_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs /// quickly, and a connect timeout is now cheap enough to allow more. const DAPI_RETRIES: usize = 6; -pub use crate::network::{Network, NetworkTarget, Registry}; +pub use crate::network::{Network, NetworkTarget}; pub mod wrap; @@ -153,9 +141,7 @@ impl LoadedContract { self.0.id().to_string(Encoding::Base58) } - /// The contract owner's base58 identity id. The owner is auto-credited both tokens' - /// `baseSupply` at creation, so it is always a WRITE+MAINTAIN holder even though no - /// `mint` history document records that crediting (data-contracts §2.1). + /// The contract owner's base58 identity id. pub fn owner_id(&self) -> String { self.0.owner_id().to_string(Encoding::Base58) } @@ -304,7 +290,7 @@ impl std::fmt::Debug for LoadedIdentity { } /// An rs-sdk-backed Platform client: a connected `Sdk` plus the network it targets and the -/// registry resolved for that network. +/// forge-v2 contracts deployed there. /// /// Construct with [`PlatformClient::connect`]. Proof verification is always on (the /// trusted context provider supplies quorum public keys over HTTPS); there is no @@ -336,9 +322,8 @@ impl PlatformClient { /// DAPI addresses; when it has none they are discovered from the devnet's quorum /// service (`/masternodes`), the same trusted source the quorum keys come from. /// - /// The target's registry is not fetched here: a network with no deployment still - /// connects (identity/balance reads work), and registry operations fail with - /// [`Error::NotDeployed`] when they need it. + /// A network with no forge-v2 deployment still connects (identity/balance reads work); + /// repository operations fail with [`Error::V2NotDeployed`] when they need it. pub async fn connect(target: NetworkTarget) -> Result { let network = &target.network; let dashcore_network = to_dashcore(network); @@ -401,9 +386,8 @@ impl PlatformClient { }) } - /// Connect to `network` with the registry from its embedded deployment (or the - /// `FORGE_REGISTRY_CONTRACT_ID` override). For callers without a config layer of their - /// own — tests and examples. + /// Connect to `network` with the contracts its embedded deployment records. For callers + /// without a config layer of their own — tests and examples. pub async fn connect_network(network: Network) -> Result { Self::connect(NetworkTarget::for_network(network)?).await } @@ -413,23 +397,11 @@ impl PlatformClient { &self.target.network } - /// The resolved network + registry this client was connected with. + /// The resolved network + forge-v2 contracts this client was connected with. pub fn target(&self) -> &NetworkTarget { &self.target } - /// The registry contract id for this network, or [`Error::NotDeployed`] when no registry - /// is deployed on it (never another network's id). - pub fn registry_contract_id(&self) -> Result<&str> { - Ok(self.target.require_registry()?.contract_id.as_str()) - } - - /// Fetch the registry contract for this network (see [`Self::registry_contract_id`]). - pub async fn fetch_registry(&self) -> Result { - let id = self.registry_contract_id()?.to_string(); - self.fetch_contract(&id).await - } - /// The Platform protocol version the SDK currently encodes and verifies with. /// /// The SDK starts at its per-network floor (13 for testnet/mainnet, 14 for a devnet) @@ -676,7 +648,7 @@ impl PlatformClient { /// Query **every** matching document, paginating past Platform's ≤100-row page cap. /// /// [`PlatformClient::query_documents`] returns a single page (≤100 rows); an - /// authorization-bearing fold (events, token history) MUST see all rows or a stranger + /// authorization-bearing fold (events, memberships) MUST see all rows or a stranger /// can bury real state-changing docs past row 100 with un-gated spam and freeze the /// displayed state. This loops on the `$id` cursor (`start_after` = the last row's id) /// until a short page is returned. `order` must be a stable traversal so the cursor @@ -729,88 +701,6 @@ impl PlatformClient { Ok(documents) } - // === Token reads (the v1 collaborator ACL, read-only) ================== - // - // forge-v1 repositories granted access with two tokens per repo contract (WRITE at - // position 0, MAINTAIN at position 1). v1 is read-only now: these reads remain so a v1 - // repo's collaborators and token history still render, but nothing mints, freezes or - // destroys any more. forge-v2 membership is documents (`crate::members`). - - /// The base58 token id for `position` (0 = WRITE, 1 = MAINTAIN) of `contract`, - /// derived as `hash("dash_token" || contractId || position)` (rs-dpp `calculate_token_id`). - pub fn token_id(&self, contract: &LoadedContract, position: u16) -> String { - let raw = calculate_token_id(&contract.0.id().to_buffer(), position); - Identifier::from(raw).to_string(Encoding::Base58) - } - - /// The token balances (`identity → amount`, absent = 0) of `token_id_b58` across - /// `identities` (base58). This is the authoritative on-chain collaborator holding - /// check — a positive balance means the token is held. - pub async fn token_balances( - &self, - token_id_b58: &str, - identities: &[String], - ) -> Result> { - if identities.is_empty() { - return Ok(BTreeMap::new()); - } - let token_id = parse_id(token_id_b58, "token id")?; - let identity_ids = identities - .iter() - .map(|s| parse_id(s, "identity id")) - .collect::>>()?; - let query = IdentitiesTokenBalancesQuery { - identity_ids, - token_id, - }; - let balances: IdentitiesTokenBalances = - retry_transient_read("query token balances", || { - TokenAmount::fetch_many(&self.sdk, query.clone()) - }) - .await - .map_err(|e| Error::Platform(format!("querying token balances: {e}")))?; - Ok(balances - .iter() - .map(|(id, amt)| (id.to_string(Encoding::Base58), amt.unwrap_or(0))) - .collect()) - } - - /// The frozen status (`identity → frozen`, absent = false) of `token_id_b58` across - /// `identities` (base58) — the suspend state included in a collaborator listing. - pub async fn token_frozen( - &self, - token_id_b58: &str, - identities: &[String], - ) -> Result> { - if identities.is_empty() { - return Ok(BTreeMap::new()); - } - let token_id = parse_id(token_id_b58, "token id")?; - let identity_ids = identities - .iter() - .map(|s| parse_id(s, "identity id")) - .collect::>>()?; - let query = IdentitiesTokenInfosQuery { - identity_ids, - token_id, - }; - let infos: IdentitiesTokenInfos = retry_transient_read("query token infos", || { - IdentityTokenInfo::fetch_many(&self.sdk, query.clone()) - }) - .await - .map_err(|e| Error::Platform(format!("querying token infos: {e}")))?; - Ok(infos - .iter() - .map(|(id, info)| { - ( - id.to_string(Encoding::Base58), - info.as_ref() - .is_some_and(IdentityTokenInfoV0Accessors::frozen), - ) - }) - .collect()) - } - /// An O(1) provable count of `document_type` documents in `contract` matching /// `filters`, via the count-tree `getDocuments`+`select count(*)` aggregate (the /// mechanism behind star / issue / PR totals, data-contracts §3). The `filters` @@ -1237,11 +1127,6 @@ impl<'a> WriteEngine<'a> { contract_version: None, }); - // For a token-gated create the transition must carry payment info matching the - // doc type's declared `tokenCost.create` (else consensus rejects with "Required - // token payment info not set"). Ungated types → `None` (platform fee only). - let token_payment = token_payment_for(doc_type_ref.document_creation_token_cost()); - let state_transition = BatchTransition::new_document_creation_transition_from_document( document, doc_type_ref, @@ -1249,7 +1134,8 @@ impl<'a> WriteEngine<'a> { &self.signing_key, nonce, 0, - token_payment, + // No forge-v2 type is token-gated: no token payment. + None, &self.signer, platform_version, None, @@ -1332,17 +1218,13 @@ impl<'a> WriteEngine<'a> { .await .map_err(|e| Error::Platform(format!("fetching identity-contract nonce: {e}")))?; - // A token-gated delete (chunk/packManifest refund) carries payment info matching - // the doc type's `tokenCost.delete`; non-deletable/ungated types → `None`. - let token_payment = token_payment_for(doc_type_ref.document_deletion_token_cost()); - let state_transition = BatchTransition::new_document_deletion_transition_from_document( document, doc_type_ref, &self.signing_key, nonce, 0, - token_payment, + None, &self.signer, self.client.sdk().version(), None, @@ -1975,10 +1857,9 @@ const MAX_PAGES: usize = 1000; /// block time, so these ties are real. Protocol 14 bounds the cursor by document id and /// does not drop them. /// -/// Limitation: the fix needs the boundary row's `$createdAt`. A proved query returns it -/// for registry types, but not for the history-keeping repo-v1 types (`packManifest`, -/// `event`, `refUpdate`, `issue`, ...), under either SDK version. Their reads keep the -/// protocol-13 gap until they move to forge-v2 contracts on protocol 14. +/// Every forge-v2 type read with an order ending in `$createdAt` requires it, so a proved +/// query returns the boundary row's +/// timestamp. fn tie_probe_allowed(filters: &[QueryFilter], order: &[QueryOrder]) -> bool { let Some((last, rest)) = order.split_last() else { return false; @@ -2106,25 +1987,6 @@ fn minimal_uint(n: u64) -> Value { } } -/// Build the [`TokenPaymentInfo`] a gated document create/delete must carry from the -/// doc type's declared [`DocumentActionTokenCost`], or `None` for an ungated action. -/// -/// `maximum_token_cost` is pinned to the contract-declared amount so a later -/// owner-side price change cannot silently overcharge the actor (the SDK's stated -/// rationale for the field); `payment_token_contract_id` / `token_contract_position` / -/// `gas_fees_paid_by` mirror the declaration exactly, which is what consensus checks. -fn token_payment_for(cost: Option) -> Option { - cost.map(|c| { - TokenPaymentInfo::V0(TokenPaymentInfoV0 { - payment_token_contract_id: c.contract_id, - token_contract_position: c.token_contract_position, - minimum_token_cost: None, - maximum_token_cost: Some(c.token_amount), - gas_fees_paid_by: c.gas_fees_paid_by, - }) - }) -} - /// Select the identity's on-chain AUTHENTICATION key that (a) the signer can sign with /// and (b) is a usable ECDSA_SECP256K1 authentication key at HIGH or CRITICAL — the /// levels document create/delete accept (spike S0.7). @@ -2182,13 +2044,13 @@ fn consensus_error_of(e: &dash_sdk::Error) -> Option<&ConsensusError> { /// Document types whose UNIQUE index makes a same-content re-upload an idempotent no-op: /// `chunk` (unique `(packHash, seq)`) and `packManifest` (unique `packHash`). A resumed /// push re-broadcasts these and a `DuplicateUniqueIndexError` means "already stored" = -/// success — NOT for e.g. `repoListing` (unique `(ownerId, normalizedName)`), where a +/// success — NOT for e.g. `repo` (unique `($ownerId, name)`), where a /// duplicate is a genuine name collision and must stay fatal. const CONTENT_ADDRESSED_UNIQUE_DOC_TYPES: [&str; 2] = ["chunk", "packManifest"]; /// Classify a `dash_sdk::Error` from a document broadcast by matching structured enum -/// variants (not lowercased Display substrings). Frozen-token (consensus 40702) and -/// unauthorized (40701) map to distinct, non-retryable crate errors; retryability comes +/// variants (not lowercased Display substrings). A missing membership (consensus 40120 on +/// `$ownerId`) maps to a distinct, non-retryable crate error; retryability comes /// from the SDK's authoritative [`CanRetry::can_retry`]. `document_type` scopes the /// unique-index idempotency (see [`CONTENT_ADDRESSED_UNIQUE_DOC_TYPES`]). fn classify_write_error(e: &dash_sdk::Error, document_type: &str) -> WriteFailure { @@ -2226,21 +2088,13 @@ fn classify_write_error(e: &dash_sdk::Error, document_type: &str) -> WriteFailur return WriteFailure::AlreadyLanded } // A unique-index collision on any OTHER type is a genuine clash (an `issue` - // /`patch` `number` already taken, a `repoListing` name collision). Surface it + // /`patch` `number` already taken, a `repo` name collision). Surface it // as a distinct, non-retryable error so the optimistic-numbering allocator can // catch it and retry with the next number (a name collision stays fatal at the // caller). NOT idempotent success — the content differs from what landed. StateError::DuplicateUniqueIndexError(err) => { return WriteFailure::Fatal(Error::DuplicateUniqueIndex(format!("{err:?}"))) } - // 40702: the identity's token account is frozen → write access revoked. - StateError::IdentityTokenAccountFrozenError(_) => { - return WriteFailure::Fatal(Error::TokenFrozen) - } - // 40701: not authorized for this token action. - StateError::UnauthorizedTokenActionError(_) => { - return WriteFailure::Fatal(Error::Unauthorized) - } // 40120 on the writer path: a protocol-14 `ownerRefersTo` gate found no // membership document for the writer (forge-v2: never granted, or revoked; or a // writer where the type needs a maintainer). @@ -3103,12 +2957,15 @@ mod tests { assert_eq!((nb, nw), (max, max)); let (out, nb, nw) = scripted_write( - vec![Err(super::WriteFailure::Fatal(Error::Unauthorized))], + vec![Err(super::WriteFailure::Fatal(Error::NotAMember { + document_type: "refUpdate".into(), + detail: "40120".into(), + }))], vec![], vec![], ) .await; - assert!(matches!(out, Err(Error::Unauthorized))); + assert!(matches!(out, Err(Error::NotAMember { .. }))); assert_eq!((nb, nw), (1, 0)); } diff --git a/crates/forge-core/src/refs.rs b/crates/forge-core/src/refs.rs index cb658fbcb..020f61894 100644 --- a/crates/forge-core/src/refs.rs +++ b/crates/forge-core/src/refs.rs @@ -55,11 +55,9 @@ //! //! One path does still use a cursor: a ref with more than a page of updates is read with //! `refNameHash == h` paged by `startAfter`. That is single-branch, so the sibling-branch -//! drop cannot happen, but protocol 13 still skips rows sharing the page boundary's -//! `$createdAt` (docs/BUILDING.md, "same-block ties"), and repo-v1 ref updates do not return -//! `$createdAt` from a proved query, so the tie probe cannot repair it. That read is the one -//! `base_ref_tips` always used; it goes away with forge-v2 on protocol 14, whose cursor is -//! bounded by document id. The mock's `ref_history` is exact, so no test here covers it. +//! drop cannot happen; on protocol 14 the cursor is bounded by document id, so rows sharing +//! the page boundary's `$createdAt` are not skipped. The mock's `ref_history` is exact, so +//! no test here covers it. use std::collections::{BTreeMap, BTreeSet}; @@ -118,11 +116,10 @@ pub(crate) trait RefDocSource { } } -/// Whether `d` is well-formed for the repository `scope` names: forge-v2's §5 rule (this -/// client reads public v2 repositories only; `RepoRef::require_readable` refuses the rest), and -/// on v1, which has no such rule, always. -fn well_formed_in(scope: &DocScope, kind: ContentKind, d: &FetchedDocument) -> bool { - !scope.is_v2() || is_well_formed(&content_of(kind, d), Visibility::Public) +/// Whether `d` is well-formed: forge-v2's §5 rule (this client reads public repositories only; +/// `RepoRef::require_readable` refuses the rest). +fn well_formed_in(kind: ContentKind, d: &FetchedDocument) -> bool { + is_well_formed(&content_of(kind, d), Visibility::Public) } /// The §5 content view of a ref-update or config row. @@ -146,10 +143,9 @@ fn content_of(kind: ContentKind, d: &FetchedDocument) -> ContentDoc { } } -/// [`RefDocSource`] over a live Platform connection, inside one repository's scope: on -/// forge-v2 every query leads with `repoId == R` (the `refState` and `reflog` indexes are -/// `(repoId, refNameHash, $createdAt)` and `(repoId, $createdAt)`), on v1 the repo -/// contract is the scope. +/// [`RefDocSource`] over a live Platform connection, inside one repository's scope: every +/// query leads with `repoId == R` (the `refState` and `reflog` indexes are +/// `(repoId, refNameHash, $createdAt)` and `(repoId, $createdAt)`). pub(crate) struct PlatformRefSource<'a> { pub(crate) client: &'a PlatformClient, pub(crate) contract: &'a LoadedContract, @@ -205,12 +201,12 @@ impl RefDocSource for PlatformRefSource<'_> { } fn well_formed(&self, d: &FetchedDocument) -> bool { - well_formed_in(self.scope, ContentKind::RefUpdate, d) + well_formed_in(ContentKind::RefUpdate, d) } } /// Read every ref's complete history of the repository `scope` names, from `contract` -/// (forge-core on v2, the repo contract on v1). See the module docs. +/// (forge-core). See the module docs. pub async fn read_all_ref_updates( client: &PlatformClient, contract: &LoadedContract, @@ -246,7 +242,7 @@ pub async fn read_config_history( .await?; Ok(docs .iter() - .filter(|d| well_formed_in(scope, ContentKind::Config, d)) + .filter(|d| well_formed_in(ContentKind::Config, d)) .map(crate::repo::config_doc) .collect()) } @@ -484,7 +480,7 @@ mod tests { FetchedDocument { id: format!("id{id:06}"), owner_id: "pusher".into(), - // The deployed repo-v1 type never recorded `$createdAt` (design-freeze-2 §3). + // The scan must not depend on `$createdAt` being present. created_at: None, fields, } @@ -754,10 +750,6 @@ mod tests { fn v2_readers_skip_malformed_ref_updates() { use crate::backends::sha256; use crate::rules::v2::ContentKind; - let v2 = crate::scope::DocScope { - contract_id: "c".into(), - repo_id: Some([1; 32]), - }; let doc = |name: &str, hash: [u8; 32], enc: bool| { let mut fields = BTreeMap::new(); fields.insert("refNameHash".into(), FieldValue::Bytes32(hash)); @@ -776,27 +768,15 @@ mod tests { }; let main = sha256(b"refs/heads/main"); let ok = doc("refs/heads/main", main, false); - assert!(super::well_formed_in(&v2, ContentKind::RefUpdate, &ok)); + assert!(super::well_formed_in(ContentKind::RefUpdate, &ok)); assert!(!super::well_formed_in( - &v2, ContentKind::RefUpdate, &doc("refs/heads/main", main, true) )); assert!(!super::well_formed_in( - &v2, ContentKind::RefUpdate, &doc("refs/heads/other", main, false) )); - // v1 has no such rule. - let v1 = crate::scope::DocScope { - contract_id: "c".into(), - repo_id: None, - }; - assert!(super::well_formed_in( - &v1, - ContentKind::RefUpdate, - &doc("refs/heads/main", main, true) - )); } #[test] diff --git a/crates/forge-core/src/repo.rs b/crates/forge-core/src/repo.rs index 291020b6c..1efe7d884 100644 --- a/crates/forge-core/src/repo.rs +++ b/crates/forge-core/src/repo.rs @@ -1,10 +1,8 @@ //! [`RepoService`] — the git data plane `git-remote-dash` and `dg` drive. //! //! Every operation takes a resolved [`RepoRef`] and reaches its documents through the -//! repo's [`DocScope`]: on forge-v2 that is the network's shared forge-core contract with -//! `repoId == R` on every query and write; on forge-v1 it is the repo's own contract. v1 -//! repositories are **read only**: every write refuses them with [`Error::V1ReadOnly`] -//! before signing anything. +//! repo's [`DocScope`]: the network's shared forge-core contract with `repoId == R` on every +//! query and write. //! //! - [`RepoService::write_ref_update`] / [`RepoService::read_refs`] — append a ref update //! (`protectedRefUpdate` for a protected ref, routed by the as-of config rule) and fold a @@ -12,11 +10,11 @@ //! - [`RepoService::write_pack_manifest`] / [`RepoService::read_pack_manifests`] and the //! chunk tier ([`PlatformChunkTarget`]). //! - [`RepoService::fetch_artifact`] — read a pack: external copies first, then Platform -//! chunks. On v2 each uploader has its own copy of a pack; readers try them in the +//! chunks. Each uploader has its own copy of a pack; readers try them in the //! `FORGE_RULES_V2` order (maintainers', then writers', then former members'), and use //! the first that hash-verifies ([`crate::rules::v2::order_pack_copies`]). -//! - [`RepoService::repack`] — consolidate the live packs into one superseding pack. On v2 -//! nothing is deleted: chunks and manifests are permanent (forge-v2 §4). +//! - [`RepoService::repack`] — consolidate the live packs into one superseding pack. Nothing +//! is deleted: chunks and manifests are permanent (forge-v2 §4). //! //! Repository creation is [`crate::create`]; resolution is [`crate::resolve`]; membership //! is [`crate::members`]. This module names no rs-sdk type (style guide §B). @@ -36,7 +34,7 @@ use crate::rules::{self, ConfigDoc, RefState}; use crate::scope::{self, DocScope, RepoRef}; use crate::storage::{PackReader, Replication, StorageTarget, UriBudget}; -// Document type names (the git data plane; the same names in forge-core and repo-v1). +// Document type names (the git data plane in forge-core). use crate::refs::DOC_CONFIG; use crate::refs::{DOC_PROTECTED_REF_UPDATE, DOC_REF_UPDATE}; const DOC_PACK_MANIFEST: &str = "packManifest"; @@ -65,7 +63,7 @@ pub struct PackManifestInfo { pub storage: u64, /// Offset-index part count. pub offset_index_parts: u64, - /// External copies (`uris`: a typed array on v2, a JSON string on v1). + /// External copies (`uris`, a typed string array). pub uris: Vec, /// Prior `packHash`es this manifest supersedes (parsed from the packed `byteArray`). pub supersedes: Vec<[u8; 32]>, @@ -336,7 +334,7 @@ pub struct LocalReseed { } /// A repository's current members as the pack reader rule needs them (maintainers' -/// copies first): empty on v1, where every copy is the repo contract's own. +/// copies first). pub type RoleMap = BTreeMap; /// The git data-plane service, bound to one signing identity and its keys. @@ -368,8 +366,8 @@ impl<'a> RepoService<'a> { WriteEngine::new(self.client, self.identity, self.bridge.doc_op_key()?) } - /// The contract holding `repo`'s git data (forge-core, or the v1 repo contract), - /// fetched and registered with the proof verifier. + /// The contract holding `repo`'s git data (forge-core), fetched and registered with the + /// proof verifier. pub async fn repo_contract(&self, repo: &RepoRef) -> Result { self.client.fetch_contract(&repo.scope()?.contract_id).await } @@ -382,9 +380,8 @@ impl<'a> RepoService<'a> { Ok((scope, contract)) } - /// The writable (v2) scope and contract of `repo`, or [`Error::V1ReadOnly`]. + /// The scope and contract of `repo`, for writing. async fn writable(&self, repo: &RepoRef) -> Result<(DocScope, LoadedContract)> { - repo.require_v2()?; self.readable(repo).await } @@ -526,8 +523,7 @@ impl<'a> RepoService<'a> { if !BACKEND_URIS_V2.fits(list) { return Err(Error::Config(format!( "config.backend.uris holds at most {} URLs of at most {} bytes each", - BACKEND_URIS_V2.max_items.unwrap_or_default(), - BACKEND_URIS_V2.max_item_len.unwrap_or_default() + BACKEND_URIS_V2.max_items, BACKEND_URIS_V2.max_item_len ))); } } @@ -631,8 +627,7 @@ impl<'a> RepoService<'a> { docs.iter().map(manifest_info).collect() } - /// Every manifest of `pack_hash` (on v2 each uploader may hold a copy; on v1 the index - /// is unique, so at most one). + /// Every manifest of `pack_hash` (each uploader may hold a copy). pub async fn read_pack_copies( &self, repo: &RepoRef, @@ -721,12 +716,8 @@ impl<'a> RepoService<'a> { )]) } - /// The uploader → current role map the v2 pack reader rule ranks copies by. Empty on - /// v1 (a v1 pack has exactly one copy). + /// The uploader → current role map the pack reader rule ranks copies by. pub async fn copy_roles(&self, repo: &RepoRef) -> Result { - if repo.is_v1() { - return Ok(RoleMap::new()); - } let members = crate::members::MemberReader::new(self.client) .list(repo) .await?; @@ -1555,7 +1546,7 @@ fn plan_push_index( /// The repository's pack list (`FORGE_RULES_V2::v2_pack_list`, forge-v2.md §4) over its /// manifests: every pack once, however many uploaders hold a copy, with its `packRef` among -/// the packs of its kind. `roles` ranks the copies (empty on v1, where each pack has one). +/// the packs of its kind. `roles` ranks the copies. /// Copies are listed unchecked (`verified: None`), so no pack counts as superseded here; /// supersession only changes which packs a reader fetches whole, never a position. pub fn pack_list( @@ -1939,7 +1930,7 @@ mod tests { .map(|m| m.document_id.clone()) .collect(); assert_eq!(order, ["m", "w", "s"]); - // With no membership known (v1), the order is by time. + // With no membership known, the order is by time. let order: Vec<_> = order_copies(&copies, &RoleMap::new()) .iter() .map(|m| m.document_id.clone()) diff --git a/crates/forge-core/src/resolve.rs b/crates/forge-core/src/resolve.rs index a4b6c10cf..2c73441e1 100644 --- a/crates/forge-core/src/resolve.rs +++ b/crates/forge-core/src/resolve.rs @@ -1,17 +1,12 @@ //! Resolving a repository reference (`owner/name`, or an id) to a [`RepoRef`]. //! -//! * `owner/name`: the name is checked and normalized as a forge-v2 slug +//! * `owner/name`: the name is checked and normalized as a slug //! ([`crate::rules::v2::normalize_repo_name`]), then looked up as a forge-core `repo` -//! through its unique `($ownerId, name)` index. Only when that lookup *proves* there is no -//! such repo does it fall back to the v1 registry listing (read-only repositories). A -//! failed lookup is an error, never a fallback, so a flaky node cannot send a push to a -//! different repository than the name means. -//! * an id: a forge-core `repo` document id first, then a v1 repo contract id. Both lookups -//! are proof-verified; the ids are 32-byte hashes of different preimages, so at most one -//! can exist, and the forge contracts themselves are refused as "repo contracts". +//! through its unique `($ownerId, name)` index (proof-verified: a proved absence is +//! [`Error::NotFound`], a failed lookup is an error). +//! * an id: a forge-core `repo` document id, proof-verified. //! -//! A network with no forge-v2 deployment resolves v1 repositories only; one with no -//! registry resolves v2 repositories only. +//! A network with no forge-v2 deployment resolves nothing: [`Error::V2NotDeployed`]. use crate::error::{Error, Result}; use crate::network::ForgeIds; @@ -21,8 +16,6 @@ use crate::scope::{visibility_of, RepoRef}; /// The forge-core document type of a repository. pub const DOC_REPO: &str = "repo"; -/// The v1 registry listing type. -const DOC_REPO_LISTING: &str = "repoListing"; /// The `repo.name` slug `input` names, or a configuration error explaining the rule. pub fn repo_slug(input: &str) -> Result { @@ -36,7 +29,7 @@ pub fn repo_slug(input: &str) -> Result { /// A forge-core `repo` document as a [`RepoRef`]. pub fn repo_ref_from_doc(forge: &ForgeIds, doc: &FetchedDocument) -> Result { - Ok(RepoRef::V2 { + Ok(RepoRef { forge: forge.clone(), repo_id: doc.id.clone(), owner_id: doc.owner_id.clone(), @@ -47,29 +40,18 @@ pub fn repo_ref_from_doc(forge: &ForgeIds, doc: &FetchedDocument) -> Result Result { let slug = repo_slug(name)?; let owner_bytes = platform::decode_identifier(owner)?; - let target = client.target(); - if let Some(forge) = &target.v2 { - if let Some(repo) = find_v2(client, forge, owner_bytes, &slug).await? { - return Ok(repo); - } - } - match (&target.registry, &target.v2) { - (Some(_), _) => find_v1(client, owner, owner_bytes, &slug) - .await? - .ok_or(Error::NotFound), - (None, Some(_)) => Err(Error::NotFound), - (None, None) => Err(Error::V2NotDeployed { - network: target.network.key(), - }), - } + let forge = client.target().require_v2()?; + find_named(client, forge, owner_bytes, &slug) + .await? + .ok_or(Error::NotFound) } -/// The forge-v2 repo `owner` named `slug`, if it exists (proved either way). -pub async fn find_v2( +/// The repo `owner` named `slug`, if it exists (proved either way). +pub async fn find_named( client: &PlatformClient, forge: &ForgeIds, owner: [u8; 32], @@ -94,73 +76,21 @@ pub async fn find_v2( .transpose() } -/// The v1 repo `owner` listed as `slug` in the registry, if any. -async fn find_v1( - client: &PlatformClient, - owner: &str, - owner_bytes: [u8; 32], - slug: &str, -) -> Result> { - let registry = client.fetch_registry().await?; - let docs = client - .query_documents( - ®istry, - DOC_REPO_LISTING, - &[ - QueryFilter::eq("$ownerId", FieldValue::identifier(owner_bytes)), - QueryFilter::eq("normalizedName", FieldValue::text(slug)), - ], - &[], - 1, - None, - ) - .await?; - let Some(listing) = docs.into_iter().next() else { - return Ok(None); - }; - let contract = listing - .field_bytes32("repoContractId") - .ok_or_else(|| Error::Platform("repoListing missing repoContractId".into()))?; - Ok(Some(RepoRef::V1 { - contract_id: platform::encode_identifier(contract), - owner_id: owner.to_string(), - // The slug (`normalizedName`), not the free-form display name: it is what - // `dash://owner/` resolves by. - name: listing - .field_str("normalizedName") - .unwrap_or_else(|| slug.to_string()), - })) -} - -/// Resolve a bare id: a forge-v2 `repo` document id, else a v1 repo contract id. +/// Resolve a bare id: a forge-core `repo` document id. pub async fn resolve_id(client: &PlatformClient, id: &str) -> Result { platform::decode_identifier(id)?; - let target = client.target(); - if let Some(forge) = &target.v2 { - let core = client.fetch_contract(&forge.core).await?; - if let Some(doc) = client.fetch_document(&core, DOC_REPO, id).await? { - return repo_ref_from_doc(forge, &doc); - } - if id == forge.core || id == forge.collab { - return Err(Error::Config(format!( - "{id} is a forge-v2 contract, not a repository; address a repo as \ - dash:/// or by its repo id" - ))); - } - } - let contract = client.fetch_contract(id).await?; - // A v1 repo contract carries the git data-plane types itself; any other contract - // (DPNS, the registry, forge-collab) is not a repository. - if !contract.has_document_type("refUpdate") || contract.has_document_type(DOC_REPO) { + let forge = client.target().require_v2()?; + if id == forge.core || id == forge.collab { return Err(Error::Config(format!( - "{id} is a data contract but not a Dash Forge v1 repository" + "{id} is a forge-v2 contract, not a repository; address a repo as \ + dash:/// or by its repo id" ))); } - Ok(RepoRef::V1 { - contract_id: contract.id(), - owner_id: contract.owner_id(), - name: contract.id(), - }) + let core = client.fetch_contract(&forge.core).await?; + match client.fetch_document(&core, DOC_REPO, id).await? { + Some(doc) => repo_ref_from_doc(forge, &doc), + None => Err(Error::NotFound), + } } /// The forks of the forge-v2 repo `parent_id` (the `forkOf` index), optionally only those @@ -189,76 +119,40 @@ pub async fn find_forks( .collect() } -/// The `forkOf` of a forge-v2 repo, if it is a fork. +/// The `forkOf` of a repo, if it is a fork. pub async fn fork_parent(client: &PlatformClient, repo: &RepoRef) -> Result> { - let RepoRef::V2 { forge, repo_id, .. } = repo else { - return Ok(None); - }; - let core = client.fetch_contract(&forge.core).await?; + let core = client.fetch_contract(&repo.forge.core).await?; Ok(client - .fetch_document(&core, DOC_REPO, repo_id) + .fetch_document(&core, DOC_REPO, &repo.repo_id) .await? .and_then(|d| d.field_bytes32("forkOf")) .map(platform::encode_identifier)) } -/// Every repository `owner` has: forge-v2 repos (when deployed), then v1 registry listings -/// (when a registry is deployed), each by name. +/// Every repository `owner` has, by name. pub async fn list_owned(client: &PlatformClient, owner: &str) -> Result> { let owner_bytes = platform::decode_identifier(owner)?; - let target = client.target(); - let mut out = Vec::new(); - if let Some(forge) = &target.v2 { - let core = client.fetch_contract(&forge.core).await?; - let docs = client - .query_all_documents( - &core, - DOC_REPO, - &[QueryFilter::eq( - "$ownerId", - FieldValue::identifier(owner_bytes), - )], - &[QueryOrder::asc("name")], - ) - .await?; - for d in &docs { - out.push(RepoSummary { + let forge = client.target().require_v2()?; + let core = client.fetch_contract(&forge.core).await?; + let docs = client + .query_all_documents( + &core, + DOC_REPO, + &[QueryFilter::eq( + "$ownerId", + FieldValue::identifier(owner_bytes), + )], + &[QueryOrder::asc("name")], + ) + .await?; + docs.iter() + .map(|d| { + Ok(RepoSummary { repo: repo_ref_from_doc(forge, d)?, description: d.field_str("description").unwrap_or_default(), - }); - } - } - if target.registry.is_some() { - let registry = client.fetch_registry().await?; - let docs = client - .query_all_documents( - ®istry, - DOC_REPO_LISTING, - &[QueryFilter::eq( - "$ownerId", - FieldValue::identifier(owner_bytes), - )], - &[QueryOrder::asc("normalizedName")], - ) - .await?; - for d in &docs { - let Some(contract) = d.field_bytes32("repoContractId") else { - continue; - }; - out.push(RepoSummary { - repo: RepoRef::V1 { - contract_id: platform::encode_identifier(contract), - owner_id: owner.to_string(), - name: d - .field_str("normalizedName") - .or_else(|| d.field_str("name")) - .unwrap_or_default(), - }, - description: d.field_str("description").unwrap_or_default(), - }); - } - } - Ok(out) + }) + }) + .collect() } /// One row of [`list_owned`]. @@ -266,7 +160,7 @@ pub async fn list_owned(client: &PlatformClient, owner: &str) -> Result bool { /// commit *A*") is an **input**: a precomputed set of `(ancestor, descendant)` pairs /// (typically the transitive closure over the relevant commits). This keeps ref /// resolution and merge-reachability pure and lets the vectors pin exactly which -/// ancestry facts are in play. [`resolve_ref`]/[`fold_pr_state`] also accept any +/// ancestry facts are in play. [`resolve_ref`]/[`v2::fold_pr_state_v2`] also accept any /// `Fn(&str, &str) -> bool` directly for callers that have a real graph. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(transparent)] @@ -220,7 +212,7 @@ pub fn tip_of(state: &RefState) -> Option { /// timeline (append-only, so order-independent). `is_ancestor(a, b)` reports whether /// commit `a` is an ancestor of (or equal to) commit `b`. /// -/// ## Algorithm (normative — `FORGE_RULES_V1`) +/// ## Algorithm (normative) /// /// This implements data-contracts §4's protected-ref pseudocode plus the §2.3 /// divergence rule, generalized so that a merge/force "supersedes both" heads exactly @@ -362,7 +354,7 @@ pub fn resolve_ref( /// Whether a ref name is legal to advertise on the git wire protocol. /// /// `refName` is stored as an arbitrary Platform string (≤255 chars) and never passed -/// `git check-ref-format`, so a hostile WRITE holder could store a name containing a +/// `git check-ref-format`, so a hostile writer could store a name containing a /// newline (`refs/heads/x\n refs/heads/main`) to **inject a spoofed /// ref-advertisement line** into every clone/fetch, or a NUL/space to corrupt parsing. /// The security-critical rule (shared by the write guard, the fold side, and the helper @@ -385,7 +377,7 @@ fn is_content_hash(h: &str) -> bool { /// /// Public because callers that only want to *display* a ref must apply the same predicate /// the fold does. `refName` is caller-supplied content and only `refNameHash` is indexed, so -/// a token holder can post an update carrying a name that does not hash to the key it is +/// a writer can post an update carrying a name that does not hash to the key it is /// filed under. `resolve_ref` already ignores such an update, and any client naming a ref /// from one would show a different branch name for the same ref than a client that does not. pub fn ref_name_hash_matches(ref_name: &str, ref_name_hash: &str) -> bool { @@ -450,7 +442,7 @@ impl Verdict { /// /// This is a shared rule, not a reader convenience, because the two halves of the ref /// document are trusted differently: `refNameHash` is the indexed key, while `refName` is -/// caller-supplied content. A token holder may therefore file an update under `main`'s hash +/// caller-supplied content. A writer may therefore file an update under `main`'s hash /// carrying any legal name. [`resolve_ref`] already ignores such an update when resolving the /// tip, so a client that named the ref from it would show a different branch name for the /// same ref than a client that did not — and `git ls-remote` would advertise the tip under a @@ -579,7 +571,7 @@ pub fn is_update_valid(u: &RefUpdate, config_history: &[ConfigDoc]) -> bool { // Protected ref: only a MAINTAIN-gated protectedRefUpdate moves it. u.protected } else { - // Unprotected: either type is fine (MAINTAIN holders may protect-push anywhere). + // Unprotected: either type is fine (maintainers may protect-push anywhere). true } } @@ -606,7 +598,7 @@ fn config_as_of(config_history: &[ConfigDoc], at: u64) -> Option<&ConfigDoc> { /// Whether `ref_name` matches **any** protected glob in `patterns`. /// -/// ## Pinned glob semantics (`FORGE_RULES_V1`) +/// ## Pinned glob semantics /// /// Matching is git **`wildmatch`** with the `WM_PATHNAME` flag — the same behavior /// `git for-each-ref ` uses. Precisely: @@ -669,151 +661,6 @@ fn neutralize_wildmatch(pattern: &str) -> String { out } -// =========================================================================== -// Token-history authorization (as-of-time) -// =========================================================================== - -/// Which repo token a history record concerns (§2.1). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum TokenKind { - /// Position 0 — push / upload / CI. - Write, - /// Position 1 — protected refs / releases / labels / webhooks / config. - Maintain, -} - -/// A token-history operation (§2.1 grant/suspend/revoke lifecycle). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum TokenOp { - /// Grant (or re-grant) the token to an identity. - Mint, - /// Suspend: the identity keeps the balance but a frozen identity cannot spend, so - /// gated actions fail at consensus — hence it cannot act, as-of the freeze. - Freeze, - /// Lift a freeze (identity can spend again). - Unfreeze, - /// Revoke: destroy the frozen balance. The holding is gone from here forward. - Destroy, -} - -/// One record from the system token-history contract: identity *X* had operation *op* -/// applied to token *token* at `created_at`. These reconstruct authorization as-of any -/// past moment (§4: "reconstructed deterministically from the token-history contract"). -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct TokenRecord { - /// Record `$id` — tiebreak for equal `created_at`. - #[serde(default)] - pub id: String, - /// The affected identity. - pub identity: String, - /// Which token. - pub token: TokenKind, - /// What happened. - pub op: TokenOp, - /// Consensus `$createdAt` (ms). - pub created_at: u64, -} - -/// Whether an identity can *spend* WRITE / MAINTAIN at a point in time. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Holdings { - /// Holds an unfrozen WRITE balance (can push). - pub write: bool, - /// Holds an unfrozen MAINTAIN balance (can protected-push / configure). - pub maintain: bool, -} - -impl Holdings { - /// Holder of either token — the "WRITE/MAINTAIN holder" the enforcement matrix - /// authorizes for every event kind. - #[must_use] - pub fn any(self) -> bool { - self.write || self.maintain - } -} - -/// Reconstruct an identity's **spendable** WRITE/MAINTAIN holdings as-of time `at`. -/// -/// Replays that identity's token-history records with `created_at <= at` (tie at equal -/// `created_at`: the record applies, ordered by `$id`) through a per-token state -/// machine: `Mint` → held & unfrozen, `Freeze` → held but suspended, `Unfreeze` → -/// spendable again, `Destroy` → not held. A token is *spendable* only when held and not -/// frozen — a frozen identity cannot spend at consensus (S0.7: rejected 40702), so it -/// cannot authorize an action at that time. -/// -/// Because this is evaluated *as-of the event's* `created_at`, a maintainer who was -/// frozen *after* acting still holds at the earlier moment: their past action stays -/// valid, exactly as §4 requires ("current balances alone would retroactively -/// invalidate a since-revoked maintainer's legitimate past actions"). -#[must_use] -pub fn holdings_as_of(records: &[TokenRecord], identity: &str, at: u64) -> Holdings { - Holdings { - write: token_spendable_as_of(records, identity, TokenKind::Write, at), - maintain: token_spendable_as_of(records, identity, TokenKind::Maintain, at), - } -} - -fn token_spendable_as_of( - records: &[TokenRecord], - identity: &str, - token: TokenKind, - at: u64, -) -> bool { - let mut relevant: Vec<&TokenRecord> = records - .iter() - .filter(|r| r.identity == identity && r.token == token && r.created_at <= at) - .collect(); - relevant.sort_by(|a, b| { - a.created_at - .cmp(&b.created_at) - .then_with(|| a.id.cmp(&b.id)) - }); - - let (mut held, mut frozen) = (false, false); - for r in relevant { - match r.op { - TokenOp::Mint => { - held = true; - frozen = false; - } - TokenOp::Freeze => frozen = true, - TokenOp::Unfreeze => frozen = false, - TokenOp::Destroy => { - held = false; - frozen = false; - } - } - } - held && !frozen -} - -/// A token-history-backed authorization resolver, as named in the module spec. Thin -/// wrapper over [`holdings_as_of`] so callers can pass one `&AuthzResolver` around -/// instead of threading the record slice. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct AuthzResolver { - /// The token-history records (mint/freeze/unfreeze/destroy). - pub records: Vec, -} - -impl AuthzResolver { - /// Build from token-history records. - #[must_use] - pub fn new(records: Vec) -> Self { - Self { records } - } - - /// [`holdings_as_of`] against the wrapped records. - #[must_use] - pub fn holdings_as_of(&self, identity: &str, at: u64) -> Holdings { - holdings_as_of(&self.records, identity, at) - } -} - // =========================================================================== // Event fold (issue / PR state) // =========================================================================== @@ -856,7 +703,7 @@ pub struct Event { pub target_id: String, /// What happened. pub kind: EventKind, - /// Document `$ownerId` — the actor whose authorization is checked as-of `created_at`. + /// Document `$ownerId`: the actor (a member for `event`, the author for `authorEvent`). pub actor: String, /// Kind-dependent payload: label name, assignee id, or retarget base ref. #[serde(default)] @@ -921,35 +768,8 @@ impl Default for PrState { } } -/// Is event `e`'s actor authorized to apply it, evaluated as-of `e.created_at`? -/// -/// Per the §4 enforcement matrix: any WRITE/MAINTAIN holder is authorized for every -/// kind; the target's author may additionally close/reopen their own issue/PR; a -/// `merge` additionally requires the merge `oid` to be reachable from the base tip -/// (an ancestor of it). Everything else from a non-holder is **inert** — the event -/// exists on-chain (the spammer paid fees) but the fold ignores it. -/// -/// This is the v1 rule only. forge-v2 splits events by gate (`event` for members, -/// `authorEvent` for the target's author, close/reopen only), so its fold -/// ([`v2::fold_issue_state_v2`], [`v2::fold_pr_state_v2`]) needs no actor check. -fn actor_authorized( - e: &Event, - target_author: &str, - authz: &AuthzResolver, - base_tip: Option<&str>, - is_ancestor: &impl Fn(&str, &str) -> bool, -) -> bool { - let holder = authz.holdings_as_of(&e.actor, e.created_at).any(); - match e.kind { - EventKind::Close | EventKind::Reopen => holder || e.actor == target_author, - EventKind::Merge => holder && merge_reachable(e, base_tip, is_ancestor), - _ => holder, - } -} - /// Whether a `merge` event's `oid` is reachable from (an ancestor of, or equal to) the base /// tip. No merge oid or no base tip means reachability cannot be proven, so the merge is inert. -/// Shared by both rule versions. fn merge_reachable( e: &Event, base_tip: Option<&str>, @@ -961,31 +781,7 @@ fn merge_reachable( } } -/// Fold an issue's `event` log into its [`IssueState`]. -/// -/// `events` may be unordered and may include spam from non-holders; they are ordered by -/// `(createdAt, id)` and each is applied only if [`actor_authorized`] passes as-of its -/// `createdAt`. Only close/reopen/label/assign kinds affect an issue; PR-only kinds -/// (merge/retarget/draft/ready) are ignored here. -#[must_use] -pub fn fold_issue_state( - events: &[Event], - target_author: &str, - authz: &AuthzResolver, -) -> IssueState { - let ordered = ordered_events(events); - let mut state = IssueState::default(); - let no_ancestry = |_: &str, _: &str| false; - - for e in ordered { - if actor_authorized(e, target_author, authz, None, &no_ancestry) { - apply_issue_event(&mut state, e); - } - } - state -} - -/// Apply one authorized event to an issue's state (both rule versions). PR-only kinds +/// Apply one authorized event to an issue's state. PR-only kinds /// (merge/retarget/draft/ready) do not apply to issues. fn apply_issue_event(state: &mut IssueState, e: &Event) { match e.kind { @@ -1015,32 +811,7 @@ fn apply_issue_event(state: &mut IssueState, e: &Event) { } } -/// Fold a PR's `event` log into its [`PrState`]. -/// -/// Like [`fold_issue_state`], plus: `merge` (holder + reachable `oid`) sets -/// `merged`+closed; `retarget` (holder) updates `base_ref`; `draft`/`ready` (holder) -/// toggle the draft flag. `base_tip` is the current tip of the PR's base ref, used for -/// merge reachability; `is_ancestor` is the commit-graph predicate. -#[must_use] -pub fn fold_pr_state( - events: &[Event], - target_author: &str, - authz: &AuthzResolver, - base_tip: Option<&str>, - is_ancestor: impl Fn(&str, &str) -> bool, -) -> PrState { - let ordered = ordered_events(events); - let mut state = PrState::default(); - - for e in ordered { - if actor_authorized(e, target_author, authz, base_tip, &is_ancestor) { - apply_pr_event(&mut state, e); - } - } - state -} - -/// Apply one authorized event to a PR's state (both rule versions). +/// Apply one authorized event to a PR's state. fn apply_pr_event(state: &mut PrState, e: &Event) { match e.kind { EventKind::Close => state.open = false, @@ -1089,13 +860,6 @@ fn apply_pr_event(state: &mut PrState, e: &Event) { } } -/// Order events deterministically by `(createdAt, id)`. -fn ordered_events(events: &[Event]) -> Vec<&Event> { - let mut v: Vec<&Event> = events.iter().collect(); - v.sort_by(|a, b| event_order(a, b)); - v -} - /// The `(createdAt, id)` total order every fold applies events in. fn event_order(a: &Event, b: &Event) -> std::cmp::Ordering { a.created_at @@ -1231,25 +995,13 @@ pub fn overlay_tree(base: &FlatIndex, later_commit_tree_diffs: &[TreeDiff]) -> F #[cfg(test)] mod tests { use super::{ - display_ref_name, fold_issue_state, fold_pr_state, holdings_as_of, is_legal_ref_name, - matches_protected, merge_base_tips, overlay_tree, resolve_ref, v2, Ancestry, AuthzResolver, - ConfigDoc, Event, EventKind, FlatIndex, Holdings, IssueState, MergeBaseTips, PrState, - RefState, RefUpdate, TokenKind, TokenOp, TokenRecord, TreeDiff, Verdict, + display_ref_name, is_legal_ref_name, matches_protected, merge_base_tips, overlay_tree, + resolve_ref, v2, Ancestry, ConfigDoc, Event, EventKind, FlatIndex, IssueState, + MergeBaseTips, PrState, RefState, RefUpdate, TreeDiff, Verdict, }; use serde::{Deserialize, Serialize}; use std::path::PathBuf; - /// A minted-at-genesis WRITE holder record (the common authz fixture). - fn write_mint(identity: &str) -> TokenRecord { - TokenRecord { - id: format!("mint-{identity}"), - identity: identity.into(), - token: TokenKind::Write, - op: TokenOp::Mint, - created_at: 0, - } - } - /// A merge event by `actor` on `target` with merge commit `oid`. fn merge_event(actor: &str, target: &str, oid: &str, created_at: u64) -> Event { Event { @@ -1269,23 +1021,21 @@ mod tests { /// to open the instant `base_tip != merge_oid`. #[test] fn pr_merge_stays_merged_after_base_advances() { - let holder = "maint1"; - let authz = AuthzResolver::new(vec![write_mint(holder)]); - let events = vec![merge_event(holder, "pr1", "M", 10)]; + let events = vec![merge_event("maint1", "pr1", "M", 10)]; // The merge oid `M` and a later base commit `T` are both historical base tips. let historical: std::collections::BTreeSet = ["M".to_string(), "T".to_string()].into_iter().collect(); // Base has advanced to `T` (T != M). Monotonic predicate keeps the PR merged. - let good = fold_pr_state(&events, "author1", &authz, Some("T"), |oid, _tip| { + let good = v2::fold_pr_state_v2(&events, &[], "author1", Some("T"), |oid, _tip| { historical.contains(oid) }); assert!(good.merged, "merge stays merged after base advances"); assert!(!good.open, "a merged PR is closed"); // The buggy reflexive stand-in rejects the merge once base_tip != merge_oid. - let bad = fold_pr_state(&events, "author1", &authz, Some("T"), |a, b| a == b); + let bad = v2::fold_pr_state_v2(&events, &[], "author1", Some("T"), |a, b| a == b); assert!( !bad.merged, "reflexive a==b wrongly un-merges once the base advances (the fixed bug)" @@ -1297,7 +1047,6 @@ mod tests { #[test] fn fold_pr_illegal_retarget_is_inert() { let holder = "m1"; - let authz = AuthzResolver::new(vec![write_mint(holder)]); let legal = Event { id: "e1".into(), target_id: "pr".into(), @@ -1316,12 +1065,10 @@ mod tests { oid: None, created_at: 10, }; - let s1 = fold_pr_state(std::slice::from_ref(&legal), "a", &authz, None, |_, _| { - false - }); + let s1 = v2::fold_pr_state_v2(std::slice::from_ref(&legal), &[], "a", None, |_, _| false); assert_eq!(s1.base_ref.as_deref(), Some("refs/heads/dev")); // The newer illegal retarget must NOT overwrite with the injection payload. - let s2 = fold_pr_state(&[legal, illegal], "a", &authz, None, |_, _| false); + let s2 = v2::fold_pr_state_v2(&[legal, illegal], &[], "a", None, |_, _| false); assert_eq!( s2.base_ref.as_deref(), Some("refs/heads/dev"), @@ -1329,32 +1076,6 @@ mod tests { ); } - /// MAJOR-3 support: `holdings_as_of` must observe a freeze applied to the repo OWNER — - /// the service now fetches the owner's freeze history unconditionally, so a frozen owner - /// reads as un-spendable as-of the freeze (not perpetually unfrozen). - #[test] - fn holdings_observes_owner_freeze() { - let owner = "owner1"; - let records = vec![ - write_mint(owner), - TokenRecord { - id: "freeze".into(), - identity: owner.into(), - token: TokenKind::Write, - op: TokenOp::Freeze, - created_at: 100, - }, - ]; - assert!( - holdings_as_of(&records, owner, 50).write, - "owner is spendable before the freeze" - ); - assert!( - !holdings_as_of(&records, owner, 150).write, - "owner is NOT spendable after the freeze (must be observed)" - ); - } - /// The parity contract: one file per scenario, dispatched by `case`. #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] @@ -1363,7 +1084,8 @@ mod tests { #[allow(dead_code)] description: String, case: String, - /// `"v1"` or `"v2"`; absent means v1 (every vector written before v2). + /// `"v2"` for the forge-v2 cases; absent for the base rules (ref resolution, + /// protected-pattern matching, display names, overlay, verdicts). #[serde(default)] rules: Option, input: serde_json::Value, @@ -1390,36 +1112,6 @@ mod tests { patterns: Vec, } - #[derive(Debug, Deserialize)] - #[serde(rename_all = "camelCase")] - struct HoldingsInput { - records: Vec, - identity: String, - at: u64, - } - - #[derive(Debug, Deserialize)] - #[serde(rename_all = "camelCase")] - struct FoldIssueInput { - events: Vec, - target_author: String, - #[serde(default)] - token_records: Vec, - } - - #[derive(Debug, Deserialize)] - #[serde(rename_all = "camelCase")] - struct FoldPrInput { - events: Vec, - target_author: String, - #[serde(default)] - token_records: Vec, - #[serde(default)] - base_tip: Option, - #[serde(default)] - ancestry: Ancestry, - } - /// A PR base ref's raw history: the fold's base tip and merge predicate then come from /// [`merge_base_tips`] instead of a vector-supplied `baseTip` / `ancestry`. #[derive(Debug, Deserialize, Serialize)] @@ -1527,38 +1219,6 @@ mod tests { serde_json::from_value(v.expected.clone()).expect("matches_protected expected"); assert_eq!(got, want, "vector `{ctx}`"); } - "holdings" => { - let inp: HoldingsInput = - serde_json::from_value(v.input.clone()).expect("holdings input"); - let got = holdings_as_of(&inp.records, &inp.identity, inp.at); - let want: Holdings = - serde_json::from_value(v.expected.clone()).expect("holdings expected"); - assert_eq!(got, want, "vector `{ctx}`"); - } - "fold_issue" => { - let inp: FoldIssueInput = - serde_json::from_value(v.input.clone()).expect("fold_issue input"); - let authz = AuthzResolver::new(inp.token_records); - let got = fold_issue_state(&inp.events, &inp.target_author, &authz); - let want: IssueState = - serde_json::from_value(v.expected.clone()).expect("fold_issue expected"); - assert_eq!(got, want, "vector `{ctx}`"); - } - "fold_pr" => { - let inp: FoldPrInput = - serde_json::from_value(v.input.clone()).expect("fold_pr input"); - let authz = AuthzResolver::new(inp.token_records); - let got = fold_pr_state( - &inp.events, - &inp.target_author, - &authz, - inp.base_tip.as_deref(), - |a, d| inp.ancestry.is_ancestor(a, d), - ); - let want: PrState = - serde_json::from_value(v.expected.clone()).expect("fold_pr expected"); - assert_eq!(got, want, "vector `{ctx}`"); - } "overlay" => { let inp: OverlayInput = serde_json::from_value(v.input.clone()).expect("overlay input"); @@ -1572,7 +1232,7 @@ mod tests { } // --- FORGE_RULES_V2 input envelopes. Unknown keys are refused at every depth (see - // `input`), so a vector cannot carry a field, such as v1's `tokenRecords` or a misspelt + // `input`), so a vector cannot carry a field, such as a token-era `tokenRecords` or a misspelt // `authorEvent` key, that the v2 rules would silently ignore ----------------------------- #[derive(Debug, Deserialize, Serialize)] @@ -1832,7 +1492,7 @@ mod tests { } /// Load every `forge-contracts/vectors/*.json` and assert the rules reproduce - /// `expected`, dispatching on the vector's `rules` (absent means v1). This is the suite the + /// `expected`, dispatching on the vector's `rules` (absent means a base rule). This is the suite the /// TypeScript port also runs. #[test] fn conformance_vectors() { @@ -1849,7 +1509,7 @@ mod tests { files.len() ); - let (mut ran_v1, mut ran_v2) = (0usize, 0usize); + let (mut ran_base, mut ran_v2) = (0usize, 0usize); for path in files { let bytes = std::fs::read(&path).expect("read vector"); let v: Vector = serde_json::from_slice(&bytes) @@ -1859,9 +1519,9 @@ mod tests { continue; } match v.rules.as_deref() { - None | Some("v1") => { + None => { run_case(&v); - ran_v1 += 1; + ran_base += 1; } Some("v2") => { run_case_v2(&v); @@ -1870,9 +1530,9 @@ mod tests { Some(other) => panic!("vector `{}`: unknown rules `{other}`", v.name), } } - assert!(ran_v1 >= 70, "ran {ran_v1} v1 vectors, expected 70+"); + assert!(ran_base >= 45, "ran {ran_base} base vectors, expected 45+"); assert!(ran_v2 >= 110, "ran {ran_v2} v2 vectors, expected 110+"); - println!("conformance_vectors: {ran_v1} v1 + {ran_v2} v2 vectors green"); + println!("conformance_vectors: {ran_base} base + {ran_v2} v2 vectors green"); } // --- targeted unit tests for the pinned glob semantics ---------------- diff --git a/crates/forge-core/src/rules/v2.rs b/crates/forge-core/src/rules/v2.rs index 9d285f85f..c62f04201 100644 --- a/crates/forge-core/src/rules/v2.rs +++ b/crates/forge-core/src/rules/v2.rs @@ -1,7 +1,7 @@ //! `FORGE_RULES_V2` — the client rules for forge-v2 repositories (the shared forge-core / //! forge-collab contracts, `docs/contracts/forge-v2.md`). //! -//! On v2, consensus does most of what v1's rules reconstructed: an `event` exists only if its +//! Consensus does most of the authorization: an `event` exists only if its //! writer held a `maintainer`/`writer` document for the repo when it was written, and an //! `authorEvent` exists only if its writer authored the target and its kind is close or //! reopen. What is left client-side, and must be identical in every client, is here: @@ -20,12 +20,11 @@ //! (`HMAC-SHA256(K_ref,e, name)`, applied after decryption). //! * [`is_valid_repo_name`] / [`normalize_repo_name`] — the `repo.name` slug (§2). //! -//! v1 rules (the parent module) are untouched: v1 repositories stay readable with them. The -//! event ordering and per-kind state changes are v1's own (`apply_issue_event`, -//! `apply_pr_event`, `event_order`, `merge_reachable` in the parent module), so the two -//! versions cannot drift apart where they are meant to agree. +//! The event ordering and per-kind state changes are the parent module's base rules +//! (`apply_issue_event`, `apply_pr_event`, `event_order`, `merge_reachable`), alongside ref +//! resolution and protected-pattern matching. //! -//! Like v1, every function is pure. The conformance vectors with `"rules": "v2"` in +//! Every function is pure. The conformance vectors with `"rules": "v2"` in //! `forge-contracts/vectors/` are the parity suite, shared with `forge-web/lib/rules/v2.ts`. use std::collections::BTreeSet; @@ -123,7 +122,7 @@ fn author_event_applies(e: &Event, target_author: &str) -> bool { matches!(e.kind, EventKind::Close | EventKind::Reopen) && e.actor == target_author } -/// The applicable documents of both types, in v1's `(createdAt, id)` order. `events` come +/// The applicable documents of both types, in `(createdAt, id)` order. `events` come /// first in the input, so two documents with the same key keep that order (the sort is /// stable; real `$id`s never collide across document types). fn merged_log<'a>( @@ -148,7 +147,7 @@ fn merged_log<'a>( /// * Every `event` applies, whoever wrote it and whatever has happened to their membership /// since (PR-only kinds do nothing to an issue). /// * An `authorEvent` applies only if it is a close or reopen by `target_author`. -/// * Both are applied as one log ordered by `(createdAt, id)`, with v1's per-kind effects. +/// * Both are applied as one log ordered by `(createdAt, id)`, with the base per-kind effects. #[must_use] pub fn fold_issue_state_v2( events: &[Event], @@ -165,7 +164,7 @@ pub fn fold_issue_state_v2( /// Fold a PR's `event` and `authorEvent` documents into its [`PrState`]. /// /// As [`fold_issue_state_v2`], and a `merge` (which can only come from `event`) applies only -/// if its `oid` is reachable from `base_tip`, v1's predicate. A merged PR cannot be reopened. +/// if its `oid` is reachable from `base_tip`. A merged PR cannot be reopened. #[must_use] pub fn fold_pr_state_v2( events: &[Event], diff --git a/crates/forge-core/src/scope.rs b/crates/forge-core/src/scope.rs index b509d1cd1..9b7dc666d 100644 --- a/crates/forge-core/src/scope.rs +++ b/crates/forge-core/src/scope.rs @@ -1,18 +1,12 @@ //! Which repository a client is talking to, and how its documents are addressed. //! -//! Two generations of repository exist side by side: +//! A repository is a `repo` document in the network's shared forge-core contract, and every +//! other document of it (refs, config, packs, chunks, membership) lives in the same contract, +//! keyed by `repoId` (`docs/contracts/forge-v2.md` §2). //! -//! * **forge-v2** (protocol 14): a repository is a `repo` document in the network's shared -//! forge-core contract, and every other document of it (refs, config, packs, chunks, -//! membership) lives in the same contract, keyed by `repoId`. This is where writes go. -//! * **forge-v1**: one data contract per repository, found through the registry. **Read -//! only**: existing v1 repositories stay cloneable, but nothing writes to them any more. -//! -//! [`RepoRef`] names one repository of either kind. [`DocScope`] turns it into the contract -//! to query and the filters/properties every query and write needs: on v2 each query gains -//! `repoId == R` and each write a `repoId` property; on v1 the contract itself is the scope. -//! The field codec here ([`text_list`], [`chunk_scope`], ...) absorbs the remaining schema -//! differences so the transport code is written once. +//! [`RepoRef`] names one repository. [`DocScope`] turns it into the contract to query and the +//! filters/properties every query and write needs: each query gains `repoId == R` and each +//! write a `repoId` property. use std::collections::BTreeMap; @@ -21,68 +15,40 @@ use crate::network::ForgeIds; use crate::platform::{self, FetchedDocument, FieldValue, QueryFilter}; use crate::rules::v2::Visibility; -/// A resolved repository. +/// A resolved repository: a `repo` document in the network's forge-core contract. #[derive(Debug, Clone, PartialEq, Eq)] -pub enum RepoRef { - /// A forge-v2 repository: a `repo` document in the network's forge-core contract. - V2 { - /// The forge-v2 contracts of the network the repo lives on. - forge: ForgeIds, - /// The base58 `repo` document id (`repoId` in every other document). - repo_id: String, - /// The base58 owner identity (`repo.$ownerId`). - owner_id: String, - /// The immutable URL slug (`repo.name`). - name: String, - /// `repo.visibility`. - visibility: Visibility, - }, - /// A forge-v1 repository: its own data contract. Read only. - V1 { - /// The base58 repo contract id. - contract_id: String, - /// The base58 owner identity (the contract owner). - owner_id: String, - /// The registry name, or the contract id when it was addressed by id. - name: String, - }, +pub struct RepoRef { + /// The forge-v2 contracts of the network the repo lives on. + pub forge: ForgeIds, + /// The base58 `repo` document id (`repoId` in every other document). + pub repo_id: String, + /// The base58 owner identity (`repo.$ownerId`). + pub owner_id: String, + /// The immutable URL slug (`repo.name`). + pub name: String, + /// `repo.visibility`. + pub visibility: Visibility, } impl RepoRef { /// The owner identity (base58). pub fn owner_id(&self) -> &str { - match self { - RepoRef::V2 { owner_id, .. } | RepoRef::V1 { owner_id, .. } => owner_id, - } + &self.owner_id } - /// The repository name (the v2 slug, the v1 registry name). + /// The repository name (the slug). pub fn name(&self) -> &str { - match self { - RepoRef::V2 { name, .. } | RepoRef::V1 { name, .. } => name, - } + &self.name } - /// The id that names this repository on chain: the `repo` document id (v2) or the - /// repo contract id (v1). Either form is accepted by `dash://`. + /// The `repo` document id that names this repository on chain; `dash://` accepts it. pub fn id(&self) -> &str { - match self { - RepoRef::V2 { repo_id, .. } => repo_id, - RepoRef::V1 { contract_id, .. } => contract_id, - } - } - - /// `v2` or `v1`, for display and `--json`. - pub fn generation(&self) -> &'static str { - match self { - RepoRef::V2 { .. } => "v2", - RepoRef::V1 { .. } => "v1", - } + &self.repo_id } - /// Whether this is a (read-only) forge-v1 repository. - pub fn is_v1(&self) -> bool { - matches!(self, RepoRef::V1 { .. }) + /// The network's forge-v2 contracts this repository lives in. + pub fn forge(&self) -> &ForgeIds { + &self.forge } /// `owner/name`, the form users type. @@ -95,56 +61,23 @@ impl RepoRef { format!("dash://{}", self.display()) } - /// The forge-v2 contracts, or [`Error::V1ReadOnly`] for a v1 repository. Every write - /// path starts here, so a v1 repository refuses writes before anything is signed. - pub fn require_v2(&self) -> Result<&ForgeIds> { - match self { - RepoRef::V2 { forge, .. } => Ok(forge), - RepoRef::V1 { .. } => Err(Error::V1ReadOnly { - repo: self.display(), - }), - } - } - - /// The v1 repo contract id, for the services that still address a repository by its - /// contract (issues, PRs, releases, labels: forge-collab lands in a later release). - pub fn v1_contract_id(&self) -> Result<&str> { - match self { - RepoRef::V1 { contract_id, .. } => Ok(contract_id), - RepoRef::V2 { .. } => Err(Error::Config(format!( - "{} is a forge-v2 repo; issues, pull requests, releases and labels on forge-v2 \ - are not supported by this version of the CLI yet", - self.display() - ))), - } - } - /// The document scope of this repository's git data plane (refs, config, packs). pub fn scope(&self) -> Result { - Ok(match self { - RepoRef::V2 { forge, repo_id, .. } => DocScope { - contract_id: forge.core.clone(), - repo_id: Some(platform::decode_identifier(repo_id)?), - }, - RepoRef::V1 { contract_id, .. } => DocScope { - contract_id: contract_id.clone(), - repo_id: None, - }, + Ok(DocScope { + contract_id: self.forge.core.clone(), + repo_id: platform::decode_identifier(&self.repo_id)?, }) } /// Refuse to operate on a repository this client cannot read correctly yet. pub fn require_readable(&self) -> Result<()> { - match self { - RepoRef::V2 { - visibility: Visibility::Private, - .. - } => Err(Error::Config(format!( + match self.visibility { + Visibility::Private => Err(Error::Config(format!( "{} is a private repository; private repositories are not supported by this \ version of the CLI yet", self.display() ))), - _ => Ok(()), + Visibility::Public => Ok(()), } } } @@ -152,29 +85,25 @@ impl RepoRef { /// Where a repository's git-data documents live, and how to address them. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DocScope { - /// The contract holding the documents: forge-core (v2) or the repo contract (v1). + /// The contract holding the documents (the network's forge-core). pub contract_id: String, - /// `Some(repoId)` on v2: every query filters on it and every write carries it. - pub repo_id: Option<[u8; 32]>, + /// The repo: every query filters on it and every write carries it. + pub repo_id: [u8; 32], } impl DocScope { - /// Whether this is a forge-v2 scope. - pub fn is_v2(&self) -> bool { - self.repo_id.is_some() - } - - /// `extra` with `repoId == R` prepended on v2 (it is the first property of every - /// forge-v2 index, so it must come first). + /// `extra` with `repoId == R` prepended (it is the first property of every forge-v2 + /// index, so it must come first). pub fn filters(&self, extra: impl IntoIterator) -> Vec { - self.repo_id - .map(|id| QueryFilter::eq("repoId", FieldValue::identifier(id))) - .into_iter() - .chain(extra) - .collect() + std::iter::once(QueryFilter::eq( + "repoId", + FieldValue::identifier(self.repo_id), + )) + .chain(extra) + .collect() } - /// Document properties with `repoId` added on v2. + /// Document properties with `repoId` added. pub fn props( &self, props: impl IntoIterator, @@ -182,68 +111,41 @@ impl DocScope { self.scoped(props.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) } - /// An already-built property map with `repoId` added on v2. + /// An already-built property map with `repoId` added. pub fn scoped(&self, mut props: BTreeMap) -> BTreeMap { - if let Some(id) = self.repo_id { - props.insert("repoId".to_string(), FieldValue::identifier(id)); - } + props.insert("repoId".to_string(), FieldValue::identifier(self.repo_id)); props } /// The filters that select one pack's chunks, in `seq` order. /// - /// v2 chunks are keyed `(repoId, $ownerId, packHash, seq)`: each uploader has its own - /// copy, so a chunk read names whose copy it reads (the manifest's `$ownerId`). v1 - /// chunks are keyed `(packHash, seq)` inside the repo contract. - pub fn chunk_filters( - &self, - owner: Option<&str>, - pack_hash: [u8; 32], - ) -> Result> { - let owner = match (self.is_v2(), owner) { - (false, _) => None, - (true, Some(o)) => Some(QueryFilter::eq( + /// Chunks are keyed `(repoId, $ownerId, packHash, seq)`: each uploader has its own copy, + /// so a chunk read names whose copy it reads (the manifest's `$ownerId`). + pub fn chunk_filters(&self, owner: &str, pack_hash: [u8; 32]) -> Result> { + Ok(self.filters([ + QueryFilter::eq( "$ownerId", - FieldValue::identifier(platform::decode_identifier(o)?), - )), - (true, None) => { - return Err(Error::Config( - "a forge-v2 chunk read must name the uploader whose copy it reads".into(), - )) - } - }; - Ok(self.filters( - owner - .into_iter() - .chain([QueryFilter::eq("packHash", FieldValue::bytes32(pack_hash))]), - )) + FieldValue::identifier(platform::decode_identifier(owner)?), + ), + QueryFilter::eq("packHash", FieldValue::bytes32(pack_hash)), + ])) } /// The `platform://` locator of a pack stored as this scope's chunks: - /// `platform://///` on v2 (the uploader is part of the - /// chunk key), `platform:///` on v1. + /// `platform://///` (the uploader is part of the chunk key). pub fn locator(&self, owner: &str, pack_hash_hex: &str) -> String { - let scheme = crate::backends::PLATFORM_SCHEME; - match self.repo_id { - Some(id) => format!( - "{scheme}://{}/{}/{owner}/{pack_hash_hex}", - self.contract_id, - platform::encode_identifier(id) - ), - None => format!("{scheme}://{}/{pack_hash_hex}", self.contract_id), - } + format!( + "{}://{}/{}/{owner}/{pack_hash_hex}", + crate::backends::PLATFORM_SCHEME, + self.contract_id, + platform::encode_identifier(self.repo_id) + ) } } -/// A string-list field, in either generation's encoding: a typed string array (v2) or a -/// JSON-encoded string (v1: `protectedPatterns`, `uris`, `backend.uris`). Absent or -/// unreadable is empty. +/// A typed string-array field. Absent or unreadable is empty. pub fn text_list(value: Option<&FieldValue>) -> Vec { - match value { - Some(FieldValue::Text(json)) => serde_json::from_str(json).unwrap_or_default(), - Some(v) => v.as_text_list().unwrap_or_default(), - None => Vec::new(), - } + value.and_then(FieldValue::as_text_list).unwrap_or_default() } /// [`text_list`] of a document's top-level field. @@ -275,17 +177,13 @@ mod tests { const REPO: &str = "GdZYaEntYPiW9dvUGCHyeqN7H7qEocbSkuj81n341i3L"; const OWNER: &str = "9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD"; - fn forge() -> ForgeIds { - ForgeIds { - core: "CORE".into(), - collab: "COLLAB".into(), - group: "GROUP".into(), - } - } - - fn v2() -> RepoRef { - RepoRef::V2 { - forge: forge(), + fn repo() -> RepoRef { + RepoRef { + forge: ForgeIds { + core: "CORE".into(), + collab: "COLLAB".into(), + group: "GROUP".into(), + }, repo_id: REPO.into(), owner_id: OWNER.into(), name: "proj".into(), @@ -293,17 +191,9 @@ mod tests { } } - fn v1() -> RepoRef { - RepoRef::V1 { - contract_id: REPO.into(), - owner_id: OWNER.into(), - name: "proj".into(), - } - } - #[test] - fn v2_scope_filters_every_query_by_repo_id_first() { - let scope = v2().scope().unwrap(); + fn scope_filters_every_query_by_repo_id_first() { + let scope = repo().scope().unwrap(); assert_eq!(scope.contract_id, "CORE"); let f = scope.filters([QueryFilter::eq("packHash", FieldValue::bytes32([1; 32]))]); assert_eq!(f.len(), 2); @@ -314,21 +204,13 @@ mod tests { FieldValue::identifier(platform::decode_identifier(REPO).unwrap()) ); assert_eq!(f[1].field, "packHash"); - // An unfiltered v2 read is still scoped to the repo. + // An unfiltered read is still scoped to the repo. assert_eq!(scope.filters([]).len(), 1); } #[test] - fn v1_scope_is_the_repo_contract_with_no_extra_filter() { - let scope = v1().scope().unwrap(); - assert_eq!(scope.contract_id, REPO); - assert!(scope.filters([]).is_empty()); - assert!(!scope.props([]).contains_key("repoId")); - } - - #[test] - fn v2_writes_carry_the_repo_id() { - let props = v2() + fn writes_carry_the_repo_id() { + let props = repo() .scope() .unwrap() .props([("refName", FieldValue::text("refs/heads/main"))]); @@ -340,56 +222,33 @@ mod tests { } #[test] - fn v2_chunk_reads_are_scoped_to_one_uploaders_copy() { - let scope = v2().scope().unwrap(); - let f = scope.chunk_filters(Some(OWNER), [7; 32]).unwrap(); + fn chunk_reads_are_scoped_to_one_uploaders_copy() { + let scope = repo().scope().unwrap(); + let f = scope.chunk_filters(OWNER, [7; 32]).unwrap(); let fields: Vec<_> = f.iter().map(|f| f.field.as_str()).collect(); assert_eq!(fields, ["repoId", "$ownerId", "packHash"]); - assert!(scope.chunk_filters(None, [7; 32]).is_err()); - // v1: the pack hash alone. - let f = v1().scope().unwrap().chunk_filters(None, [7; 32]).unwrap(); - assert_eq!(f.len(), 1); + assert!(scope.chunk_filters("not base58!", [7; 32]).is_err()); } #[test] - fn locators_name_the_uploader_on_v2() { + fn locators_name_the_uploader() { let h = "ab".repeat(32); assert_eq!( - v2().scope().unwrap().locator(OWNER, &h), + repo().scope().unwrap().locator(OWNER, &h), format!("platform://CORE/{REPO}/{OWNER}/{h}") ); - assert_eq!( - v1().scope().unwrap().locator(OWNER, &h), - format!("platform://{REPO}/{h}") - ); - } - - #[test] - fn v1_refuses_writes_and_v2_refuses_v1_only_services() { - let err = v1().require_v2().unwrap_err().to_string(); - assert!(err.contains("v1 repo (read-only)"), "{err}"); - assert!(err.contains("dg migrate"), "{err}"); - assert!(v2().require_v2().is_ok()); - assert!(v2().v1_contract_id().is_err()); - assert_eq!(v1().v1_contract_id().unwrap(), REPO); } #[test] - fn private_v2_repos_are_refused_until_supported() { - let mut r = v2(); - if let RepoRef::V2 { visibility, .. } = &mut r { - *visibility = Visibility::Private; - } + fn private_repos_are_refused_until_supported() { + let mut r = repo(); + r.visibility = Visibility::Private; assert!(r.require_readable().is_err()); - assert!(v2().require_readable().is_ok()); + assert!(repo().require_readable().is_ok()); } #[test] - fn text_lists_decode_both_generations() { - assert_eq!( - text_list(Some(&FieldValue::text(r#"["a","b"]"#))), - vec!["a", "b"] - ); + fn text_lists_decode_typed_arrays() { assert_eq!( text_list(Some(&FieldValue::text_list(["a", "b"]))), vec!["a", "b"] @@ -397,6 +256,6 @@ mod tests { // An empty typed array comes back as empty bytes. assert!(text_list(Some(&FieldValue::bytes(Vec::new()))).is_empty()); assert!(text_list(None).is_empty()); - assert!(text_list(Some(&FieldValue::text("not json"))).is_empty()); + assert!(text_list(Some(&FieldValue::text(r#"["a"]"#))).is_empty()); } } diff --git a/crates/forge-core/src/storage/targets.rs b/crates/forge-core/src/storage/targets.rs index 563fc1068..0c9a165b0 100644 --- a/crates/forge-core/src/storage/targets.rs +++ b/crates/forge-core/src/storage/targets.rs @@ -37,48 +37,28 @@ pub struct Replica { pub platform: bool, } -/// What a manifest's `uris` field can hold. v1 stores the list as one JSON string of at -/// most `max_json_len` bytes; v2 stores a typed array of at most `max_items` strings of at -/// most `max_item_len` bytes each. +/// What a manifest's `uris` field can hold: a typed array of at most `max_items` strings of +/// at most `max_item_len` bytes each. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct UriBudget { - /// The JSON-encoded length limit (v1), if any. - pub max_json_len: Option, - /// The item-count limit (v2), if any. - pub max_items: Option, - /// The per-item length limit (v2), if any. - pub max_item_len: Option, + /// The item-count limit. + pub max_items: usize, + /// The per-item length limit. + pub max_item_len: usize, } impl UriBudget { - /// A v1 JSON-string field of `max_json_len` bytes. - pub const fn json(max_json_len: usize) -> Self { - Self { - max_json_len: Some(max_json_len), - max_items: None, - max_item_len: None, - } - } - - /// A v2 typed string array. + /// A typed string array. pub const fn array(max_items: usize, max_item_len: usize) -> Self { Self { - max_json_len: None, - max_items: Some(max_items), - max_item_len: Some(max_item_len), + max_items, + max_item_len, } } /// Whether `uris` fits. pub fn fits(&self, uris: &[String]) -> bool { - let json_ok = self - .max_json_len - .is_none_or(|max| serde_json::to_string(uris).map_or(usize::MAX, |s| s.len()) <= max); - let count_ok = self.max_items.is_none_or(|max| uris.len() <= max); - let items_ok = self - .max_item_len - .is_none_or(|max| uris.iter().all(|u| u.len() <= max)); - json_ok && count_ok && items_ok + uris.len() <= self.max_items && uris.iter().all(|u| u.len() <= self.max_item_len) } } @@ -560,7 +540,7 @@ pub(crate) mod tests { }], failures: vec![], }; - assert!(rep.manifest_uris(UriBudget::json(2600)).is_err()); + assert!(rep.manifest_uris(UriBudget::array(8, 300)).is_err()); } #[tokio::test] @@ -649,12 +629,7 @@ pub(crate) mod tests { }], failures: vec![], }; - assert_eq!(rep.manifest_uris(UriBudget::json(2600)).unwrap().len(), 2); - let trimmed = rep.manifest_uris(UriBudget::json(60)).unwrap(); - assert_eq!(trimmed.len(), 1); - assert!(trimmed[0].starts_with("https://")); - assert!(rep.manifest_uris(UriBudget::json(10)).is_err()); - // v2: a typed array bounded per item and in count. + // A typed array bounded per item and in count. assert_eq!( rep.manifest_uris(UriBudget::array(8, 300)).unwrap().len(), 2 diff --git a/crates/forge-core/src/tokens.rs b/crates/forge-core/src/tokens.rs deleted file mode 100644 index 4f8a6e706..000000000 --- a/crates/forge-core/src/tokens.rs +++ /dev/null @@ -1,313 +0,0 @@ -//! [`TokenService`] — the collaborator list of a **forge-v1** repository, read only. -//! -//! A v1 repo's two tokens were its access-control list: position **0 = WRITE** (push, -//! upload), position **1 = MAINTAIN** (protected refs, releases, config). v1 is read only -//! now, so this module only reads: [`TokenService::list_collaborators`] / -//! [`TokenService::holdings`] (balances + frozen status) and -//! [`TokenService::token_history`] (mint/freeze/unfreeze/destroy records with consensus -//! `$createdAt`, fed to [`crate::rules::holdings_as_of`] for as-of-time event authorization -//! when folding a v1 repo's issues and PRs). -//! -//! forge-v2 membership is documents: see [`crate::members`]. - -use std::collections::BTreeSet; - -use crate::error::Result; -use crate::platform::{self, FieldValue, PlatformClient, QueryFilter, QueryOrder}; -use crate::rules::{TokenKind, TokenOp, TokenRecord}; - -/// WRITE token position (push / upload / CI). -pub const WRITE_POSITION: u16 = 0; -/// MAINTAIN token position (protected refs / releases / labels / config). -pub const MAINTAIN_POSITION: u16 = 1; - -/// The system **TokenHistory** contract holding the `mint` / `freeze` / -/// `unfreeze` / `destroyFrozenFunds` audit documents with consensus `$createdAt` -/// (S0.7 experiment 7). A Platform system contract: its id is fixed by rs-dpp -/// (`token_history_contract::ID_BYTES`) and identical on every network, so it is not a -/// per-network deployment value. -pub const TOKEN_HISTORY_CONTRACT_ID: &str = "43gujrzZgXqcKBiScLa4T8XTDnRhenR9BLx8GWVHjPxF"; - -// TokenHistory document types. -const TH_MINT: &str = "mint"; -const TH_FREEZE: &str = "freeze"; -const TH_UNFREEZE: &str = "unfreeze"; -const TH_DESTROY: &str = "destroyFrozenFunds"; - -/// A collaborator role, mapped to its token position. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Role { - /// WRITE (position 0). - Write, - /// MAINTAIN (position 1). - Maintain, -} - -impl Role { - /// The token position this role grants. - pub fn position(self) -> u16 { - match self { - Role::Write => WRITE_POSITION, - Role::Maintain => MAINTAIN_POSITION, - } - } - - /// The [`crate::rules::TokenKind`] this role corresponds to. - fn kind(self) -> TokenKind { - match self { - Role::Write => TokenKind::Write, - Role::Maintain => TokenKind::Maintain, - } - } -} - -/// An identity's **current** spendable holdings (from live balance + frozen queries). -/// -/// Two token axes (WRITE / MAINTAIN) each with a held + frozen flag — four booleans that -/// model distinct on-chain facts, not a state enum. -#[allow(clippy::struct_excessive_bools)] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct HoldingStatus { - /// Holds a WRITE balance. - pub write: bool, - /// The WRITE balance is frozen (suspended). - pub write_frozen: bool, - /// Holds a MAINTAIN balance. - pub maintain: bool, - /// The MAINTAIN balance is frozen (suspended). - pub maintain_frozen: bool, -} - -impl HoldingStatus { - /// Whether the identity holds either token (a collaborator at all). - pub fn is_collaborator(self) -> bool { - self.write || self.maintain - } -} - -/// One on-chain collaborator: an identity and the tokens it currently holds. -#[derive(Debug, Clone)] -pub struct Collaborator { - /// The collaborator's base58 identity id. - pub identity_id: String, - /// Which tokens it holds, and whether they are frozen. - pub holdings: HoldingStatus, -} - -/// Read access to a v1 repository's token ACL. -pub struct TokenService<'a> { - client: &'a PlatformClient, -} - -impl<'a> TokenService<'a> { - /// A reader over `client`. - pub fn new(client: &'a PlatformClient) -> Self { - Self { client } - } - - /// The **on-chain collaborator list**: every identity that currently holds either - /// token, with its frozen status. Candidate identities are discovered from the token - /// mint history (no all-holders query exists on Platform); the repo owner (auto-credited - /// via `baseSupply`) is always included. Only positive balances are returned. - pub async fn list_collaborators(&self, repo_contract_id: &str) -> Result> { - let contract = self.client.fetch_contract(repo_contract_id).await?; - let write_token = self.client.token_id(&contract, WRITE_POSITION); - let maintain_token = self.client.token_id(&contract, MAINTAIN_POSITION); - - // Candidates: everyone ever minted to (from history) + the owner (baseSupply). - let history = self.token_history(repo_contract_id).await?; - let mut candidates: BTreeSet = history.into_iter().map(|r| r.identity).collect(); - candidates.insert(contract.owner_id()); - let candidates: Vec = candidates.into_iter().collect(); - - let write_bal = self - .client - .token_balances(&write_token, &candidates) - .await?; - let maintain_bal = self - .client - .token_balances(&maintain_token, &candidates) - .await?; - let write_frozen = self.client.token_frozen(&write_token, &candidates).await?; - let maintain_frozen = self - .client - .token_frozen(&maintain_token, &candidates) - .await?; - - let mut out = Vec::new(); - for id in candidates { - let holdings = HoldingStatus { - write: write_bal.get(&id).copied().unwrap_or(0) > 0, - write_frozen: write_frozen.get(&id).copied().unwrap_or(false), - maintain: maintain_bal.get(&id).copied().unwrap_or(0) > 0, - maintain_frozen: maintain_frozen.get(&id).copied().unwrap_or(false), - }; - if holdings.is_collaborator() { - out.push(Collaborator { - identity_id: id, - holdings, - }); - } - } - Ok(out) - } - - /// The current [`HoldingStatus`] of one identity (both tokens + frozen state). - pub async fn holdings(&self, repo_contract_id: &str, member_id: &str) -> Result { - let contract = self.client.fetch_contract(repo_contract_id).await?; - let write_token = self.client.token_id(&contract, WRITE_POSITION); - let maintain_token = self.client.token_id(&contract, MAINTAIN_POSITION); - let member = [member_id.to_string()]; - - let write_bal = self.client.token_balances(&write_token, &member).await?; - let maintain_bal = self.client.token_balances(&maintain_token, &member).await?; - let write_frozen = self.client.token_frozen(&write_token, &member).await?; - let maintain_frozen = self.client.token_frozen(&maintain_token, &member).await?; - - Ok(HoldingStatus { - write: write_bal.get(member_id).copied().unwrap_or(0) > 0, - write_frozen: write_frozen.get(member_id).copied().unwrap_or(false), - maintain: maintain_bal.get(member_id).copied().unwrap_or(0) > 0, - maintain_frozen: maintain_frozen.get(member_id).copied().unwrap_or(false), - }) - } - - /// The repo's full token history as [`crate::rules::TokenRecord`]s (both tokens), - /// ready to feed [`crate::rules::holdings_as_of`] / [`crate::rules::AuthzResolver`] for - /// as-of-time event authorization (§4). Mints are enumerated by token; freeze / - /// unfreeze / destroy records are then fetched per affected identity (the byte index - /// on the TokenHistory contract is keyed by `frozenIdentityId`). - pub async fn token_history(&self, repo_contract_id: &str) -> Result> { - let repo_contract = self.client.fetch_contract(repo_contract_id).await?; - let history_contract = self - .client - .fetch_contract(TOKEN_HISTORY_CONTRACT_ID) - .await?; - - let mut records = Vec::new(); - - // The repo owner is auto-credited both tokens' `baseSupply` at contract creation, - // which does NOT emit a `mint` history document — so token-history reconstruction - // alone would (wrongly) treat the owner as a non-holder and invalidate its - // legitimate past actions. Synthesize an as-of-genesis (`created_at = 0`) mint for - // the owner on both tokens so [`crate::rules::holdings_as_of`] sees it as a holder - // from the start (data-contracts §2.1 reconciliation). - let owner = repo_contract.owner_id(); - for role in [Role::Write, Role::Maintain] { - records.push(TokenRecord { - id: format!("baseSupply:{}:{}", owner, role.position()), - identity: owner.clone(), - token: role.kind(), - op: TokenOp::Mint, - created_at: 0, - }); - } - - for role in [Role::Write, Role::Maintain] { - let token_b58 = self.client.token_id(&repo_contract, role.position()); - let token_bytes = platform::decode_identifier(&token_b58)?; - let kind = role.kind(); - - // Mints (byDate index: tokenId, $createdAt). Paginated to exhaustion — a repo - // with >100 grants would otherwise drop late collaborators from BOTH the - // collaborator list AND the AuthzResolver (their legitimate events would then - // fold as unauthorized). - let mints = self - .client - .query_all_documents( - &history_contract, - TH_MINT, - &[QueryFilter::eq("tokenId", FieldValue::bytes32(token_bytes))], - &[QueryOrder::asc("$createdAt")], - ) - .await?; - - // Always include the repo owner: they hold `baseSupply` (no mint doc) but CAN - // be frozen/destroyed under the org joint-ownership pattern, and that freeze - // history must be reconstructed or the owner reads as perpetually unfrozen. - let mut affected: BTreeSet = BTreeSet::new(); - affected.insert(owner.clone()); - for m in &mints { - let Some(recipient) = m - .field_bytes32("recipientId") - .map(platform::encode_identifier) - else { - continue; - }; - affected.insert(recipient.clone()); - records.push(TokenRecord { - id: m.id.clone(), - identity: recipient, - token: kind, - op: TokenOp::Mint, - created_at: m.created_at.unwrap_or(0), - }); - } - - // Freeze / unfreeze / destroy per affected identity (byFrozenIdentityId index). - for identity in affected { - let identity_bytes = platform::decode_identifier(&identity)?; - for (doc_type, op) in [ - (TH_FREEZE, TokenOp::Freeze), - (TH_UNFREEZE, TokenOp::Unfreeze), - (TH_DESTROY, TokenOp::Destroy), - ] { - let docs = self - .client - .query_all_documents( - &history_contract, - doc_type, - &[ - QueryFilter::eq("tokenId", FieldValue::bytes32(token_bytes)), - QueryFilter::eq( - "frozenIdentityId", - FieldValue::bytes32(identity_bytes), - ), - ], - &[QueryOrder::asc("$createdAt")], - ) - .await?; - for d in &docs { - records.push(TokenRecord { - id: d.id.clone(), - identity: identity.clone(), - token: kind, - op, - created_at: d.created_at.unwrap_or(0), - }); - } - } - } - } - Ok(records) - } -} - -#[cfg(test)] -mod tests { - use super::{HoldingStatus, Role, MAINTAIN_POSITION, WRITE_POSITION}; - use crate::rules::TokenKind; - - #[test] - fn role_maps_to_position_and_kind() { - assert_eq!(Role::Write.position(), WRITE_POSITION); - assert_eq!(Role::Maintain.position(), MAINTAIN_POSITION); - assert_eq!(Role::Write.kind(), TokenKind::Write); - assert_eq!(Role::Maintain.kind(), TokenKind::Maintain); - } - - #[test] - fn holding_status_collaborator_predicate() { - assert!(!HoldingStatus::default().is_collaborator()); - assert!(HoldingStatus { - write: true, - ..Default::default() - } - .is_collaborator()); - assert!(HoldingStatus { - maintain: true, - ..Default::default() - } - .is_collaborator()); - } -} diff --git a/crates/forge-core/src/user_error.rs b/crates/forge-core/src/user_error.rs index 5c6a70bbc..74bc46f3b 100644 --- a/crates/forge-core/src/user_error.rs +++ b/crates/forge-core/src/user_error.rs @@ -88,10 +88,8 @@ pub const CATALOGUE: &[(&str, &str)] = &[ (codes::STORAGE_TEST, "storage profile failed its checks"), (codes::RECORDED_COPY_LOST, "recorded pack copy unreachable"), (codes::NOT_A_WRITER, "not a writer of this repository"), - (codes::SUSPENDED, "write access suspended"), (codes::ALREADY_EXISTS, "already exists"), (codes::REJECTED, "rejected by Platform"), - (codes::READ_ONLY, "v1 repository is read only"), (codes::UNREACHABLE, "Dash Platform unreachable"), ( codes::NOT_DEPLOYED, @@ -152,16 +150,14 @@ pub mod codes { pub const STORAGE_TEST: &str = "E506"; /// A re-push found the pack already recorded, with no copy readable. pub const RECORDED_COPY_LOST: &str = "E507"; - /// Consensus refused a write: no WRITE token (v1) / no writer document (v2, 40120). + /// Consensus refused a write: no `writer`/`maintainer` document (40120). pub const NOT_A_WRITER: &str = "E601"; - /// Consensus refused a write: the WRITE/MAINTAIN token is frozen (40702). - pub const SUSPENDED: &str = "E602"; + // E602 (token suspended) is retired with forge-v1 and stays reserved. /// A unique index collision (a name or number already taken). pub const ALREADY_EXISTS: &str = "E603"; /// Any other consensus rejection. pub const REJECTED: &str = "E604"; - /// A write to a forge-v1 repository, which is read only. - pub const READ_ONLY: &str = "E605"; + // E605 (v1 repository is read only) is retired with forge-v1 and stays reserved. /// DAPI / the quorum service could not be reached. pub const UNREACHABLE: &str = "E701"; /// The selected network has no Dash Forge deployment. @@ -538,7 +534,6 @@ fn from_core(core: &CoreError, chain: &str, ctx: &ErrorContext<'_>) -> Option suspended(ctx, &format!("40702 {core}")), CoreError::NotAMember { document_type, detail, @@ -551,13 +546,6 @@ fn from_core(core: &CoreError, chain: &str, ctx: &ErrorContext<'_>) -> Option not_permitted(ctx, action, reason, needs), - CoreError::V1ReadOnly { repo } => UserError::new( - codes::READ_ONLY, - ctx.headline(&format!("{repo} is a v1 repository, which is read only")), - ) - .cause("forge-v1 repositories (one contract each) can still be cloned and viewed, but no longer written") - .fix("create a forge-v2 repository (`dg repo create `) and push there") - .note("`dg migrate` (moving a v1 repo to forge-v2) is coming soon"), CoreError::V2NotDeployed { network } => UserError::new( codes::NOT_DEPLOYED, ctx.headline(&format!("forge-v2 isn't deployed on {network} yet")), @@ -565,9 +553,7 @@ fn from_core(core: &CoreError, chain: &str, ctx: &ErrorContext<'_>) -> Option not_a_writer(ctx, &format!("40700/40701 {core}")), + .fix("use a network where it is: `--network devnet --devnet-name moutai`"), CoreError::Timeout { retryable } => timed_out(ctx, *retryable), CoreError::IncompleteRead { document_type, @@ -612,15 +598,6 @@ fn from_core(core: &CoreError, chain: &str, ctx: &ErrorContext<'_>) -> Option identity_unreadable(msg), CoreError::Config(msg) => from_config(msg, chain, ctx), - CoreError::NotDeployed { network } => UserError::new( - codes::NOT_DEPLOYED, - ctx.headline(&format!("Dash Forge is not deployed on {network}")), - ) - .cause(format!( - "forge-contracts/deployments/{network}.json records no registry contract" - )) - .fix("use a network with a deployment: `--network testnet`") - .fix("point FORGE_REGISTRY_CONTRACT_ID (dg: `registry_contract_id` in config.toml) at a registry you deployed; `dg doctor` shows what is configured"), CoreError::Platform(msg) => return from_platform_text(msg, ctx), _ => return None, }) @@ -704,19 +681,6 @@ fn from_platform_text(msg: &str, ctx: &ErrorContext<'_>) -> Option { ); return Some(insufficient(ctx, &detail)); } - // 40702 IdentityTokenAccountFrozen. - if m.contains("account is frozen for token") || m.contains("token frozen") { - return Some(suspended(ctx, &format!("40702: {}", one_line(msg)))); - } - // 40700 IdentityDoesNotHaveEnoughTokenBalance / 40701 UnauthorizedTokenAction. - if m.contains("does not have enough balance for token") - || m.contains("is not authorized to perform action") - { - return Some(not_a_writer( - ctx, - &format!("40700/40701: no WRITE token: {}", one_line(msg)), - )); - } // 40120 ReferencedEntityNotFound. On path `$ownerId` it is forge-v2's writer gate // (`ownerRefersTo`): no current `writer`/`maintainer` document for the signer. On any // other path a referenced document, contract or identity is missing — a rejection, @@ -762,9 +726,9 @@ fn not_found(chain: &str, ctx: &ErrorContext<'_>) -> UserError { let repo = ctx.repo_or("the repository"); if chain.contains("resolving") || chain.contains("fetching contract") { return UserError::new(codes::NOT_FOUND, ctx.headline(&format!("{repo} was not found"))) - .cause("the registry has no repository with that owner and name on this network") + .cause("there is no repository with that owner and name on this network") .fix("check the owner id and name: `dg repo list --owner ` lists an owner's repositories") - .fix("check the network: `dg doctor` shows which network and registry are in use"); + .fix("check the network: `dg doctor` shows which network and contracts are in use"); } UserError::new(codes::NOT_FOUND, ctx.headline("not found")) .cause("Platform returned a proof that it does not exist") @@ -783,21 +747,6 @@ fn insufficient(ctx: &ErrorContext<'_>, detail: &str) -> UserError { .note("reads, clones and browsing are free and unaffected") } -fn suspended(ctx: &ErrorContext<'_>, why: &str) -> UserError { - let repo = ctx.repo_or("/"); - UserError::new( - codes::SUSPENDED, - ctx.rejected_headline(&format!( - "your write access to {} is suspended", - ctx.repo_or("this repo") - )), - ) - .cause(format!("Platform refused the write at consensus ({why})")) - .fix(format!( - "ask a maintainer to run `dg collab unsuspend {repo} `" - )) -} - /// forge-core document types only a `maintainer` may create (forge-v2.md §2). const MAINTAINER_ONLY: [&str; 4] = ["protectedRefUpdate", "config", "release", "repoKey"]; @@ -1351,13 +1300,17 @@ mod tests { "docs/errors.md has no `## {code}` section ({title})" ); } - // …and documents nothing that is not in the catalogue. + // …and documents nothing that is not in the catalogue, except retired codes, whose + // numbers stay reserved and must not come back. for line in docs.lines().filter(|l| l.starts_with("## E")) { - let code = line.trim_start_matches("## ").trim(); - assert!( - seen.contains(code), - "docs/errors.md documents unknown {code}" - ); + let heading = line.trim_start_matches("## ").trim(); + match heading.strip_suffix(" (retired)") { + Some(code) => assert!(!seen.contains(code), "retired {code} is in the catalogue"), + None => assert!( + seen.contains(heading), + "docs/errors.md documents unknown {heading}" + ), + } } } @@ -1463,14 +1416,7 @@ mod tests { } #[test] - fn v1_writes_and_undeployed_v2_have_their_own_codes() { - let u = core_chain( - CoreError::V1ReadOnly { - repo: "alice/old".into(), - }, - &PUSH, - ); - assert_eq!((u.code, u.exit_code()), ("E605", 6)); + fn undeployed_v2_has_its_own_code() { let u = core_chain( CoreError::V2NotDeployed { network: "testnet".into(), @@ -1517,41 +1463,6 @@ mod tests { assert!(u.cause.unwrap().starts_with("40120: ")); } - #[test] - fn maps_v1_token_errors() { - assert_eq!(core_chain(CoreError::Unauthorized, &PUSH).code, "E601"); - assert_eq!(core_chain(CoreError::TokenFrozen, &PUSH).code, "E602"); - let frozen = core_chain( - CoreError::Platform("token freeze failed: Identity X account is frozen for token Y. Action attempted: Document create token payment".into()), - &PUSH, - ); - assert_eq!(frozen.code, "E602"); - assert!(frozen.fix[0].contains("dg collab unsuspend alice/project")); - // The e2e suite recognizes a consensus freeze by these words; a local pre-check by - // "token on this repo is frozen", which must NOT appear here. - let typed = core_chain(CoreError::TokenFrozen, &PUSH); - let text = typed.render("", false); - assert!( - text.contains("token frozen") && text.contains("access has been suspended"), - "{text}" - ); - assert!(!text.contains("on this repo is frozen"), "{text}"); - let unauthorized = core_chain(CoreError::Unauthorized, &PUSH).render("", false); - assert!( - unauthorized.contains("WRITE or MAINTAIN token"), - "{unauthorized}" - ); - assert!( - !unauthorized.contains("no WRITE token on this repo"), - "{unauthorized}" - ); - let no_token = core_chain( - CoreError::Platform("Identity X does not have enough balance for token Y: required 1, actual 0, action: Document create token payment".into()), - &PUSH, - ); - assert_eq!(no_token.code, "E601"); - } - #[test] fn maps_insufficient_balance_with_amounts() { let ctx = ErrorContext { @@ -1640,7 +1551,7 @@ mod tests { ); assert_eq!(pushed.message, "push failed: could not reach Dash Platform"); let u = core_chain( - CoreError::NotDeployed { + CoreError::V2NotDeployed { network: "mainnet".into(), }, &ErrorContext::default(), @@ -1653,9 +1564,7 @@ mod tests { assert_eq!(u.code, "E202"); assert_eq!(u.exit_code(), 2); let u = core_chain( - CoreError::Config( - "no CRITICAL AUTHENTICATION key in identity file (required for token admin)".into(), - ), + CoreError::Config("no HIGH or CRITICAL AUTHENTICATION key in identity file".into()), &ErrorContext::default(), ); assert_eq!(u.code, "E302"); diff --git a/crates/forge-core/src/webhooks.rs b/crates/forge-core/src/webhooks.rs index faf8ad6a8..9d2077f99 100644 --- a/crates/forge-core/src/webhooks.rs +++ b/crates/forge-core/src/webhooks.rs @@ -462,7 +462,6 @@ impl<'a> WebhookService<'a> { /// Fail early (with a message rather than consensus code 40120) when the signer is not a /// maintainer of `repo`. Advisory: consensus is the authority. pub async fn require_maintainer(&self, repo: &RepoRef) -> Result<()> { - repo.require_v2()?; let me = self.identity.id(); if MemberReader::new(self.client) .role_doc(repo, &me, Role::Maintainer) @@ -480,7 +479,7 @@ impl<'a> WebhookService<'a> { /// Build the document for `input` on `repo`: pick the relay's encryption key and the /// signer's, and encrypt the secret between them. Nothing is sent. pub async fn prepare(&self, repo: &RepoRef, input: &NewWebhook) -> Result { - let forge = repo.require_v2()?; + let forge = repo.forge(); check_url_and_events(&input.url, &input.events, input.allow_credentials_in_url)?; check_secret(input.secret.expose())?; @@ -559,7 +558,7 @@ impl<'a> WebhookService<'a> { /// Write a prepared webhook document; returns its id. pub async fn send(&self, repo: &RepoRef, prepared: &PreparedWebhook) -> Result { - let forge = repo.require_v2()?; + let forge = repo.forge(); let contract = self.client.fetch_contract(&forge.collab).await?; WriteEngine::new(self.client, self.identity, self.bridge.doc_op_key()?)? .create_document(&contract, DOC_WEBHOOK, prepared.properties.clone()) @@ -575,7 +574,7 @@ impl<'a> WebhookService<'a> { /// means there is no moment in which the other maintainer's document is current again. /// Then delete every other document of the hook the signer wrote. pub async fn remove(&self, repo: &RepoRef, hook_id: [u8; 32]) -> Result { - let forge = repo.require_v2()?; + let forge = repo.forge(); let contract = self.client.fetch_contract(&forge.collab).await?; let me = self.identity.id(); let history = WebhookReader::new(self.client) diff --git a/crates/forge-core/tests/collab_tokens.rs b/crates/forge-core/tests/collab_tokens.rs deleted file mode 100644 index ee934691d..000000000 --- a/crates/forge-core/tests/collab_tokens.rs +++ /dev/null @@ -1,270 +0,0 @@ -//! Live testnet collaboration + v1 token-read test (gated `#[ignore]`). -//! -//! Reuses the DEPLOYER-owned M1 repo contract (cheap — the token contract already exists) -//! to exercise the [`forge_core::collab`] and [`forge_core::tokens`] service layer against -//! real testnet: -//! -//! * **Issue lifecycle** (un-gated, ~0.0001 tDASH each): create an issue → comment → close -//! event → fold shows closed → reopen event → fold shows open. `issue_count` reflects the -//! count tree. -//! * **Social** (registry, un-gated): star a listing id → `star_count` reflects it → unstar. -//! * **Tokens** (the v1 ACL, read only now): `list_collaborators` includes the repo owner, -//! and `token_history` reads the mint records back. Granting and revoking is forge-v2 -//! membership (`forge_core::members`), exercised by the moutai live tests. -//! -//! Run with: -//! ```text -//! cargo test -p forge-core --test collab_tokens -- --ignored --nocapture -//! ``` - -use forge_core::collab::{IssueService, SocialService, StateFilter}; -use forge_core::keystore::BridgeIdentity; -use forge_core::platform::{self, FieldValue, Network, PlatformClient, QueryFilter, QueryOrder}; -use forge_core::tokens::TokenService; - -/// Whether the `event` docs for `target_id` carry a consensus `$createdAt` — the clock the -/// close/reopen fold needs. `false` on a stale pre-`$createdAt` contract (M1). -async fn event_timestamps_present(client: &PlatformClient, target_id: &str) -> bool { - let contract = client - .fetch_contract(M1_REPO_CONTRACT) - .await - .expect("fetch contract"); - let target = platform::decode_identifier(target_id).expect("decode target id"); - let docs = client - .query_all_documents( - &contract, - "event", - &[QueryFilter::eq("targetId", FieldValue::identifier(target))], - &[QueryOrder::asc("$createdAt")], - ) - .await - .expect("query events"); - docs.iter().any(|d| d.created_at.is_some()) -} - -const DEPLOYER_PATH: &str = - "/Users/pasta/.config/dash-forge/test-identities/DEPLOYER.identity.json"; -const COLLAB_PATH: &str = "/Users/pasta/.config/dash-forge/test-identities/COLLAB.identity.json"; - -/// The DEPLOYER-owned M1 repo contract (resolvable, holds both tokens' baseSupply). -const M1_REPO_CONTRACT: &str = "5rrwgjjVUqMghnessfiXPXubpiM2QLNNXH142Hv4PDyX"; - -#[tokio::test] -#[ignore = "live testnet; spends a few tDASH; run manually"] -#[allow(clippy::too_many_lines)] -async fn collab_and_token_lifecycle_on_testnet() { - let bridge = BridgeIdentity::load_from_file(DEPLOYER_PATH).expect("load DEPLOYER identity"); - let owner_id = bridge.identity_id.clone(); - let collab = BridgeIdentity::load_from_file(COLLAB_PATH).expect("load COLLAB identity"); - let collab_id = collab.identity_id.clone(); - println!("owner (DEPLOYER): {owner_id}"); - println!("collaborator (COLLAB): {collab_id}"); - - let client = PlatformClient::connect_network(Network::Testnet) - .await - .expect("connect testnet"); - let identity = client - .fetch_identity(&owner_id) - .await - .expect("fetch DEPLOYER identity"); - let balance_before = identity.balance(); - println!("balance before: {balance_before} credits"); - - // ===================================================================== - // 1. Issue lifecycle: create -> comment -> close -> reopen (folded state) - // ===================================================================== - let issues = IssueService::new(&client, &identity, &bridge); - - let count_before = issues - .issue_count(M1_REPO_CONTRACT) - .await - .expect("issue_count"); - println!("issue_count before: {count_before}"); - - let issue = issues - .create_issue( - M1_REPO_CONTRACT, - "collab_tokens live test issue", - "created by the collab+tokens integration test", - ) - .await - .expect("create_issue"); - println!( - "created issue #{} (doc {})", - issue.number, issue.document_id - ); - - let comment_id = issues - .comment( - M1_REPO_CONTRACT, - &issue.document_id, - "a live-test comment", - None, - ) - .await - .expect("comment"); - println!("posted comment {comment_id}"); - - // Fold: fresh issue is open. - let state = issues - .issue_state(M1_REPO_CONTRACT, issue.number) - .await - .expect("issue_state") - .expect("issue exists"); - assert!(state.state.open, "new issue should fold to open"); - println!("issue folds OPEN (correct)"); - - // Close event -> fold shows closed. - let close_id = issues - .close(M1_REPO_CONTRACT, &issue.document_id) - .await - .expect("close event"); - println!("posted close event {close_id}"); - let state = issues - .issue_state(M1_REPO_CONTRACT, issue.number) - .await - .expect("issue_state") - .expect("issue exists"); - assert!( - !state.state.open, - "after close, issue should fold to closed" - ); - println!("issue folds CLOSED after close event (correct)"); - - // Reopen event. Fold ordering is by (`$createdAt`, `$id`); the deployed M1 contract - // predates the template's `$createdAt`-in-`required` fix, so its `event`/`issue` docs - // record NO consensus timestamp (verified: token-history mints return `Some(createdAt)` - // via the same read path, M1 issue/event return `None`). Without a clock, close/reopen - // ordering degrades to random `$id` order and is non-deterministic on M1 specifically. - // The fold logic itself is correct (rules.rs conformance vectors). So: assert the - // reopen-to-open fold ONLY when the contract actually timestamps events; otherwise log - // the M1 staleness (a data-contract reconciliation item) and continue. - let reopen_id = issues - .reopen(M1_REPO_CONTRACT, &issue.document_id) - .await - .expect("reopen event"); - println!("posted reopen event {reopen_id}"); - - let events_ts = event_timestamps_present(&client, &issue.document_id).await; - let state = issues - .issue_state(M1_REPO_CONTRACT, issue.number) - .await - .expect("issue_state") - .expect("issue exists"); - if events_ts { - assert!(state.state.open, "after reopen, issue should fold to open"); - println!("issue folds OPEN after reopen event (correct)"); - } else { - println!( - "NOTE: M1 event docs carry NO $createdAt (stale pre-fix contract) — close/reopen \ - fold ordering is non-deterministic on M1; folded open={} (not asserted). A repo \ - from the current repo-v1 template records $createdAt and folds deterministically.", - state.state.open - ); - } - - let count_after = issues - .issue_count(M1_REPO_CONTRACT) - .await - .expect("issue_count"); - println!("issue_count after: {count_after}"); - assert!(count_after > count_before, "issue count tree should grow"); - - // list_issues (All) should include our issue. - let all = issues - .list_issues(M1_REPO_CONTRACT, StateFilter::All, 20, None) - .await - .expect("list_issues"); - assert!( - all.iter().any(|i| i.issue.number == issue.number), - "our issue should appear in the list" - ); - println!("list_issues(All) includes issue #{}", issue.number); - - // ===================================================================== - // 2. Social: star a listing id -> star_count -> unstar - // ===================================================================== - // The M1 contract id is used as a stand-in listing id (the registry `star` schema - // stores a bare 32-byte identifier with no existence FK) — this exercises the - // star/count/unstar path without minting a ~1 DASH listing. - let social = SocialService::new(&client, &identity, &bridge); - let listing_id = M1_REPO_CONTRACT; - - let stars_before = social.star_count(listing_id).await.expect("star_count"); - println!("star_count before: {stars_before}"); - // Ensure a clean slate (a prior interrupted run may have left our star). - social.unstar(listing_id).await.expect("unstar (pre-clean)"); - - let star_id = social.star(listing_id).await.expect("star"); - println!("starred (doc {star_id})"); - let stars_mid = social.star_count(listing_id).await.expect("star_count"); - println!("star_count after star: {stars_mid}"); - assert!(stars_mid >= 1, "star count should reflect our star"); - - social.unstar(listing_id).await.expect("unstar"); - let stars_after = social.star_count(listing_id).await.expect("star_count"); - println!("star_count after unstar: {stars_after}"); - assert_eq!( - stars_after, - stars_mid - 1, - "unstar should decrement the count tree" - ); - - // ===================================================================== - // 3. Tokens (v1, read only): the owner is a collaborator; history reads back. - // ===================================================================== - let tokens = TokenService::new(&client); - let collaborators = tokens - .list_collaborators(M1_REPO_CONTRACT) - .await - .expect("list_collaborators"); - println!("collaborators: {collaborators:#?}"); - assert!( - collaborators.iter().any(|c| c.identity_id == owner_id), - "the repo owner holds the baseSupply tokens" - ); - let history = tokens - .token_history(M1_REPO_CONTRACT) - .await - .expect("token_history"); - println!("token_history: {} record(s)", history.len()); - let _ = &collab_id; - - // ===================================================================== - // 4. Cleanup (best-effort refund of the deletable docs). - // ===================================================================== - // The issue + comment are author-owned & deletable; close/reopen events are - // non-deletable (permanent audit log) and stay. - let contract = client - .fetch_contract(M1_REPO_CONTRACT) - .await - .expect("fetch repo contract"); - let engine = forge_core::platform::WriteEngine::new( - &client, - &identity, - bridge.doc_op_key().expect("doc key"), - ) - .expect("engine"); - if let Err(e) = engine - .delete_document(&contract, "comment", &comment_id) - .await - { - println!("comment cleanup skipped: {e}"); - } - if let Err(e) = engine - .delete_document(&contract, "issue", &issue.document_id) - .await - { - println!("issue cleanup skipped: {e}"); - } - println!("cleanup done (events remain permanently by design)"); - - let balance_after = client.get_balance(&owner_id).await.expect("balance after"); - println!("balance before: {balance_before} credits"); - println!("balance after: {balance_after} credits"); - println!( - "net spend: {} credits ({:.6} DASH)", - balance_before.saturating_sub(balance_after), - forge_core::repo::credits_to_dash(balance_before.saturating_sub(balance_after)) - ); -} diff --git a/crates/forge-import/Cargo.toml b/crates/forge-import/Cargo.toml index 025d0c6c8..e0c8bd6c5 100644 --- a/crates/forge-import/Cargo.toml +++ b/crates/forge-import/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true repository.workspace = true rust-version.workspace = true -description = "forge-import — mirror GitHub repositories into Dash Forge, and migrate forge-v1 repositories to forge-v2." +description = "forge-import — mirror GitHub repositories into Dash Forge." [lib] path = "src/lib.rs" diff --git a/crates/forge-import/src/claim.rs b/crates/forge-import/src/claim.rs index 66e3060b3..306a55ba9 100644 --- a/crates/forge-import/src/claim.rs +++ b/crates/forge-import/src/claim.rs @@ -12,12 +12,11 @@ //! `github` login, plus a `signature` produced by that identity's key over the challenge //! string. The structure is verified here; the cryptographic signature check against the //! identity's public key is the documented mechanism (a full BLS/ECDSA verify needs the -//! SDK key material and is folded in `FORGE_RULES_V1` alongside the on-chain claim doc). -//! 3. On success an `authorClaim` record is produced — the doc a `FORGE_RULES_V1`-aware -//! client folds so the placeholder thereafter renders as the claiming identity. The -//! `authorClaim` document type is a repo-template v2 addition (the deployed v1 template -//! carries no claim type yet), so this command verifies + emits the record and reports -//! the write as pending that template bump. +//! SDK key material and belongs with the on-chain claim doc's client rule). +//! 3. On success an `authorClaim` record is produced — the doc a client folds so the +//! placeholder thereafter renders as the claiming identity. The contracts carry no +//! `authorClaim` document type yet, so this command verifies + emits the record and reports +//! the write as pending that contract addition. //! //! Challenge format (the string the identity signs, one field per line): //! ```text @@ -171,8 +170,8 @@ fn parse_challenge(body: &str) -> Result { .filter(|s| !s.is_empty()) .ok_or_else(|| anyhow!("challenge missing a non-empty `signature:` line"))?; // Structural signature check (base64-ish, non-trivial length). The full cryptographic - // verify against the identity's public key is the documented mechanism folded in - // FORGE_RULES_V1 with the on-chain authorClaim doc (template v2). + // verify against the identity's public key is the documented mechanism, folded with the + // on-chain authorClaim doc once the contracts carry it. if signature.len() < 16 { bail!( "challenge `signature:` is implausibly short ({} chars)", diff --git a/crates/forge-import/src/dest.rs b/crates/forge-import/src/dest.rs index fd52fc9cb..a4c3ccaea 100644 --- a/crates/forge-import/src/dest.rs +++ b/crates/forge-import/src/dest.rs @@ -10,7 +10,7 @@ use forge_core::create::{create_repo, default_journal_dir, CreateRepoOpts}; use forge_core::keystore::BridgeIdentity; use forge_core::members::MemberReader; use forge_core::platform::{LoadedIdentity, PlatformClient}; -use forge_core::resolve::{find_v2, repo_slug, resolve_id}; +use forge_core::resolve::{find_named, repo_slug, resolve_id}; use forge_core::rules::v2::{Role, Visibility}; use forge_core::scope::RepoRef; @@ -126,7 +126,7 @@ impl DestRepo { } /// Resolve `spec` (`owner/name`, `dash://owner/name`, a repo id, or a bare name meaning the -/// signer's) on the destination network. A forge-v1 repository is refused: v1 is read only. +/// signer's) on the destination network. pub async fn resolve( client: &PlatformClient, signer: Option<&str>, @@ -150,9 +150,6 @@ pub async fn resolve( let repo = resolve_id(client, spec) .await .with_context(|| format!("resolving repo {spec}"))?; - if repo.is_v1() { - bail!("{spec} is a forge-v1 repository (read only); mirror into a forge-v2 repository"); - } return Ok(DestRepo { owner: repo.owner_id().to_string(), name: repo.name().to_string(), @@ -173,7 +170,7 @@ pub async fn resolve( let name = repo_slug(&name)?; let owner_bytes = forge_core::platform::decode_identifier(&owner) .with_context(|| format!("owner {owner:?} is not an identity id"))?; - let existing = find_v2(client, &forge, owner_bytes, &name).await?; + let existing = find_named(client, &forge, owner_bytes, &name).await?; Ok(DestRepo { owner, name, diff --git a/crates/forge-import/src/sink.rs b/crates/forge-import/src/sink.rs index 918445cfb..9ff6f1d62 100644 --- a/crates/forge-import/src/sink.rs +++ b/crates/forge-import/src/sink.rs @@ -494,7 +494,7 @@ impl<'a> Sink<'a> { } let mut index = Vec::new(); if let Some(repo) = &self.repo { - let forge = repo.require_v2()?; + let forge = repo.forge(); let client = self.ledger.client; let collab = client.fetch_contract(&forge.collab).await?; let repo_id = diff --git a/crates/forge-import/src/summary.rs b/crates/forge-import/src/summary.rs index b9cff75aa..b2ea959d9 100644 --- a/crates/forge-import/src/summary.rs +++ b/crates/forge-import/src/summary.rs @@ -103,7 +103,7 @@ pub struct Summary { pub status: Status, /// `testnet`, `mainnet`, `devnet-`. pub network: String, - /// The source (`owner/repo`, or the v1 repo). + /// The source (`owner/repo`). pub source: String, /// The destination. pub repo: RepoInfo, diff --git a/crates/forge-relay/README.md b/crates/forge-relay/README.md index bae333526..9a9f186b2 100644 --- a/crates/forge-relay/README.md +++ b/crates/forge-relay/README.md @@ -4,7 +4,7 @@ Delivers forge-v2 repository activity as GitHub-shaped webhooks (`push`, `issues `pull_request`, `issue_comment`, `pull_request_review`, `release`, `check_run`), signed with `X-Hub-Signature-256`. A relay is trusted for availability only: consumers verify what a webhook says against Platform (see `examples/ci_consumer.rs`, which folds the pushed ref's -history and checks the tip). forge-v1 repositories are read-only and are not served. +history and checks the tip). ## How a hook reaches a relay diff --git a/crates/forge-relay/examples/ci_consumer.rs b/crates/forge-relay/examples/ci_consumer.rs index cd9e77443..fd01ac69d 100644 --- a/crates/forge-relay/examples/ci_consumer.rs +++ b/crates/forge-relay/examples/ci_consumer.rs @@ -159,7 +159,7 @@ async fn verify_and_check_run( let client = PlatformClient::connect_network(network.clone()).await?; let repo = forge_core::resolve::resolve_id(&client, &repo_id).await?; - let forge = repo.require_v2()?.clone(); + let forge = repo.forge().clone(); let scope = repo.scope()?; // Independent verification: did a *valid* update of this ref set it to `after`? forge's diff --git a/crates/forge-relay/src/config.rs b/crates/forge-relay/src/config.rs index 42a2f8387..ee4230963 100644 --- a/crates/forge-relay/src/config.rs +++ b/crates/forge-relay/src/config.rs @@ -55,7 +55,7 @@ impl std::fmt::Debug for StaticWebhook { } } -/// The on-disk TOML shape (all optional; CLI flags override). Unknown keys (such as the v1 +/// The on-disk TOML shape (all optional; CLI flags override). Unknown keys (such as an older /// relay's `secrets` map or `registry-contract-id`) are ignored. #[derive(Debug, Default, Deserialize)] #[serde(rename_all = "kebab-case")] @@ -161,7 +161,6 @@ impl RelayConfig { devnet_name: file.devnet_name.clone(), dapi_addresses: file.dapi_addresses.clone(), quorum_base_url: file.quorum_url.clone(), - registry: None, }; let target = cli .network diff --git a/crates/forge-relay/src/daemon.rs b/crates/forge-relay/src/daemon.rs index b01fb2862..91b9031d0 100644 --- a/crates/forge-relay/src/daemon.rs +++ b/crates/forge-relay/src/daemon.rs @@ -167,8 +167,7 @@ fn now_ms() -> u64 { pub async fn run(cfg: RelayConfig) -> Result<()> { let forge = cfg.target.v2.clone().ok_or_else(|| { RelayError::Config(format!( - "forge-v2 is not deployed on {}; the relay serves forge-v2 repositories only \ - (v1 repositories are read-only and have no webhooks)", + "forge-v2 is not deployed on {}; the relay serves forge-v2 repositories only", cfg.target.network )) })?; @@ -300,16 +299,10 @@ fn shared_refresh_interval(cfg: &RelayConfig) -> Duration { /// `owner/name` or a repo id → the forge-v2 repo. async fn resolve_repo(client: &PlatformClient, r: &str) -> Result { - let repo = match r.split_once('/') { + Ok(match r.split_once('/') { Some((owner, name)) => forge_core::resolve::resolve_named(client, owner, name).await?, None => forge_core::resolve::resolve_id(client, r).await?, - }; - if repo.is_v1() { - return Err(RelayError::Config(format!( - "{r} is a forge-v1 repository; the relay serves forge-v2 repositories only" - ))); - } - Ok(repo) + }) } /// `repoId == repo_id`, the pinned prefix of every repo-scoped stream. @@ -577,17 +570,12 @@ async fn prime_ref_streams( /// opened PR heads. async fn init_repo(shared: &Shared, repo_id: &str, baseline: Baseline) -> Result { let repo = forge_core::resolve::resolve_id(&shared.client, repo_id).await?; - let RepoRef::V2 { + let RepoRef { owner_id, name, visibility, .. - } = &repo - else { - return Err(RelayError::Config(format!( - "{repo_id} is not a forge-v2 repo" - ))); - }; + } = &repo; if *visibility == Visibility::Private { // A private repo's content is encrypted to its members; the relay is not one. return Err(RelayError::Config(format!( diff --git a/crates/forge-relay/src/main.rs b/crates/forge-relay/src/main.rs index b316a3210..879a9b31a 100644 --- a/crates/forge-relay/src/main.rs +++ b/crates/forge-relay/src/main.rs @@ -10,8 +10,6 @@ //! at another relay is one document. Consumers re-fetch and verify from Platform, so a relay //! is trusted for availability only. //! -//! forge-v1 repositories (one contract each) are read-only and not served. -//! //! Module map: //! * [`config`] — TOML + CLI configuration. //! * [`subscriptions`] — discovery of the `webhook` documents addressed to this relay. diff --git a/crates/git-remote-dash/src/helper.rs b/crates/git-remote-dash/src/helper.rs index f46c984a4..05549cb21 100644 --- a/crates/git-remote-dash/src/helper.rs +++ b/crates/git-remote-dash/src/helper.rs @@ -2,9 +2,8 @@ //! `list` / `fetch` / `push` operations against `forge-core`'s [`RepoService`]. //! //! Data flow (architecture §6): -//! - **resolve** → `dash://owner/name` is a forge-v2 `repo` (else a v1 registry listing, -//! read only); `dash://` a v2 repo id or a v1 repo contract id -//! (`forge_core::resolve`). +//! - **resolve** → `dash://owner/name` is a forge-v2 `repo` by `($ownerId, name)`; +//! `dash://` a repo document id (`forge_core::resolve`). //! - **list** → `read_refs` (proof-verified, folded by the ref rules) → ` ` lines //! + the `HEAD` symref from the repo's default branch. //! - **fetch** → every kind-0 pack's copies → the first copy that verifies, in the @@ -18,7 +17,7 @@ //! `write_pack_manifest` (every confirmed URI + the SHA-256) → `write_ref_update` //! (prevOid recorded; non-FF refused without `+`) → post-push ref re-read for a //! lost-race late non-fast-forward. Refs are written ONLY after the storage policy is -//! met and the manifest has landed. A v1 repository refuses every push (read only). +//! met and the manifest has landed. use std::path::PathBuf; @@ -165,7 +164,6 @@ impl Helper { repo.require_readable()?; tracing::info!( repo = %repo.id(), - generation = repo.generation(), owner = %repo.owner_id(), "resolved dash:// repo" ); @@ -284,7 +282,7 @@ impl Helper { // `storage = 0` copy must not turn an unreadable pack into a failed clone (git's // connectivity check still fails the fetch if a wanted object was in it). let on_chain = copies.iter().any(|m| { - m.storage == 0 && (repo.is_v1() || roles.contains_key(&m.owner_id)) + m.storage == 0 && roles.contains_key(&m.owner_id) }); let bytes = match got { Ok((bytes, _)) => bytes, @@ -363,8 +361,6 @@ impl Helper { None }; let conn = self.ensure_conn().await?; - // v1 repositories are read only: refuse before building or paying for anything. - conn.repo.require_v2()?; // How the repo is named in fixes the user may paste into `dg`: `owner/name`. let repo_label = conn.repo.display(); let svc = RepoService::new(&conn.client, &conn.identity, &conn.bridge); @@ -876,7 +872,7 @@ async fn store_pack( observed.iter().map(|t| t as &dyn StorageTarget).collect(); // No policy (Platform only): keep the pre-policy behaviour exactly — the chunk - // upload's own typed error (TokenFrozen, Unauthorized, InsufficientCredits, …) under + // upload's own typed error (NotAMember, InsufficientCredits, …) under // the familiar context, with no policy/fallback advice that cannot apply. if let (true, 1, Some(chain)) = (resolved.external.is_empty(), resolved.total(), &chain) { let uris = Observed::new(chain, &report) @@ -1106,9 +1102,8 @@ async fn publish_browse_index( replication: &Replication, externals: &[ExternalTarget], ) { - // `DASH_FORGE_NO_BROWSE_INDEX=1` skips it on purpose: the nightly's read fixture - // (e2e/cli/seed-read-fixture.sh) must stay unindexed so the web app's fallback clone is - // what the browser specs exercise. + // `DASH_FORGE_NO_BROWSE_INDEX=1` skips it on purpose, for a test repo that must stay + // unindexed so the web app's in-browser fallback clone is what gets exercised. if matches!( std::env::var("DASH_FORGE_NO_BROWSE_INDEX").as_deref(), Ok("1" | "true") @@ -1214,11 +1209,11 @@ fn oid_to_bytes(oid: &str) -> Result> { Ok(raw) } -/// Resolve the network and registry. Precedence, field by field: the environment -/// (`DASH_FORGE_NETWORK`, `DASH_FORGE_DEVNET_NAME`, `DASH_FORGE_DAPI_ADDRESSES`, -/// `DASH_FORGE_QUORUM_URL`, `FORGE_REGISTRY_CONTRACT_ID` — what `dg` and forge-import set -/// per invocation) > git config (`dash.network`, `dash.devnetName`, `dash.dapiAddresses`, -/// `dash.quorumUrl`, `dash.registryContractId`) > the embedded deployment > testnet. +/// Resolve the network and its forge-v2 contracts. Precedence, field by field: the +/// environment (`DASH_FORGE_NETWORK`, `DASH_FORGE_DEVNET_NAME`, `DASH_FORGE_DAPI_ADDRESSES`, +/// `DASH_FORGE_QUORUM_URL` — what `dg` and forge-import set per invocation) > git config +/// (`dash.network`, `dash.devnetName`, `dash.dapiAddresses`, `dash.quorumUrl`) > the embedded +/// deployment > testnet. pub(crate) fn network_target() -> Result { resolve_network( NetworkSettings::from_env(), @@ -1461,7 +1456,6 @@ mod tests { fn nothing_configured_is_testnet() { let t = resolve_network(NetworkSettings::default(), NetworkSettings::default()).unwrap(); assert_eq!(t.network.key(), "testnet"); - assert!(t.registry.is_some()); } #[test] diff --git a/crates/git-remote-dash/src/url.rs b/crates/git-remote-dash/src/url.rs index 881495d55..60fe4181d 100644 --- a/crates/git-remote-dash/src/url.rs +++ b/crates/git-remote-dash/src/url.rs @@ -2,11 +2,10 @@ //! //! * `dash:///` — the human form. `owner` is a base58 Dash identity id (a DPNS //! label is a later addition, resolved upstream of this parser); a trailing `.git` on the -//! repo name is stripped. Resolved as a forge-v2 `repo` by `(owner, name)`, falling back to -//! the v1 registry listing (read-only repositories). -//! * `dash://` — a single segment: a forge-v2 `repo` document id, or a v1 repo contract -//! id (both are tried, v2 first; see `forge_core::resolve::resolve_id`). This is how a -//! pull request points at the repo holding its head commit. +//! repo name is stripped. Resolved as a forge-v2 `repo` by `(owner, name)`. +//! * `dash://` — a single segment: a forge-v2 `repo` document id (see +//! `forge_core::resolve::resolve_id`). This is how a pull request points at the repo +//! holding its head commit. //! //! The two are unambiguous: the human form always has a `/`. @@ -25,7 +24,7 @@ pub enum DashUrl { /// The repository name (any trailing `.git` removed). repo: String, }, - /// `dash://` — a forge-v2 repo id or a v1 repo contract id. + /// `dash://` — a forge-v2 repo document id. Id { /// The base58 id. id: String, diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 5ecb590a1..42c155f43 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -166,41 +166,44 @@ complete readers (`query_all_documents` / `queryAllDocuments`): - **Same-block ties.** A `start_after` cursor excludes the cursor's whole `$createdAt`, so documents created in the same block as a page's last row, and sorting after it, are skipped. When the index ends in `$createdAt`, the readers also query the boundary - timestamp with `==`. This needs the boundary row's `$createdAt`. The history-keeping - repo-v1 types (`packManifest`, `event`, `refUpdate`, `issue`, ...) do not return it from a - proved query, so their reads keep the gap until they move to forge-v2 on protocol 14, - which bounds the cursor by document id. + timestamp with `==`. This needs the boundary row's `$createdAt`, which history-keeping + types (`packManifest`, `event`, `refUpdate`, `issue`, ...) do not return from a proved + query on protocol 13. forge-v2 runs only on protocol 14, where the readers bound the + cursor by document id. ## Networks -Every binary and the web app target one of **testnet** (the default), **mainnet**, or a -**named devnet** such as `moutai`. Contract ids are never written into code: they come from +Every binary and the web app target one of **testnet**, **mainnet**, or a **named devnet** +such as `moutai`. The CLI tools default to testnet, but forge-v2 is deployed only on devnet +moutai today (Platform protocol 14). Testnet and mainnet run protocol 13; forge-v2 is +registered on testnet once protocol 14 reaches it, and on mainnet after protocol 14 +activates there ([mainnet-runbook.md](mainnet-runbook.md)). Until then, pass +`--network devnet --devnet-name moutai` (or just `--devnet-name moutai`), or record it once +with `dg auth login --network devnet --devnet-name moutai`, which saves the network in +`~/.config/dash-forge/config.toml`. + +Contract ids are never written into code: they come from the `v2` section of `forge-contracts/deployments/.json`, where the key is `testnet`, `mainnet` or `devnet-`. The Rust crates embed every file in that directory at build time (`crates/forge-core/build.rs`); forge-web bundles them through `forge-web/lib/deployments.ts`, and a unit test fails if that map is missing a file. -A network with no registry id in its deployment file is **not deployed**. Commands that need -the registry fail with - -``` -no Dash Forge registry is deployed on mainnet yet; see docs/mainnet-runbook.md -``` - -and never fall back to another network's ids. Identity and balance reads still work there. -`dg doctor` prints the network, the registry id, and where the id came from. +A network whose deployment file has no registered forge-v2 pair (or has no file at all) is +**not deployed**. Commands that need the contracts fail with a "not deployed" error and never +fall back to another network's ids. Identity and balance reads still work there. `dg doctor` +prints the network, the forge-core and forge-collab ids, and where they came from. ### Selecting a network -| Tool | Network | Devnet name | Devnet DAPI addresses | Registry override | -|---|---|---|---|---| -| `dg` (flags) | `--network testnet\|mainnet\|devnet` | `--devnet-name moutai` | `--dapi-addresses a,b` | — | -| `dg` (`~/.config/dash-forge/config.toml`) | `network` | `devnet_name` | `dapi_addresses` | `registry_contract_id` | -| `git-remote-dash` (git config) | `dash.network` | `dash.devnetName` | `dash.dapiAddresses` | `dash.registryContractId` | -| `forge-relay` (flags / TOML) | `--network` / `network` | `--devnet-name` / `devnet-name` | `--dapi-addresses` / `dapi-addresses` | `registry-contract-id` | -| `forge-import` (flags) | `--network` | `--devnet-name` | `--dapi-addresses` | — | -| any of the above (env) | `DASH_FORGE_NETWORK` | `DASH_FORGE_DEVNET_NAME` | `DASH_FORGE_DAPI_ADDRESSES` | `FORGE_REGISTRY_CONTRACT_ID` | -| forge-web (build env) | `NEXT_PUBLIC_NETWORK` | `NEXT_PUBLIC_DEVNET_NAME` | `NEXT_PUBLIC_DAPI_ADDRESSES` | `NEXT_PUBLIC_REGISTRY_CONTRACT_ID` | +| Tool | Network | Devnet name | Devnet DAPI addresses | +|---|---|---|---| +| `dg` (flags) | `--network testnet\|mainnet\|devnet` | `--devnet-name moutai` | `--dapi-addresses a,b` | +| `dg` (`~/.config/dash-forge/config.toml`) | `network` | `devnet_name` | `dapi_addresses` | +| `git-remote-dash` (git config) | `dash.network` | `dash.devnetName` | `dash.dapiAddresses` | +| `forge-relay` (flags / TOML) | `--network` / `network` | `--devnet-name` / `devnet-name` | `--dapi-addresses` / `dapi-addresses` | +| `forge-import` (flags) | `--network` | `--devnet-name` | `--dapi-addresses` | +| any of the above (env) | `DASH_FORGE_NETWORK` | `DASH_FORGE_DEVNET_NAME` | `DASH_FORGE_DAPI_ADDRESSES` | +| forge-web (build env) | `NEXT_PUBLIC_NETWORK` | `NEXT_PUBLIC_DEVNET_NAME` | `NEXT_PUBLIC_DAPI_ADDRESSES` | Precedence is per field. For `dg`, `forge-relay` and `forge-import` it is: flags, then the config file, then the environment, then the deployment file. For `git-remote-dash` it is the @@ -210,7 +213,7 @@ more rules apply to every tool: - `--devnet-name` on its own implies `--network devnet`. - A layer that names a different network contributes nothing network-specific. For example, - a `registry_contract_id` saved for testnet in `config.toml` is ignored under + `dapi_addresses` saved for a devnet in `config.toml` are ignored under `--network mainnet`. A devnet's quorum keys come from `https://quorums..networks.dash.org`. Override the @@ -233,19 +236,20 @@ git clone -c dash.network=devnet -c dash.devnetName=moutai dash:/// NEXT_PUBLIC_NETWORK=devnet NEXT_PUBLIC_DEVNET_NAME=moutai pnpm build # forge-web ``` -The web header shows a network badge on every network except mainnet. On a network with no -registry, the badge is amber and the pages that need the registry show a "not deployed" -state instead of querying. +The web header shows a network badge on every network except mainnet (the production build +at forge.dashhq.org is built for devnet moutai and shows "devnet"). On a network with no +forge-v2 deployment, the badge is amber and the pages that need the contracts show a "not +deployed" state instead of querying. ### Adding a network -To add a network, commit its deployment file: `deploy.mjs` writes `mainnet.json`, and a new -devnet gets `devnet-.json`. Then add a matching import to -`forge-web/lib/deployments.ts`. `devnet-moutai.json` records moutai's DAPI addresses and, -under `v2`, the forge-v2 contracts `deploy-v2.mjs` registered there. It has no v1 `registry`. -Deployment resolution exposes the `v2` ids (forge-core `NetworkTarget::v2`, forge-web -`NETWORKS[n].v2`) once both contracts are `registered`, but no client operation reads them -yet, so moutai reports "not deployed" until the clients move to forge-v2. +To add a network, register forge-v2 there with `forge-contracts/scripts/deploy-v2.mjs` +([contracts/forge-v2.md §8](contracts/forge-v2.md#8-deploying)). It writes the `v2` section of +`forge-contracts/deployments/.json` (`devnet-.json` for a devnet). Commit the +file, then add a matching import to `forge-web/lib/deployments.ts`. The script's SDK is +pinned in `forge-contracts/sdk-v2` (`(cd forge-contracts/sdk-v2 && npm ci)` once). Deployment +resolution exposes the ids (forge-core `NetworkTarget::v2`, forge-web `NETWORKS[n].v2`) once +both contracts are `registered`. `devnet-moutai.json` also records moutai's DAPI addresses. ## Checks @@ -266,20 +270,20 @@ one. * `make storage-it`: brings up `infra/docker-compose.yml`, then runs the bring-your-own storage tests against it. Covered: SigV4-signed S3 operations on a bucket that refuses anonymous writes, kubo CIDs matching the local CIDv1 derivation, and N-of-M - replication with gateway read-back. Localhost only; no testnet. `FORGE_IT_S3=1` / + replication with gateway read-back. Localhost only; no Platform network. `FORGE_IT_S3=1` / `FORGE_IT_IPFS=1` make an unreachable fixture fail instead of skip. * `make storage-e2e`: a real `git push` / `git clone` over `dash://` with packs on the - local MinIO + kubo. Only the manifest and ref go to testnet, and it spends a few hundred - thousand credits of the e2e DEPLOYER identity. See `e2e/cli/storage-byo.sh`. + local MinIO + kubo. Only the manifest and ref go to devnet moutai, paid by the e2e OWNER + identity. See `e2e/cli/storage-byo.sh`. ## End-to-end suites -Both e2e suites run against **live Dash Platform testnet** and are not part of the -per-push gate: +Both e2e suites run against **live devnet moutai** (forge-v2, protocol 14) and are not part +of the per-push gate: -* `make e2e` — the CLI suite (`e2e/cli/run.sh`, 7 scenarios). Needs the funded fixture +* `make e2e` — the CLI suite (`e2e/cli/run.sh`, 11 scenarios). Needs the funded fixture identities described in `e2e/cli/config.sh` under - `~/.config/dash-forge/test-identities/`. + `~/.config/dash-forge/test-identities/devnet-moutai/` (OWNER, COLLAB, CONTRIB). * `cd forge-web && pnpm test:e2e` — the Playwright suite. `pnpm install` does not download browsers, so a fresh clone needs one extra step first: @@ -290,11 +294,13 @@ per-push gate: pnpm test:e2e ``` - The read-path, fallback-browse, zero-backend and a11y specs need only network access to - testnet; `auth-write.spec.ts` needs a funded identity. + The specs run against a moutai build and read the forge-v2 read fixture that + `forge-contracts/scripts/seed-v2-fixture.mjs` seeds (idempotent); the write specs need a + funded identity. -The `Testnet Nightly` workflow runs the read-only half unconditionally and the funded half -only when the fixture secrets are configured, reporting a clear SKIP when they are not. +The `Devnet Nightly` workflow seeds the v2 fixture, runs Playwright against a moutai build, +and runs the CLI suite on moutai. The funded jobs run only when the fixture secrets are +configured, reporting a clear SKIP when they are not. ## Notes for sandboxed / offline environments diff --git a/docs/FAQ.md b/docs/FAQ.md index e38b6a62d..b756b8da7 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -42,7 +42,7 @@ You, directly, and only for what you write. Platform fees come from your identit ## How much does it cost? -On forge-v2, creating a repository will cost about **0.001 DASH**. A push to your own bucket costs about **0.0003 DASH** today. On today's testnet (v1) a repository costs about 1.18 tDASH, which is free test money. Storing packs on Platform costs about 0.28 DASH per MiB. The full table is in [Costs](guides/costs.md). +Creating a repository costs about **0.001 DASH**. A push to your own bucket costs about **0.0003 DASH**. Storing packs on Platform costs about 0.28 DASH per MiB. On devnet moutai all of it is paid in free test Dash. The full table is in [Costs](guides/costs.md). ## When is it on mainnet? @@ -50,10 +50,12 @@ After **Dash Platform protocol 14** activates on mainnet. forge-v2 depends on pr | Network | Status | |---|---| -| **Testnet** | v1 is live: one contract per repository, token-based access. Protocol 14 is expected on testnet shortly before mainnet. | -| **Devnet moutai** | forge-v2 contracts are registered. The CLI and web app cannot use them yet; client support is landing now. | +| **Devnet moutai** | Live. forge-v2 is registered, and `dg`, `git-remote-dash` and forge.dashhq.org use it. | +| **Testnet** | Not deployed. Testnet runs protocol 13; forge-v2 is registered there when protocol 14 reaches it, shortly before mainnet. | | **Mainnet** | Not deployed. The forge-v2 contracts will be registered once protocol 14 is active. | +An earlier version of Forge (forge-v1, one contract per repository) ran on testnet. It was removed on 2026-09-26 with no backwards compatibility, so its repositories cannot be read or migrated. + `dg doctor` shows which network you are on, its protocol version, and whether forge-v2 is deployed there. ## Can I have private repositories? @@ -80,7 +82,7 @@ No. Your repositories are on Platform and in your storage. Your identity survive ## I lost my 12 words and my identity file. -Then that identity is gone. Nobody can recover it, and nobody can sign as it again. Everything it published stays readable and clonable. Its repositories can no longer gain or lose members, because only the owner can change membership. On forge-v2, members it already added can keep pushing; on v1, token holders can too. To carry on under a new identity, create a new repository and push your clone to it. [Keep the words safe.](guides/identity-and-keys.md#backup-and-recovery) +Then that identity is gone. Nobody can recover it, and nobody can sign as it again. Everything it published stays readable and clonable. Its repositories can no longer gain or lose members, because only the owner can change membership. Members it already added can keep pushing. To carry on under a new identity, create a new repository and push your clone to it. [Keep the words safe.](guides/identity-and-keys.md#backup-and-recovery) ## Where do I report a bug? diff --git a/docs/architecture.md b/docs/architecture.md index ae8aa4889..714bd2c5a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2,30 +2,32 @@ Follows `../INIT.md` (design path & PRDs); deviations forced by verified platform constraints are listed in [init-reconciliation.md](init-reconciliation.md). +The on-chain model is **forge-v2**: two shared contracts, forge-core and forge-collab, in one Platform protocol 14 contract group. The full specification is [contracts/forge-v2.md](contracts/forge-v2.md). (forge-v1, a global registry contract plus one contract per repository with token access control, was removed on 2026-09-26 with no backwards compatibility.) + ## 1. Goals and non-goals **Goals** - Zero backend: Platform is the sole source of truth; every other component is a static asset, a local tool, or an *interchangeable, integrity-irrelevant* daemon anyone can run (relay). - Trustless reads: refs/manifests proof-verified from Platform; content verified by SHA-256 + git OIDs. A third party can verify a full clone from Platform data alone. - Real git: standard `git` (and jj's git backend) via a remote helper; `gh`-shaped CLI. -- Cost as first-class UX: estimates before every write batch, DASH primary / USD secondary, repack-with-refund keeps steady-state cost ≈ current repo size. +- Cost as first-class UX: estimates before every write batch, DASH primary / USD secondary; a repository costs ~0.001 DASH to create, and bulky pack bytes can live in storage the user brings. - Migration path: one-command GitHub import. -**Non-goals (v1)**: private repos (v2 encryption design in Phase 4), on-chain fast-forward/merge validation (reflog auditability instead — explicit INIT.md limit), Actions-equivalent (CI is external by design, bridged via relay), global cross-repo search, notifications inbox (poll badge only), wikis (`docs/` convention). +**Non-goals (first release)**: private repos (Phase 3 design: [security/private-repos.md](security/private-repos.md)), on-chain fast-forward/merge validation (reflog auditability instead — explicit INIT.md limit), Actions-equivalent (CI is external by design, bridged via relay), global cross-repo search, notifications inbox (poll badge only), wikis (`docs/` convention). ## 2. Components ``` ┌───────────────────────────────────────────────────────┐ - │ Dash Platform │ - │ registry contract repo contract (per repo, │ - │ (repoListing, profile, │ from versioned template): │ - │ star, follow) │ refUpdate, protectedRefUpdate, - │ │ packManifest, manifestPart, │ - │ │ chunk, issue, comment, patch, - │ │ review, release, label, │ - │ │ checkRun, webhook, event │ - │ │ + WRITE / MAINTAIN tokens │ + │ Dash Platform (contract group dash-forge) │ + │ forge-core contract │ forge-collab contract │ + │ repo, maintainer, │ issue, patch, comment, │ + │ writer, config, │ review, event, authorEvent,│ + │ refUpdate, │ checkRun, webhook, │ + │ protectedRefUpdate, │ profile, star, follow │ + │ packManifest, │ │ + │ manifestPart, chunk, │ all keyed by repoId; │ + │ release, label, repoKey │ writes gated by membership │ └────────▲───────────────▲───────────────▲──────────────┘ │ DAPI (proofs) │ │ block/ST stream ┌───────────────────┴───┐ ┌───────┴────────┐ ┌───┴───────────────┐ @@ -47,46 +49,44 @@ Follows `../INIT.md` (design path & PRDs); deviations forced by verified platfor ## 3. Naming & resolution -`dash://alice/project` → DPNS name → identity → registry `repoListing` by unique `(ownerId, normalizedName)` → repo contract ID → repo-contract `config` (defaultBranch, backend descriptor, protected patterns). Direct identity-ID form supported. Web routes use query params (static export). +`dash:///` → owner identity (base58 id; DPNS names are a later addition) → forge-core `repo` by unique `($ownerId, name)` → `repoId` → newest `config` for that `repoId` (defaultBranch, backend descriptor, protected patterns). `dash://` names a `repo` document directly. Contract ids come only from `forge-contracts/deployments/.json` (`v2` section); a network without a forge-v2 deployment fails with "not deployed" and never falls back to another network. Web routes use query params (static export). -## 4. On-chain model (summary — full schemas in [data-contracts.md](contracts/data-contracts.md)) +## 4. On-chain model (summary — full schemas and rules in [contracts/forge-v2.md](contracts/forge-v2.md)) -### 4.1 Registry contract (deployed once; DCG/DAO-owned identity) -Discovery + social graph only: `repoListing` (name, repoContractId, description, topics, forkOf; indexed owner+name and name; count-trees for repo/fork counts), `profile`, `star`, `follow` (count-trees for stars/followers). Operational settings live in the repo contract so MAINTAIN collaborators can change them. +### 4.1 Contract topology +Two shared contracts, registered once per network by one deployer identity and joined by a protocol 14 **contract group** (`dash-forge`). Every repository is a set of documents in them, keyed by the `repo` document's id (`repoId`). Creating a repository writes three documents: `repo`, the owner's `maintainer` membership, and the first `config`. -### 4.2 Repo contract (per repository, from canonical template) -- **Settings**: `config` — append-only, non-deletable, MAINTAIN-gated (defaultBranch, protected-ref patterns, backend descriptor). Append-only history makes protection evaluable *as-of any past update*. -- **Git data**: append-only, **non-deletable** `refUpdate` (ref name-hash, old/new OID, force flag — ref state *and* reflog; reconciliation D2) and `protectedRefUpdate` (MAINTAIN-gated); `packManifest` (pack SHA-256, size, chunk count, external URIs, supersedes list, per-object offset index with `manifestPart` continuation docs), `chunk` (seq + 3 × ~4.9 KiB byte fields; count-tree gives O(1) availability audits). -- **Collaboration**: `issue`, `comment`, `patch` (PR), `review`, `release`, `label`, `event` (close/reopen/merge/label/assign audit log — non-deletable), `checkRun` (CI results written by runner identities), `webhook` (relay subscription, secret encrypted to relay identity). Count-trees on issue/patch totals and per-target comment counts; open/closed splits are event folds (see data-contracts §3). +- **forge-core**: `repo` (the listing; `name` immutable, unique per owner), membership (`maintainer`, `writer`), **settings** (`config`: append-only, non-deletable, maintainer-gated; append-only history makes protection evaluable *as-of any past update*), **git data** (`refUpdate`, `protectedRefUpdate`, `packManifest`, `manifestPart`, `chunk`: all non-deletable), `release`, `label`, and `repoKey` (private repositories). +- **forge-collab**: `issue`, `patch` (PR), `comment`, `review`, `event` (member actions: close, reopen, merge, label, assign, ...), `authorEvent` (the target's author: close and reopen only), `checkRun` (CI results written by runner identities), `webhook` (relay subscription, secret encrypted to the relay identity), and the social graph (`profile`, `star`, `follow`). Open/closed state is a fold over `event` + `authorEvent`. -### 4.3 Token ACL (the authorization system) -- Tokens at position 0 (`WRITE`) and 1 (`MAINTAIN`), mintable/freezable by the contract owner, with **control-rule groups** so org admin powers can be held by multiple identities. -- `tokenCost` on write-path types: `refUpdate`, `chunk`, `packManifest`/`manifestPart`, `checkRun` → 1 WRITE; `protectedRefUpdate`, `release`, `label`, `webhook`, `config` → 1 MAINTAIN. Social types (`issue`, `comment`, `review`, `patch`) are un-gated — platform fees are the spam floor (patch gating: open question D3). Contract updates (template migrations) are **owner/control-group only** — Platform does not token-gate `DataContractUpdate`. -- Tokens carry `baseSupply: 10⁹` credited to the owner atomically at contract creation — no self-mint bootstrap step exists to forget. -- Grant = mint 10⁹ units (spend is a meter, not the control); suspend = freeze; revoke = freeze + destroy frozen funds. Balances publicly queryable → **the collaborator list is on-chain for free**. -- **Delete-gating**: `tokenCost` also applies to `delete` on chunks/manifests/releases — a frozen identity cannot yank the availability of what it previously uploaded. Ref/event/config docs are non-deletable outright (rewind-proof audit trail). -- Because creation is consensus-gated, clients resolve refs by *newest refUpdate per name* — no client-side authorization judgment needed (a frozen identity's push fails at consensus; INIT.md acceptance test). Protected refs add one client rule: updates to a pattern-matched ref only count if they are MAINTAIN-gated `protectedRefUpdate` docs, evaluated as-of each update's consensus time against the append-only config history (normative algorithm in data-contracts §4). +### 4.2 Membership gates (the authorization system) +- Access is **membership documents** in forge-core: `maintainer` and `writer`, unique per `(repoId, memberId)`, created only by the repo owner (`dg collab add --role writer|maintainer`, `dg collab remove`, `dg collab list`). The membership list is on-chain and publicly queryable. +- Each gated type declares an `ownerRefersTo` rule that consensus checks on create: `refUpdate`, `packManifest`, `manifestPart`, `chunk`, `label`, `event`, `checkRun` need a maintainer or writer document; `protectedRefUpdate`, `config`, `release`, `webhook`, `repoKey` need a maintainer document. `issue`, `patch`, `comment`, `review` are un-gated; platform fees are the spam floor. +- **Revoke = delete the membership document.** The member's next gated write is refused at consensus (Platform error 40120). Past documents stay valid: a document's existence proves its writer was authorized at its block time. +- **Non-deletable audit types** (`refUpdate`, `protectedRefUpdate`, `config`, `packManifest`, `manifestPart`, `chunk`, `event`, `authorEvent`, `issue`, `patch`, `repo`, `repoKey`): Platform never reference-checks a delete, so these types forbid deletion outright, which makes branch rewinds and yanking packs others depend on impossible. +- Because creation is consensus-gated, clients resolve refs by *newest refUpdate per name*, with no client-side authorization judgment (a revoked or never-member identity's push fails at consensus; INIT.md acceptance test). Protected refs add one client rule: updates to a pattern-matched ref only count if they are maintainer-gated `protectedRefUpdate` docs, evaluated as-of each update's consensus time against the append-only config history. +- Contract updates are owner-only and cannot loosen an existing gate (protocol 14 freezes indexes and `ownerRefersTo` on update). ## 5. Storage model -**Platform is primary storage** and always holds refs + manifests. The backend descriptor (in the repo contract's `config`) selects where **pack bytes** live: +**Platform is primary storage** and always holds refs + manifests. The backend descriptor (in the repo's `config`) selects where **pack bytes** live: | Backend | Pack bytes | Cost profile | Trust | |---|---|---|---| -| `platform` (default) | `chunk` docs, ~14.4 KiB payload each (3 × 4.8 KiB fields), one ST per chunk | ~0.283 DASH/MiB (~$9/MiB @ $34), **refundable**; repack+delete reclaims superseded storage | Fully on-chain | +| `platform` (default) | `chunk` docs, ~14.4 KiB payload each (3 × 4.8 KiB fields), one ST per chunk | ~0.283 DASH/MiB (~$9/MiB @ $34), **permanent**: `chunk` and `packManifest` are non-deletable, so the deposit is never refunded | Fully on-chain | | `ipfs` | CID in manifest; pin via Storacha/Pinata/self-host Kubo | Pinning costs only | Hash-verified cache | | `s3` / `https` | URL in manifest | Hosting costs only | Hash-verified cache | | **mixed** | Recent packs on Platform, archival packs external | Best of both | — | - Pack = unit of storage. **Stored packs are always self-contained and locator-quality**: every delta base is inside the pack, ahead of the deltas that use it, and the producer refuses anything else. Storing the `index-pack --fix-thin` pack directly does not qualify — completion appends the bases after the deltas — so a push builds two candidates (the delta packed non-thin; the completed pack re-emitted bases-first) and stores the smaller; neither dominates (`economics.md`). O(bytes/14 KiB) STs, not O(objects). - Partial clone & single-object reads: the merged `objectLocator` (§6.3) → ranged `chunk` fetch by seq (or HTTP Range on external backends); packs pushed since the last repack are covered by their own index fragments. The one-contiguous-span read is sound for **blobs** (OFS_DELTA bases sit earlier in the same pack after repack); **trees need the per-base delta-chain fallback** (a single span over-fetches them catastrophically — §6.3). **Shallow clone (`--depth`) is out of scope** — a fetch/push helper gives git no reply channel to serve depth negotiation (S0.9); partial clone (`--filter=blob:none` + `.promisor` markers) is the supported subsetting path, and `--depth` fails loudly. -- **Repack/GC** (`dg repack`): rewrite history into one optimized pack, upload, delete superseded chunk/manifest docs → storage refund. Long-lived repo cost ≈ current size, not cumulative pushes. +- **Repack** (`dg repack`): rewrite history into one optimized pack and upload it as a superseding pack. On the Platform tier this only consolidates (fewer packs to read); it deletes nothing, because the old chunks and manifests are non-deletable. Garbage collection applies only to external storage the user controls. - Availability for external backends: multiple URIs per manifest + anyone-can-reseed (`packMirror`-style additional-URI docs, `dg reseed`); loss is availability-only, never integrity, and any clone can restore. ## 6. Data flow ### Push (`git push dash://alice/project main`) -1. Helper resolves listing → repo contract; reads refs (proof-verified); builds **one self-contained, locator-quality pack** over the push delta. +1. Helper resolves `repo` → `repoId`; reads refs (proof-verified); builds **one self-contained, locator-quality pack** over the push delta. 2. **Cost estimate displayed; prompt above configurable threshold** (`dash.costWarnThreshold`). 3. Upload pack per backend (chunk STs pipelined with sequential nonces — batch=1 constraint, see D1); journal file records uploaded chunk IDs → **interrupted push resumes without re-paying**. 4. Write `packManifest`, then the pack's **browse-index fragment** (§6.3) — best-effort, since the pack is already stored and paid for, and a repo whose index is behind still clones, fetches and pushes. Then `refUpdate` per ref (prevOid for force detection; non-FF refused without `+`). @@ -94,10 +94,10 @@ Discovery + social graph only: `repoListing` (name, repoContractId, description, 6. **Post-push verification**: re-read ref state — Platform has no CAS, so a concurrent same-prevOid push by another maintainer also lands; the helper reports a lost race as a late non-fast-forward instead of silently orphaning commits (divergence rules: data-contracts §2.3). ### Clone/fetch -Resolve listing → refs → collect non-superseded manifests covering want-set → fetch chunks (DAPI) or CID/URL (external) → SHA-256-verify reassembled pack → `git index-pack`. **Partial clone** via the `objectLocator` (bare-OID fetches + `.promisor` markers); **shallow clone is unsupported** — the helper has no reply channel for git's depth negotiation (S0.9), so `--depth` fails loudly. Local git odb is the cache (helper never re-fetches objects git has). +Resolve `repo` → refs → collect non-superseded manifests covering want-set → fetch chunks (DAPI) or CID/URL (external) → SHA-256-verify reassembled pack → `git index-pack`. **Partial clone** via the `objectLocator` (bare-OID fetches + `.promisor` markers); **shallow clone is unsupported** — the helper has no reply channel for git's depth negotiation (S0.9), so `--depth` fails loudly. Local git odb is the cache (helper never re-fetches objects git has). ### Web browse (no clone) — the browse plane -Browsing never materializes the repo. Two auxiliary **browse artifacts** (stored/transported exactly like packs — content-addressed, chunked or external, supersedable with refunds; `packManifest.kind` distinguishes them) make every view a handful of small ranged reads: +Browsing never materializes the repo. Two auxiliary **browse artifacts** (stored/transported exactly like packs — content-addressed, chunked or external, supersedable; `packManifest.kind` distinguishes them) make every view a handful of small ranged reads: - **`objectLocator`** — a merged multi-pack index (git MIDX analog): fanout header + oid-sorted entries of `(oid → pack, offset, length, deltaChainSpan, deltaHint)`. ~34–36 B/object (S0.5-corrected widths: `deltaChainSpan` 4-byte varint, `length` 4 B — see data-contracts §2.3); the fanout means a lookup fetches the header plus one ~1/256 slice by HTTP Range / chunk seq. **Single-span read works for blobs** — after `repack -adf` all bases are OFS_DELTA earlier in the same pack, so `deltaChainSpan` yields one contiguous ranged read returning the blob and its bases (median 1.21× over-fetch). **Trees are the exception** — a contiguous span over-fetches catastrophically (root tree measured 212×), so above a span threshold readers use the `deltaHint` to walk each delta base individually instead. **Published in fragments, one per stored pack** (`RepoService::publish_push_locator`): a push publishes a locator over just the pack it stored, so the write costs 36 B per object the push actually ADDED rather than republishing the whole index — on a 40k-object repo that is the difference between a few KB and ~1.4 MB of `chunk` deposits to record a one-file change. A reader merges the live fragments (`ObjectLocator::merge`, mirrored in forge-web). Fan-out is bounded the other way by folding: once the live fragment count would exceed 16, the push merges them into one locator and supersedes the parts, and a repack rebuilds the whole index as a single artifact. A reader that finds the live fragments do NOT cover every live pack reports the index as behind and falls back to the in-browser clone — it never serves reads through an index that would miss recent objects. - **`flatIndex`** — the tip's complete recursive file listing (`path → oid, mode, size`, path-sorted, compressed), i.e. GitHub's tree API as one static artifact. **It is O(files), not "tens of KB": S0.5 measured ~471 KB @ 10k files and ~4.5 MB @ 100k files.** Gives instant tree navigation at any depth *and* client-side filename search with zero object fetches — but because it scales with the tree, **cold repo-home must NOT eagerly fetch it**. Published on default-branch pushes, batched for hyperactive repos (every 20 pushes / 24 h); readers overlay the ≤ 20 commits since the indexed tip via locator tree-diffs, so views are always current without a full walk. Other refs fall back to object walking. @@ -109,22 +109,23 @@ No document subscriptions → web/CLI poll indexed queries with cursors; **relay ## 7. Cross-client parity -Ref-resolution, event-folding, and cost-estimation rules are versioned (`FORGE_RULES_V1`) with **shared conformance vectors** (JSON fixtures) consumed by the Rust workspace tests and forge-web tests alike — the only defense against Rust/TS divergence. On the forge-v2 contracts, consensus enforces who may write each type, and the rules that remain client-side are listed in [`contracts/forge-v2.md`](contracts/forge-v2.md) §6: event kinds by role (§3 there), issue/PR numbering, PR approvals, the pack and repoKey reader rules, and the plaintext-or-`enc` rule. +Client-side rules are versioned (`FORGE_RULES_V2`: `forge-core::rules::v2`, `forge-web/lib/rules/v2.ts`) with **shared conformance vectors** (JSON fixtures in `forge-contracts/vectors/`) consumed by the Rust workspace tests and forge-web tests alike — the only defense against Rust/TS divergence. Consensus enforces who may write each type; what remains client-side is listed in [`contracts/forge-v2.md`](contracts/forge-v2.md) §6: ref resolution, protected-pattern globs and the as-of config overlay, event kinds by role (§3 there), issue/PR numbering, PR approvals, the pack and repoKey reader rules, and the plaintext-or-`enc` rule. ## 8. Economics (full model: [economics.md](economics.md)) -- 27,000 credits/byte permanent storage (refundable, 50-era amortization); 1 DASH = 10¹¹ credits. +- 27,000 credits/byte storage deposit (refundable on delete, 50-era amortization; the non-deletable types never refund); 1 DASH = 10¹¹ credits. - On-Platform data ≈ **$9/MiB @ $34/DASH** (DASH-primary display; USD secondary; fee-multiplier governance lever flagged). -- Social artifacts are noise (2 KiB issue ≈ 2¢). Ref update ≈ 0.00008 DASH. Contract instantiation per repo ≈ **0.24 DASH** (S0.7-measured for a token contract; repo-v1 re-measured Stage 2). +- Social artifacts are noise (2 KiB issue ≈ 2¢). Ref update ≈ 0.00008 DASH. Creating a repository ≈ **0.001 DASH** (three documents; the v1 per-repo contract was ~1.18 DASH). +- forge-v2 registration: forge-core 0.60 + forge-collab 0.55 DASH in fees (1.161234 DASH measured on devnet moutai), paid once per network by the deployer ([forge-v2.md §7](contracts/forge-v2.md#7-measured-size-and-cost)). - Cost engine (forge-core) quotes every write batch pre-broadcast and tracks running spend (`dg cost`, web settings). ## 9. Security & trust -- Writes need AUTHENTICATION keys at HIGH; identity keys via keychain/agent (SSH-key UX shape). CI runners get their own identity holding WRITE tokens (optionally ContractBounds-scoped). +- Writes need AUTHENTICATION keys at HIGH; identity keys via keychain/agent (SSH-key UX shape). CI runners get their own identity with a `writer` membership (optionally a ContractBounds-scoped key). - Proof verification default-on in helper/CLI; web benchmarks trusted vs proof mode (S0.3). - Relay is availability-only: payload consumers (CI) re-fetch and verify from Platform; webhook secrets encrypted to relay identity; instances interchangeable. - Markdown/filename rendering sanitized (XSS), CSP per yappr static-export pattern. -- Top risks + open questions: see implementation plan risk register and init-reconciliation open questions (frozen-identity refunds, template migration, ST throughput). +- Top risks + open questions: see implementation plan risk register and init-reconciliation open questions (ST throughput), and roadmap decisions D-D/D-J (mainnet contract ownership and `config.readonly`). ## 10. Technology choices diff --git a/docs/contracts/data-contracts.md b/docs/contracts/data-contracts.md index 6bbc662c1..3efef7155 100644 --- a/docs/contracts/data-contracts.md +++ b/docs/contracts/data-contracts.md @@ -1,6 +1,6 @@ # Dash Forge — Data Contract Design (v3) -> **Superseded for protocol 14 by [forge-v2](forge-v2.md)**: two shared contracts (forge-core, forge-collab) with consensus writer gates replace the per-repo template and the registry described here. This document remains the reference for reading v1 repositories. +> **Historical — not implemented.** This document describes the forge-v1 design: a global registry contract plus one contract per repository from the `repo-v1` template, with WRITE/MAINTAIN token access control. It is superseded by [forge-v2](forge-v2.md) (two shared contracts, forge-core and forge-collab, with membership documents checked at consensus). forge-v1 was removed on 2026-09-26 with no backwards compatibility; no code reads or writes these contracts, and v1 repositories cannot be cloned. The body is kept unchanged as a design record. One global **registry contract** + **one repo contract per repository** from a versioned template (INIT.md). This revision adds: explicit count-tree assignments per user story, delete-gating via `tokenCost.delete`, a `config` document type that makes protected refs enforceable, non-deletable audit types (closing the ref-rewind hole), and an enforcement matrix stating exactly what consensus enforces vs what `FORGE_RULES_V1` client rules enforce. diff --git a/docs/contracts/forge-v2.md b/docs/contracts/forge-v2.md index 9dd2f58af..3e8089ada 100644 --- a/docs/contracts/forge-v2.md +++ b/docs/contracts/forge-v2.md @@ -1,17 +1,17 @@ # Dash Forge v2 contracts (protocol 14) -Two shared data contracts, **forge-core** and **forge-collab**, registered once per network and joined by a PV14 contract group. They replace the per-repo contract template (`templates/repo-v1.json`, token ACL) and the global registry (`contracts/registry.json`). Every repository is a set of documents in these two contracts, keyed by the `repo` document's id (`repoId`). +Two shared data contracts, **forge-core** and **forge-collab**, registered once per network and joined by a PV14 contract group. Every repository is a set of documents in these two contracts, keyed by the `repo` document's id (`repoId`). This is the only data model Dash Forge implements. - Schemas: `forge-contracts/contracts/forge-core.json`, `forge-contracts/contracts/forge-collab.json` - Offline validation: `tools/contract-validate` (rs-dpp `v4.2.0-beta.4`, `PlatformVersion` 14) - Registration: `forge-contracts/scripts/deploy-v2.mjs` (evo-sdk `4.2.0-beta.4`) - Decision record: roadmap D-A (owner decision of 2026-09-24, reviewed by a protocol architect) -## 1. Why the model changed +## 1. Why shared contracts -Under v1 each repository was its own contract. Write access came from two tokens (WRITE, MAINTAIN): a `tokenCost` on each write-path type, with freezing to suspend and destroying to revoke. That worked at consensus, but a repository cost about 1.18 DASH, most of it contract registration fees (base fee, plus a fee per document type, per index and per token), and a fork cost the same again. Nothing could make that cheap. +Contract registration is priced per contract (a base fee plus a fee per document type, per index and per token). A design where each repository is its own contract therefore pays that fee for every repository and every fork, whatever its size. That was forge-v1: a global registry contract plus one contract per repository, with access control by WRITE/MAINTAIN tokens, at about 1.18 DASH a repository. It was removed on 2026-09-26 with no backwards compatibility; [data-contracts.md](data-contracts.md) keeps its design for the record. -Protocol 14 can express the same access control inside a shared contract: +Protocol 14 can express per-repository access control inside a shared contract: - **`ownerRefersTo`**: a document type can require its writer (`$ownerId`) to be found through a unique index of another document type. Consensus checks this on create, and on every replace when the target is a `deletableDocument`. - **`lookup`** references resolve a key such as `(repoId, memberId)` through a unique index, so a membership document is enough; the writer does not have to name it. @@ -87,12 +87,12 @@ Both types are immutable and non-deletable, and the gate is judged at creation. | kind | from `event` (any M/W at write time) | from `authorEvent` | |---|---|---| | close, reopen | yes | yes | -| merge | yes, if `oid` is reachable from the base tip (the v1 predicate) | never (consensus refuses the kind) | +| merge | yes, if `oid` is reachable from the base tip | never (consensus refuses the kind) | | label+, label−, assign, unassign, retarget, draft, ready | yes | never | -An `authorEvent` whose `kind` is not close or reopen cannot exist on chain; the fold treats one handed to it as inert anyway, and ignores one whose writer is not `target_author`. Events of both types are merged into one log and ordered by `($createdAt, $id)`, the v1 order, with `$id` compared by Unicode code point (UTF-8 byte order; JavaScript's `<` compares UTF-16 code units and disagrees on astral characters, so the TypeScript port uses `compareStrings`). Documents with the same key keep their input order, `event`s first. A merged PR cannot be reopened, as in v1. +An `authorEvent` whose `kind` is not close or reopen cannot exist on chain; the fold treats one handed to it as inert anyway, and ignores one whose writer is not `target_author`. Events of both types are merged into one log and ordered by `($createdAt, $id)`, with `$id` compared by Unicode code point (UTF-8 byte order; JavaScript's `<` compares UTF-16 code units and disagrees on astral characters, so the TypeScript port uses `compareStrings`). Documents with the same key keep their input order, `event`s first. A merged PR cannot be reopened. -**Known design choices, kept from v1.** The author may reopen what a member closed, and a member can close it again; nothing stops the two alternating except fees. A member's approval counts on their own PR (§6), because a `review` does not know the PR's author; clients may show a self-approval distinctly. +**Known design choices.** The author may reopen what a member closed, and a member can close it again; nothing stops the two alternating except fees. A member's approval counts on their own PR (§6), because a `review` does not know the PR's author; clients may show a self-approval distinctly. ## 4. Non-deletable audit types @@ -108,7 +108,7 @@ Protocol 14 checks references on create and replace only; **a delete is never re **Platform-tier storage is permanent.** A chunk once written stays, so bring-your-own storage (S3-compatible, IPFS) is the cheap default and Platform chunks are the tier you pick for packs that must outlive every bucket. Consequences: - **Repack on the Platform tier only consolidates.** It writes a superseding pack (a new `packManifest` with `supersedes`, new chunks) and deletes nothing. Readers prefer the consolidated pack; the old one stays readable. -- **`dg repack` / GC must change**: today they delete superseded chunks and manifests for the refund (`crates/dg`, `forge-core::pack`). On v2 those deletes are refused at consensus, so the delete step goes, and GC applies only to external storage the user controls. +- **`dg repack` deletes nothing on Platform**: deleting superseded chunks and manifests would be refused at consensus. GC applies only to external storage the user controls. **Front-running.** Every pack-write unique index includes `$ownerId` (`packManifest (repoId, $ownerId, packHash)`, `manifestPart (…, partSeq)`, `chunk (…, seq)`). Without it, the first writer to claim a `(repoId, packHash)` would own that slot forever: a hostile writer could post a manifest with the right hash and wrong content, or one chunk, and block the honest upload. With it, each writer has its own slot. **Reader rule** (`FORGE_RULES_V2`: `order_pack_copies`, `select_pack_copy`, `pack_read_order`, vectors `pack_copies__*`): for a `packHash`, gather every writer's manifest (`(repoId, packHash)` index) and try them in order: uploaders who are currently maintainers, then current writers, then everyone else (members since revoked), each group by `$createdAt` then `$id`. Read the first copy whose reassembled bytes verify against `packHash`; a copy that fails verification is ignored, and a pack with no verifying copy is unreadable. A `supersedes` list is honoured only from the copy actually read, and only when it verifies. A superseded pack is read after the others as a fallback, never dropped: a hash proves a pack's bytes, not that it holds everything it claims to replace. @@ -120,7 +120,7 @@ Protocol 14 checks references on create and replace only; **a delete is never re 4. `packRef` is the pack's index, by first upload, **among the packs of its kind**: kind-0 git packs are numbered 0..n regardless of interleaved kind-1 index fragments. 5. A pack is superseded when another listed pack's representative names it in `supersedes` **and that representative verified**; an unchecked claim supersedes nothing. Superseded packs keep their `packRef` (positions never shift); readers skip them only when fetching whole packs, and read them as a fallback. -The function is kind-agnostic: callers pass every copy and select a kind from its output (the locator space is the kind-0 packs). It is not the v1 rule: v1 drops superseded packs from the packRef space (live kind-0 packs, oldest first), while v2 keeps them in place. The two agree only when nothing is superseded. v2 manifests are permanent, and a position that never moves means no locator ever needs renumbering; locators of v1 repositories keep the v1 rule. +The function is kind-agnostic: callers pass every copy and select a kind from its output (the locator space is the kind-0 packs). Superseded packs keep their place in the packRef space. Manifests are permanent, and a position that never moves means no locator ever needs renumbering. **Chunks referenced across repositories (forks).** A `platform://` locator names whose chunks it reads: `platform://///`. A fork records its parent's Platform-stored packs without re-uploading them: its `packManifest` has `storage = 1`, `chunkCount = 0`, and in `uris` the parent's chunk locators (`` = the parent), members' copies first, followed by any external URIs the parent's copies record. A reader of such a manifest reads the chunks from the named repo's scope, within the same forge-core contract only, and accepts only bytes that hash to the manifest's `packHash`; a locator naming another pack hash or another contract is ignored. `chunk` and `packManifest` are non-deletable, so the parent cannot pull the bytes out from under the fork. (Rust: `repo::fetch_artifact_from`, `fork.rs`; the web reader must follow these locators the same way, or a fork of a Platform-stored repository does not browse.) @@ -150,17 +150,17 @@ A private repo is a `repo` with `visibility: "private"`; `visibility` is immutab The AEAD layouts, key derivation, anchors, rotation and conformance vectors are specified in `docs/security/private-repos.md` (reviewed; normative where it differs from this section). The cryptographic core is `forge-core::private` and `forge-web/lib/private`, held in byte-for-byte parity by the `private_*` vectors. -## 6. What moves from client rules to consensus +## 6. What consensus enforces and what stays a client rule -| v1 (client rules / `FORGE_RULES_V1`) | v2 | +| Concern | Enforced by | |---|---| -| Push authorization: WRITE token spend | consensus: `ownerRefersTo` M or W | -| Protected refs: MAINTAIN spend on `protectedRefUpdate` | consensus: M gate. **Routing stays a rule**: consensus cannot read `protectedPatterns`, so a plain `refUpdate` naming a protected ref still exists and is inert by the as-of config rule — for ref resolution and for merge verification alike (`merge_base_tips`: the base history a merge is checked against holds only valid updates, so a plain update cannot put a PR head "on" a protected branch; vectors `merge_base_tips__*`, `fold_pr*__merge_via_*`) | -| Revocation: freeze (+ destroy) | delete the `maintainer`/`writer` document; the next write is refused (40120) | -| Event actor authorization, reconstructed as-of from token history | consensus at create time (§3): `event` is M/W only, `authorEvent` is the target's author with kind close/reopen only. **Merge reachability stays a rule**: `merge` needs `oid` reachable from the base tip | -| Listing authenticity (listing owner == repo contract owner) | gone: `repo` is the listing | -| Owner lock-out prevention (`baseSupply`) | client rule: the owner self-enrols as maintainer in the same session that creates the repo | -| Concurrent-push divergence, newest-wins resolution, ref-name glob matching, overlay | unchanged, still rules | +| Push authorization | consensus: `ownerRefersTo` M or W | +| Protected refs | consensus: M gate on `protectedRefUpdate`. **Routing is a rule**: consensus cannot read `protectedPatterns`, so a plain `refUpdate` naming a protected ref can exist, and it is inert by the as-of config rule — for ref resolution and for merge verification alike (`merge_base_tips`: the base history a merge is checked against holds only valid updates, so a plain update cannot put a PR head "on" a protected branch; vectors `merge_base_tips__*`, `fold_pr*__merge_via_*`) | +| Revocation | delete the `maintainer`/`writer` document; the next write is refused (40120) | +| Event actor authorization | consensus at create time (§3): `event` is M/W only, `authorEvent` is the target's author with kind close/reopen only. **Merge reachability is a rule**: `merge` needs `oid` reachable from the base tip | +| Repository listing | the `repo` document is the listing; its `$ownerId` is the owner | +| Owner lock-out prevention | client rule: the owner self-enrols as maintainer in the same session that creates the repo | +| Concurrent-push divergence, newest-wins resolution, ref-name glob matching, overlay | client rules (the base rules, shared by every client) | | Issue and PR numbering | client rule, see below | | PR approvals | client rule (`count_approvals`, vectors `approvals__*`): `review` is un-gated. Its input is the PR's reviews filtered by `is_well_formed` (§5) first. A review counts only if it is on the PR's current `headOid` and its reviewer had a current `maintainer`/`writer` document created at or before the review's `$createdAt`. Each reviewer's newest counting approve (1) or request-changes (2) review by `($createdAt, $id)` stands; comment (3) and unknown verdicts neither count nor clear. A revoked reviewer's document is gone, so their reviews stop counting. A member's approval of their own PR counts (§3, known design choices) | @@ -176,7 +176,7 @@ Gaps below `base` are never filled. A number above the ceiling cannot be reached **Repository names** (`is_valid_repo_name`, `normalize_repo_name`, vectors `repo_name__*`). A name is valid when it matches the contract's pattern `^[a-z0-9][a-z0-9._-]{0,62}$` in full; a trailing newline does not match. Clients lowercase ASCII `A`–`Z` in user input before checking, and change nothing else, so `Dash-Forge` names `dash-forge`. Other characters are not folded: `é`, or the Kelvin sign that Unicode lowercases to `k`, leaves the name invalid. -**Conformance.** `FORGE_RULES_V2` is `forge-core::rules::v2` (Rust) and `forge-web/lib/rules/v2.ts` (TypeScript). The shared vectors in `forge-contracts/vectors/` carry `"rules": "v2"`; a vector without `rules` is v1, and both harnesses dispatch on the field. The v2 rules are: +**Conformance.** `FORGE_RULES_V2` is `forge-core::rules::v2` (Rust) and `forge-web/lib/rules/v2.ts` (TypeScript). The shared vectors in `forge-contracts/vectors/` are dispatched on their `rules` field: a vector without one tests a base rule (ref resolution, protected-pattern matching, display ref name, overlay, verdict mapping), which `FORGE_RULES_V2` builds on, and `"rules": "v2"` tests one of the rules below: | Rule | Functions | Vectors | |---|---|---| @@ -195,8 +195,6 @@ Gaps below `base` are never filled. A number above the ceiling cannot be reached The v2 fold takes no membership input: an `event`'s existence is its authorization. `RoleOracle` answers "was X a member at time t" from the repo's *current* `maintainer`/`writer` documents, so a revoked member (whose document was deleted) is not a member at any time, and a re-added member counts from their new document. The repoKey reader rule of §5 is `resolve_epochs`, a pure function over flattened rows with `private_epoch__*` vectors; `comment.path` is a content field of `is_well_formed` (vector `well_formed__private_comment_plaintext_path`). -**Holdings vectors.** The `holdings__*` conformance vectors (token-history reconstruction) and the v1 `fold_issue__*` / `fold_pr__*` vectors do not apply to v2 repos. They stay, unchanged, for reading v1 repos. - ## 7. Measured size and cost From `tools/contract-validate` (rs-dpp v4.2.0-beta.4, `PlatformVersion` 14). The signed-shape transitions carry a 65-byte recoverable signature and the contract group fields. The deploy script's dry run built the same transitions with the evo-sdk wasm, signed them, and got the same byte counts. @@ -211,7 +209,7 @@ From `tools/contract-validate` (rs-dpp v4.2.0-beta.4, `PlatformVersion` 14). The `estimated_contract_max_serialized_size` (16,384 B) is not a limit. It is the size Drive's fee *estimation* assumes when it prices reading a stored contract (`apply_contract_with_serialization` v0). Both contracts are under it anyway. -Total one-time registration fees are **1.15 DASH**, paid once by the deployer, plus storage. A new repository is now three documents (`repo`, the owner's `maintainer`, the first `config`), about 0.001 DASH in storage by the 27,000 credits/byte rate, compared with ~1.18 DASH for a v1 repo contract. The per-repo figure is an estimate still to be measured on moutai. +Total one-time registration fees are **1.15 DASH**, paid once by the deployer, plus storage. A new repository is three documents (`repo`, the owner's `maintainer`, the first `config`), about 0.001 DASH in storage by the 27,000 credits/byte rate. `dg repo create` quotes an upper bound of 0.002 DASH before signing and reports the measured cost afterwards. **Measured on devnet moutai**, as the deployer's balance change. The current pair (2026-09-26, with the private-repository changes of `docs/security/private-repos.md` §13): diff --git a/docs/design-freeze-2.md b/docs/design-freeze-2.md index ab4b98d2e..b83e294b4 100644 --- a/docs/design-freeze-2.md +++ b/docs/design-freeze-2.md @@ -1,5 +1,7 @@ # Dash Forge — Design Freeze #2 (as-built) +> **Historical.** This records the as-built state of forge-v1 (a global registry contract plus one contract per repository, with token access control) on testnet in July 2026. forge-v1 was removed on 2026-09-26 with no backwards compatibility; the testnet contracts named here are no longer used. The current design is [forge-v2](contracts/forge-v2.md) and the current plan is [roadmap.md](roadmap.md). Findings about the Platform SDK, pack format and query behaviour still apply. + Design Freeze #1 (`spike-results.md`) froze decisions from the Phase-0 spikes. Design Freeze #2 records what the **implementation** actually established — the deviations, discoveries, and final decisions that emerged while building every component to a working, testnet-verified product. This is the "as-built" delta. ## Verified end-to-end on testnet diff --git a/docs/design/style-guide.md b/docs/design/style-guide.md index 4f71e31d7..9d0aa0308 100644 --- a/docs/design/style-guide.md +++ b/docs/design/style-guide.md @@ -53,7 +53,7 @@ colors: { ### Signature elements 1. **Verification chip** — every repo view carries a compact chip row: `refs ✓ proof · packs ✓ sha256 · src: platform/ipfs/s3`. Colors per semantic palette. Clicking opens the trust panel explaining the verification chain. 2. **Cost preview** — any write button shows cost inline before signing, **DASH primary, USD secondary** (`~0.0003 DASH ≈ $0.01`); destructive deletes show refund estimate in green. Running spend surfaced in settings. -3. **Identity pill** — DPNS name + dicebear avatar (yappr generator) + abbreviated identity id; consistent everywhere an owner/author appears. Collaborators shown with token-role badge (WRITE/MAINTAIN). +3. **Identity pill** — DPNS name + dicebear avatar (yappr generator) + abbreviated identity id; consistent everywhere an owner/author appears. Members shown with a role badge (writer/maintainer). 4. **Backend badge** — `⛓ platform` / `🌐 ipfs|s3|https` / `⛓+🌐 mixed` on repo headers and clone box. ### Accessibility @@ -64,7 +64,7 @@ colors: { ### Rust (forge-core, git-remote-dash, dg, forge-relay, forge-import) - One cargo workspace; edition 2021+; `clippy -D warnings`, `rustfmt` CI-enforced; `#![forbid(unsafe_code)]` outside vetted FFI. - Depend on rs-sdk/rs-dpp workspace-pinned to a Platform release tag; SDK touched only inside `forge-core::platform` (PlatformClient) — binaries consume forge-core services. -- Errors: `thiserror` taxonomy mirroring the product error classes (insufficient credits → bridge link, frozen token, timeout-retryable…); every user-facing failure maps to an actionable message. +- Errors: `thiserror` taxonomy mirroring the product error classes (insufficient credits → bridge link, not a member (write refused at consensus), timeout-retryable…); every user-facing failure maps to an actionable message. - All Platform writes via WriteEngine (idempotent ST lifecycle + journal); no ad-hoc document creation. - Secrets: OS keychain/agent only; no WIF/mnemonic in logs, journals, or `Debug` impls (newtype with redacted Debug). @@ -75,9 +75,9 @@ colors: { - Heavy work (materialization, search indexing, pack assembly) in web workers; main thread renders. ### Cross-language parity -- Ref-resolution / event-fold / cost rules exist twice (Rust + TS) by necessity → both implement `FORGE_RULES_V1` against **shared JSON conformance vectors** (`forge-contracts/vectors/`); CI runs both suites on every vector change. +- Ref-resolution / event-fold / cost rules exist twice (Rust + TS) by necessity → both implement `FORGE_RULES_V2` against **shared JSON conformance vectors** (`forge-contracts/vectors/`); CI runs both suites on every vector change. - Every list read: index-backed orderBy + cursor pagination; never assume < 100 results. -- Constants (contract IDs, template versions, fee schedule) generated from `forge-contracts/deployments/*.json` into both languages. +- Constants (contract IDs, fee schedule) generated from `forge-contracts/deployments/*.json` into both languages. ### Repo layout (monorepo) ``` @@ -87,13 +87,13 @@ crates/ dg/ # CLI bin (clap; gh-style aliases) forge-relay/ # webhook daemon forge-import/ # importer (Forgejo-semantics mapping) -forge-contracts/ # registry + repo template JSON, deploy scripts, deployments/, vectors/ +forge-contracts/ # forge-v2 contract JSON (forge-core, forge-collab), deploy-v2 + fixture scripts, deployments/, vectors/ forge-web/ # Next.js static app (pnpm) spikes/ # Phase 0 throwaway prototypes ``` ### Quality gates -- CI: cargo test/clippy/fmt + TS typecheck/lint/vitest + builds on every PR; testnet integration suite nightly + pre-release (see e2e plan). +- CI: cargo test/clippy/fmt + TS typecheck/lint/vitest + builds on every PR; devnet (moutai) integration suite nightly + pre-release (see e2e plan). - Conventional commits; PRs small and single-purpose. - Logging: `tracing` (Rust) / `debug` namespaces (TS); helper honors git's `GIT_TRACE` conventions. - Cost discipline: any code path that broadcasts a state transition must route through CostEngine so estimates/audits never drift from reality. diff --git a/docs/design/ux-dx-spec.md b/docs/design/ux-dx-spec.md index 600d0d0f3..76e96a5f6 100644 --- a/docs/design/ux-dx-spec.md +++ b/docs/design/ux-dx-spec.md @@ -258,7 +258,7 @@ Footer, always: *"This app is served by GitHub Pages. If you don't trust that, p ### 6.3 Degraded states - **Storage unreachable** (refs fine, no pack readable): a card, not a spinner: *"Code unavailable right now. The places this repo stores its files didn't answer: `pub-9a1.r2.dev` (timed out), `ipfs` (not found on 3 gateways). Branches, issues and pull requests are unaffected."* Buttons **Try again** · **Add a gateway**; for members: *"Have a clone? `dg reseed alice/project --from-local` restores it."* Rail row 4 reads *Failed* with the same list. - **Partial data**: show what arrived plus a sticky footer *"Showing 340 of 512 — Platform answered slowly. Loading the rest…"*; totals come from countable indexes so they stay honest. -- **Network not deployed** (mainnet before PV14): read-only chrome and one card: *"Dash Forge isn't on mainnet yet (waiting for Platform v14). Browse testnet → · Follow progress →"*. No "New repo" button exists in that state. +- **Network not deployed** (a network with no forge-v2 deployment, e.g. mainnet or testnet before PV14): read-only chrome and one card: *"Dash Forge isn't on mainnet yet (waiting for Platform v14). Browse the devnet build → · Follow progress →"*. No "New repo" button exists in that state, and the app never falls back to another network's contracts. - **Private repo, non-member**: name, owner, size, last activity, member count, and *"Private: contents are encrypted for members. You're not one."* No decrypted string ever renders, titles included. --- diff --git a/docs/economics.md b/docs/economics.md index 551632b14..17cfd8e82 100644 --- a/docs/economics.md +++ b/docs/economics.md @@ -1,6 +1,6 @@ # Dash Forge — Storage Economics & Fee Minimization -How bytes are compressed before they ever hit Platform, what each byte costs, and how obsolete data is deleted and refunded. Constants verified in `../platform` (protocol v12 era). +How bytes are compressed before they ever hit Platform, what each byte costs, and which data can be deleted and refunded. Constants verified in `../platform` (protocol v12 era). The on-chain model is forge-v2 ([contracts/forge-v2.md](contracts/forge-v2.md)); the user-facing summary is [guides/costs.md](guides/costs.md). ## 1. Compression: blobs are never stored raw @@ -23,26 +23,26 @@ Additional levers on top: |---|---|---| | Aggressive repack (`git repack -F --window=250 --depth=100` equivalent) | typically 10–30% over default packing | `dg repack` always uses max-effort settings — CPU is free, bytes cost 27k credits each | | Per-push browse-index fragment | *mandatory* for git packs (36 B per object **in that push** — an incremental push indexes a handful of objects) | it is the only random-access path to objects newer than the last repack; skipping it would break fresh-push browsing | -| Browse artifacts (`objectLocator` ~34–36 B/object, `flatIndex` O(files): ~471 KB @ 10k files, ~4.5 MB @ 100k — S0.5) | *cost*, not saving: ~3.5 MB locator + ~4.5 MB flatIndex ≈ **~8 MB deposit** for a 100k-object repo on platform backend (negligible external) | supersedable — steady-state deposit is one copy; the locator is published as per-push fragments and folded every 16, so a push pays for its own objects rather than republishing the whole index; flatIndex batched on hyperactive repos (20 pushes / 24 h) | +| Browse artifacts (`objectLocator` ~34–36 B/object, `flatIndex` O(files): ~471 KB @ 10k files, ~4.5 MB @ 100k — S0.5) | *cost*, not saving: ~3.5 MB locator + ~4.5 MB flatIndex ≈ **~8 MB deposit** for a 100k-object repo on platform backend (negligible external) | supersedable, but on the Platform tier a superseded artifact's chunks stay (non-deletable), so each republish adds to the permanent deposit; the locator is published as per-push fragments and folded every 16, so a push pays for its own objects rather than republishing the whole index; flatIndex batched on hyperactive repos (20 pushes / 24 h) | | zstd-wrapping chunks | marginal (~3–8%, pack is already deflated) | evaluated in S0.2; only adopted if measured gain beats the added format complexity | ## 2. What a byte costs (credits; 1 DASH = 10¹¹ credits) | Component | Credits/byte | Refundable? | Source | |---|---|---|---| -| Storage (prepaid, ~50-year horizon) | **27,000** | **Yes** (see §3) | `fee/storage/v1.rs` | +| Storage (prepaid, ~50-year horizon) | **27,000** | **Yes, for deletable types** (see §3) | `fee/storage/v1.rs` | | Storage processing | 400 | No | same | | ST processing | 12 | No | `default_costs/constants.rs` | | Per-document bases (write 6,000 + seek 2,000 + ST base 10,000) | ~18k/doc (~1.2 credits/byte at 15 KiB fill) | No | same | Two headline numbers fall out: -- **A retained byte costs ~27,400 credits** (~$9.30/MiB @ $34/DASH) — almost all of it a refundable deposit. -- **A churned byte** (stored, then deleted after a repack) permanently costs only the **non-refundable ~1.5%** (≈ 412 credits + the elapsed-epoch share of storage, §3) ≈ **~$0.15–0.30/MiB**. +- **A retained byte costs ~27,400 credits** (~$9.30/MiB @ $34/DASH) — almost all of it a storage deposit. +- **Pack bytes on the Platform tier are permanent.** `chunk`, `packManifest` and `manifestPart` are non-deletable on forge-v2 (owner decision 2026-09-25: an unbreakable repository outweighs the refund), so their deposit is a one-time cost, never refunded. A byte in a *deletable* document (comment, review, release, label, ...) that is later deleted permanently costs only the **non-refundable ~1.5%** (≈ 412 credits + the elapsed-epoch share of storage, §3). -This is why chunk geometry maximizes fill (3 × 4,900 B fields → ~14.4 KiB/doc): per-doc base fees amortize to noise, and why external backends exist: a manifest-only push is a few hundred bytes total. +This is why chunk geometry maximizes fill (3 × 4,900 B fields → ~14.4 KiB/doc): per-doc base fees amortize to noise, and why external backends exist: a manifest-only push is a few hundred bytes total, and bulky pack bytes in a bucket the user controls can be garbage-collected there. -**Token spend is not a cost — it recirculates.** The WRITE token a push spends (and the MAINTAIN token a protected/config write spends) is **not burned**: `tokenCost` payments flow to the **contract owner's** token balance (S0.7), so the unit spent on a push returns to the repo owner rather than being destroyed. The token is a per-collaborator meter, not a fee — the only real money on a push is the storage deposit (mostly refundable) plus the small non-refundable processing burn above. Don't read the WRITE token as a spam floor that consumes value; it circulates within the repo. +Writing requires a `maintainer` or `writer` membership document, which consensus checks on create; membership carries no per-write charge. The only money on a push is the storage deposit plus the small non-refundable processing burn above. ## 3. Refunds: how deletion gives money back @@ -53,40 +53,42 @@ Mechanics (verified: `fee/epoch/distribution.rs::calculate_storage_fee_refund_am - Delete within weeks-to-months of writing → recover the overwhelming majority of the deposit (the elapsed slice of a 50-year schedule). The refund lands as identity credits, immediately spendable on the next push. - Processing fees (the ~412 credits/byte + bases) are never refunded — that's the true "cost of churn." -Constraints that shape the GC design: +Constraints: -- **Only the document's owner can delete it** — refunds are per-uploader. Each collaborator prunes (and recoups) their own docs. -- **Frozen identities can't pay `tokenCost.delete`** — a revoked collaborator's chunks stay put (availability protected); their deposit stays locked with the docs. The repo can re-store those objects in a new pack and simply carry the orphan cost. -- **Non-deletable audit types** (`refUpdate`, `protectedRefUpdate`, `event`, `config`) forgo refunds deliberately — the rewind-proof audit trail is worth more than the ~0.00008 DASH each. Honesty about aggregates: this line **grows unbounded with activity and is never reclaimed** — ~0.08 DASH per 1,000 pushes, so a monorepo with 50k historical pushes has ~4 DASH (~$135) permanently locked in reflog. The "steady-state ≈ current size" promise (§4) applies to the *pack store*; the audit log is a separate, slow-growing permanent line item. A checkpoint/compaction scheme for ancient reflog is a named open design question (not v1). +- **Only the document's owner can delete it** — refunds are per-writer. A delete is never reference-checked, so this holds even after the writer's membership is revoked. +- **Non-deletable types forgo refunds deliberately** ([forge-v2.md §4](contracts/forge-v2.md#4-non-deletable-audit-types)): `refUpdate`, `protectedRefUpdate`, `config`, `packManifest`, `manifestPart`, `chunk`, `event`, `authorEvent`, `issue`, `patch`, `repo`, `repoKey`. Deleting any of them would let a writer rewind a branch, rewrite a thread, or pull pack bytes out from under refs that other people's history points into. Still deletable, and so refundable to their author: `comment`, `review`, `release`, `label`, `checkRun`, `webhook`, `profile`, `star`, `follow`, and the membership documents. +- Honesty about aggregates: the audit trail **grows unbounded with activity and is never reclaimed** — ~0.08 DASH per 1,000 pushes in ref updates alone, so a monorepo with 50k historical pushes has ~4 DASH (~$135) permanently locked in reflog. A checkpoint/compaction scheme for ancient reflog is a named open design question. -## 4. How old, no-longer-relevant data actually gets deleted +## 4. Old, no-longer-relevant data -Git never deletes eagerly and neither does Forge — objects become *unreachable* (force-push, branch delete, PR closed unmerged) and are collected at repack: +Git never deletes eagerly and neither does Forge — objects become *unreachable* (force-push, branch delete, PR closed unmerged). What happens to them depends on where the packs live. -1. **`dg repack`** builds one consolidated max-compression pack of all *currently reachable* objects and uploads it (platform chunks or external). -2. New `packManifest` lists `supersedes: [old packHashes]` — readers immediately prefer it. -3. The repacker **deletes their own superseded `chunk`/`packManifest`/`manifestPart` docs** (WRITE-gated deletes) → storage refund flows back to them. -4. Unreachable objects simply aren't in the new pack — their bytes are gone from Platform and their deposit refunded. Reachable objects were re-stored in step 1 before anything was deleted (no availability gap). +**Platform tier: repack only consolidates.** -Steady-state result (the INIT.md promise): **a long-lived repo's locked deposit ≈ its current packed size, not its cumulative push history**; the permanent spend is ~1.5% of bytes ever churned plus retained-byte deposits. +1. **`dg repack`** builds one consolidated max-compression pack of all *currently reachable* objects and uploads it. +2. The new `packManifest` lists `supersedes: [old packHashes]` — readers prefer it and read fewer packs. +3. Nothing is deleted: the superseded `chunk`/`packManifest`/`manifestPart` documents are non-deletable, stay readable as a fallback, and keep their deposit. The consolidated pack is an *additional* deposit. -Suggested cadence (`dg doctor` nags): repack when superseded-but-undeleted bytes exceed ~2× current pack size, or before a large history rewrite lands. `dg cost audit` reports: locked deposit, reclaimable-now amount, lifetime non-refundable spend. +So on the Platform tier **a repo's locked deposit is its cumulative push history plus any repacks**, not its current size. Repack there for read performance, not for cost. + +**External tier (S3-compatible, IPFS): garbage collection is the user's.** Only the `packManifest` (a few hundred bytes) is on Platform; the pack bytes are in storage the user controls. After a repack writes a superseding pack, the old objects in the bucket can be deleted to stop paying the provider. This is the tier to use for large or fast-churning repositories. ## 5. Per-scenario cost sketch (@ $34/DASH) | Scenario | Platform backend | External backend | |---|---|---| -| Create repo (contract + config + listing) | **~1.18 DASH** one-time (Stage-2 measured: repo-v1 = 2 tokens + 15 doc types + count-trees; registry alone was 0.68). Refundable? No — contract create is not refundable. This is the dominant one-time cost and the main barrier to casual repo creation. | same | -| Push 100 KiB source delta (~30 KiB packed) | ~$0.28 deposit + ~$0.005 burn | ~$0.01 (manifest + refUpdate only) | -| 1,000 issues + 5,000 comments over a year | ~$25–60 deposit (refundable on delete) | same (always on Platform) | -| Force-push away 10 MiB of history, then repack | recover ~$90 deposit; ~$1.50–3 burned | n/a (bytes were external) | -| Delete whole repo | recover ~all chunk/manifest deposits; audit docs' dust + parked contract remain | recover listing/manifest dust | +| Create repo (`repo` + owner's `maintainer` + first `config`) | **~0.001 DASH** one-time (estimate from the storage rate; not refundable, all three are kept). The v1 per-repo contract cost ~1.18 DASH. | same | +| Fork a repo | ~0.001 DASH plus one small manifest per pack and one ref update per branch (measured on moutai: 0.03 DASH for a 36-pack repo); the parent's packs are referenced, never re-uploaded | same | +| Push 100 KiB source delta (~30 KiB packed) | ~$0.28 deposit (permanent) + ~$0.005 burn | ~$0.01 (manifest + refUpdate only) | +| 1,000 issues + 5,000 comments over a year | ~$25–60 deposit; issues are permanent, comments refundable on delete | same (always on Platform) | +| Force-push away 10 MiB of history, then repack | nothing recovered; the repack adds a deposit for the consolidated pack | delete the old objects in your bucket | +| Deployer: register forge-v2 (once per network) | forge-core 0.60 + forge-collab 0.55 DASH in fees, 1.161234 DASH measured on moutai including storage ([forge-v2.md §7](contracts/forge-v2.md#7-measured-size-and-cost)) | same | ## 6. Fee-minimization checklist (encoded in defaults) 1. External or mixed backend for anything bulky (the biggest lever by 100×). 2. Store the smaller of the two locator-quality push-pack candidates (`build_pack`); max-effort compression at repack. 3. Fill chunks to ~14.4 KiB. Each push also publishes its **browse-index fragment** — a locator over just that pack, 36 B per object the push added. It is the only random-access path to objects newer than the last repack, and it replaces the `manifestPart` per-pack offset index the design originally called for: same role, but it is the same artifact and the same reader as the repack-time index, rather than a second format. Nothing writes a `manifestPart`, so `packManifest.offsetIndexParts` is 0 on every kind. -4. Repack regularly — refunds fund future pushes; surface reclaimable credits in `dg cost audit`. +4. Repack on the external tier and garbage-collect the bucket; on the Platform tier repack only for read performance (it adds a deposit and refunds nothing). 5. Keep social docs lean (5 KiB body cap already enforces this); `documentsKeepHistory` means every edit re-deposits the doc — the UI shows edit cost like any write. -6. Cost engine displays deposit vs burn separately (DASH primary), so users learn that most of a platform push is a *recoverable deposit*, not a fee. +6. Cost engine displays deposit vs burn separately (DASH primary). diff --git a/docs/errors.md b/docs/errors.md index fb78a39ca..107e6e680 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -16,7 +16,7 @@ The helper prints the same block with each line prefixed `dash: `, because git s { "error": { "code": "E601", "message": "…", "cause": "…", "fix": ["…"], "note": null, "docs": "…#e601", "exitCode": 6 } } ``` -Codes never change meaning once shipped, so scripts can match on them. The code's first digit is the process exit code: +Codes never change meaning once shipped, so scripts can match on them. A code that no longer occurs is marked **retired** below and its number is never reused. The code's first digit is the process exit code: | Class | Exit code | Meaning | |---|---|---| @@ -45,7 +45,7 @@ Fix: run the command again with `RUST_LOG=debug` for more detail. If it keeps ha **Not found.** The repository, issue, pull request, release or document does not exist on the network in use. Platform returned a proof that it is absent. -Fix: check the owner id and the name (`dg repo list --owner `). Also check the network, because a repo created on testnet does not exist on mainnet: `dg doctor` shows which network and registry are in use. +Fix: check the owner id and the name (`dg repo list --owner `). Also check the network, because a repo created on testnet does not exist on mainnet: `dg doctor` shows which network and contracts are in use. ## E103 @@ -105,7 +105,7 @@ Fix: `dg auth login --identity ` records a default identity (use the bridg ## E302 -**This key can't sign that.** The identity file has no key at the security level the operation needs. Document writes need a HIGH or CRITICAL AUTHENTICATION key. Token administration (`dg collab add/suspend/remove`, `dg repo create`) needs a CRITICAL one. +**This key can't sign that.** The identity file has no key at the security level the operation needs. Document writes (every `dg` and `git push` write) need a HIGH or CRITICAL AUTHENTICATION key. Fix: use the identity export that includes that key. @@ -176,7 +176,7 @@ Fix: restore that storage, or re-upload the pack from this clone with `dg reseed ## E601 -**Not a writer of this repository.** Platform refused the write at consensus. On a v1 repository your identity holds no WRITE (or MAINTAIN) token (consensus 40700/40701). On a forge-v2 repository there is no current `writer` or `maintainer` document for your identity (40120 on path `$ownerId`, the `ownerRefersTo` gate). +**Not a writer of this repository.** Platform refused the write at consensus: there is no current `writer` or `maintainer` document for your identity (40120 on path `$ownerId`, the `ownerRefersTo` gate). Outside a push (collaborator admin, releases, repo config) the headline says your identity "is not authorized for this action", because those need a different role. @@ -184,11 +184,9 @@ The helper checks this before building or paying for anything and refuses early Fix: ask the owner to add you (`dg collab add / --role writer`), or push to a repository of your own. -## E602 +## E602 (retired) -**Write access suspended.** Your WRITE or MAINTAIN token on a v1 repository is frozen (consensus 40702). v1 repositories are read only now, so this only appears for a write attempted against one. forge-v2 has no suspend: removing a member revokes access at once (E601). - -Fix: push to a forge-v2 repository instead. +**Write access suspended.** Retired with forge-v1 (2026-09-26): it reported a frozen WRITE or MAINTAIN token on a per-repository contract. forge-v2 has no suspend; removing a member revokes access at once (E601). The number stays reserved. ## E603 @@ -202,11 +200,9 @@ Fix: pick another name. Issue and PR numbers are retried automatically, so this Fix: if the message does not explain it, [open an issue](https://github.com/PastaPastaPasta/dash-forge/issues) with it. -## E605 - -**v1 repository is read only.** The repository is a forge-v1 repository (one data contract per repo). v1 repositories can still be cloned, fetched and viewed, but nothing writes to them any more. The refusal happens before anything is signed. +## E605 (retired) -Fix: create a forge-v2 repository (`dg repo create `, about 0.001 DASH) and push there. `dg migrate`, which moves a v1 repository to forge-v2, is coming soon. +**v1 repository is read only.** Retired with forge-v1 (2026-09-26), which the tools no longer read or write. The number stays reserved. ## E701 @@ -216,9 +212,9 @@ Fix: check your connection and run the command again after a minute. `dg doctor` ## E702 -**Dash Forge not deployed on this network.** The embedded `forge-contracts/deployments/.json` records no registry contract, so there is nothing to read or write. The tools never fall back to another network's contract. +**Dash Forge not deployed on this network.** The embedded `forge-contracts/deployments/.json` records no registered forge-v2 contracts (forge-core, forge-collab and their contract group), so there is nothing to read or write. The tools never fall back to another network's contracts. Today forge-v2 is deployed on devnet moutai only; testnet and mainnet follow once they run Platform protocol 14. -Fix: use a network with a deployment (`--network testnet`), or point `FORGE_REGISTRY_CONTRACT_ID` (`dg`: `registry_contract_id` in `config.toml`; helper: `git config dash.registryContractId`) at a registry you deployed. See [the mainnet runbook](mainnet-runbook.md). +Fix: use a network with a deployment (`--network devnet --devnet-name moutai`). See [the mainnet runbook](mainnet-runbook.md). ## E703 diff --git a/docs/guides/README.md b/docs/guides/README.md index 59947e61d..c821b18cd 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -20,6 +20,10 @@ Also: ## What "coming soon" means -These guides describe what is on `master` today. Features that are specified but not built yet are marked **Coming soon**, and nothing marked that way works yet. forge-v2 behavior is described as planned. Its contracts are registered on devnet moutai, but `dg`, `git-remote-dash`, `forge-import` and the web app still create and use v1 repositories only. Client support is being built now, and forge-v2 comes to mainnet after Platform protocol 14 activates. When it lands on moutai, the forge-v2 notes in these guides become instructions. +These guides describe what is on `master` today. Features that are specified but not built yet are marked **Coming soon**, and nothing marked that way works yet. -The product specification the planned features come from (`docs/design/ux-dx-spec.md` and `docs/roadmap.md`) is not on `master` yet. +## Which network + +Forge runs on **devnet moutai** (Platform protocol 14), the only network with a forge-v2 deployment today. The guides use it throughout. Testnet and mainnet run protocol 13 and have no Forge deployment: forge-v2 is registered on testnet when protocol 14 reaches it, and on mainnet after protocol 14 activates there. On a network without a deployment, the tools stop with a "not deployed" error. See [the network status table](../../README.md#status). + +The product specification the planned features come from is [`docs/design/ux-dx-spec.md`](../design/ux-dx-spec.md) and [`docs/roadmap.md`](../roadmap.md). diff --git a/docs/guides/bring-your-own-storage.md b/docs/guides/bring-your-own-storage.md index d7d6e95fc..583c69c79 100644 --- a/docs/guides/bring-your-own-storage.md +++ b/docs/guides/bring-your-own-storage.md @@ -304,7 +304,7 @@ The command looks for the pack's exact bytes in two places: - `.git/dash/packs/.pack`: `git-remote-dash` keeps a copy there of every pack it stores on external storage only. This covers the pusher's own clone, including a push that was interrupted before its refs landed. - `.git/objects/pack/pack-*.pack`: any clone that fetched the pack holds its exact bytes. -It verifies the SHA-256, uploads to the targets (at least `dash.replicas` must confirm), and reports which recorded copies are readable again. Copies it stored at **new** locations can't be added to the immutable manifest. On contracts with a `packMirror` type they are announced as `packMirror` documents. On repo-v1 (today's testnet repos) they are only printed, so re-upload through the pack's original profile to make the recorded copy readable again. +It verifies the SHA-256, uploads to the targets (at least `dash.replicas` must confirm), and reports which recorded copies are readable again. Copies it stored at **new** locations can't be added to the immutable manifest, and the forge-v2 contracts have no document type to announce them yet, so they are only printed. Re-upload through the pack's original profile to make the recorded copy readable again. Plain `dg reseed --profile ` (without `--from-local`) re-uploads packs that are still readable to an additional target. It downloads them first, so it can't restore a pack whose copies are all gone. diff --git a/docs/guides/collaborating.md b/docs/guides/collaborating.md index 2617416d8..de3222294 100644 --- a/docs/guides/collaborating.md +++ b/docs/guides/collaborating.md @@ -10,8 +10,6 @@ Everything a team does on Forge is a signed document on Dash Platform: who may p The commands below take a repository as `/`, where `` is the owner's **identity id** (base58). A bare `` means one of your own repositories. DPNS usernames are not resolved yet. -> **Two access models.** Today's **testnet** repositories are **v1**: access is a pair of tokens on each repository's own contract. **forge-v2** uses membership documents in one shared contract instead. Its contracts are registered on devnet moutai, but `dg`, `git-remote-dash` and the web app cannot use them yet; it comes to mainnet after Platform protocol 14 activates. The commands below work on v1 today. The differences on forge-v2 are called out where they matter. - --- ## Collaborators @@ -20,50 +18,32 @@ There are two roles: | Role | `--role` | Can | |---|---|---| -| Writer | `write` | Push to unprotected branches; label, close and reopen any issue or PR; record merges. | -| Maintainer | `maintain` | Protected branches, releases, labels, webhooks and repository settings, plus the issue and PR actions a writer has. On forge-v2 a maintainer can also push anywhere a writer can. | - -**On v1, give a maintainer both roles.** Pushing needs the WRITE token, even to a protected branch (the pack and manifest are WRITE-gated). A collaborator with only `maintain` cannot push: +| Writer | `writer` (default) | Push to unprotected branches; label, close and reopen any issue or PR; record merges. | +| Maintainer | `maintainer` | Everything a writer can, plus protected branches, releases, repository settings (`config`) and webhooks. | -```sh -dg collab add / --role write -dg collab add / --role maintain -``` +`--role write` and `--role maintain` are accepted as aliases. Anyone, member or not, can open issues and PRs, comment and review. ```sh dg collab list / -dg collab add / --role write -dg collab remove / --role write +dg collab add / --role writer +dg collab remove / --role writer ``` -Adding or removing a collaborator is a write by the repository owner. On v1 it needs the owner's CRITICAL key. +Adding or removing a collaborator is a write by the repository owner, signed with the owner's HIGH key. -### v1 (testnet today): token ACL +### How access works -Each v1 repository has two tokens, WRITE and MAINTAIN. `dg collab add` mints one to the collaborator. Every push spends one WRITE token and pays it back to the owner, so consensus rejects a push from anyone who holds none. Only the repository owner can mint, freeze or destroy tokens. - -v1 also has **suspend**, which freezes the tokens without taking them away: - -```sh -dg collab suspend / --role write -dg collab unsuspend / --role write -``` - -A suspended writer's next push is rejected at consensus ([`E602`](../errors.md#e602)). `dg collab remove` freezes the tokens and then destroys them. - -### forge-v2: membership documents - -*Contracts registered on devnet moutai, client support in progress; mainnet after Platform protocol 14 activates.* - -On forge-v2, a collaborator is a `writer` or `maintainer` document keyed by (repository, member). Only the repository owner can create one, and consensus enforces that. Every write-path document type (ref updates, packs, releases, config, events) names its gate, and consensus refuses a write whose author has no current membership document ([`E601`](../errors.md#e601), Platform code 40120). +A collaborator is a `writer` or `maintainer` document in Forge's shared forge-core contract, keyed by (repository, member). Only the repository owner can create one, and consensus enforces that. Every write-path document type (ref updates, packs, releases, config, events) names its gate, and consensus refuses a write whose author has no current membership document ([`E601`](../errors.md#e601), Platform code 40120). - **Add** creates the membership document. **Remove** deletes it. The member's next write is refused. - **There is no suspend.** Remove the member, and add them again later. - **Past work stays valid.** A document's existence proves its writer was a member at the time it was written. Removing a maintainer later does not undo their past merges or ref updates. - The owner is enrolled as a maintainer when the repository is created. +[forge-v2.md](../contracts/forge-v2.md) §2 lists which role each document type needs. + --- ## Issues @@ -84,7 +64,7 @@ dg issue label / 12 --add bug # or --remove bug **Numbers.** Issue numbers are claimed by the client, by a rule every client shares: the count of issues bounds how far ahead a number can be, so someone squatting #4294967295 does not move numbering. If two people take the same number at once, consensus rejects the second one, and `dg` retries with the next free number. An interrupted `dg issue create` resumes when run again rather than opening a second issue. -**No deletes on v2.** Issues, PRs and their state events cannot be deleted on forge-v2, so nobody can rewrite a thread's history. Comments can be deleted by their author. +**No deletes.** Issues, PRs and their state events cannot be deleted, so nobody can rewrite a thread's history. Comments can be deleted by their author. --- @@ -107,7 +87,7 @@ dg repo fork /project # or --name cost: ~0.03 DASH ≈ $0.90 ``` -A fork is a new forge-v2 repository with `forkOf` set to the parent. It records the parent's packs **by reference**, so nothing is uploaded again. Packs on external storage keep their URLs, and packs on Platform are read from the parent's chunks, which are permanent. The fork's cost is its own documents: the repo, one small manifest per pack, and the refs. Re-running an interrupted fork finishes it without paying twice. It never moves a branch you have already pushed to the fork. +A fork is a new repository with `forkOf` set to the parent. It records the parent's packs **by reference**, so nothing is uploaded again. Packs on external storage keep their URLs, and packs on Platform are read from the parent's chunks, which are permanent. The fork's cost is its own documents: the repo, one small manifest per pack, and the refs. Re-running an interrupted fork finishes it without paying twice. It never moves a branch you have already pushed to the fork. **2. Push your branch to it.** @@ -151,7 +131,7 @@ dg pr review /project 7 --request-changes --body "Needs a test" dg pr review /project 7 --comment --body "Why this approach?" ``` -A review records the commit it was made on, which is the PR's head at the time. **Approvals follow the forge-v2 rule:** +A review records the commit it was made on, which is the PR's head at the time. **Which approvals count:** - Only reviews from current writers and maintainers count. - Only reviews on the PR's **current** head count. A new push makes older ones stale, and `dg pr view` marks them so. @@ -195,7 +175,7 @@ A PR shows as merged only when **both** are true: the `merge` event exists (cons ## Releases -A release names a tag, a title, notes and optionally files. Only maintainers can publish one. On forge-v2 consensus enforces this, and `dg` checks it before uploading anything. +A release names a tag, a title, notes and optionally files. Only maintainers can publish one. Consensus enforces this, and `dg` checks it before uploading anything. ```sh git tag v1.0.0 && git push dash:/// v1.0.0 @@ -233,16 +213,17 @@ dg repo unstar / ## From the web app -On forge.dashhq.org, signed in with your identity file: +On forge.dashhq.org, signed in with a limited key ([Identity and keys](identity-and-keys.md#limited-keys-and-the-web-app)): | You can | Not yet | |---|---| -| Browse code, commits, branches, tags and PR diffs | Open a PR, or record a review verdict | +| Browse code, commits, branches, tags and PR diffs | Open a PR | | File issues, comment, close and reopen | Merge code (see below) | -| Create a repository (v1, with a cost preview) | Web editing, private repositories | -| Grant, suspend and revoke collaborators (owner) | | +| Review a PR: approve, request changes or comment | Inline review comments | +| Create a repository, with a cost preview | Web editing, private repositories | +| Add and remove collaborators (owner) | | | Star repositories | | -The web app has a **Mark as merged** button, shown only to writers and maintainers. It posts the `merge` event (step 2 above). It does not merge code. The PR counts as merged only once the head is already on the base branch. +The web app has a **Mark as merged** button, shown only to writers and maintainers. It posts the `merge` event (step 4 of `dg pr merge` above). It does not merge code. The PR counts as merged only once the head is already on the base branch. -**Coming soon:** open a PR from a branch or fork, inline review comments, approve / request changes, and real merges from the browser (fast-forward and clean merges, uploaded to your own storage). +**Coming soon:** open a PR from a branch or fork, inline review comments, and real merges from the browser (fast-forward and clean merges, uploaded to your own storage). diff --git a/docs/guides/costs.md b/docs/guides/costs.md index 2a4e519c2..fc6f90a5d 100644 --- a/docs/guides/costs.md +++ b/docs/guides/costs.md @@ -17,7 +17,7 @@ Amounts are in **DASH**. Dollar figures are examples at **$30/DASH**, the same f Platform fees are paid in **credits**, from your identity's balance. **1 DASH = 100,000,000,000 credits.** -You get credits by locking Dash into your identity from any Dash wallet: when you create the identity, or later with a top-up (the bridge's **Top Up Existing Identity**). Forge does not sponsor identities, and mainnet has no faucet. Testnet Dash is free, from the faucet. +You get credits by locking Dash into your identity from any Dash wallet: when you create the identity, or later with a top-up (the bridge's **Top Up Existing Identity**). Forge does not sponsor identities, and mainnet has no faucet. Devnet moutai Dash is free, from the [moutai faucet](https://faucet.moutai.networks.dash.org). ```sh dg auth balance @@ -51,8 +51,8 @@ dg cost estimate --bytes 1048576 ``` Estimate for 1048576 bytes (platform tier): total: ~0.28743583 DASH ≈ $8.62 - refundable: ~0.28311552 DASH ≈ $8.49 (storage deposit, reclaimable on delete) - burned: ~0.00432031 DASH ≈ $0.13 (non-refundable processing) + storage: ~0.28311552 DASH ≈ $8.49 (deposit; Platform packs are permanent, not refunded) + processing: ~0.00432031 DASH ≈ $0.13 ``` A deposit only comes back when the document is deleted. Some documents can never be deleted, by design (see [Refunds](#refunds)). For those, the deposit is effectively a one-time cost. @@ -61,18 +61,18 @@ A deposit only comes back when the document is deleted. Some documents can never ## What each action costs -| Action | v1 (testnet today) | forge-v2 (planned: devnet moutai once client support lands; mainnet after protocol 14) | -|---|---|---| -| Create a repository | **~1.18 DASH**, not refundable | **~0.001 DASH** (three small documents; estimated, still being measured) | -| Fork a repository | not supported on v1 | ~0.001 DASH plus one small manifest per pack and one ref update per branch (measured on moutai: 0.03 DASH for a 36-pack repo); the parent's packs are referenced, never re-uploaded | -| Push to **your own bucket** | ~0.0002–0.0004 DASH: manifest + ref update | same | -| Push with packs **on Platform** | ~0.28 DASH per MiB of packed data, plus the above | same, and the storage is permanent | -| Issue or comment (~500 bytes) | ~0.00014 DASH | same | -| Ref update (~200 bytes) | ~0.000055 DASH | same | -| Add or remove a collaborator | a token mint or freeze, small | one small document | -| Clone, fetch, browse, read issues | **free** | **free** | +| Action | Cost | +|---|---| +| Create a repository | **~0.001 DASH**: three small documents (`repo`, your `maintainer` membership, the first `config`) | +| Fork a repository | ~0.001 DASH plus one small manifest per pack and one ref update per branch (measured on moutai: 0.03 DASH for a 36-pack repo); the parent's packs are referenced, never re-uploaded | +| Push to **your own bucket** | ~0.0002–0.0004 DASH: manifest + ref update | +| Push with packs **on Platform** | ~0.28 DASH per MiB of packed data, plus the above; the storage is permanent | +| Issue or comment (~500 bytes) | ~0.00014 DASH | +| Ref update (~200 bytes) | ~0.000055 DASH | +| Add or remove a collaborator | one small document (created, or deleted) | +| Clone, fetch, browse, read issues | **free** | -Where the numbers come from: `dg cost audit` (the per-operation reference below), [economics.md](../economics.md), and the measured forge-v2 contract costs in [forge-v2.md §7](../contracts/forge-v2.md#7-measured-size-and-cost). +Where the numbers come from: `dg cost audit` (the per-operation reference below), [economics.md](../economics.md), and the measured contract costs in [forge-v2.md §7](../contracts/forge-v2.md#7-measured-size-and-cost). ```sh dg cost audit @@ -80,13 +80,15 @@ dg cost audit ``` Per-operation cost reference (no live spend tracking yet): - repo create ~1.18 DASH ≈ $35.40 + repo create ~0.002 DASH ≈ $0.06 ref update (~200 B doc) ~0.000055 DASH ≈ $0.00 pack chunk (~4900 B) ~0.00134337 DASH ≈ $0.04 issue / comment (~500 B) ~0.00013724 DASH ≈ $0.00 ``` -**Why v1 repositories are expensive.** A v1 repository is its own Platform data contract, and Platform charges contract registration by the number of document types, indexes and tokens. That is about 0.88 DASH in fees for a v1 repository, before storage. forge-v2 puts every repository into one shared pair of contracts, which were registered once (for about 1.16 DASH, paid by the deployer, not by you). A new repository is then just three documents. +The `repo create` line is the upper bound `dg` quotes before it signs; the measured cost is about half that. + +**Why a repository is cheap.** Every repository lives in one shared pair of contracts, forge-core and forge-collab, registered once per network (for about 1.16 DASH, paid by the deployer, not by you). A new repository is then just three documents. The first version of Forge gave each repository its own contract, and contract registration fees made that cost about 1.18 DASH per repository; it was removed on 2026-09-26. Packs are git packfiles: delta-compressed and deflated, typically 20–35% of the size of a checkout. Forge never stores raw files. @@ -101,7 +103,7 @@ Pack bytes are almost all of a repository's size, so where you keep them decides | **Your bucket** (R2, B2, S3, MinIO) or IPFS | Platform: manifest + refs per push. Provider: storage and egress, at their prices. | ~0.003 DASH a month on Platform, plus cents to your provider (R2 has no egress fees) | | **Dash Platform** | ~0.28 DASH per MiB pushed | ~14 DASH for the first upload, then ~0.28 DASH per MiB pushed | -Platform storage buys you something: it is stored by the network, and on forge-v2 it can never be deleted, even by you. Your bucket is cheap, but it is only as available as your account with the provider. You can have both: `dg storage use r2-main,platform` keeps a copy in each place. See [Bring your own storage](bring-your-own-storage.md). +Platform storage buys you something: it is stored by the network, and it can never be deleted, even by you. Your bucket is cheap, but it is only as available as your account with the provider. You can have both: `dg storage use r2-main,platform` keeps a copy in each place. See [Bring your own storage](bring-your-own-storage.md). If you set nothing, **packs go to Platform**. That is fine for small repositories, and expensive for large ones. @@ -113,15 +115,16 @@ When a document is deleted, Platform refunds the part of its storage deposit tha **What can be deleted, and so refunded:** -| | v1 (testnet today) | forge-v2 | -|---|---|---| -| Pack chunks and manifests | Yes: `dg repack` consolidates and deletes superseded ones; `dg repo delete` deletes all of them | **No.** Platform-tier storage is permanent, so that nobody can break a repository by deleting what others depend on. | -| Issues, PRs | Yes, by the author | **No**, so that threads cannot be rewritten | -| Ref updates, config, events | No, never (they are the audit trail) | No, never | -| Comments, reviews, releases, labels, stars, follows | Yes, by the author | Yes, by the author | -| The repository contract (v1) or `repo` document (v2) | No | No | +| | Deletable? | +|---|---| +| Pack chunks and manifests | **No.** Platform-tier storage is permanent, so that nobody can break a repository by deleting what others depend on. `dg repack` consolidates into a new pack and deletes nothing on Platform. | +| Issues, PRs | **No**, so that threads cannot be rewritten | +| Ref updates, config, events | No, never (they are the audit trail) | +| The `repo` document | No | +| Membership documents (`writer`, `maintainer`) | Yes, by the owner (that is how a collaborator is removed) | +| Comments, reviews, releases, labels, webhooks, stars, follows | Yes, by the author | -On v1, `dg repo delete` deletes the repository's chunks and manifests, removes its listing, and prints the estimated refund. The contract itself stays, because contracts cannot be deleted. +There is no `dg repo delete`: a repository cannot be deleted. The audit trail grows forever: about 0.08 DASH per 1,000 pushes stays locked in ref updates. That is the price of a history nobody can rewind. @@ -129,7 +132,7 @@ The audit trail grows forever: about 0.08 DASH per 1,000 pushes stays locked in ## Seeing costs before you pay -- **`dg` asks first.** Every command that writes asks `[y/N]` unless you pass `--yes`. `dg repo create` and `dg repack` show their price in the question, and `dg repo delete` its refund. For other commands, use `dg cost estimate` and `dg cost audit`. With `--json` or no terminal, `dg` refuses to write without `--yes` ([`E802`](../errors.md#e802)). +- **`dg` asks first.** Every command that writes asks `[y/N]` unless you pass `--yes`. `dg repo create` and `dg repack` show their price before the question. For other commands, use `dg cost estimate` and `dg cost audit`. With `--json` or no terminal, `dg` refuses to write without `--yes` ([`E802`](../errors.md#e802)). - **`git push` prints its estimate** before it writes to Platform, and what Platform actually charged when it is done. To make it ask: ```sh git config --global dash.costWarnThreshold 0.01 # ask above 0.01 DASH diff --git a/docs/guides/identity-and-keys.md b/docs/guides/identity-and-keys.md index c3b407268..e55e5d9d8 100644 --- a/docs/guides/identity-and-keys.md +++ b/docs/guides/identity-and-keys.md @@ -38,14 +38,13 @@ An identity file from the bridge has five keys, all ECDSA secp256k1: |---|---|---|---| | 0 | AUTHENTICATION | **MASTER** | Changing the identity's own keys (add, disable). Nothing on Forge needs it. | | 1 | AUTHENTICATION | HIGH | Signing documents: pushes, issues, comments, reviews, releases. | -| 2 | AUTHENTICATION | CRITICAL | What HIGH does, plus v1 token administration: `dg repo create`, `dg collab …`. | +| 2 | AUTHENTICATION | CRITICAL | What HIGH does. Forge uses it only when the file has no HIGH key. | | 3 | TRANSFER | CRITICAL | Moving credits to another identity, or withdrawing them. | | 4 | ENCRYPTION | MEDIUM | Reserved for private repositories (coming soon). | What each tool signs with: -- `git push` (`git-remote-dash`) and most `dg` commands sign with the **HIGH** key, falling back to CRITICAL. -- `dg repo create` and `dg collab add/suspend/unsuspend/remove` need the **CRITICAL** key, because on v1 they mint and freeze tokens. Without it they fail with [`E302`](../errors.md#e302). On forge-v2 these become ordinary documents that the HIGH key can sign. +- `git push` (`git-remote-dash`) and every `dg` command that writes, including `dg repo create` and `dg collab add/remove`, sign with the **HIGH** key, falling back to CRITICAL. They are all ordinary documents. Without either key they fail with [`E302`](../errors.md#e302). - No Forge tool ever needs the MASTER key. --- @@ -77,8 +76,7 @@ Your **repository data** needs no backup of its own. Refs, issues and PRs are on | `dg` | A copy of the identity file in `~/.config/dash-forge/identities//.identity.json` | `--identity ` > `DASH_FORGE_KEY` > the default recorded by `dg auth login` | | `git-remote-dash` | The same file | `DASH_FORGE_KEY`, else `~/.config/dash-forge/identities/.identity.json` | | `forge-import` | The same file | `--identity ` > `DASH_FORGE_KEY` | -| Web app, forge-v2 networks (devnet moutai) | A **limited key** only, encrypted in the browser's IndexedDB (passkey or passphrase), unlocked for the session | Registered once from your identity file, recovery phrase, a new identity, or your wallet; see [below](#limited-keys-and-the-web-app) | -| Web app, testnet (v1) | The file's CRITICAL (or HIGH) key, held in the tab's memory only; gone on reload | Loaded from an identity file in the **Sign in** sheet | +| Web app | A **limited key** only, encrypted in the browser's IndexedDB (passkey or passphrase), unlocked for the session | Registered once from your identity file, recovery phrase, a new identity, or your wallet; see [below](#limited-keys-and-the-web-app) | Things to know: @@ -95,9 +93,8 @@ Things to know: A web page is whoever served it. If the page, or a script it loads, is compromised, anything you paste into it is gone. - **Never paste your MASTER key, your 12 words, or your main identity file into a website.** That includes forge.dashhq.org. Nothing on Forge needs them. -- On forge-v2 networks the web app's **Import** reads your identity file (or recovery phrase) once: its master key signs one update that registers a [limited key](#limited-keys-and-the-web-app) for this browser, and is not retained. If you would rather not load the master key into a web page at all, use **Use my Dash wallet** instead (the wallet registers the key), or register a limited key with `dg` once that lands. -- On testnet (v1) the sign-in picks the CRITICAL key (or HIGH) from the file you load and keeps it in the tab only. It does not store the MASTER key or the mnemonic, but it does read the whole file you choose. If you want to be careful, give it a copy that contains only the HIGH or CRITICAL key (the `jq` recipe in the [mirror guide](mirror-a-github-repo.md#the-ci-secret) makes one). -- The same goes for CI: give a pipeline a stripped copy or, better, a separate identity with a small balance. +- The web app's **Import** reads your identity file (or recovery phrase) once: its master key signs one update that registers a [limited key](#limited-keys-and-the-web-app) for this browser, and is not retained. If you would rather not load the master key into a web page at all, use **Use my Dash wallet** instead (the wallet registers the key), or register a limited key with `dg` once that lands. +- For CI, give a pipeline a copy of the identity file stripped to its HIGH key (the `jq` recipe in the [mirror guide](mirror-a-github-repo.md#the-ci-secret) makes one) or, better, a separate identity with a small balance. - Prefer a copy of the web app that you [serve yourself](verify-forge.md#run-your-own-copy-of-the-web-app) if you do not want to trust the one on forge.dashhq.org. With limited keys (below) the web app keeps nothing but a limited key. The master key is used only in one-time steps: registering, renewing or revoking a limited key. @@ -110,7 +107,7 @@ Platform lets the MASTER key add new keys to an identity and disable old ones. A Today you do this in the Dash bridge, not in `dg`: -1. Open (it defaults to testnet; add `?network=mainnet` for mainnet) and choose **Manage Identity Keys**. +1. Open (it defaults to testnet; add `?network=devnet-moutai` for moutai or `?network=mainnet` for mainnet) and choose **Manage Identity Keys**. 2. Sign in with the identity id and the **MASTER** key's private key. This is the one place where the master key is used. Do it on a machine you trust, and check the page address first. 3. Add a new key (for example a new HIGH authentication key), or disable a key you think is exposed. 4. Update your identity file: add an `identityKeys` entry for the new key, and **delete the entry for the key you disabled**. The bridge gives you the new key's private key (WIF). Signing uses only `id`, `purpose`, `securityLevel` and `privateKeyWif`, but every field of an entry must be present for the file to load, so set the ones you don't have (`privateKeyHex`, `publicKeyHex`, `derivationPath`, `name`) to `""` and `keyType` to `"ECDSA_SECP256K1"`. `dg` and `git-remote-dash` sign with the first HIGH authentication key in the file, so a disabled key left in it makes every write fail. Then run `dg auth login --identity ` again to refresh the copy `dg` uses. @@ -120,7 +117,7 @@ When to rotate: - a laptop or CI secret that held a signing key was lost or leaked: **disable that key**; - you gave a CI job the HIGH key and are retiring the job. -If the **MASTER** key or the 12 words leak, rotating does not help: whoever has them can add keys and disable yours. The identity is lost. Move your credits out with the TRANSFER key to a new identity, and start over there with new repositories: push your clones to them. Repository ownership cannot be transferred on either v1 or forge-v2, and the attacker now controls everything only the owner can do, such as adding and removing members. +If the **MASTER** key or the 12 words leak, rotating does not help: whoever has them can add keys and disable yours. The identity is lost. Move your credits out with the TRANSFER key to a new identity, and start over there with new repositories: push your clones to them. Repository ownership cannot be transferred, and the attacker now controls everything only the owner can do, such as adding and removing members. **Coming soon:** `dg auth keys list | add | disable`. @@ -128,7 +125,7 @@ If the **MASTER** key or the 12 words leak, rotating does not help: whoever has ## Limited keys and the web app -*Live in the web app on devnet moutai (protocol 14). Mainnet after Platform protocol 14 activates. CLI support (`dg auth …`) is coming.* +*Live in the web app. CLI support (`dg auth …`) is coming.* A limited key is an identity key with four restrictions: diff --git a/docs/guides/mirror-a-github-repo.md b/docs/guides/mirror-a-github-repo.md index a856154f8..648909906 100644 --- a/docs/guides/mirror-a-github-repo.md +++ b/docs/guides/mirror-a-github-repo.md @@ -30,7 +30,7 @@ You need: - The [GitHub CLI](https://cli.github.com), logged in with `gh auth login`. The importer reads issues, PRs and releases through it. - Optional but recommended: a storage profile for your own bucket ([Bring your own storage](bring-your-own-storage.md)), so that pack bytes do not go on Platform at ~0.28 DASH/MiB. -> **Network.** The importer writes **forge-v2** repositories (about **0.001 DASH** to create). They exist on devnet moutai today (`--network devnet --devnet-name moutai`) and come to mainnet after Platform protocol 14 activates. +> **Network.** The importer writes **forge-v2** repositories (about **0.001 DASH** to create). They exist on devnet moutai today (`--network devnet --devnet-name moutai`), come to testnet when Platform protocol 14 reaches it, and to mainnet after protocol 14 activates there. --- @@ -112,7 +112,7 @@ Check that it contains exactly one key: jq '.identityKeys | length' ci-identity.json # 1 ``` -This lowers the risk but does not remove it. A leaked HIGH key can still sign documents and spend the identity's credits until you disable the key. For CI, a cleaner setup is a **separate identity** with a small balance, added to the repository as a collaborator (`dg collab add … --role write`). Then a leak costs only that balance. See [Identity and keys](identity-and-keys.md). +This lowers the risk but does not remove it. A leaked HIGH key can still sign documents and spend the identity's credits until you disable the key. For CI, a cleaner setup is a **separate identity** with a small balance, added to the repository as a collaborator (`dg collab add … --role writer`). Then a leak costs only that balance. See [Identity and keys](identity-and-keys.md). Store the file as a GitHub Actions secret named `DASH_FORGE_IDENTITY`: Settings → Secrets and variables → Actions → New repository secret, and paste the file's contents. @@ -134,7 +134,8 @@ jobs: permissions: { contents: read } env: FORGE_REMOTE: dash:/// - DASH_FORGE_NETWORK: testnet + DASH_FORGE_NETWORK: devnet + DASH_FORGE_DEVNET_NAME: moutai DASH_FORGE_REF: steps: - uses: actions/checkout@v4 @@ -230,6 +231,8 @@ jobs: - uses: PastaPastaPasta/dash-forge/action@master with: repo: dash:/// + network: devnet # the default is mainnet, which has no Forge deployment yet + devnet-name: moutai sync: code,releases,issues,prs storage-kind: s3 s3-endpoint: https://.r2.cloudflarestorage.com diff --git a/docs/guides/quick-start.md b/docs/guides/quick-start.md index 65db6d6d8..8ac9714be 100644 --- a/docs/guides/quick-start.md +++ b/docs/guides/quick-start.md @@ -1,6 +1,6 @@ # Quick start -This guide takes you from nothing to a repository on Dash Forge that you can clone, push to and browse on the web. It uses **testnet**, where Dash is free, so you can try everything without spending real money. +This guide takes you from nothing to a repository on Dash Forge that you can clone, push to and browse on the web. It uses **devnet moutai**, where Dash is free, so you can try everything without spending real money. You will: @@ -13,9 +13,9 @@ You will: Replace every `<…>` placeholder in the commands with your own value before running them; the shell reads a bare `<` or `>` as a redirection. -Allow about 15 minutes. Most of it is the first build, or waiting for testnet to confirm your identity. +Allow about 15 minutes. Most of it is the first build, or waiting for the network to confirm your identity. -> **Which network?** Testnet runs the first version of Forge ("v1": one Platform contract per repository). **forge-v2**, which makes repositories about 1,000× cheaper, has its contracts registered on **devnet moutai**. The tools cannot use them yet: client support is being built now. It comes to mainnet after Platform protocol 14 activates there. Mainnet has no Forge deployment yet. See [the network status table](../../README.md#status). +> **Which network?** Forge (forge-v2) needs Platform protocol 14, which only devnet **moutai** runs today. Testnet gets a deployment when protocol 14 reaches it, and mainnet after protocol 14 activates there. On a network without a deployment the tools stop with a "not deployed" error. See [the network status table](../../README.md#status). --- @@ -63,13 +63,12 @@ dg doctor A Dash Platform **identity** is your account on Forge. It holds your keys and your credit balance. Nobody issues it to you: you create it yourself by locking some Dash. [Identity and keys](identity-and-keys.md) explains what it is. -**Forge never funds or creates identities for you.** On testnet, free test Dash is available for trying things out: +**Forge never funds or creates identities for you.** On devnet moutai, free test Dash is available for trying things out: -1. Open the **Dash bridge** in testnet mode: . -2. Choose **Create New Identity**. On testnet the deposit step has a **Request Testnet Funds** button that sends you 1 free tDASH, so you do not need a wallet. +1. Open the **Dash bridge** in moutai mode: . +2. Choose **Create New Identity**. Fund the deposit address it shows from the moutai faucet at . A little is enough: a repository costs about 0.001 DASH. 3. **Write down the 12 words it shows you.** They are the only way to recover the identity. 4. When the identity is registered, choose **Download Key Backup**. You get a file named `dash-identity-.json`. `dg` reads your keys from it. -5. **Top up once more.** A testnet repository costs about 1.18 tDASH, which is more than one faucet request. Choose **Top Up Existing Identity**, enter your identity id, and use **Request Testnet Funds** again. The faucet allows 3 requests an hour. Keep the file private. It holds every private key of the identity. Move it somewhere safe, for example: @@ -79,29 +78,29 @@ mv ~/Downloads/dash-identity-*.json ~/.config/dash-forge/ chmod 600 ~/.config/dash-forge/dash-identity-*.json ``` -> **Devnet moutai.** Use `https://bridge.thepasta.org/?network=devnet-moutai`. Fund it from the moutai faucet at . -> > **Mainnet.** Use (the bridge defaults to testnet) and fund the deposit address from any Dash wallet. There is no faucet on mainnet. Forge itself is not on mainnet yet. -**Coming soon:** `dg auth new`, which creates and funds an identity from the terminal (it shows a QR code for the deposit) and stores the keys in your OS keychain. Creating an identity in the web app is coming too. +You can also create an identity in the web app: choose **Sign in**, then create a new identity there (see [Identity and keys](identity-and-keys.md#limited-keys-and-the-web-app)). The CLI still needs the key backup file. + +**Coming soon:** `dg auth new`, which creates and funds an identity from the terminal (it shows a QR code for the deposit) and stores the keys in your OS keychain. --- ## 3. Sign in -Point `dg` at the identity file once: +Point `dg` at the identity file and the network once: ```sh -dg auth login --identity ~/.config/dash-forge/dash-identity-.json +dg auth login --network devnet --devnet-name moutai --identity ~/.config/dash-forge/dash-identity-.json ``` ``` -Logged in as 8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB on testnet. -Stored default identity at /home/you/.config/dash-forge/identities/testnet/8hJm….identity.json. +Logged in as 8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB on devnet-moutai. +Stored default identity at /home/you/.config/dash-forge/identities/devnet-moutai/8hJm….identity.json. Balance: 199980000000 credits (~1.999800 DASH). ``` -`dg` copies the file into `~/.config/dash-forge/identities//` and uses it by default from now on. The copy is created with your default file mode, so make it private: +`dg` copies the file into `~/.config/dash-forge/identities//` and records the identity and the network as defaults, so later commands need neither flag. The copy is created with your default file mode, so make it private: ```sh dg doctor --fix # chmod 700 the directory and 600 the copied key file @@ -109,12 +108,16 @@ dg doctor --fix # chmod 700 the directory and 600 the copied key file `dg doctor --fix` also sets `git config --global dash.costWarnThreshold 0.01` if you have no threshold yet, so that pushes ask before spending more than 0.01 DASH. Inside a git repository it can also pin `dash.network` in that repository's config to match `dg`. It never spends anything. -**git needs to find the key too.** `git-remote-dash` does not read `dg`'s settings. It reads the `DASH_FORGE_KEY` environment variable. It needs an identity even to **clone**, although cloning spends nothing. Add this line to your shell profile (`~/.zshrc`, `~/.bashrc`): +**git needs to find the key and the network too.** `git-remote-dash` does not read `dg`'s settings. It reads the `DASH_FORGE_KEY` environment variable for the key, and `DASH_FORGE_NETWORK` / `DASH_FORGE_DEVNET_NAME` (or git config `dash.network` / `dash.devnetName`) for the network. It needs an identity even to **clone**, although cloning spends nothing. Add these lines to your shell profile (`~/.zshrc`, `~/.bashrc`): ```sh -export DASH_FORGE_KEY="$HOME/.config/dash-forge/identities/testnet/.identity.json" +export DASH_FORGE_KEY="$HOME/.config/dash-forge/identities/devnet-moutai/.identity.json" +export DASH_FORGE_NETWORK=devnet +export DASH_FORGE_DEVNET_NAME=moutai ``` +Without the network settings the helper uses testnet, which has no Forge deployment, and stops with a "not deployed" error. + Then check everything. `dg doctor` should now show no warnings for your identity: ```sh @@ -136,15 +139,16 @@ dg repo create my-project --description "My first Forge repo" ``` ``` -Creating repo "my-project" (platform storage) — estimated cost ~1.18 DASH ≈ $35.40 -Create repo "my-project"? This instantiates a contract (~1.18 DASH ≈ $35.40) [y/N] y -Created 8hJm…/my-project - contract: 5rrw… +Creating my-project on devnet-moutai (platform storage) + repo + maintainer + config ~0.002 DASH ≈ $0.06 +Create my-project? [y/N] y +✓ created 8hJm…/my-project + repo id: 4Fq9… remote: dash://8hJm…/my-project - cost: ~1.18 DASH ≈ $35.40 + cost: ~0.00098 DASH ≈ $0.03 ``` -On testnet this costs about **1.18 tDASH**, which is free test money. It is that expensive because a v1 repository is a whole Platform contract. `dg repo create` makes v1 repositories only. On forge-v2 a repository will be three small documents, about **0.001 DASH**. See [Costs](costs.md). +A repository is three small documents in Forge's shared contracts: the `repo` itself, your `maintainer` membership, and the first `config`. The estimate is an upper bound; the measured cost, about **0.001 DASH**, is printed after the create lands. See [Costs](costs.md). Names are 1–63 characters: lowercase letters, digits, `.`, `_` and `-`, starting with a letter or digit. @@ -210,7 +214,7 @@ https://forge.dashhq.org/repo?owner=&name=my-project The web app has no server behind it. Your browser reads the repository straight from Dash Platform, checks the Platform proofs, and re-hashes every file it shows. The **Assay** panel on the right says what was checked. [Verify Forge](verify-forge.md) explains it. -Browsing and cloning are free and need no sign-in. To file an issue from the browser, choose **Sign in** and load your identity file. The browser keeps the signing key in local storage. +Browsing and cloning are free and need no sign-in. To file an issue from the browser, choose **Sign in**. The web app registers a limited key for this browser (a small budget, an expiry, usable only on Forge) and keeps it encrypted; your master key is used once and not stored. [Identity and keys](identity-and-keys.md#limited-keys-and-the-web-app) explains the options. --- diff --git a/docs/guides/verify-forge.md b/docs/guides/verify-forge.md index 09875fd7a..5d290159e 100644 --- a/docs/guides/verify-forge.md +++ b/docs/guides/verify-forge.md @@ -26,9 +26,9 @@ The chain runs: quorum key → proof → ref tip and pack SHA-256 → pack bytes Two things are **rules**, not proofs, and every client applies them identically: - **Which tip wins.** A branch's tip is folded from its ref-update log (the `FORGE_RULES` fold). If two pushes raced, the ref shows as *diverged*, and the web app says so. -- **Who counts.** Whether a close, merge or approval was made by someone with the right role. On v1 this is reconstructed from token history. On forge-v2, consensus checks membership when the document is written. +- **Who counts.** Whether an approval was made by someone with the right role, and whether a merge's commit is reachable from the base branch. Consensus already checks membership when a close, merge or other state change is written; the rules decide which approvals count and when a PR shows as merged. -The Rust and TypeScript clients share 70+ conformance vectors (`forge-contracts/vectors/`), so the CLI and the web app reach the same answer from the same documents. +The Rust and TypeScript clients share 170+ conformance vectors (`forge-contracts/vectors/`), so the CLI and the web app reach the same answer from the same documents. --- @@ -128,7 +128,7 @@ The CLI end-to-end suite has a scenario that automates steps 1–3 above (the co 3. clones, then runs `git fsck --strict` and `git verify-pack`; 4. checks that the clone's tip equals the raw on-chain tip, re-hashes the tip commit and its tree by hand, and checks that no reachable object is missing. -It runs in the nightly against testnet. It is written against the suite's own fixture repository and identities (`e2e/cli/config.sh`). To use it on another repository, copy the steps. Each is a plain `git`, `dg` or `git-remote-dash` command. +It runs in the nightly against devnet moutai. It is written against the suite's own fixture repository and identities (`e2e/cli/config.sh`). To use it on another repository, copy the steps. Each is a plain `git`, `dg` or `git-remote-dash` command. --- @@ -145,7 +145,7 @@ pnpm build # writes the static site to forge-web/out/ npx serve out # or any static file server ``` -Choose the network at build time: `NEXT_PUBLIC_NETWORK=testnet|mainnet|devnet`, plus `NEXT_PUBLIC_DEVNET_NAME=moutai` for a devnet. Contract ids come from `forge-contracts/deployments/`. +Choose the network at build time: `NEXT_PUBLIC_NETWORK=testnet|mainnet|devnet`, plus `NEXT_PUBLIC_DEVNET_NAME=moutai` for a devnet. The hosted app is built with `NEXT_PUBLIC_NETWORK=devnet NEXT_PUBLIC_DEVNET_NAME=moutai`, the only network with a Forge deployment today; a build for a network without one shows "not deployed". Contract ids come from `forge-contracts/deployments/`. **Host it anywhere static:** another static host, your own server, or IPFS: diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 7d3dc9bf0..59cbbff4e 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -1,5 +1,7 @@ # Dash Forge — Implementation Plan +> **Historical.** This is the original phase plan for forge-v1 (a global registry contract plus one contract per repository, with token access control). It is not the current plan. forge-v1 was removed on 2026-09-26 with no backwards compatibility; current planning lives in [roadmap.md](roadmap.md) and the current design is [forge-v2](contracts/forge-v2.md). + Phasing per INIT.md's design path, with constraint-forced adjustments (reconciliation D1) folded in. Each phase ends with runnable, tested software. ## Phase 0 — De-risk (2–4 wks) — the go/no-go gate diff --git a/docs/init-reconciliation.md b/docs/init-reconciliation.md index a4fffc6a1..04b03ac82 100644 --- a/docs/init-reconciliation.md +++ b/docs/init-reconciliation.md @@ -1,5 +1,7 @@ # INIT.md Reconciliation +> **Partly historical.** The contract topology reconciled here (a global registry contract plus one repo contract per repository from a versioned template, with WRITE/MAINTAIN token ACLs) was replaced by [forge-v2](contracts/forge-v2.md): two shared contracts (forge-core, forge-collab) in one contract group, with access granted by `maintainer`/`writer` membership documents and checked at consensus. forge-v1 was removed on 2026-09-26 with no backwards compatibility. Items 2 and 3 below, the token and template parts of D2–D4, the v3 contract refinements, the token findings of Design Freeze #1 and the first two open questions describe that removed design. The other adopted items, D1, D5, D6 and the Platform findings still hold. + `../INIT.md` (the original design path & PRDs) was located after the first planning pass. The docs have been updated to follow it. This file records **where INIT.md's design is adopted verbatim, and the few places where verified platform constraints (see [research](research/platform-constraints.md)) force a deviation** — each deviation is flagged for review. ## Adopted from INIT.md (now reflected throughout) diff --git a/docs/mainnet-runbook.md b/docs/mainnet-runbook.md index 5cd09beef..4504e8999 100644 --- a/docs/mainnet-runbook.md +++ b/docs/mainnet-runbook.md @@ -1,61 +1,77 @@ # Dash Forge — Mainnet Deployment Runbook -**Status: NOT EXECUTED.** Per the project decision, Dash Forge is *testnet-complete*: everything is built and end-to-end verified on testnet. This runbook is the rehearsed procedure to bring it to mainnet when you choose to fund it. Every step has a testnet analog that already passed. +**Status: NOT EXECUTED.** forge-v2 needs Platform protocol 14 (contract groups, `ownerRefersTo`). Mainnet runs protocol 13 today; the owner registers forge-v2 on mainnet after protocol 14 activates there (roadmap D-J, expected about a month after 2026-09-24). Everything below is rehearsed on **devnet moutai**, where forge-v2 is registered and the CLI and web suites run; testnet gets the same rehearsal once protocol 14 reaches it (~1–2 weeks after 2026-09-24). + +Deploying Dash Forge to a network means registering one pair of shared contracts, **forge-core** and **forge-collab**, joined by one contract group. There is no per-repository contract and no registry: a repository is three documents in those contracts, created by its owner. See [contracts/forge-v2.md](contracts/forge-v2.md) for the schemas and §8 there for the deploy script's behaviour. ## 0. Prerequisites -- A funded **mainnet** Dash identity to act as the **registry deployer / DCG identity**. Cost budget below. -- The `dg` CLI and `git-remote-dash` helper built from a release tag (`cargo build --release`). -- A mainnet identity from the bridge (`bridge.thepasta.org`). `tools/mint-identity` supports only `--network testnet` and `--network devnet` (it has no mainnet config and there is **no faucet on mainnet**), so create and fund the mainnet identity through the bridge. -- Decide the registry owner custody model: for an org, the deployer identity should be **jointly held** (multiple high-security keys across principals) — this is the *only* succession mechanism (contract owners are immutable; see PRD 01 open questions). +- **Mainnet runs protocol 14.** The deploy script checks this and refuses to broadcast on an older protocol. +- **Decide who owns the contracts (roadmap D-D).** The deployer identity owns forge-core, forge-collab and the contract group, and only the owner can update the contracts. Contract owners are immutable, so custody of that identity is the only succession mechanism. For an org, hold it jointly (multiple high-security keys across principals). +- **Decide `config.readonly` before registering** ([forge-v2.md §4](contracts/forge-v2.md#4-non-deletable-audit-types), §8). The contracts are registered not readonly, so the owner can later add optional properties and new document types. Readonly can only be set at registration: a later update to `readonly: true` is refused. If the mainnet contracts should be final, set `config.readonly` in `forge-contracts/contracts/forge-core.json` and `forge-collab.json` before running the script. +- **Land the schema changes that must precede mainnet**, e.g. the private-repository changes in [security/private-repos.md §13](security/private-repos.md), and register them on moutai first (`--force-new` if the update rules refuse them). Whatever is registered on mainnet is what every mainnet repository lives in. +- A funded **mainnet** deployer identity, as a bridge-format identity JSON with its CRITICAL authentication key (the script signs with it and refuses a key that is missing, different from the file, or disabled on chain). Create and fund it through the bridge (`bridge.thepasta.org`). `tools/mint-identity` supports only testnet and devnets, and there is **no faucet on mainnet**. +- `dg` and `git-remote-dash` built from a release tag (`cargo build --release`), and Node for the deploy script. ## 1. Cost budget (mainnet DASH — real money) -Measured on testnet (identical fee schedule, protocol-versioned): +The fee schedule is the same on every network. Measured on devnet moutai: | Item | Cost | Refundable? | |---|---|---| -| Registry contract deploy (one-time) | ~0.68 DASH | No | -| Per-repo instantiation (repo-v1) | ~1.18 DASH | No | -| Push (tiny) | ~0.003 DASH | storage portion yes | -| Issue/comment | ~0.0001–0.0005 DASH | on delete | -| Smoke-suite run (create+push+issue+delete) | ≤ 0.05 DASH net | mostly refunded | +| forge-core registration (once per network, deployer) | 0.60 DASH fee + storage; 0.605711 DASH measured | No | +| forge-collab registration (once per network, deployer) | 0.55 DASH fee + storage; 0.555523 DASH measured | No | +| Create a repository (`repo` + `maintainer` + `config`) | ~0.001 DASH | No (the documents are permanent) | +| Push (tiny) | ~0.003 DASH | No for Platform-stored packs | +| Issue / comment | ~0.0001–0.0005 DASH | issues no; comments on delete | +| Smoke-suite run (create + push + issue) | ≤ 0.05 DASH | mostly not: repos, issues and Platform packs are permanent | -Minimum to launch: **~0.7 DASH** (registry) + **~1.2 DASH** per canonical repo + a smoke buffer. Budget ~3 DASH for a comfortable launch + smoke. +Minimum to register: **~1.17 DASH** (1.161234 DASH measured on moutai). Budget ~2 DASH for registration plus a smoke run and a buffer. If you run the script with `--dry-run` first, it costs nothing. -## 2. Deploy the registry +## 2. Register forge-v2 ```bash -# Fund the deployer mainnet identity first (bridge), and confirm its credit balance in the bridge. +# Once: the pinned protocol-14 SDK the script uses. +(cd forge-contracts/sdk-v2 && npm ci) + +# Offline check of the id derivation (no network). +node forge-contracts/scripts/deploy-v2.mjs --self-test + +# Build, validate and size both transitions against mainnet without broadcasting. +node forge-contracts/scripts/deploy-v2.mjs --identity \ + --network mainnet --dry-run -# Deploy the registry (uses the reconciled source with single-property count indices): -cd forge-contracts -node scripts/deploy.mjs --contract registry --identity --network mainnet -# → writes forge-contracts/deployments/mainnet.json with the registry contract id +# Register: forge-core (creating the contract group), then forge-collab enrolled in it. +node forge-contracts/scripts/deploy-v2.mjs --identity \ + --network mainnet +# → writes the v2 section of forge-contracts/deployments/mainnet.json ``` -**Use the reconciled `contracts/registry.json`** (post-Stage-5: it has the single-property `recent`/`star`/`follow` count indices the testnet-deployed registry lacks). Verify with the post-deploy canary (fetch + per-type doc create/delete) before proceeding. +- Before broadcasting, the script checks the network's protocol version, rebuilds both contracts with full validation locally, and prints the transition sizes. +- Each step's nonce, contract id, group id and pre-broadcast balance are recorded in `deployments/mainnet.json` before it broadcasts. If the run is interrupted, **run the same command again**: it completes what landed and never registers a second copy. Do not pass `--force-new` on mainnet unless you mean to supersede the registered pair with a new one. +- Afterwards the record shows both contracts as `registered`, with their cost, and the script has checked on chain that the group exists, the deployer owns it, and both contracts are enrolled. -## 3. Wire the mainnet registry id into clients +## 3. Wire the mainnet deployment into clients -- Until `mainnet.json` exists, every client reports "no Dash Forge registry is deployed on mainnet yet" for registry operations. That is the expected pre-deploy state; they never fall back to testnet ids. -- `forge-core` embeds every `forge-contracts/deployments/*.json` at build time (`crates/forge-core/build.rs`), so committing `mainnet.json` is the whole Rust change; rebuild and confirm with `dg doctor --network mainnet` (the `contracts` line names `forge-contracts/deployments/mainnet.json` as the source). +- Until `mainnet.json` has a registered `v2` pair, every client reports "not deployed" on mainnet. That is the expected pre-deploy state; clients never fall back to another network's ids. +- `forge-core` embeds every `forge-contracts/deployments/*.json` at build time (`crates/forge-core/build.rs`), so committing `mainnet.json` is the whole Rust change. Rebuild and confirm with `dg doctor --network mainnet`: the `contracts` check names forge-core and forge-collab and `forge-contracts/deployments/mainnet.json` as the source, and verifies both are enrolled in the group. - forge-web: add `mainnet` to `forge-web/lib/deployments.ts` (the `deployments bundle` unit test fails until you do), then build with `NEXT_PUBLIC_NETWORK=mainnet`; the SDK uses `EvoSDK.mainnetTrusted()`. See [BUILDING.md § Networks](BUILDING.md#networks). +- Once mainnet is live, consider making it the CLI's default network (today the default is testnet, which has no forge-v2 deployment yet). -## 4. Contract-update rehearsal (before any template change) +## 4. Schema changes after registration -The repo-v1 template is instantiated per-repo by clients (not deployed once), so a template fix only affects *new* repos. If you ever change it: validate with `fullValidation` + the state-level create path on **testnet first** (a real create), then ship the new template in a client release. Existing repos keep their (immutable) schema — clients already handle this via runtime compat shims + name-addressing. +Protocol 14 lets the owner update the contracts only within its update rules: new optional properties and new document types are accepted; indexes, `refersTo`/`ownerRefersTo`, `immutable`, `encryptedFor` and new required fields are frozen. Check a proposed change against the registered schema with `tools/contract-validate --previous` ([forge-v2.md §8](contracts/forge-v2.md#8-deploying)) and rehearse it on moutai. A change the rules refuse ships as a new registration (`--force-new`, or `--only collab --force-new` for forge-collab alone); documents written under the old contracts stay under their ids and are no longer read, so on mainnet that is effectively a fresh start and needs a deliberate decision. ## 5. Deploy forge-web to production -- The static export already deploys to GitHub Pages (`.github/workflows/pages.yml`). For mainnet, either flip `NEXT_PUBLIC_NETWORK` in the Pages build or host a second mainnet instance. +- The static export deploys to GitHub Pages (`.github/workflows/pages.yml`), currently built for devnet moutai (`NEXT_PUBLIC_NETWORK=devnet`, `NEXT_PUBLIC_DEVNET_NAME=moutai`). For mainnet, either switch the Pages build to `NEXT_PUBLIC_NETWORK=mainnet` or host a second mainnet instance. - Optional: publish an IPFS snapshot of `out/` for a censorship-resistant mirror (`ipfs add -r out/` via a pinning service) — the app is fully static and self-verifying. ## 6. Production smoke suite (post-deploy + weekly) -Adapt `e2e/cli/run.sh` to mainnet with a small-balance PROD identity (budget ≤ 0.05 DASH/run, mostly refunded): +Adapt `e2e/cli/run.sh` to mainnet with a small-balance PROD identity (budget ≤ 0.05 DASH/run). forge-v2 repositories, issues and Platform-stored packs cannot be deleted, so reuse one smoke repository with fresh branches per run rather than creating a repository each time: -1. Create `forge-smoke-` (or reuse a canonical dogfood repo), tiny push, fresh clone verify (fsck + byte-identical), issue create/close, **repo teardown** (reclaim refund). +1. Tiny push to `forge-smoke` on a fresh `smoke/` branch, fresh clone verify (fsck + byte-identical), issue create/close, delete the branch. 2. forge-web smoke: `pnpm exec playwright test` (the web e2e suite) pointed at the production URL on mainnet — landing + repo home + zero-backend + a11y. 3. Relay heartbeat: a smoke webhook delivered from a mainnet push (if running a relay). 4. Alerting: on failure, open a repo issue + notify; balance watchdog warns when the PROD identity < 2× run cost. @@ -66,16 +82,17 @@ Host the Dash Forge repo itself on mainnet Forge: `dg repo create dash-forge` (o ## 8. Rollback / incident -- Contracts are immutable + non-deletable — there is no "undo deploy." A bad registry deploy means deploying a *new* registry and re-pointing clients (existing listings are orphaned). So **rehearse on testnet and run the canary before mainnet**. +- Contracts are immutable in their gates and cannot be deleted — there is no "undo register." A bad registration means registering a *new* pair (`--force-new`) and shipping clients that read it; repositories created under the old pair stay there, unread. So **rehearse on moutai (and testnet once it runs protocol 14) and dry-run on mainnet first**. - A client bug ships via a normal client release (Pages redeploy / new `dg` binary) — no on-chain action. - External-backend outage: `dg reseed` from any clone restores availability; refs/manifests on Platform are unaffected. ## Pre-flight checklist -- [ ] Deployer mainnet identity funded (~3 DASH), custody model decided (jointly-held for orgs) -- [ ] `contracts/registry.json` is the reconciled source (has count indices) -- [ ] `dg`/helper built from a tagged release; `dg doctor --network mainnet` green -- [ ] Registry deployed + canary passed; `deployments/mainnet.json` committed +- [ ] Mainnet runs protocol 14 +- [ ] Contract owner and custody decided (D-D; jointly held for an org), deployer identity funded (~2 DASH) +- [ ] `config.readonly` decided and set in the schemas if wanted; pre-mainnet schema changes landed and rehearsed on moutai +- [ ] `node forge-contracts/scripts/deploy-v2.mjs --identity --network mainnet --dry-run` clean +- [ ] forge-v2 registered; `deployments/mainnet.json` (`v2`) committed; `dg doctor --network mainnet` green - [ ] forge-web built for mainnet, deployed, Playwright smoke green - [ ] Smoke suite scheduled; balance watchdog + alerting wired - [ ] Dogfood repo created and pushed diff --git a/docs/prd/01-product-overview.md b/docs/prd/01-product-overview.md index 9718746f0..a66af0cc1 100644 --- a/docs/prd/01-product-overview.md +++ b/docs/prd/01-product-overview.md @@ -1,5 +1,7 @@ # PRD 01 — Dash Forge Product Overview +> **Historical.** Written for forge-v1 (a global registry contract plus one contract per repository, with WRITE/MAINTAIN token access control). forge-v1 was removed on 2026-09-26 with no backwards compatibility. Access control is still enforced at consensus, now by `maintainer`/`writer` membership documents in the shared [forge-v2](../contracts/forge-v2.md) contracts; current planning is in [roadmap.md](../roadmap.md). + ## Vision Git hosting that cannot be taken down, censored, or rug-pulled — because there is no host. Repositories, refs, issues, and pull requests live on Dash Platform under users' own cryptographic identities, with **consensus-enforced access control** (token ACLs); bulk content lives on Platform or on cheaper hash-verified backends. GitHub's *workflow*, Bitcoin's *trust model*. diff --git a/docs/prd/02-git-remote-helper-cli.md b/docs/prd/02-git-remote-helper-cli.md index 686900827..939292fad 100644 --- a/docs/prd/02-git-remote-helper-cli.md +++ b/docs/prd/02-git-remote-helper-cli.md @@ -1,5 +1,7 @@ # PRD 02 — git-remote-dash & dg +> **Historical.** Written for forge-v1 (a global registry contract plus one contract per repository, with token access control). forge-v1 was removed on 2026-09-26 with no backwards compatibility: `dash://` URLs, token grants and `dg collab suspend` no longer exist. The current design is [forge-v2](../contracts/forge-v2.md); the current CLI surface is in [ux-dx-spec.md](../design/ux-dx-spec.md) §7 (`dg collab add|remove|list --role writer|maintainer`). + One **Rust workspace** (shared `forge-core` crate on rs-sdk/rs-dpp), multiple binaries. Radicle's remote helper is the reference implementation for helper-protocol mechanics. ## A. git-remote-dash (remote helper) diff --git a/docs/prd/03-web-app.md b/docs/prd/03-web-app.md index 57fceb135..60bc98965 100644 --- a/docs/prd/03-web-app.md +++ b/docs/prd/03-web-app.md @@ -1,5 +1,7 @@ # PRD 03 — Forge Web (zero backend) +> **Historical.** Written for forge-v1 (a global registry contract plus one contract per repository, with token access control). forge-v1 was removed on 2026-09-26 with no backwards compatibility; the token collaborator UI described below no longer exists. The current design is [forge-v2](../contracts/forge-v2.md) and the current web spec is [ux-dx-spec.md](../design/ux-dx-spec.md). + Static SPA deployable to IPFS or any static host, fully replacing github.com browsing and collaboration. Stack: Next.js static export (query-param routing, yappr rules), **wasm/evo-sdk for all Platform reads/writes**, and the zero-backend trick: **in-browser repo materialization** — isomorphic-git + lightning-fs in a web worker, cloning from chunk/CID fetches, never from a git server. ## Stack (reuse-first, per INIT.md) diff --git a/docs/prd/04-storage-adapters.md b/docs/prd/04-storage-adapters.md index 56d543a99..f7c8c3846 100644 --- a/docs/prd/04-storage-adapters.md +++ b/docs/prd/04-storage-adapters.md @@ -1,5 +1,7 @@ # PRD 04 — Storage Backends (Platform primary; IPFS / S3 / HTTPS / mirrors for fee reduction) +> **Partly historical.** References to "the repo contract" and MAINTAIN-gated `config` come from forge-v1 (one contract per repository, with token access control), removed on 2026-09-26. `config` is now a forge-core document written by maintainers ([forge-v2](../contracts/forge-v2.md)); the as-built storage section below is current. + **Platform is primary storage and always the source of truth**: refs and pack manifests live on Platform in every mode. Backends control only where **pack bytes** rest. External backends are verifiable caches — integrity comes from manifest SHA-256 + git OIDs, never from the host. This is the "reduced fees on certain projects" layer; GA in Phase 4 (platform + basic ipfs read earlier for import/dogfood needs). ## Backend descriptor @@ -50,7 +52,7 @@ User guide: [`docs/guides/bring-your-own-storage.md`](../guides/bring-your-own-s **Where things live.** The backend descriptor above assumed that the on-chain `config.backend` chooses where a push writes. As built, it does not, because the chain cannot hold the credentials a write needs: - **Profiles** (`forge_core::storage::profiles`) live in `~/.config/dash-forge/storage.toml` (or `$DASH_FORGE_STORAGE_CONFIG`). Kinds are `s3 | ipfs-kubo | ipfs-pinning-service | platform`. Secret fields hold only `env:VAR` or `keychain:/` references (macOS `security`, freedesktop `secret-tool`). They resolve into the redacting `keystore::Secret`, and loading a file that contains a literal secret fails without echoing it. Field names are chosen so the web app's encrypted vault can store the same shape. - **Policy** (`forge_core::storage::policy`) is in git config: `dash.storage` (profile names), `dash.replicas` (N, defaulting to every target) and `dash.platformFallback`, with `remote..dash*` overrides. **No policy means Platform only**, byte-for-byte the old behaviour, including the resumable chunk journal. -- The on-chain `config.backend { mode, uris }` only **advertises** the policy's mode and public read bases (`dg storage advertise`, via `RepoService::set_backend`). The contract schemas are unchanged (repo-v1, nested `backend`). +- The on-chain `config.backend { mode, uris }` only **advertises** the policy's mode and public read bases (`dg storage advertise`, via `RepoService::set_backend`). The contract schema is unchanged (forge-core `config`, nested `backend`). **Push path** (`git-remote-dash/src/helper.rs`): 1. Build the pack. diff --git a/docs/prd/05-forge-relay.md b/docs/prd/05-forge-relay.md index 63f96d129..249e49ee1 100644 --- a/docs/prd/05-forge-relay.md +++ b/docs/prd/05-forge-relay.md @@ -1,5 +1,7 @@ # PRD 05 — Forge Relay +> **Partly historical.** The design section and the WRITE-token wording come from forge-v1 (one contract per repository, with token access control), removed on 2026-09-26. The "As built" section describes the current [forge-v2](../contracts/forge-v2.md) relay; a CI runner now writes `checkRun` documents as a `writer` or `maintainer` member. + ## Goal Bridge Platform's pull-only world to webhook-driven CI and notifications **without becoming a trusted party**. Trust is only availability, never integrity: consumers re-fetch and verify everything from Platform. @@ -15,7 +17,7 @@ Stateless Rust daemon (workspace member alongside dg/helper): ### As built (forge-v2, protocol 14) -The relay serves forge-v2 repositories only; v1 repositories are read-only and have no webhooks. It polls rather than subscribing to the firehose (item 1): per repo, the `$createdAt`-ending indexes of `refUpdate`/`protectedRefUpdate`, `release`, `issue`, `patch`, `event`/`authorEvent` (feed), `comment` (per target), `review` (per PR) and `checkRun` (per head). Subscriptions are forge-collab `webhook` documents, gated to maintainers at consensus; the relay finds its hooks through the `relay` index, resolves newest per `(repoId, hookId)`, requires the writer to still be a maintainer, and decrypts the `encryptedFor` secret with its ENCRYPTION key (`forge_core::envelope`, `forge_core::webhooks`). Delivery is best effort: up to 5 attempts within 30 s per delivery, then a dead-letter log line; there is no durable retry queue (item 3 is not built). Delivery runs on per-hook workers with a circuit breaker, decoupled from polling. Operator docs: `crates/forge-relay/README.md`. +The relay serves forge-v2 repositories. It polls rather than subscribing to the firehose (item 1): per repo, the `$createdAt`-ending indexes of `refUpdate`/`protectedRefUpdate`, `release`, `issue`, `patch`, `event`/`authorEvent` (feed), `comment` (per target), `review` (per PR) and `checkRun` (per head). Subscriptions are forge-collab `webhook` documents, gated to maintainers at consensus; the relay finds its hooks through the `relay` index, resolves newest per `(repoId, hookId)`, requires the writer to still be a maintainer, and decrypts the `encryptedFor` secret with its ENCRYPTION key (`forge_core::envelope`, `forge_core::webhooks`). Delivery is best effort: up to 5 attempts within 30 s per delivery, then a dead-letter log line; there is no durable retry queue (item 3 is not built). Delivery runs on per-hook workers with a circuit breaker, decoupled from polling. Operator docs: `crates/forge-relay/README.md`. ## Deployment - Docker one-liner; config = relay identity key + network. DCG/community run public instances; anyone can run their own (per-repo choice via `webhook.relayIdentityId`). diff --git a/docs/prd/06-forge-import.md b/docs/prd/06-forge-import.md index 08bdc3851..6f98beb98 100644 --- a/docs/prd/06-forge-import.md +++ b/docs/prd/06-forge-import.md @@ -1,5 +1,7 @@ # PRD 06 — Forge Import +> **Historical.** Written for forge-v1 (one contract per repository from the `repo-v1` template), removed on 2026-09-26 with no backwards compatibility. Imported data now lands in the shared [forge-v2](../contracts/forge-v2.md) contracts. + ## Goal `dg import github.com/org/repo` migrates code + issues + PRs + releases + labels + milestones in one command. Launch adoption depends on this. diff --git a/docs/research/platform-constraints.md b/docs/research/platform-constraints.md index e91b1c26a..3ce9c03dc 100644 --- a/docs/research/platform-constraints.md +++ b/docs/research/platform-constraints.md @@ -1,5 +1,7 @@ # Dash Platform — Constraints & Research Findings +> **Historical.** Research from the forge-v1 design phase (protocol 12). Most Platform limits below still apply, but the design consequences that rely on per-repo contracts and token-cost ACLs describe forge-v1, which was removed on 2026-09-26. The current design is [forge-v2](../contracts/forge-v2.md) on Platform protocol 14. + All findings verified against the local monorepo `../platform` (version **4.0.0-beta.3**, protocol v12 era). File paths below are relative to that repo. These numbers are the load-bearing inputs to every Dash Forge design decision. ## 1. Hard system limits diff --git a/docs/research/spike-results.md b/docs/research/spike-results.md index cb0c64999..3d92c51b0 100644 --- a/docs/research/spike-results.md +++ b/docs/research/spike-results.md @@ -1,5 +1,7 @@ # Dash Forge — Spike Results (Stage 1) & Design Freeze #1 +> **Historical.** Spike results for forge-v1 (a global registry contract plus one contract per repository, with token access control), run on testnet in July 2026. forge-v1 was removed on 2026-09-26 with no backwards compatibility; the token-ACL and contract-topology decisions below no longer apply. The current design is [forge-v2](../contracts/forge-v2.md). + All nine Phase-0 spikes executed against live testnet / real backends. Per-spike detail lives in `spikes/S0.*/RESULTS.md`; this is the consolidated record and the input to Design Freeze #1. **Headline: GO.** Every load-bearing assumption held or was corrected without a structural redesign. ## Results at a glance diff --git a/docs/roadmap.md b/docs/roadmap.md index df9f07e3b..35ef29522 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -17,10 +17,13 @@ This document covers three things: | 2026-07-22 → 23 | Stages 2–6 built in about 36 hours: `forge-core`, `git-remote-dash` (**M1**: byte-identical `git clone`/`git push` round-trip on testnet), `dg` plus `forge-relay` (**M2**: push → webhook → CI check written back), `forge-web` plus `forge-import` (**M3**: web app live, GitHub import within 1.1% of the cost estimate), backends and repack/GC (**M4**), CLI and Playwright e2e suites. The registry was redeployed to fix a `$createdAt` index defect. `EXECUTION.md` declared "ALL STAGES COMPLETE". | | 2026-08-06 → 26 | Maintenance: a watchdog for stalled pushes in the importer, GFM tables, a persistent in-browser clone cache, and moving the web app to `forge.dashhq.org`. A web PR-diff renderer was written on `fix/pull-request-diff` but **never merged**. | | 2026-09-10 → 22 | An honesty and correctness pass (PRs #1–#4):
• **#1** The Rust workspace did not even parse, and the nightly had been passing without running anything.
• **#2** Every read was silently capped at 100 rows. That made folds confidently wrong: issues showed open after being closed, branches froze at push #100, packs were read from the wrong index, and branch protection turned itself off.
• **#3** Three PR commands reported success for work they never did, and review verdicts were written but never read.
• **#4** No code path ever published the browse index (open). | +| 2026-09-24 → 26 | forge-v2 (D-A) registered on devnet moutai and built out in the CLI, web app, importer, relay and Mirror Action. forge-v1 removed with no backwards compatibility (D-M); forge.dashhq.org and the nightly moved to moutai. | **What the history tells us.** The architecture is sound and the hard protocol problems are solved. Consensus-enforced ACLs work: a frozen push is rejected with 40702. Proof-verified reads, resumable pushes, and a cross-client rules engine with 70 conformance vectors are all in place. The build log's "complete", though, meant *demonstrated once on testnet*, not *usable by a stranger*. Every audit since has found product claims the code doesn't back up. The first job is to make the product true. The second is to make it wanted. -## 2. Where it stands today (verified on `master` @ `b0bc7bb`) +## 2. Where it stood (verified on `master` @ `b0bc7bb`, 2026-09-24) + +> This is the forge-v1 baseline the plan started from. Gaps 1 and 2 are closed by forge-v2 (D-A, D-M): contract ids come from per-network deployment records, a repository costs about 0.001 DASH, and v1 no longer exists. The execution tracker (§6) has the current state. ### Works - `git clone`/`git push` over `dash:///`: resumable push, partial clone, jj compatibility, consensus-rejected unauthorized pushes. @@ -78,11 +81,12 @@ Every roadmap item must keep all of these true: | D-J | **Mainnet contracts are registered by the owner** once PV14 is active on mainnet (expected ~1 month after 2026-09-24; testnet ~1–2 weeks). All PV14 development happens on **devnet moutai** (protocol 14, drive 4.2.0-beta.4) until then. | | D-L | **Sign in with a mobile Dash wallet (yappr / App Connect style)** is a launch requirement (owner, 2026-09-26). A user scans a QR (or taps a deep link on mobile) with the Dash Wallet app on iOS or Android, approves on the phone, and is signed in with a limited, contract-group-bound key. No key file and no key paste in the browser. See Phase 4. | | D-K | External accounts (Apple signing, pinning services, cloud buckets) are **out of scope for now**. S3 and IPFS are tested against local MinIO and kubo only. | +| D-M | **2026-09-26: forge-v1 removed, no backwards compatibility; forge-v2 only.** The registry contract, the per-repo contract template, token ACLs, v1 read compatibility (`dash://`, `?contract=` routes), the registry overrides and `dg collab suspend/unsuspend` are gone, and there is no migration path. The v1 data on testnet and on forge.dashhq.org was test data only the owner used. The hosted web app is built for devnet moutai until forge-v2 is registered on testnet (when PV14 reaches it) and mainnet. | ### Still open | # | Question | Default until decided | |---|---|---| -| D-D | Who owns the mainnet registry and shared contract (identity and key custody)? | The owner decides before registering. The deploy script takes the owner identity as input. | +| D-D | Who owns the mainnet forge-v2 contracts and contract group (identity and key custody)? | The owner decides before registering. The deploy script takes the owner identity as input. | | D-C | Trust anchor: web app and CLI take quorum keys from a known HTTPS endpoint. | Cross-check ≥2 endpoints, disclose honestly in the trust panel; SPV quorum verification in the CLI later. | | D-E | Should opening a PR require a token? | No: anyone may open one, with client-side spam filtering. | @@ -94,8 +98,8 @@ Sizes: S ≈ days, M ≈ 1–2 weeks, L ≈ 3+ weeks of focused work. Phase 0 co - [ ] Land PR #4 (browse index on push). Rebase and land `fix/pull-request-diff` (PR diff renderer). - [ ] Fix the nightly: the landing-page contrast failure; the scenario 07 hang/timeout; transport flakes retried until they give a verdict rather than a SKIP. - [ ] Trust panel driven by actual verification state, with "unverified" and "partial" states; remove the hard-coded "verified" chips. -- [ ] Show "Merge" only to WRITE/MAINTAIN holders and label it for what it does until Phase 4. Star/follow read their initial state; Archive is implemented or removed. -- [ ] Network config: registry and contract ids per network (testnet, **devnet** with a name such as `moutai`, mainnet) loaded from `forge-contracts/deployments/.json` in forge-core, dg, the relay, doctor and web. No hard-coded ids. +- [ ] Show "Merge" only to writers and maintainers and label it for what it does until Phase 4. Star/follow read their initial state; Archive is implemented or removed. +- [ ] Network config: contract ids per network (testnet, **devnet** with a name such as `moutai`, mainnet) loaded from `forge-contracts/deployments/.json` in forge-core, dg, the relay, doctor and web. No hard-coded ids. - [ ] Docs: correct the CLI trust mode, the README status and domain, `EXECUTION.md` → this roadmap. ### Phase 1 — Bring your own storage, for real (L) · *gate: the survivability drill passes* @@ -112,8 +116,7 @@ Sizes: S ≈ days, M ≈ 1–2 weeks, L ≈ 3+ weeks of focused work. Phase 0 co - [ ] `forge-v2` shared contract: `repo`, `writer`/`maintainer` membership docs keyed `(repoId, memberId)`, with the owner-only grant enforced by a `$ownerId` `propertyAgreement` against the repo doc; `ownerRefersTo` writer gates on ref/pack/manifest/release/config types; no moderation; `readonly` once final. Validated offline against rs-dpp beta.4, then registered on moutai. - [ ] If the schema exceeds 16 KiB, split it into core and collab contracts that reference each other, joined by a PV14 contract group. - [ ] forge-core, the web app and the conformance vectors on the new model. Cross-repo queries arrive for free (my PRs, activity, issue search), and forks point at parent packs. -- [ ] Migration: the importer copies v1 repos into forge-v2 (history preserved); v1 stays readable. -- [ ] Remove the per-repo contract (repo-v1 token ACL) write paths once forge-v2 is the default. Keep read compatibility. +- [x] Remove forge-v1 (registry, per-repo contracts, token ACL) entirely, with no read compatibility and no migration (D-M). - [ ] e2e on moutai: grant → push → revoke → the push is rejected at consensus, plus everything from the CLI suite. - [ ] `git push` cost guard (`dash.costWarnThreshold`, `dash.confirm`). - [ ] PV14 extras: **budget- and expiry-limited keys** bound to the forge contract for web login and CI runners (in place of raw key paste); `encryptedFor` for relay webhook secrets; `indexOnly` stars/follows. @@ -168,18 +171,16 @@ Work: ### Later Organizations (multi-member admin sets, key custody guide), template versioning, audit-log compaction, large files through pointers to the user's bucket, SHA-256 repos, optional user-run indexer for global search. -### Execution tracker (updated 2026-09-25) +### Execution tracker (updated 2026-09-26) Landed on master: - **Phase 0:** #4 browse index · #6 honest UI · #8 PR/commit diffs · #10 + #14 nightly green (CLI and Playwright, fixture isolation, keyset ref reads) · #11 per-network config. - **Phase 1:** #12 bring-your-own storage on push (SigV4 S3, IPFS/pinning, replication, `dg storage`, `dg reseed --from-local`). -- **Phase 2 (forge-v2 on devnet moutai):** #5 devnet tooling · #7 forge-v2 contracts · #9 FORGE_RULES_V2 + authorEvent · #15 SDK 4.2 · #18 CLI data plane (repo create ≈0.001 DASH, consensus-enforced membership) · #17 web reads. +- **Phase 2 (forge-v2 on devnet moutai):** #5 devnet tooling · #7 forge-v2 contracts · #9 FORGE_RULES_V2 + authorEvent · #15 SDK 4.2 · #18 CLI data plane (repo create ≈0.001 DASH, consensus-enforced membership) · #17 web reads · #25 moutai re-registration · #22 CLI issues/PRs/releases/forks · #23 web writes · #26 web fork reads · #27 relay (chain-encrypted webhook secrets) · #30 forge-import on v2 (`dg import`). +- **Phase 4:** #24 web limited-key sign-in, vault and in-browser identity creation · #31 GitHub Mirror Action. - **Adoption:** #13 release pipeline + install.sh · #16 actionable errors (`docs/errors.md`) · #19 user guides. +- **D-M:** forge-v1 removed; forge.dashhq.org and the nightly ("Devnet Nightly") target moutai. -The nightly is green on master, and the CLI suite now runs on moutai. - -In flight: CLI issues/PRs/releases/forks on v2 (D) · import/relay/migrate + GitHub Mirror Action (G) · web v2 writes + limited-key sign-in + cost UX (F). - -Next: private repos (Phase 3, design: [docs/security/private-repos.md](security/private-repos.md), reviewed; its §13 lists contract changes required before mainnet registration) · storage wizard in web · Explore/notifications · docs refresh for v2. +Next: private repos (Phase 3, design: [docs/security/private-repos.md](security/private-repos.md), reviewed; its §13 lists contract changes required before mainnet registration) · storage wizard in web · Explore/notifications · register forge-v2 on testnet when PV14 reaches it, and move the nightly and a testnet web build there. Launch UX/DX is specified in [docs/design/ux-dx-spec.md](design/ux-dx-spec.md) §11. Its **P0 backlog is the launch checklist** and supersedes the per-phase bullet lists below where they overlap. @@ -199,7 +200,7 @@ Public beta ships when all of these hold on **mainnet**: | Risk | Mitigation | |---|---| | PV14 semantics shift before mainnet (4.2 is beta), or the devnet is reset | Pin the SDK tag, keep the forge-v2 schema in tests validated against each new 4.2 tag, and script the full moutai deploy so a reset costs minutes. | -| A revoked writer can still delete the Platform chunks they uploaded (no token cost on delete) | External storage is the default, and repack re-uploads. Documented in the trust model. | +| A revoked member can still delete their own deletable documents (Platform does not reference-check deletes) | Every history-bearing type (refs, packs, chunks, config, events, issues, PRs) is non-deletable. The residual case is a revoked maintainer deleting a release they published; readers fall back to the next-newest release for that tag ([forge-v2.md §4](contracts/forge-v2.md#4-non-deletable-audit-types)). | | Private-repo key handling mistakes | A separate design doc, an independent security review, test vectors, and no "private" label in the UI until it passes. | | A user's bucket disappears (unpaid, deleted) | Replication to N targets the user chooses, `packMirror` + reseed by anyone, a storage-status warning when a pack's live copies drop below N, and Platform as a fallback tier. | | Testnet instability makes CI flaky | Tell transport flakes apart from real failures, retry with backoff, and record flake rates. | diff --git a/docs/testing/e2e-test-plan.md b/docs/testing/e2e-test-plan.md index 3a0977d82..7300d1112 100644 --- a/docs/testing/e2e-test-plan.md +++ b/docs/testing/e2e-test-plan.md @@ -4,78 +4,84 @@ Full pyramid with emphasis on **real end-to-end testing against live networks**, ## 1. Test infrastructure: identities & funding -### 1.1 Obtaining identities (testnet) +forge-v2 (shared contracts forge-core + forge-collab, Platform protocol 14; [contracts/forge-v2.md](../contracts/forge-v2.md)) is deployed only on **devnet moutai** today, so every live suite runs there. Testnet runs resume once protocol 14 reaches testnet and forge-v2 is registered there. -**A. Pre-provisioned fixture pool (primary).** 8+ funded testnet identities minted via bridge.thepasta.org (`?network=testnet`), exported bridge-format JSON (mnemonic + 5 keys incl. High/Critical AUTH WIFs). Roles: OWNER, MAINTAINER, COLLAB, CONTRIB (no tokens), FROZEN (suspended collaborator), CI-RUNNER, RELAY, DEPLOYER, TREASURY. CI secrets; locally `~/.config/dash-forge/test-identities/` (gitignored — yappr's checked-in identity JSONs are explicitly not repeated). `pretest` balance guard auto-tops-up or fails with instructions. +### 1.1 Obtaining identities (devnet moutai) -**B. Programmatic minting (`spikes/mint-identity` → `tools/mint-identity`, built in Phase 0 S0.4).** Headless flow reimplementing the bridge: derive HD keys → `POST https://faucet.thepasta.org/api/core-faucet {address}` (~1 tDASH; **3/hour/IP**, optional CAP PoW solver; on 429 fall back to L1 spend from TREASURY) → poll Insight for UTXO → type-8 asset-lock tx → InstantSend lock → `identities.create` → bridge-format JSON out. Used for onboarding tests, pool replenishment, top-ups. +**A. Pre-provisioned fixture pool (primary).** Funded moutai identities minted by `make devnet-identities` (`tools/mint-identity pool`, funded from the devnet's faucet wallet key; manual top-ups from https://faucet.moutai.networks.dash.org or the bridge at https://bridge.thepasta.org/?network=devnet-moutai), as bridge-format JSON (mnemonic + keys incl. High/Critical AUTH WIFs). Roles: OWNER (owns the test repos, adds and removes members), MAINTAINER, COLLAB (added as a writer, then removed), CONTRIB (never a member), CI-RUNNER, RELAY, DEPLOYER (registered forge-v2 on moutai), TREASURY. CI secrets; locally `~/.config/dash-forge/test-identities/devnet-moutai/` (gitignored — yappr's checked-in identity JSONs are explicitly not repeated). `make devnet-identities-verify` checks balances and keys. + +**B. Programmatic minting (`tools/mint-identity`, built in Phase 0 S0.4).** Headless flow reimplementing the bridge: derive HD keys → fund the deposit address (a devnet funding key; on testnet `POST https://faucet.thepasta.org/api/core-faucet {address}`, **3/hour/IP**, with TREASURY as the fallback) → asset-lock tx → chain lock (devnet) or InstantSend lock (testnet) → `identities.create` → bridge-format JSON out. Used for onboarding tests, pool replenishment, top-ups. ### 1.2 Environments | Env | Purpose | |---|---| -| Local devnet (dashmate, `../platform`) | Contract/template update rehearsals, destructive token-ACL probing | -| **Testnet** | All integration + e2e suites (default) | -| Mainnet | Phase 1 M1 protocol validation (small repos) + production smoke (§8) | +| **Devnet moutai** (protocol 14, drive 4.2.0-beta.4) | All integration + e2e suites; contract re-registration rehearsals (`deploy-v2.mjs --force-new`) | +| Testnet | The same suites once protocol 14 and forge-v2 are live there | +| Mainnet | Production smoke (§8) after forge-v2 is registered there | -Contract/template IDs from `forge-contracts/deployments/.json`; never hardcoded. Test repos namespaced `e2e--*`, deleted in teardown (refunds keep the pool solvent — deletion is itself under test). +Contract ids from the `v2` section of `forge-contracts/deployments/.json` (`devnet-moutai.json`); never hardcoded. forge-v2 repositories, issues, PRs, events and Platform-stored packs cannot be deleted, so suites reuse reserved fixture repos (e2e/README.md) and write fresh `e2e//…` branches, deleting the refs after each run, instead of creating and deleting repositories. ## 2. Pyramid | Layer | Tooling | Network | When | |---|---|---|---| | Unit: chunker bounds, offset index, pack assembly, rules folds, cost math, backends (mocked) | cargo test / vitest | none | every PR | -| **Conformance vectors** (`FORGE_RULES_V1`): Rust and TS suites against shared JSON fixtures — ref resolution, protected patterns, event folds, claim mapping | both | none | every PR | -| Contract validation: registry+template construct `fullValidation`, serialized < 16 KiB, index bounds, tokenCost config | wasm-sdk harness | none | every PR | -| Integration: forge-core services against live contracts | cargo test (serial per identity) | testnet | nightly + pre-merge label | -| E2E CLI (real `git` + helper + dg) | bash/rust harness | testnet | nightly + release | -| E2E Web | Playwright | testnet | nightly + release | -| Relay + import + chaos | mixed | testnet | release | +| **Conformance vectors** (`FORGE_RULES_V2`, `forge-contracts/vectors/`): Rust and TS suites against shared JSON fixtures — ref resolution, protected patterns, issue/PR folds over `event` + `authorEvent`, numbering, approvals, pack reader rule and pack list, plaintext-or-`enc`, repo names | both | none | every PR | +| Contract validation: `tools/contract-validate` builds forge-core + forge-collab with `fullValidation` at `PlatformVersion` 14, signed transition < 20,480 B, index bounds; `--previous` checks an update against the registered schema | cargo | none | every PR | +| Integration: forge-core services against live contracts | cargo test (serial per identity) | devnet moutai | nightly + pre-merge label | +| E2E CLI (real `git` + helper + dg) | bash harness (`e2e/cli/run.sh`) | devnet moutai | nightly + release | +| E2E Web | Playwright | devnet moutai | nightly + release | +| Relay + import + chaos | mixed | devnet moutai | release | | Production smoke | scripted | mainnet | post-deploy + weekly | -Flake policy: writes always via the idempotent WriteEngine (a timeout-flake is a product bug, not a test bug); one job-level retry; persistent failures invoke the testnet-instability playbook (devnet contingency). +Flake policy: writes always via the idempotent WriteEngine (a timeout-flake is a product bug, not a test bug); one job-level retry; persistent failures invoke the network-instability playbook. -## 3. Token-ACL consensus suite (the novel risk — S0.7 grown into permanent tests) +## 3. Membership-gate consensus suite (the novel risk) -1. ⭐ **Frozen identity's push fails at consensus**: OWNER grants COLLAB (mint 10⁹ WRITE) → COLLAB pushes OK → OWNER freezes → COLLAB's next chunk/refUpdate ST **rejected by the network** (assert consensus error, not client refusal). -2. Revoke = freeze + destroy frozen funds → balance query shows removal (on-chain collaborator list correct). -3. CONTRIB (no tokens) refUpdate ST rejected; un-gated `issue`/`comment`/`patch` creation succeeds. -4. MAINTAIN gating: COLLAB (WRITE only) cannot create `protectedRefUpdate`/`release`/`label`/`webhook`; MAINTAINER can. -5. Group-held admin: two-identity group mints/freezes (org scenario). -6. **Delete-gating**: FROZEN identity attempts to delete its own previously-uploaded `chunk`/`packManifest` docs → **rejected at consensus** (availability of past uploads survives revocation); active COLLAB's gated delete succeeds with storage refund. -7. **Non-deletable audit docs**: any identity's attempt to delete its own `refUpdate`/`event`/`config` doc is rejected by the platform (`canBeDeleted: false`) — the branch-rewind and silent-reopen attacks are structurally impossible. -8. **Protected-ref rules**: MAINTAINER posts `config` protecting `refs/heads/main` → COLLAB (WRITE-only) plain refUpdate on main is accepted at consensus but **inert under FORGE_RULES** (fresh clone ignores it; conformance vectors cover the as-of-time boundary: pre-protection updates remain valid, tie-at-same-timestamp resolves protected). -9. **Count-tree correctness**: star/follow/fork/issue/PR/comment counts via count queries (+WithProof) match paginated ground truth after concurrent create/delete churn; `chunk(packHash)` count vs `manifest.chunkCount` audit detects a deliberately withheld chunk. -10. Edge probes (documented, not asserted until semantics reviewed): re-grant after destroy; token behavior across contract update; unique+countable flag combination (S0.6). +1. ⭐ **Revoked writer's push fails at consensus**: OWNER adds COLLAB (`dg collab add --role writer`) → COLLAB pushes OK → OWNER removes it (`dg collab remove`, deleting the `writer` document) → COLLAB's next chunk/refUpdate ST **rejected by the network** with 40120 (assert the consensus error, not a client refusal). CLI scenario 04. +2. `dg collab list` reflects adds and removes (the on-chain member list is correct). +3. CONTRIB (never a member) refUpdate ST rejected at consensus (40120, CLI scenario 05); un-gated `issue`/`comment`/`patch`/`review` creation succeeds. +4. Maintainer gating: a writer cannot create `protectedRefUpdate`/`config`/`release`/`webhook`/`repoKey`; a maintainer can. Only the repo owner can create `maintainer`/`writer` documents. +5. **Events**: a member's `event` is accepted for every kind; the target's author may post `authorEvent` close/reopen only; a stranger's close is refused at consensus (40120, CLI scenario 09). A revoked member's past events stay valid. +6. **Non-deletable types**: any identity's attempt to delete its own `refUpdate`/`protectedRefUpdate`/`config`/`packManifest`/`manifestPart`/`chunk`/`event`/`authorEvent`/`issue`/`patch`/`repo` is rejected by the platform — the branch-rewind, silent-reopen and pack-yank attacks are structurally impossible. +7. **Protected-ref rules**: MAINTAINER posts `config` protecting `refs/heads/main` → a writer's plain refUpdate on main is accepted at consensus but **inert under FORGE_RULES_V2** (fresh clone ignores it; conformance vectors cover the as-of-time boundary: pre-protection updates remain valid, tie-at-same-timestamp resolves protected). +8. **Pack front-running**: a stranger (or revoked writer) posting a manifest or chunk with an honest pack's hash does not block the honest upload (`$ownerId` in every pack-write unique index) and is ranked last by the reader rule. +9. **Count correctness**: star/follow/issue/PR/comment counts via count queries (+WithProof) match paginated ground truth after concurrent create/delete churn; `chunk(packHash)` count vs `manifest.chunkCount` audit detects a deliberately withheld chunk. +10. Edge probes (documented, not asserted until semantics reviewed): re-add after remove (counts from the new document); contract update that tries to loosen a gate (refused by `validate_update`). ## 4. E2E CLI suite Assertions: `git fsck` clean, `git rev-parse` equality, object counts, worktree `diff -r`. +**Implemented today** (`e2e/cli/run.sh`, `make e2e`, 11 scenarios on moutai against the OWNER-owned `e2e-cli` repo; details in `e2e/README.md`): 01 round-trip, 02 non-ff, 03 ref delete, 04 revoked-writer push, 05 non-member push, 06 third-party verify, 07 depth + filter, 09 issue lifecycle, 10 PR from a fork, 11 release asset, 12 star/unstar. (08 was the forge-v1 read-compat scenario, removed with v1; the number is not reused.) `make storage-e2e` (`e2e/cli/storage-byo.sh`) covers bring-your-own storage. The full plan: + 1. **Round-trip, platform backend**: seeded repo (100 commits, binaries, tags, symlinks) push → fresh clone byte-identical; proof-verified refs. 2. ⭐ **Monorepo round-trip**: clone/push of the **Dash Platform monorepo** itself (mixed backend). 3. **Scale ladder** (from S0.1, kept as regression): 5 MB / 25 MB / 100 MB packfile pushes — wall-clock + credits vs estimates recorded; alert on >20% drift (fees-ledger regression). 4. ⭐ **Interrupted 100 MB push resumes**: kill -9 mid-upload → re-push completes **without re-paying for uploaded chunks** (journal), fees ≈ single-push. -5. **Multi-maintainer**: grant → COLLAB pushes → third machine sees COLLAB's tip; suspend → push fails (overlaps §3.1 at git-porcelain level). +5. **Multi-member**: `dg collab add` → COLLAB pushes → third machine sees COLLAB's tip; `dg collab remove` → push fails at consensus (overlaps §3.1 at git-porcelain level; scenario 04). 5b. **Concurrent-push race**: OWNER and COLLAB both push fast-forwards from the identical prevOid simultaneously → both STs land at consensus; the losing helper's post-push verification reports a late non-fast-forward (never a silent success); fresh clone shows the ref as diverged/provisional per FORGE_RULES until a superseding merge/force push; conformance vectors cover the divergence fold. -6. **Force-push / delete / protected refs**: non-FF refused without `+`; force flag recorded; zero-OID delete; protected pattern routes to `protectedRefUpdate` and WRITE-only pusher fails. +6. **Force-push / delete / protected refs**: non-FF refused without `+`; force flag recorded; zero-OID delete; protected pattern routes to `protectedRefUpdate` and a writer (not maintainer) pusher fails. 7. **Partial clone**: `--filter=blob:none` clone writes `.promisor` markers, then a lazy blob read triggers a bare-OID fetch via offset index — bytes transferred ≪ full pack (assert ranged fetch happened). **Shallow clone unsupported**: `--depth 1` **fails loudly** with a clear error (never a silent full clone) — Design Freeze #1, S0.9. 8. ⭐ **jj compatibility**: jj (git backend, ≥ 0.43, **no colocation**) init/fetch/push against dash:// remote unmodified — S0.9-confirmed; kept as a CI smoke test guarding the gitoxide transport-delegation guarantee. -9. **Repack/GC**: 10 pushes → `dg repack` → superseded docs deleted → clone exact; **storage refund observed** in balance; steady-state cost ≈ current size. +9. **Repack**: 10 pushes → `dg repack` → a superseding consolidated pack; nothing deleted on Platform (non-deletable chunks/manifests); readers prefer the consolidated pack; clone exact. 10. **Backends**: same pack via IPFS and S3 (MinIO) clones identically; tampered URI detected + failed over; `dg reseed` after host loss restores availability; mixed-mode cold/hot split works. 11. **dg workflow** ⭐: maintainer triages issues, reviews and lands a PR (`pr checkout`→`review`→`merge`), cuts a release — terminal only. 12. **Fresh-user onboarding**: mint identity via §1.1-B → `dg auth login` → repo create → push (zero prior state). 13. ⭐ **Third-party verification**: standalone script (no forge-core) reconstructs a clone from raw DAPI queries + manifests and verifies every hash — "no trust in any server" acceptance. -## 5. E2E Web suite (Playwright vs static build on testnet) +## 5. E2E Web suite (Playwright vs a static build for devnet moutai) -1. **Logged-out browse**: tree/blob/blame/history/README/diff on CLI-seeded repo; verification chips; request-interception proves zero non-DAPI/non-backend origins. +The specs read the forge-v2 read fixture (`forge-v2-demo` and `forge-v2-empty` on moutai), seeded idempotently by `forge-contracts/scripts/seed-v2-fixture.mjs`. + +1. **Logged-out browse**: tree/blob/blame/history/README/diff on the seeded repo; verification chips; request-interception proves zero non-DAPI/non-backend origins. 2. **Auth**: key login, password vault, passkey PRF (virtual authenticator), logout clears storage. -3. **Repo lifecycle**: create (contract instantiate + cost preview), settings, backend switch, delete + refund estimate. -4. **Issues**: full lifecycle across two browser identities; labels (MAINTAIN); event timeline order; visitor sees updates within poll interval. +3. **Repo lifecycle**: create (three documents + cost preview), settings, backend switch. +4. **Issues**: full lifecycle across two browser identities; labels (member); event timeline order; visitor sees updates within poll interval. 5. ⭐ **Full review flow**: line comment → request changes → re-review → **merge from browser** (FF/clean via isomorphic-git); merged state visible to CLI clone. 6. **Browser edit**: CodeMirror edit → commit → push → visible in CLI clone. -7. **Collaborator token UI ↔ CLI parity**: web grant → immediate CLI push; web suspend → CLI push fails at consensus. +7. **Collaborator UI ↔ CLI parity**: web add member → immediate CLI push; web remove → CLI push fails at consensus (40120). 8. **checkRun rendering**: CI-RUNNER writes check docs → PR shows status. 9. **Browse plane**: repo-of-any-size fixture (largest available, e.g. imported platform monorepo) → cold repo home renders < 500 KB transferred / < 3 s (request-interception byte accounting); blob + directory + commit-log views stay O(view); degraded path (repo with no flatIndex/locator) still renders via object walk; materialization-tier features (search/blame) show the 100 MB size warning; warm reload < 1.5 s. 10. **Search**: per-repo client-side index finds seeded symbol; index persists in IndexedDB. @@ -88,13 +94,15 @@ Assertions: `git fsck` clean, `git rev-parse` equality, object counts, worktree **Import**: ⭐ dashpay/platform import — fidelity spot-check script (GitHub API vs Platform docs: counts, titles, states, threads, labels) and ⭐ **cost within 10% of pre-estimate**; `--dry-run` writes nothing; interrupt + `--resume` no duplicates/double fees; gist-claim flow renders claimed identity in web + dg. -## 7. Contract & template lifecycle testing +## 7. Contract lifecycle testing + +Every forge-core/forge-collab schema change: `tools/contract-validate` (with `--previous` against the registered schema, to tell an in-place update from a re-registration) → register or update on moutai (`deploy-v2.mjs`, `--force-new` when the update rules refuse the change) → re-seed the read fixture → full nightly; testnet the same once it runs protocol 14. Post-deploy assertion: both contracts fetch with proof and are enrolled in the recorded contract group (`dg doctor` checks this), plus a canary document per gated type. -Devnet → testnet rehearsal for every registry/template change; post-deploy assertion (fetch, diff vs source, canary doc per type incl. token-gated ones); template-migration drill: repo on template v1 while v2 exists — listing `templateVersion` honored by all clients; backward-compat CI gate (additive-only schema changes). +## 8. Production (mainnet) smoke — post-deploy + weekly, budget ≤ 0.05 DASH/run -## 8. Production (mainnet) smoke — post-deploy + weekly, budget ≤ 0.05 DASH/run (mostly refunded) +forge-v2 repositories, issues and Platform-stored packs are permanent, so the smoke reuses one repository rather than creating and deleting one per run. -1. PROD identity creates `forge-smoke-` (platform backend) → tiny push → fresh clone verify → issue create/close → **repo delete** (refund reclaimed). +1. PROD identity pushes a tiny commit to a fresh `smoke/` branch of `forge-smoke` (platform backend) → fresh clone verify → issue create/close → delete the branch. 2. Playwright against production web deploy (Pages + IPFS mirror) on mainnet: browse dogfood repo (`dash://forge/dash-forge`), chips green. 3. Relay heartbeat: smoke webhook delivered from mainnet push. 4. Alerting: failure → repo issue + notification channel; balance watchdog at < 2× run cost. @@ -102,7 +110,7 @@ Devnet → testnet rehearsal for every registry/template change; post-deploy ass ## 9. CI wiring - **PR**: unit + vectors + contract validation + builds (< 10 min, no network). -- **Nightly**: testnet integration + token-ACL + CLI e2e + web e2e; pool balance check first; teardown deletes `e2e-*` repos (`finally` + weekly orphan sweeper). +- **Nightly** (`Devnet Nightly` workflow): seeds the v2 read fixture (`forge-contracts/scripts/seed-v2-fixture.mjs`, idempotent) → Playwright against a moutai build → CLI e2e suite (`e2e/cli`, 11 scenarios) on moutai. Funded jobs run only when the fixture identity secrets are configured and report SKIP otherwise. Teardown deletes the run's `e2e//…` refs; documents that cannot be deleted stay in the reserved fixture repos. - **Release**: nightly + scale ladder + backends/chaos + relay + import + fees ledger + onboarding. - **Post-deploy/weekly**: mainnet smoke. -- Serialization: one testnet job per fixture identity (nonce discipline); parallelism across identities, not within. +- Serialization: one live job per fixture identity (nonce discipline); parallelism across identities, not within. diff --git a/e2e/README.md b/e2e/README.md index 3fe66fba5..63b555af3 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -1,8 +1,10 @@ # End-to-end suites -- `cli/run.sh`: the CLI suite, run against **live devnet moutai** (forge-v2, protocol 14) with `make e2e`. Configuration is in `cli/config.sh`; fixture identities come from `~/.config/dash-forge/test-identities/devnet-moutai/` (OWNER, COLLAB, CONTRIB). Scenario 08 reads a forge-v1 repo on **testnet** to prove v1 read-compatibility (needs a testnet identity, default `test-identities/CONTRIB.identity.json`). -- `cli/seed-read-fixture.sh`: checks the testnet read fixture that the browser specs read (`make e2e-fixture`). The nightly runs it before Playwright. The fixture is a forge-v1 repo, which is read only now, so the script verifies it and can no longer reseed it; the fixture moves to forge-v2 together with the web app. -- `../forge-web/e2e/`: the Playwright specs. The read specs only read the read fixture. +- `cli/run.sh`: the CLI suite, run against **live devnet moutai** (forge-v2, protocol 14) with `make e2e`. Configuration is in `cli/config.sh`; fixture identities come from `~/.config/dash-forge/test-identities/devnet-moutai/` (OWNER, COLLAB, CONTRIB). +- `../forge-contracts/scripts/seed-v2-fixture.mjs`: seeds the forge-v2 read fixture that the browser specs read (`make e2e-fixture`; needs `npm ci` in `forge-contracts/sdk-v2` and the moutai OWNER, MAINTAINER, COLLAB and CONTRIB identities). Idempotent: each step's result is recorded in `~/.cache/dash-forge/seed-v2-devnet-moutai.json` and a rerun skips what is recorded. The Devnet Nightly runs it before Playwright. +- `../forge-web/e2e/`: the Playwright specs, run against a moutai build (`E2E_DEVNET=moutai`, the default). The read specs only read the read fixture. + +Everything runs on devnet moutai because forge-v2 needs Platform protocol 14, which testnet and mainnet do not run yet. Testnet runs resume once protocol 14 reaches testnet and forge-v2 is deployed there. - `cli/storage-byo.sh`: bring-your-own storage (`make storage-e2e`). A real `git push` / `git clone` whose packs go to the local MinIO + kubo from `infra/docker-compose.yml`. | Scenario | Proves | @@ -14,7 +16,6 @@ | 05 non-member push | a never-member's push is refused at consensus (40120) | | 06 third-party verify | refs and manifests read raw from Platform bind to a locally hash-verified clone | | 07 depth / filter | `--depth` fails loudly, `--filter=blob:none` works | -| 08 v1 read-compat | a testnet v1 repo clones by name and by contract id; a push to it is refused as read only | | 09 issue lifecycle | a non-member opens an issue (§6 numbering), closes and reopens it as the author (`authorEvent`); a stranger's close is refused by `dg` before signing (E601) and, with the pre-check off, **at consensus** (40120); a maintainer labels, comments and closes it (member `event`) | | 10 PR from a fork | `dg repo fork` records the parent's packs by reference (nothing re-uploaded) and the fork clones; a PR opened from the fork with no `--head-repo`; `pr view/diff/checkout` fetch the head from the fork; only a member's approval counts; `dg pr merge` builds a real 3-way merge commit, pushes it to the base and posts the merge event, and a fresh clone shows the merge | | 11 release asset | a non-maintainer is refused before uploading; a maintainer publishes a release whose asset goes to local MinIO with its sha256 recorded; a reader without storage credentials downloads and verifies it. SKIPs when MinIO is down (`make infra-up`) | @@ -38,8 +39,7 @@ The CLI suite's repos are forge-v2 repos owned by the moutai OWNER fixture, crea | `storage-e2e-b` (moutai) | `cli/storage-byo.sh` steps 5–6 | the same script | Same, plus the step-5 "copy deleted" scenario. Step 6 restores that copy, so the repo stays clonable. | | `relay-e2e` (moutai) | the forge-relay live check (`crates/forge-relay/README.md`) | the same | Repo id `3HKxeeGrJjfVP6msx7yEKUPp9ghev2sAPFHEFLQ1c1x1` (recreated on the re-registered forge-v2 contracts). Webhooks on it point at `127.0.0.1` receivers and are removed after each run; pushes are tiny Platform-stored commits on `main`. Last run 2026-09-26: push delivered with a valid `X-Hub-Signature-256`, secret decrypted from chain by a relay-only key file; none delivered after `dg webhook remove`. | | `mirror-ci-dash-faucet` (moutai) | `.github/workflows/mirror-action.yml` | the same | The Mirror Action's live test: a mirror of `PastaPastaPasta/dash-faucet` (code, issues, PRs, releases, labels), Platform-stored packs only. Created on first run; each run mirrors twice and requires the second to write nothing. | -| `m1-5124` (testnet, v1) | nothing now (v1 is read only); `cli/seed-read-fixture.sh` verifies it | `forge-web/e2e/*` (read-paths, fallback-browse, zero-backend, a11y) | The read fixture: `main` holds one deterministic commit (`README.md`, `src/`, `lib/`) with its pack stored on Platform and no browse index. DEPLOYER-owned (`8hJmcHWT…`). Override with `NIGHTLY_FIXTURE_REPO` (seeder) and `E2E_FIXTURE_NAME` (Playwright). | -| `m1-75299` (testnet, v1) | nothing now | scenario 08; `forge-web/e2e/auth-write.spec.ts` with `E2E_WRITE=1` (issues only) | The former CLI suite repo, read only now. It still holds seven stale external packs (MinIO/IPFS on `127.0.0.1`) from the 2026-09-25 incident; clones skip them with a warning. | +| `forge-v2-demo` (moutai, OWNER) and `forge-v2-empty` (moutai, MAINTAINER) | `forge-contracts/scripts/seed-v2-fixture.mjs` | `forge-web/e2e/*` read specs | The browser read fixture: `main` (three commits, `docs/`), a feature branch and tag `v0.1.0` with a published locator; three issues, an open PR with a maintainer approval, a merged PR, a star. `forge-v2-empty` has nothing pushed. Override with `E2E_V2_OWNER` / `E2E_V2_NAME`. | | `gh-bvs-mirror` (moutai) | `forge-import PastaPastaPasta/backports-validation-script` (manual, PR G live check) | the same | A GitHub mirror (re-created 2026-09-26 on the re-registered contracts): 2 branches + the open PR's head, 1 issue, 2 PRs, 15 comments, 7 reviews, 9 labels, 0.112 DASH. Branches match GitHub's. Re-running the import is a no-op at cost 0. | Override the storage repo names with `STORAGE_E2E_REPO` / `STORAGE_E2E_REPO_B`. When you add a suite that writes, give it its own repo and add a row here. diff --git a/e2e/cli/config.sh b/e2e/cli/config.sh index 1130084ee..f520af994 100644 --- a/e2e/cli/config.sh +++ b/e2e/cli/config.sh @@ -5,9 +5,8 @@ # # The CLI suite runs against devnet MOUTAI, where forge-v2 (protocol 14) is deployed. A v2 # repo costs ~0.001 DASH, so the suite's repo is created on the first run (by -# `harness_ensure_repo`, resumably) rather than hard-coded. Two things stay on TESTNET, -# where every repo is forge-v1 (read only now): scenario 08 (v1 read-compat) and the -# browser specs' read fixture (seed-read-fixture.sh), which move to forge-v2 with the web. +# `harness_ensure_repo`, resumably) rather than hard-coded. Testnet runs resume once +# testnet runs protocol 14 and forge-v2 is deployed there. # --- network ----------------------------------------------------------------- : "${DASH_FORGE_NETWORK:=devnet}" @@ -15,7 +14,7 @@ export DASH_FORGE_NETWORK DASH_FORGE_DEVNET_NAME # --- fixture identity files -------------------------------------------------- -# Per-network directory (tools/devnet-identities provisions devnet-moutai). The testnet +# Per-network directory (`make devnet-identities` provisions devnet-moutai). The testnet # pool lives directly under test-identities/. if [[ "$DASH_FORGE_NETWORK" == devnet ]]; then : "${E2E_IDENTITY_DIR:=${HOME}/.config/dash-forge/test-identities/devnet-${DASH_FORGE_DEVNET_NAME}}" @@ -55,18 +54,3 @@ export E2E_REMOTE="dash://${E2E_OWNER_ID}/${E2E_REPO_NAME}" : "${STORAGE_E2E_REPO:=storage-e2e-a}" : "${STORAGE_E2E_REPO_B:=storage-e2e-b}" export STORAGE_E2E_REPO STORAGE_E2E_REPO_B - -# --- the nightly's read fixture (TESTNET, forge-v1) --------------------------- -# The repo the browser (Playwright) specs read: DEPLOYER-owned on testnet, written ONLY by -# e2e/cli/seed-read-fixture.sh (which runs with DASH_FORGE_NETWORK=testnet). forge-web's -# e2e/helpers.ts names the same repo. v1 is read only now, so the seeder verifies it. -: "${NIGHTLY_FIXTURE_REPO:=m1-5124}" -export NIGHTLY_FIXTURE_REPO - -# --- the testnet v1 repo for read-compat (scenario 08) ------------------------ -# The DEPLOYER-owned M1 repo contract on testnet: read-only now, cloned by 08. -export V1_TESTNET_OWNER="8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB" -export V1_TESTNET_REPO="m1-75299" -export V1_TESTNET_CONTRACT="5rrwgjjVUqMghnessfiXPXubpiM2QLNNXH142Hv4PDyX" -: "${V1_TESTNET_IDENTITY:=${HOME}/.config/dash-forge/test-identities/CONTRIB.identity.json}" -export V1_TESTNET_IDENTITY diff --git a/e2e/cli/run.sh b/e2e/cli/run.sh index 5a124a5e8..4aab85ee3 100755 --- a/e2e/cli/run.sh +++ b/e2e/cli/run.sh @@ -2,9 +2,8 @@ # run.sh — Dash Forge CLI end-to-end suite driver. # # Runs every scenario against LIVE devnet moutai (forge-v2), on the suite's reserved -# OWNER-owned repo (config.sh; created on the first run). Scenario 08 reads a v1 repo on -# testnet. Prints a PASS/FAIL/SKIP matrix and exits non-zero if ANY scenario -# FAILs. A scenario SKIPs only when a check flaked on every retry; one SKIP is reported +# OWNER-owned repo (config.sh; created on the first run). Prints a PASS/FAIL/SKIP matrix +# and exits non-zero if ANY scenario FAILs. A scenario SKIPs only when a check flaked on every retry; one SKIP is reported # but tolerated, more than E2E_MAX_SKIPS fails the run. # # Usage: @@ -41,7 +40,6 @@ SCENARIOS=( "05-non-member-push" "06-third-party-verify" "07-depth-and-filter" - "08-v1-read-compat" "09-issue-lifecycle" "10-pr-from-fork" "11-release-asset" diff --git a/e2e/cli/scenarios/08-v1-read-compat.sh b/e2e/cli/scenarios/08-v1-read-compat.sh deleted file mode 100755 index 3998bcecc..000000000 --- a/e2e/cli/scenarios/08-v1-read-compat.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env bash -# Scenario 8: forge-v1 read compatibility on TESTNET. v1 repositories (one contract each) -# are read only now, but must stay cloneable: -# * `git clone dash:///` of the testnet M1 repo resolves through the v1 -# registry (testnet has no forge-v2 deployment) and clones cleanly (fsck); -# * `git clone dash://` resolves the same repo by its contract id; -# * a push to it is refused locally as read only, before anything is signed. -# Read-only: no Platform writes. Needs a testnet identity (any; only reads are signed-free). -SCENARIO_NAME="08 v1 read-compat (testnet clone)" -source "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/lib.sh" -harness_init - -LOG="${WORKROOT}/s08" -[[ -f "$V1_TESTNET_IDENTITY" ]] || skip_scenario "no testnet identity at ${V1_TESTNET_IDENTITY}" -V1_REMOTE="dash://${V1_TESTNET_OWNER}/${V1_TESTNET_REPO}" -# Every command below targets testnet, whatever the suite's network is. -testnet() { DASH_FORGE_NETWORK=testnet DASH_FORGE_DEVNET_NAME= DASH_FORGE_DAPI_ADDRESSES= "$@"; } - -step "clone the v1 repo by name on testnet" -C1="${WORKROOT}/s08-named" -if ! testnet git_dash_retry "$V1_TESTNET_IDENTITY" "$LOG-named" clone "$V1_REMOTE" "$C1"; then - cat "$LOG-named.err" >&2 || true - is_flake "$LOG-named.err" && skip_scenario "testnet clone flaked on every attempt" - bad "v1 clone by name failed"; finish_scenario -fi -ok "cloned ${V1_REMOTE}" -if git -C "$C1" fsck --full >"$LOG-fsck.out" 2>&1; then ok "fsck clean"; else cat "$LOG-fsck.out" >&2; bad "fsck failed"; fi -NREFS="$(git -C "$C1" for-each-ref refs/remotes | wc -l | tr -d ' ')" -check "the clone has branches (${NREFS})" bash -c "[[ ${NREFS:-0} -ge 1 ]]" - -step "resolve the same repo by its contract id" -if testnet git_dash_retry "$V1_TESTNET_IDENTITY" "$LOG-id" ls-remote "dash://${V1_TESTNET_CONTRACT}"; then - HEAD_BY_ID="$(awk '$2=="HEAD"{print $1}' "$LOG-id.out")" - HEAD_BY_NAME="$(git -C "$C1" rev-parse HEAD)" - check "dash:// advertises the same HEAD" assert_eq "$HEAD_BY_NAME" "$HEAD_BY_ID" "HEAD" -else - cat "$LOG-id.err" >&2 || true - is_flake "$LOG-id.err" && skip_scenario "contract-id ls-remote flaked" - bad "dash:// did not resolve" -fi - -step "a push to the v1 repo is refused as read only (nothing signed)" -git -C "$C1" -c user.email=e2e@x -c user.name=e2e -c commit.gpgsign=false commit -q --allow-empty -m "v1 push probe ${RUN_ID}" -if testnet git_dash "$V1_TESTNET_IDENTITY" "$LOG-push" -C "$C1" push "$V1_REMOTE" "HEAD:refs/heads/e2e/${RUN_ID}/v1probe"; then - bad "a push to a v1 repo was ACCEPTED" -elif grep -qiE 'v1 repository, which is read only|\[E605\]' "$LOG-push.err" "$LOG-push.out" 2>/dev/null; then - ok "push refused: v1 repo is read only" -else - cat "$LOG-push.err" >&2 - bad "push failed without the read-only message" -fi - -finish_scenario diff --git a/e2e/cli/seed-read-fixture.sh b/e2e/cli/seed-read-fixture.sh deleted file mode 100644 index bb9b383a3..000000000 --- a/e2e/cli/seed-read-fixture.sh +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env bash -# seed-read-fixture.sh — make the nightly's browser read fixture exist and hold exactly -# the expected content. Idempotent: a run that finds `main` already at the fixture commit -# writes nothing. -# -# The fixture (NIGHTLY_FIXTURE_REPO, config.sh; reserved in e2e/README.md) is what -# forge-web's Playwright specs read. It is written only here, so no other suite's refs, -# packs or storage choices can reach what the browser sees: -# * `main` = one deterministic commit (fixed author, committer and dates) holding a -# README, a `src/` and a `lib/` directory — the entries the tree-browse spec looks for; -# * its pack is stored on Platform (chunk documents), never external storage; -# * no browse index is published (DASH_FORGE_NO_BROWSE_INDEX), so the web app takes the -# in-browser fallback clone, which fallback-browse.spec.ts exercises. -# -# The fixture is a forge-v1 repo on TESTNET. v1 is read only now: the script verifies the -# fixture and fails (it cannot reseed) when it is wrong; the fixture moves to forge-v2 with -# the web app. Exit 0 = the fixture is as expected; 1 = it is not, or could not be read. -SCENARIO_NAME="seed the nightly read fixture (${NIGHTLY_FIXTURE_REPO:-m1-5124})" -# The fixture lives on testnet with the testnet pool, whatever the CLI suite targets. -export DASH_FORGE_NETWORK=testnet DASH_FORGE_DEVNET_NAME= E2E_OWNER_ROLE=DEPLOYER -export E2E_IDENTITY_DIR="${E2E_TESTNET_IDENTITY_DIR:-${HOME}/.config/dash-forge/test-identities}" -source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib.sh" -harness_init - -FIX_REPO="${E2E_OWNER_ID}/${NIGHTLY_FIXTURE_REPO}" -FIX_REMOTE="dash://${FIX_REPO}" -SRC="${WORKROOT}/fixture-src" -LOG="${WORKROOT}/fixture" - -step "fixture repo ${FIX_REPO}" -if dg_read_retry "$ID_DEPLOYER" "$LOG-view.json" "$LOG-view.err" --json repo view "$FIX_REPO"; then - info "reusing ${FIX_REPO}" -else - cat "$LOG-view.err" >&2; bad "could not read ${FIX_REPO}"; finish_scenario -fi - -step "build the deterministic fixture commit" -rm -rf "$SRC"; mkdir -p "$SRC/src" "$SRC/lib" -git init -q -b main "$SRC" -cat >"$SRC/README.md" <<'EOF' -# Dash Forge nightly read fixture - -This repository is the fixture the Dash Forge web app's browser tests read. It is written -only by `e2e/cli/seed-read-fixture.sh`; do not push to it. -EOF -printf 'fn main() {\n println!("hello from the nightly fixture");\n}\n' >"$SRC/src/main.rs" -printf 'pub fn answer() -> u32 {\n 42\n}\n' >"$SRC/lib/answer.rs" -export GIT_AUTHOR_NAME="Dash Forge Fixture" GIT_AUTHOR_EMAIL="fixture@dash-forge.test" -export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL" -export GIT_AUTHOR_DATE="2026-09-25T00:00:00Z" GIT_COMMITTER_DATE="2026-09-25T00:00:00Z" -git -C "$SRC" -c commit.gpgsign=false add -A -git -C "$SRC" -c commit.gpgsign=false commit -q -m "nightly read fixture" -WANT="$(git -C "$SRC" rev-parse HEAD)" -info "fixture commit ${WANT}" - -remote_main() { # prints the remote main oid, or nothing - git_dash_retry "$ID_DEPLOYER" "$1" ls-remote "$FIX_REMOTE" refs/heads/main || return 1 - awk '$2 == "refs/heads/main" { print $1 }' "$1.out" -} - -# The stored packs, as `dg storage status` sees them: prints "ok" when every manifest is a -# kind-0 git pack stored on Platform (no external copy, no browse index), else what is wrong. -packs_ok() { # packs_ok - dg_read_retry "$ID_DEPLOYER" "$1.json" "$1.err" --json storage status "$FIX_REPO" || return 1 - python3 - "$1.json" <<'PY' -import json, sys -packs = json.load(open(sys.argv[1])).get("packs", []) -bad = [f"{p.get('packHash','?')[:12]} kind={p.get('kind')} tier={p.get('storageTier')}" - for p in packs if p.get("kind") != 0 or p.get("storageTier") != "platform"] -print("ok" if packs and not bad else ("no packs" if not packs else "; ".join(bad))) -PY -} - -step "is ${FIX_REMOTE} main already at the fixture commit, on Platform, unindexed?" -if ! HAVE="$(remote_main "$LOG-ls1")"; then - cat "$LOG-ls1.err" >&2; bad "could not list the fixture's refs"; finish_scenario -fi -if [[ "$HAVE" == "$WANT" ]]; then - if ! PACKS="$(packs_ok "$LOG-packs1")"; then - cat "$LOG-packs1.err" >&2; bad "could not read the fixture's pack manifests"; finish_scenario - fi - if [[ "$PACKS" == "ok" ]]; then - ok "already seeded (main = ${WANT}, Platform-stored, no browse index); nothing written" - else - # A re-push cannot fix this: the right pack is already recorded and the helper will not - # store it again. The repo needs its storage torn down (dg repo delete) and reseeding. - bad "main is at the fixture commit but its storage is wrong (${PACKS}); tear the fixture's storage down and reseed" - fi - finish_scenario -fi -info "main is ${HAVE:-absent}; force-pushing the fixture commit (fails: v1 is read only)" - -step "push the fixture (Platform storage only, no browse index)" -# `-c` is git's command scope, which the helper ranks above any global or repo setting, so -# a developer's `dash.storage=minio` (or a per-remote override) cannot redirect this pack. -if ! DASH_FORGE_NO_BROWSE_INDEX=1 git_dash_retry "$ID_DEPLOYER" "$LOG-push" \ - -C "$SRC" -c dash.storage=platform -c dash.platformFallback=false \ - -c "remote.origin.dashStorage=platform" \ - push "$FIX_REMOTE" "+refs/heads/main:refs/heads/main"; then - cat "$LOG-push.err" >&2; bad "fixture push failed"; finish_scenario -fi -if HAVE="$(remote_main "$LOG-ls2")" && [[ "$HAVE" == "$WANT" ]]; then - ok "seeded: main = ${WANT}" -else - bad "after the push, main is ${HAVE:-unreadable}, not ${WANT}" -fi -if PACKS="$(packs_ok "$LOG-packs2")" && [[ "$PACKS" == "ok" ]]; then - ok "fixture packs are Platform-stored with no browse index" -else - bad "fixture storage after the push: ${PACKS:-unreadable}" -fi -finish_scenario diff --git a/forge-contracts/contracts/registry.json b/forge-contracts/contracts/registry.json deleted file mode 100644 index a9d78be3d..000000000 --- a/forge-contracts/contracts/registry.json +++ /dev/null @@ -1,283 +0,0 @@ -{ - "$formatVersion": "1", - "id": "11111111111111111111111111111111", - "ownerId": "11111111111111111111111111111111", - "version": 1, - "documentSchemas": { - "repoListing": { - "type": "object", - "properties": { - "name": { - "type": "string", - "maxLength": 100, - "position": 0 - }, - "normalizedName": { - "type": "string", - "pattern": "^[a-z0-9][a-z0-9._-]{0,62}$", - "maxLength": 63, - "position": 1 - }, - "repoContractId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 2 - }, - "templateVersion": { - "type": "integer", - "position": 3, - "minimum": 0 - }, - "description": { - "type": "string", - "maxLength": 500, - "position": 4 - }, - "topics": { - "type": "string", - "maxLength": 400, - "position": 5, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "forkOf": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 6 - } - }, - "indices": [ - { - "name": "ownerName", - "properties": [ - { - "$ownerId": "asc" - }, - { - "normalizedName": "asc" - } - ], - "unique": true, - "countable": "countable" - }, - { - "name": "name", - "properties": [ - { - "normalizedName": "asc" - } - ] - }, - { - "name": "forkOf", - "properties": [ - { - "forkOf": "asc" - } - ], - "nullSearchable": false, - "countable": "countable" - }, - { - "name": "recent", - "properties": [ - { - "$createdAt": "asc" - } - ], - "countable": "countable" - } - ], - "required": [ - "$createdAt", - "name", - "normalizedName", - "repoContractId", - "templateVersion" - ], - "additionalProperties": false - }, - "profile": { - "type": "object", - "properties": { - "displayName": { - "type": "string", - "maxLength": 60, - "position": 0 - }, - "bio": { - "type": "string", - "maxLength": 500, - "position": 1 - }, - "avatarConfig": { - "type": "string", - "maxLength": 200, - "position": 2 - }, - "links": { - "type": "string", - "maxLength": 900, - "position": 3, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - } - }, - "indices": [ - { - "name": "owner", - "properties": [ - { - "$ownerId": "asc" - } - ], - "unique": true - } - ], - "required": [], - "additionalProperties": false - }, - "star": { - "type": "object", - "documentsMutable": false, - "properties": { - "listingId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - } - }, - "indices": [ - { - "name": "ownerListing", - "properties": [ - { - "$ownerId": "asc" - }, - { - "listingId": "asc" - } - ], - "unique": true - }, - { - "name": "listing", - "properties": [ - { - "listingId": "asc" - }, - { - "$createdAt": "asc" - } - ], - "countable": "countable" - }, - { - "name": "owner", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "listingCount", - "properties": [ - { - "listingId": "asc" - } - ], - "countable": "countable" - } - ], - "required": [ - "$createdAt", - "listingId" - ], - "additionalProperties": false - }, - "follow": { - "type": "object", - "documentsMutable": false, - "properties": { - "identityId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - } - }, - "indices": [ - { - "name": "ownerIdentity", - "properties": [ - { - "$ownerId": "asc" - }, - { - "identityId": "asc" - } - ], - "unique": true - }, - { - "name": "identity", - "properties": [ - { - "identityId": "asc" - }, - { - "$createdAt": "asc" - } - ], - "countable": "countable" - }, - { - "name": "owner", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ], - "countable": "countable" - }, - { - "name": "identityCount", - "properties": [ - { - "identityId": "asc" - } - ], - "countable": "countable" - } - ], - "required": [ - "$createdAt", - "identityId" - ], - "additionalProperties": false - } - }, - "keywords": [ - "git", - "forge", - "repository", - "vcs" - ], - "description": "Dash Forge registry: repository discovery and social graph." -} diff --git a/forge-contracts/deployments/devnet-moutai.json b/forge-contracts/deployments/devnet-moutai.json index aef3b9899..eb2360c57 100644 --- a/forge-contracts/deployments/devnet-moutai.json +++ b/forge-contracts/deployments/devnet-moutai.json @@ -13,12 +13,6 @@ "https://68.67.122.199:1443", "https://68.67.122.84:1443" ], - "registry": { - "contractId": null, - "ownerId": null, - "deployedAt": null, - "version": 1 - }, "v2": { "forgeCollabSuperseded": [ { diff --git a/forge-contracts/deployments/mainnet.json b/forge-contracts/deployments/mainnet.json index c54485e68..a07ec63ef 100644 --- a/forge-contracts/deployments/mainnet.json +++ b/forge-contracts/deployments/mainnet.json @@ -1,5 +1,4 @@ { - "registry": null, "dapiAddresses": [ "https://15.235.102.215:443", "https://2.59.156.192:443", diff --git a/forge-contracts/deployments/testnet.json b/forge-contracts/deployments/testnet.json index 1446cade9..536dc1754 100644 --- a/forge-contracts/deployments/testnet.json +++ b/forge-contracts/deployments/testnet.json @@ -1,20 +1,4 @@ { - "registry": { - "contractId": "DXocbV5xJb9hYwSAUGsyTTskdem7nVmngeJbH5TRzLnh", - "ownerId": "8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB", - "deployedAt": "2026-07-23T15:51:42.807Z", - "version": 1 - }, - "registrySuperseded": [ - { - "contractId": "5fu48xTUVDj2QtBTY6pPH9w2t73YHb1fxf1WMg6Rt9pd", - "ownerId": "8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB", - "deployedAt": "2026-07-22T23:17:37.820Z", - "version": 1, - "supersededAt": "2026-07-23T15:51:42.807Z", - "reason": "repoListing/star/follow indexed $createdAt without declaring it required, so Platform never stored the timestamp, and the $createdAt `recent` index was missing entirely. Indices are immutable after creation (rs-dpp index_level::validate_update), so a contract update could not fix either — redeploy was the only path." - } - ], "dapiAddresses": [ "https://68.67.122.1:1443", "https://68.67.122.2:1443", diff --git a/forge-contracts/node_modules b/forge-contracts/node_modules deleted file mode 120000 index 068624a3d..000000000 --- a/forge-contracts/node_modules +++ /dev/null @@ -1 +0,0 @@ -../spikes/S0.7-token-acl/node_modules \ No newline at end of file diff --git a/forge-contracts/package.json b/forge-contracts/package.json deleted file mode 100644 index 0e1f6ac98..000000000 --- a/forge-contracts/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "@dash-forge/spike-s0.7-token-acl", - "version": "0.1.0", - "description": "S0.7 spike: validate token-cost ACL at consensus (tokenCost gating, freeze blocks create+delete, mint/freeze/destroy, baseSupply, token-history reconstruction)", - "type": "module", - "private": true -} diff --git a/forge-contracts/scripts/deploy-v2.mjs b/forge-contracts/scripts/deploy-v2.mjs index 4f5b78de8..d313fdb46 100644 --- a/forge-contracts/scripts/deploy-v2.mjs +++ b/forge-contracts/scripts/deploy-v2.mjs @@ -31,7 +31,7 @@ // 2. forge-collab: substitute forge-core's id for FORGE_CORE_CONTRACT_ID in its schema, then a // DataContractCreate v1 enrolling forge-collab in the group. // Both are signed with the deployer's CRITICAL authentication key (contract create needs -// CRITICAL or HIGH; CRITICAL is what deploy.mjs has always used). The deployer owns the +// CRITICAL or HIGH; CRITICAL is used). The deployer owns the // contracts and the group; no moderation, not readonly (flip readonly in a later update once // the schema is final). // @@ -50,8 +50,7 @@ import { createHash } from 'node:crypto'; const HERE = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(HERE, '..'); -// The pinned protocol-14 SDK lives in sdk-v2/ so it cannot collide with the evo-sdk 4.0 that -// deploy.mjs (v1) resolves from ../node_modules. The package is ESM-only. +// The pinned protocol-14 SDK lives in sdk-v2/ (`npm ci` there). The package is ESM-only. const EVO_SDK_ENTRY = join(ROOT, 'sdk-v2', 'node_modules', '@dashevo', 'evo-sdk', 'dist', 'evo-sdk.module.js'); export async function loadEvoSdk() { if (!existsSync(EVO_SDK_ENTRY)) throw new Error('run `npm ci` in forge-contracts/sdk-v2 first'); diff --git a/forge-contracts/scripts/deploy.mjs b/forge-contracts/scripts/deploy.mjs deleted file mode 100644 index cd14671c7..000000000 --- a/forge-contracts/scripts/deploy.mjs +++ /dev/null @@ -1,123 +0,0 @@ -// Deploy a Dash Forge data contract to a network and record its id. -// -// node scripts/deploy.mjs --contract registry --identity [--network testnet] -// -// The registry is deployed once per network (global discovery contract). The -// repo template is NOT deployed here — clients instantiate it per repo (see -// forge-core). Deployed ids are written to forge-contracts/deployments/.json. -// -// Pattern proven in spikes/S0.7-token-acl/01-register.mjs (DataContract.fromJSON, -// CRITICAL key signing, broadcastAndWait for a single contract create). -import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'; -import { dirname, resolve, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import * as evoSdk from '@dashevo/evo-sdk'; - -const HERE = dirname(fileURLToPath(import.meta.url)); -const ROOT = resolve(HERE, '..'); -const PUT_SETTINGS = { connectTimeoutMs: 10000, timeoutMs: 60000, retries: 3 }; -const log = (m) => console.error(`${new Date().toISOString().slice(11, 19)} ${m}`); - -function parseArgs(argv) { - const a = { _: [] }; - for (let i = 0; i < argv.length; i++) { - const t = argv[i]; - if (t.startsWith('--')) { - const k = t.slice(2); - const v = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : true; - a[k] = v; - } else a._.push(t); - } - return a; -} - -const CONTRACT_FILES = { - registry: 'contracts/registry.json', -}; - -function pickAuthKey(rec, level) { - const k = rec.identityKeys.find( - (x) => x.purpose === 'AUTHENTICATION' && x.securityLevel === level, - ); - if (!k) throw new Error(`no ${level} AUTHENTICATION key in identity`); - return k; -} - -async function main() { - const args = parseArgs(process.argv.slice(2)); - const which = args.contract || 'registry'; - const network = args.network || 'testnet'; - const idFile = args.identity; - if (!idFile || idFile === true) throw new Error('--identity required'); - if (!CONTRACT_FILES[which]) throw new Error(`unknown contract: ${which}`); - - const rec = JSON.parse(readFileSync(resolve(String(idFile)), 'utf8')); - const ownerId = rec.identityId; - const contractJson = JSON.parse(readFileSync(join(ROOT, CONTRACT_FILES[which]), 'utf8')); - - const { EvoSDK, DataContract, DataContractCreateTransition, PrivateKey, IdentityPublicKey } = evoSdk; - const sdk = network === 'mainnet' ? EvoSDK.mainnetTrusted({ settings: PUT_SETTINGS }) : EvoSDK.testnetTrusted({ settings: PUT_SETTINGS }); - log(`connecting (${network})...`); - await sdk.connect(); - - // identity nonce for contract-id derivation (facade returns the masked value) - const nextNonce = ((await sdk.identities.nonce(ownerId)) ?? 0n) + 1n; - - // The network's protocol version, not the SDK's latest (evo-sdk 4.2 knows 14 - // while testnet still runs 13). Read it only after the proved nonce query: - // the SDK starts at the network's protocol floor and ratchets up to the live - // version on its first verified response. - const pv = sdk.version(); - - const schemas = contractJson.documentSchemas; - const idProbe = new DataContract({ ownerId, identityNonce: nextNonce, schemas, fullValidation: false, platformVersion: pv }); - const contractId = idProbe.id.toString(); - const fullJson = { - $formatVersion: '1', id: contractId, ownerId, version: 1, - documentSchemas: schemas, - ...(contractJson.keywords ? { keywords: contractJson.keywords } : {}), - ...(contractJson.description ? { description: contractJson.description } : {}), - }; - const contract = DataContract.fromJSON(fullJson, true, pv); - log(`built ${which} contract; id: ${contractId}`); - - const critKey = pickAuthKey(rec, 'CRITICAL'); - const publicKey = new IdentityPublicKey({ - keyId: critKey.id, - purpose: critKey.purpose, // UPPERCASE enum strings (wasm-sdk convention) - securityLevel: critKey.securityLevel, - keyType: critKey.keyType, - isReadOnly: false, - data: Buffer.from(critKey.publicKeyHex, 'hex'), - }); - const priv = PrivateKey.fromWIF(critKey.privateKeyWif); - - const tr = new DataContractCreateTransition(contract, nextNonce, pv); - const st = tr.toStateTransition(); - st.sign(priv, publicKey); - log(`signed DataContractCreate (${st.toBytes().length} B); broadcasting...`); - - const balBefore = Number(await sdk.identities.balance(ownerId)); - await sdk.stateTransitions.broadcastAndWait(st, PUT_SETTINGS); - const balAfter = Number(await sdk.identities.balance(ownerId)); - log(`deployed. cost ${((balBefore - balAfter) / 1e11).toFixed(6)} DASH`); - - // verify by fetch - const fetched = await sdk.contracts.fetch(contractId); - if (!fetched) throw new Error('post-deploy fetch returned nothing'); - log('post-deploy fetch OK.'); - - // record - const depDir = join(ROOT, 'deployments'); - if (!existsSync(depDir)) mkdirSync(depDir, { recursive: true }); - const depFile = join(depDir, `${network}.json`); - const dep = existsSync(depFile) ? JSON.parse(readFileSync(depFile, 'utf8')) : {}; - dep[which] = { contractId, ownerId, deployedAt: new Date().toISOString(), version: 1 }; - writeFileSync(depFile, `${JSON.stringify(dep, null, 2)}\n`); - log(`recorded ${which} -> ${depFile}`); - - console.log(JSON.stringify({ contract: which, network, contractId, cost: (balBefore - balAfter) / 1e11 }, null, 2)); - await sdk.disconnect?.(); -} - -main().catch((e) => { log(`ERROR: ${e.message || e}`); process.exit(1); }); diff --git a/forge-contracts/scripts/seed-v2-fixture.mjs b/forge-contracts/scripts/seed-v2-fixture.mjs index ec8a6915b..248abd0b6 100644 --- a/forge-contracts/scripts/seed-v2-fixture.mjs +++ b/forge-contracts/scripts/seed-v2-fixture.mjs @@ -26,8 +26,10 @@ // (fanout || 36-byte rows, deltaChainSpan = the sentinel so readers walk each base). // // Idempotent: the result of every step is recorded in -// ~/.cache/dash-forge/seed-v2-.json and a rerun skips what is recorded. Delete that -// file (and pick new repo names) to seed from scratch. +// ~/.cache/dash-forge/seed-v2-.json and a rerun skips what is recorded. Without that +// file (a fresh CI runner), a fixture that already exists on chain is left alone: the run +// checks `forge-v2-demo` resolves and exits. Delete the file (and pick new repo names) to +// seed from scratch. import { execFileSync } from 'node:child_process'; import { createHash } from 'node:crypto'; @@ -216,6 +218,38 @@ async function main() { const statePath = join(homedir(), '.cache/dash-forge', `seed-v2-${key}.json`); mkdirSync(dirname(statePath), { recursive: true }); + if (!existsSync(statePath)) { + // No local record: if the fixture is already on chain (seeded from another machine), + // there is nothing to do. Re-seeding would fail on the unique `($ownerId, name)` index. + const found = await sdk.documents.query({ + dataContractId: core, + documentTypeName: 'repo', + where: [ + ['$ownerId', '==', OWNER.id], + ['name', '==', DEMO], + ], + limit: 1, + }); + const doc = found instanceof Map ? [...found.values()].find((v) => v != null) : null; + if (doc) { + // The last step the seeder writes is the star; a fixture without it was interrupted + // on the machine that holds its state file, and must be finished there. + const stars = await sdk.documents.count({ + dataContractId: collab, + documentTypeName: 'star', + where: [['repoId', '==', String(doc.toJSON?.().$id ?? doc.id)]], + }); + let n = 0n; + for (const v of stars.values()) n += v; + if (n === 0n) { + throw new Error(`${DEMO} exists on ${key} but its seed never finished (no star); finish it where ~/.cache/dash-forge/seed-v2-${key}.json lives`); + } + const repoId = String(doc.toJSON?.().$id ?? doc.id?.toBase58?.() ?? doc.id); + log(`${DEMO} already exists on ${key} (${repoId}); nothing to seed`); + console.log(JSON.stringify({ network: key, forgeCore: core, forgeCollab: collab, demo: { owner: OWNER.id, name: DEMO, repoId }, seeded: false }, null, 2)); + return; + } + } const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : {}; const save = () => writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`); diff --git a/forge-contracts/sdk-v2/package.json b/forge-contracts/sdk-v2/package.json index 973399f73..e0f57fbf0 100644 --- a/forge-contracts/sdk-v2/package.json +++ b/forge-contracts/sdk-v2/package.json @@ -2,7 +2,7 @@ "name": "@dash-forge/forge-v2-deploy-sdk", "version": "0.0.0", "private": true, - "description": "Pinned Platform SDK for scripts/deploy-v2.mjs (protocol 14). Kept apart from ../node_modules, which scripts/deploy.mjs (v1, evo-sdk 4.0) uses.", + "description": "Pinned Platform SDK for scripts/deploy-v2.mjs and scripts/seed-v2-fixture.mjs (protocol 14).", "type": "module", "dependencies": { "@dashevo/evo-sdk": "4.2.0-beta.4" diff --git a/forge-contracts/templates/repo-collab.json b/forge-contracts/templates/repo-collab.json deleted file mode 100644 index d9d249027..000000000 --- a/forge-contracts/templates/repo-collab.json +++ /dev/null @@ -1,1019 +0,0 @@ -{ - "$formatVersion": "1", - "id": "11111111111111111111111111111111", - "ownerId": "11111111111111111111111111111111", - "version": 1, - "documentSchemas": { - "issue": { - "type": "object", - "documentsKeepHistory": true, - "documentsCountable": true, - "properties": { - "number": { - "type": "integer", - "position": 0, - "minimum": 1 - }, - "title": { - "type": "string", - "maxLength": 256, - "position": 1 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 2 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 3 - }, - "createdAt": { - "type": "integer", - "position": 4, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 5 - } - }, - "required": [], - "additionalProperties": false, - "position": 6 - } - }, - "indices": [ - { - "name": "number", - "properties": [ - { - "number": "asc" - } - ], - "unique": true - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "owner", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "number", - "title" - ], - "additionalProperties": false - }, - "patch": { - "type": "object", - "documentsKeepHistory": true, - "documentsCountable": true, - "properties": { - "number": { - "type": "integer", - "position": 0, - "minimum": 1 - }, - "title": { - "type": "string", - "maxLength": 256, - "position": 1 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 2 - }, - "baseRefNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 3 - }, - "baseRefName": { - "type": "string", - "maxLength": 255, - "position": 4 - }, - "sourceListingId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 5 - }, - "sourceContractId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 6 - }, - "sourceRefNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 7 - }, - "sourceRefName": { - "type": "string", - "maxLength": 255, - "position": 8 - }, - "headOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 9 - }, - "patchManifestHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 10 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 11 - }, - "createdAt": { - "type": "integer", - "position": 12, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 13 - } - }, - "required": [], - "additionalProperties": false, - "position": 14 - } - }, - "indices": [ - { - "name": "number", - "properties": [ - { - "number": "asc" - } - ], - "unique": true - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "source", - "properties": [ - { - "sourceListingId": "asc" - } - ] - } - ], - "required": [ - "number", - "title", - "baseRefNameHash", - "sourceContractId", - "headOid" - ], - "additionalProperties": false - }, - "comment": { - "type": "object", - "documentsKeepHistory": true, - "properties": { - "targetId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 1 - }, - "replyTo": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 2 - }, - "commitOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - }, - "path": { - "type": "string", - "maxLength": 500, - "position": 4 - }, - "line": { - "type": "integer", - "position": 5, - "minimum": 0 - }, - "side": { - "type": "integer", - "position": 6, - "minimum": 0, - "maximum": 1 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 7 - }, - "createdAt": { - "type": "integer", - "position": 8, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 9 - } - }, - "required": [], - "additionalProperties": false, - "position": 10 - } - }, - "indices": [ - { - "name": "target", - "properties": [ - { - "targetId": "asc" - }, - { - "$createdAt": "asc" - } - ], - "countable": "countable" - } - ], - "required": [ - "targetId", - "body" - ], - "additionalProperties": false - }, - "event": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "properties": { - "targetId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - }, - "kind": { - "type": "integer", - "position": 1, - "minimum": 1 - }, - "value": { - "type": "string", - "maxLength": 120, - "position": 2 - }, - "oid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - } - }, - "indices": [ - { - "name": "target", - "properties": [ - { - "targetId": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "feed", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "targetId", - "kind" - ], - "additionalProperties": false - }, - "review": { - "type": "object", - "documentsMutable": false, - "properties": { - "patchId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - }, - "verdict": { - "type": "integer", - "position": 1, - "minimum": 1, - "maximum": 3 - }, - "commitOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 2 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 3 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 4 - }, - "createdAt": { - "type": "integer", - "position": 5, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 6 - } - }, - "required": [], - "additionalProperties": false, - "position": 7 - } - }, - "indices": [ - { - "name": "patch", - "properties": [ - { - "patchId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "patchId", - "verdict", - "commitOid" - ], - "additionalProperties": false - }, - "label": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - }, - "delete": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "name": { - "type": "string", - "maxLength": 30, - "position": 0 - }, - "color": { - "type": "string", - "maxLength": 7, - "position": 1 - }, - "description": { - "type": "string", - "maxLength": 200, - "position": 2 - }, - "retired": { - "type": "boolean", - "position": 3 - } - }, - "indices": [ - { - "name": "name", - "properties": [ - { - "name": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "name" - ], - "additionalProperties": false - }, - "release": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - }, - "delete": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "tagName": { - "type": "string", - "maxLength": 63, - "position": 0 - }, - "name": { - "type": "string", - "maxLength": 120, - "position": 1 - }, - "notes": { - "type": "string", - "maxLength": 5120, - "position": 2 - }, - "yanked": { - "type": "boolean", - "position": 3 - }, - "assets": { - "type": "string", - "maxLength": 4096, - "position": 4, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - } - }, - "indices": [ - { - "name": "tag", - "properties": [ - { - "tagName": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "tagName" - ], - "additionalProperties": false - }, - "checkRun": { - "type": "object", - "documentsMutable": true, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "headOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 0 - }, - "name": { - "type": "string", - "maxLength": 100, - "position": 1 - }, - "status": { - "type": "string", - "maxLength": 30, - "position": 2 - }, - "conclusion": { - "type": "string", - "maxLength": 30, - "position": 3 - }, - "detailsUrl": { - "type": "string", - "maxLength": 300, - "position": 4 - }, - "summary": { - "type": "string", - "maxLength": 1000, - "position": 5 - } - }, - "indices": [ - { - "name": "head", - "properties": [ - { - "headOid": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "headOid", - "name", - "status" - ], - "additionalProperties": false - }, - "webhook": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - }, - "delete": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "hookId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 1 - }, - "events": { - "type": "string", - "maxLength": 600, - "position": 2, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "relayIdentityId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 3 - }, - "encryptedSecret": { - "type": "array", - "byteArray": true, - "maxItems": 128, - "position": 4 - }, - "disabled": { - "type": "boolean", - "position": 5 - } - }, - "indices": [ - { - "name": "hook", - "properties": [ - { - "hookId": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "list", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "hookId", - "url", - "relayIdentityId" - ], - "additionalProperties": false - } - }, - "groups": { - "0": { - "$formatVersion": "0", - "members": { - "11111111111111111111111111111111": 1 - }, - "requiredPower": 1 - } - }, - "tokens": { - "0": { - "$formatVersion": "0", - "conventions": { - "$formatVersion": "0", - "localizations": { - "en": { - "$formatVersion": "0", - "shouldCapitalize": true, - "singularForm": "write", - "pluralForm": "writes" - } - }, - "decimals": 0 - }, - "conventionsChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "baseSupply": 1000000000, - "maxSupply": null, - "keepsHistory": { - "$formatVersion": "0", - "keepsTransferHistory": true, - "keepsFreezingHistory": true, - "keepsMintingHistory": true, - "keepsBurningHistory": true, - "keepsDirectPricingHistory": true, - "keepsDirectPurchaseHistory": true - }, - "startAsPaused": false, - "allowTransferToFrozenBalance": true, - "maxSupplyChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "distributionRules": { - "$formatVersion": "0", - "perpetualDistribution": null, - "perpetualDistributionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "preProgrammedDistribution": null, - "newTokensDestinationIdentity": null, - "newTokensDestinationIdentityRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mintingAllowChoosingDestination": true, - "mintingAllowChoosingDestinationRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "changeDirectPurchasePricingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "marketplaceRules": { - "$formatVersion": "0", - "tradeMode": "NotTradeable", - "tradeModeChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "manualMintingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "manualBurningRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "freezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "unfreezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "destroyFrozenFundsRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "emergencyActionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mainControlGroup": 0, - "mainControlGroupCanBeModified": "ContractOwner", - "description": null - }, - "1": { - "$formatVersion": "0", - "conventions": { - "$formatVersion": "0", - "localizations": { - "en": { - "$formatVersion": "0", - "shouldCapitalize": true, - "singularForm": "maintain", - "pluralForm": "maintains" - } - }, - "decimals": 0 - }, - "conventionsChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "baseSupply": 1000000000, - "maxSupply": null, - "keepsHistory": { - "$formatVersion": "0", - "keepsTransferHistory": true, - "keepsFreezingHistory": true, - "keepsMintingHistory": true, - "keepsBurningHistory": true, - "keepsDirectPricingHistory": true, - "keepsDirectPurchaseHistory": true - }, - "startAsPaused": false, - "allowTransferToFrozenBalance": true, - "maxSupplyChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "distributionRules": { - "$formatVersion": "0", - "perpetualDistribution": null, - "perpetualDistributionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "preProgrammedDistribution": null, - "newTokensDestinationIdentity": null, - "newTokensDestinationIdentityRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mintingAllowChoosingDestination": true, - "mintingAllowChoosingDestinationRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "changeDirectPurchasePricingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "marketplaceRules": { - "$formatVersion": "0", - "tradeMode": "NotTradeable", - "tradeModeChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "manualMintingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "manualBurningRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "freezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "unfreezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "destroyFrozenFundsRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "emergencyActionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mainControlGroup": 0, - "mainControlGroupCanBeModified": "ContractOwner", - "description": null - } - }, - "keywords": [ - "git", - "forge", - "repository" - ], - "description": "Dash Forge per-repository contract (template v1)." -} \ No newline at end of file diff --git a/forge-contracts/templates/repo-core.json b/forge-contracts/templates/repo-core.json deleted file mode 100644 index 20b832005..000000000 --- a/forge-contracts/templates/repo-core.json +++ /dev/null @@ -1,777 +0,0 @@ -{ - "$formatVersion": "1", - "id": "11111111111111111111111111111111", - "ownerId": "11111111111111111111111111111111", - "version": 1, - "documentSchemas": { - "config": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "defaultBranch": { - "type": "string", - "maxLength": 255, - "position": 0 - }, - "protectedPatterns": { - "type": "string", - "maxLength": 900, - "position": 1, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "backend": { - "type": "object", - "properties": { - "mode": { - "type": "integer", - "position": 2, - "minimum": 0, - "maximum": 4 - }, - "uris": { - "type": "string", - "maxLength": 1300, - "position": 3, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - } - }, - "required": [ - "mode" - ], - "additionalProperties": false, - "position": 4 - }, - "archived": { - "type": "boolean", - "position": 5 - } - }, - "indices": [ - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "defaultBranch" - ], - "additionalProperties": false - }, - "refUpdate": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "refNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "refName": { - "type": "string", - "maxLength": 255, - "position": 1 - }, - "newOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 2 - }, - "prevOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - }, - "force": { - "type": "boolean", - "position": 4 - } - }, - "indices": [ - { - "name": "refState", - "properties": [ - { - "refNameHash": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "reflog", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "pusher", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "refNameHash", - "refName", - "newOid" - ], - "additionalProperties": false - }, - "protectedRefUpdate": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "refNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "refName": { - "type": "string", - "maxLength": 255, - "position": 1 - }, - "newOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 2 - }, - "prevOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - }, - "force": { - "type": "boolean", - "position": 4 - } - }, - "indices": [ - { - "name": "refState", - "properties": [ - { - "refNameHash": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "reflog", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "pusher", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "refNameHash", - "refName", - "newOid" - ], - "additionalProperties": false - }, - "packManifest": { - "type": "object", - "documentsMutable": false, - "documentsCountable": true, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "packHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "kind": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "sizeBytes": { - "type": "integer", - "position": 2, - "minimum": 0 - }, - "objectCount": { - "type": "integer", - "position": 3, - "minimum": 0 - }, - "chunkCount": { - "type": "integer", - "position": 4, - "minimum": 0 - }, - "storage": { - "type": "integer", - "position": 5, - "minimum": 0, - "maximum": 1 - }, - "uris": { - "type": "string", - "maxLength": 2600, - "position": 6, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "tips": { - "type": "array", - "byteArray": true, - "maxItems": 512, - "position": 7 - }, - "supersedes": { - "type": "array", - "byteArray": true, - "maxItems": 1024, - "position": 8 - }, - "offsetIndexParts": { - "type": "integer", - "position": 9, - "minimum": 0 - } - }, - "indices": [ - { - "name": "packHash", - "properties": [ - { - "packHash": "asc" - } - ], - "unique": true - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "kind", - "properties": [ - { - "kind": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "packHash", - "kind", - "sizeBytes", - "objectCount", - "chunkCount", - "storage", - "offsetIndexParts" - ], - "additionalProperties": false - }, - "manifestPart": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "packHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "partSeq": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "entries": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 2 - } - }, - "indices": [ - { - "name": "part", - "properties": [ - { - "packHash": "asc" - }, - { - "partSeq": "asc" - } - ], - "unique": true - } - ], - "required": [ - "packHash", - "partSeq", - "entries" - ], - "additionalProperties": false - }, - "chunk": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "packHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "seq": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "d0": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 2 - }, - "d1": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 3 - }, - "d2": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 4 - } - }, - "indices": [ - { - "name": "chunk", - "properties": [ - { - "packHash": "asc" - }, - { - "seq": "asc" - } - ], - "unique": true, - "countable": "countable" - } - ], - "required": [ - "packHash", - "seq", - "d0" - ], - "additionalProperties": false - } - }, - "groups": { - "0": { - "$formatVersion": "0", - "members": { - "11111111111111111111111111111111": 1 - }, - "requiredPower": 1 - } - }, - "tokens": { - "0": { - "$formatVersion": "0", - "conventions": { - "$formatVersion": "0", - "localizations": { - "en": { - "$formatVersion": "0", - "shouldCapitalize": true, - "singularForm": "write", - "pluralForm": "writes" - } - }, - "decimals": 0 - }, - "conventionsChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "baseSupply": 1000000000, - "maxSupply": null, - "keepsHistory": { - "$formatVersion": "0", - "keepsTransferHistory": true, - "keepsFreezingHistory": true, - "keepsMintingHistory": true, - "keepsBurningHistory": true, - "keepsDirectPricingHistory": true, - "keepsDirectPurchaseHistory": true - }, - "startAsPaused": false, - "allowTransferToFrozenBalance": true, - "maxSupplyChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "distributionRules": { - "$formatVersion": "0", - "perpetualDistribution": null, - "perpetualDistributionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "preProgrammedDistribution": null, - "newTokensDestinationIdentity": null, - "newTokensDestinationIdentityRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mintingAllowChoosingDestination": true, - "mintingAllowChoosingDestinationRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "changeDirectPurchasePricingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "marketplaceRules": { - "$formatVersion": "0", - "tradeMode": "NotTradeable", - "tradeModeChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "manualMintingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "manualBurningRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "freezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "unfreezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "destroyFrozenFundsRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "emergencyActionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mainControlGroup": 0, - "mainControlGroupCanBeModified": "ContractOwner", - "description": null - }, - "1": { - "$formatVersion": "0", - "conventions": { - "$formatVersion": "0", - "localizations": { - "en": { - "$formatVersion": "0", - "shouldCapitalize": true, - "singularForm": "maintain", - "pluralForm": "maintains" - } - }, - "decimals": 0 - }, - "conventionsChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "baseSupply": 1000000000, - "maxSupply": null, - "keepsHistory": { - "$formatVersion": "0", - "keepsTransferHistory": true, - "keepsFreezingHistory": true, - "keepsMintingHistory": true, - "keepsBurningHistory": true, - "keepsDirectPricingHistory": true, - "keepsDirectPurchaseHistory": true - }, - "startAsPaused": false, - "allowTransferToFrozenBalance": true, - "maxSupplyChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "distributionRules": { - "$formatVersion": "0", - "perpetualDistribution": null, - "perpetualDistributionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "preProgrammedDistribution": null, - "newTokensDestinationIdentity": null, - "newTokensDestinationIdentityRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mintingAllowChoosingDestination": true, - "mintingAllowChoosingDestinationRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "changeDirectPurchasePricingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "marketplaceRules": { - "$formatVersion": "0", - "tradeMode": "NotTradeable", - "tradeModeChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "manualMintingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "manualBurningRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "freezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "unfreezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "destroyFrozenFundsRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "emergencyActionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mainControlGroup": 0, - "mainControlGroupCanBeModified": "ContractOwner", - "description": null - } - }, - "keywords": [ - "git", - "forge", - "repository" - ], - "description": "Dash Forge per-repository contract (template v1)." -} \ No newline at end of file diff --git a/forge-contracts/templates/repo-v1.json b/forge-contracts/templates/repo-v1.json deleted file mode 100644 index b51634494..000000000 --- a/forge-contracts/templates/repo-v1.json +++ /dev/null @@ -1,1483 +0,0 @@ -{ - "$formatVersion": "1", - "id": "11111111111111111111111111111111", - "ownerId": "11111111111111111111111111111111", - "version": 1, - "documentSchemas": { - "config": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "defaultBranch": { - "type": "string", - "maxLength": 255, - "position": 0 - }, - "protectedPatterns": { - "type": "string", - "maxLength": 900, - "position": 1, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "backend": { - "type": "object", - "properties": { - "mode": { - "type": "integer", - "position": 0, - "minimum": 0, - "maximum": 4 - }, - "uris": { - "type": "string", - "maxLength": 1300, - "position": 1, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - } - }, - "required": [ - "mode" - ], - "additionalProperties": false, - "position": 2 - }, - "archived": { - "type": "boolean", - "position": 3 - } - }, - "indices": [ - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "defaultBranch", - "$createdAt" - ], - "additionalProperties": false - }, - "refUpdate": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "refNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "refName": { - "type": "string", - "maxLength": 255, - "position": 1 - }, - "newOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 2 - }, - "prevOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - }, - "force": { - "type": "boolean", - "position": 4 - } - }, - "indices": [ - { - "name": "refState", - "properties": [ - { - "refNameHash": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "reflog", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "pusher", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "refNameHash", - "refName", - "newOid", - "$createdAt" - ], - "additionalProperties": false - }, - "protectedRefUpdate": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "refNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "refName": { - "type": "string", - "maxLength": 255, - "position": 1 - }, - "newOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 2 - }, - "prevOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - }, - "force": { - "type": "boolean", - "position": 4 - } - }, - "indices": [ - { - "name": "refState", - "properties": [ - { - "refNameHash": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "reflog", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "pusher", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "refNameHash", - "refName", - "newOid", - "$createdAt" - ], - "additionalProperties": false - }, - "packManifest": { - "type": "object", - "documentsMutable": false, - "documentsCountable": true, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "packHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "kind": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "sizeBytes": { - "type": "integer", - "position": 2, - "minimum": 0 - }, - "objectCount": { - "type": "integer", - "position": 3, - "minimum": 0 - }, - "chunkCount": { - "type": "integer", - "position": 4, - "minimum": 0 - }, - "storage": { - "type": "integer", - "position": 5, - "minimum": 0, - "maximum": 1 - }, - "uris": { - "type": "string", - "maxLength": 2600, - "position": 6, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "tips": { - "type": "array", - "byteArray": true, - "maxItems": 512, - "position": 7 - }, - "supersedes": { - "type": "array", - "byteArray": true, - "maxItems": 1024, - "position": 8 - }, - "offsetIndexParts": { - "type": "integer", - "position": 9, - "minimum": 0 - } - }, - "indices": [ - { - "name": "packHash", - "properties": [ - { - "packHash": "asc" - } - ], - "unique": true - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "kind", - "properties": [ - { - "kind": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "packHash", - "kind", - "sizeBytes", - "objectCount", - "chunkCount", - "storage", - "offsetIndexParts" - ], - "additionalProperties": false - }, - "manifestPart": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "packHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "partSeq": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "entries": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 2 - } - }, - "indices": [ - { - "name": "part", - "properties": [ - { - "packHash": "asc" - }, - { - "partSeq": "asc" - } - ], - "unique": true - } - ], - "required": [ - "packHash", - "partSeq", - "entries" - ], - "additionalProperties": false - }, - "chunk": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "packHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "seq": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "d0": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 2 - }, - "d1": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 3 - }, - "d2": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 4 - } - }, - "indices": [ - { - "name": "chunk", - "properties": [ - { - "packHash": "asc" - }, - { - "seq": "asc" - } - ], - "unique": true, - "countable": "countable" - } - ], - "required": [ - "packHash", - "seq", - "d0" - ], - "additionalProperties": false - }, - "issue": { - "type": "object", - "documentsKeepHistory": true, - "documentsCountable": true, - "properties": { - "number": { - "type": "integer", - "position": 0, - "minimum": 1 - }, - "title": { - "type": "string", - "maxLength": 256, - "position": 1 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 2 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 0 - }, - "createdAt": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 2 - } - }, - "required": [], - "additionalProperties": false, - "position": 3 - } - }, - "indices": [ - { - "name": "number", - "properties": [ - { - "number": "asc" - } - ], - "unique": true - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "owner", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "number", - "title" - ], - "additionalProperties": false - }, - "patch": { - "type": "object", - "documentsKeepHistory": true, - "documentsCountable": true, - "properties": { - "number": { - "type": "integer", - "position": 0, - "minimum": 1 - }, - "title": { - "type": "string", - "maxLength": 256, - "position": 1 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 2 - }, - "baseRefNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 3 - }, - "baseRefName": { - "type": "string", - "maxLength": 255, - "position": 4 - }, - "sourceListingId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 5 - }, - "sourceContractId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 6 - }, - "sourceRefNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 7 - }, - "sourceRefName": { - "type": "string", - "maxLength": 255, - "position": 8 - }, - "headOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 9 - }, - "patchManifestHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 10 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 0 - }, - "createdAt": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 2 - } - }, - "required": [], - "additionalProperties": false, - "position": 11 - } - }, - "indices": [ - { - "name": "number", - "properties": [ - { - "number": "asc" - } - ], - "unique": true - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "source", - "properties": [ - { - "sourceListingId": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "number", - "title", - "baseRefNameHash", - "sourceContractId", - "headOid" - ], - "additionalProperties": false - }, - "comment": { - "type": "object", - "documentsKeepHistory": true, - "properties": { - "targetId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 1 - }, - "replyTo": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 2 - }, - "commitOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - }, - "path": { - "type": "string", - "maxLength": 500, - "position": 4 - }, - "line": { - "type": "integer", - "position": 5, - "minimum": 0 - }, - "side": { - "type": "integer", - "position": 6, - "minimum": 0, - "maximum": 1 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 0 - }, - "createdAt": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 2 - } - }, - "required": [], - "additionalProperties": false, - "position": 7 - } - }, - "indices": [ - { - "name": "target", - "properties": [ - { - "targetId": "asc" - }, - { - "$createdAt": "asc" - } - ], - "countable": "countable" - } - ], - "required": [ - "$createdAt", - "targetId", - "body" - ], - "additionalProperties": false - }, - "event": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "properties": { - "targetId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - }, - "kind": { - "type": "integer", - "position": 1, - "minimum": 1 - }, - "value": { - "type": "string", - "maxLength": 120, - "position": 2 - }, - "oid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - } - }, - "indices": [ - { - "name": "target", - "properties": [ - { - "targetId": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "feed", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "targetId", - "kind", - "$createdAt" - ], - "additionalProperties": false - }, - "review": { - "type": "object", - "documentsMutable": false, - "properties": { - "patchId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - }, - "verdict": { - "type": "integer", - "position": 1, - "minimum": 1, - "maximum": 3 - }, - "commitOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 2 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 3 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 0 - }, - "createdAt": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 2 - } - }, - "required": [], - "additionalProperties": false, - "position": 4 - } - }, - "indices": [ - { - "name": "patch", - "properties": [ - { - "patchId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "patchId", - "verdict", - "commitOid" - ], - "additionalProperties": false - }, - "label": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - }, - "delete": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "name": { - "type": "string", - "maxLength": 30, - "position": 0 - }, - "color": { - "type": "string", - "maxLength": 7, - "position": 1 - }, - "description": { - "type": "string", - "maxLength": 200, - "position": 2 - }, - "retired": { - "type": "boolean", - "position": 3 - } - }, - "indices": [ - { - "name": "name", - "properties": [ - { - "name": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "name" - ], - "additionalProperties": false - }, - "release": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - }, - "delete": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "tagName": { - "type": "string", - "maxLength": 63, - "position": 0 - }, - "name": { - "type": "string", - "maxLength": 120, - "position": 1 - }, - "notes": { - "type": "string", - "maxLength": 5120, - "position": 2 - }, - "yanked": { - "type": "boolean", - "position": 3 - }, - "assets": { - "type": "string", - "maxLength": 4096, - "position": 4, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - } - }, - "indices": [ - { - "name": "tag", - "properties": [ - { - "tagName": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "tagName" - ], - "additionalProperties": false - }, - "checkRun": { - "type": "object", - "documentsMutable": true, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "headOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 0 - }, - "name": { - "type": "string", - "maxLength": 100, - "position": 1 - }, - "status": { - "type": "string", - "maxLength": 30, - "position": 2 - }, - "conclusion": { - "type": "string", - "maxLength": 30, - "position": 3 - }, - "detailsUrl": { - "type": "string", - "maxLength": 300, - "position": 4 - }, - "summary": { - "type": "string", - "maxLength": 1000, - "position": 5 - } - }, - "indices": [ - { - "name": "head", - "properties": [ - { - "headOid": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "headOid", - "name", - "status" - ], - "additionalProperties": false - }, - "webhook": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - }, - "delete": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "hookId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 1 - }, - "events": { - "type": "string", - "maxLength": 600, - "position": 2, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "relayIdentityId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 3 - }, - "encryptedSecret": { - "type": "array", - "byteArray": true, - "maxItems": 128, - "position": 4 - }, - "disabled": { - "type": "boolean", - "position": 5 - } - }, - "indices": [ - { - "name": "hook", - "properties": [ - { - "hookId": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "list", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "hookId", - "url", - "relayIdentityId" - ], - "additionalProperties": false - } - }, - "tokens": { - "0": { - "$formatVersion": "0", - "conventions": { - "$formatVersion": "0", - "localizations": { - "en": { - "$formatVersion": "0", - "shouldCapitalize": true, - "singularForm": "write", - "pluralForm": "writes" - } - }, - "decimals": 0 - }, - "conventionsChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "baseSupply": 1000000000, - "maxSupply": null, - "keepsHistory": { - "$formatVersion": "0", - "keepsTransferHistory": true, - "keepsFreezingHistory": true, - "keepsMintingHistory": true, - "keepsBurningHistory": true, - "keepsDirectPricingHistory": true, - "keepsDirectPurchaseHistory": true - }, - "startAsPaused": false, - "allowTransferToFrozenBalance": true, - "maxSupplyChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "distributionRules": { - "$formatVersion": "0", - "perpetualDistribution": null, - "perpetualDistributionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "preProgrammedDistribution": null, - "newTokensDestinationIdentity": null, - "newTokensDestinationIdentityRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mintingAllowChoosingDestination": true, - "mintingAllowChoosingDestinationRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "changeDirectPurchasePricingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "marketplaceRules": { - "$formatVersion": "0", - "tradeMode": "NotTradeable", - "tradeModeChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "manualMintingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "manualBurningRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "freezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "unfreezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "destroyFrozenFundsRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "emergencyActionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mainControlGroup": null, - "mainControlGroupCanBeModified": "ContractOwner", - "description": null - }, - "1": { - "$formatVersion": "0", - "conventions": { - "$formatVersion": "0", - "localizations": { - "en": { - "$formatVersion": "0", - "shouldCapitalize": true, - "singularForm": "maintain", - "pluralForm": "maintains" - } - }, - "decimals": 0 - }, - "conventionsChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "baseSupply": 1000000000, - "maxSupply": null, - "keepsHistory": { - "$formatVersion": "0", - "keepsTransferHistory": true, - "keepsFreezingHistory": true, - "keepsMintingHistory": true, - "keepsBurningHistory": true, - "keepsDirectPricingHistory": true, - "keepsDirectPurchaseHistory": true - }, - "startAsPaused": false, - "allowTransferToFrozenBalance": true, - "maxSupplyChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "distributionRules": { - "$formatVersion": "0", - "perpetualDistribution": null, - "perpetualDistributionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "preProgrammedDistribution": null, - "newTokensDestinationIdentity": null, - "newTokensDestinationIdentityRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mintingAllowChoosingDestination": true, - "mintingAllowChoosingDestinationRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "changeDirectPurchasePricingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "marketplaceRules": { - "$formatVersion": "0", - "tradeMode": "NotTradeable", - "tradeModeChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "manualMintingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "manualBurningRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "freezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "unfreezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "destroyFrozenFundsRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "emergencyActionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mainControlGroup": null, - "mainControlGroupCanBeModified": "ContractOwner", - "description": null - } - }, - "keywords": [ - "git", - "forge", - "repository" - ], - "description": "Dash Forge per-repository contract (template v1)." -} diff --git a/forge-contracts/vectors/fold_issue__issue_assign_unassign_by_maintainer.json b/forge-contracts/vectors/fold_issue__issue_assign_unassign_by_maintainer.json deleted file mode 100644 index 0c69216fa..000000000 --- a/forge-contracts/vectors/fold_issue__issue_assign_unassign_by_maintainer.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "issue_assign_unassign_by_maintainer", - "description": "Assign/assign/unassign folds to the net assignee set.", - "case": "fold_issue", - "input": { - "events": [ - { - "id": "e1", - "targetId": "ISSUE", - "kind": "assign", - "actor": "maint", - "value": "dev1", - "oid": null, - "createdAt": 100 - }, - { - "id": "e2", - "targetId": "ISSUE", - "kind": "assign", - "actor": "maint", - "value": "dev2", - "oid": null, - "createdAt": 200 - }, - { - "id": "e3", - "targetId": "ISSUE", - "kind": "unassign", - "actor": "maint", - "value": "dev1", - "oid": null, - "createdAt": 300 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "maint", - "token": "maintain", - "op": "mint", - "createdAt": 50 - } - ] - }, - "expected": { - "open": true, - "labels": [], - "assignees": [ - "dev2" - ] - } -} diff --git a/forge-contracts/vectors/fold_issue__issue_close_by_already_frozen_maintainer_inert.json b/forge-contracts/vectors/fold_issue__issue_close_by_already_frozen_maintainer_inert.json deleted file mode 100644 index b274dc28b..000000000 --- a/forge-contracts/vectors/fold_issue__issue_close_by_already_frozen_maintainer_inert.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "issue_close_by_already_frozen_maintainer_inert", - "description": "A maintainer frozen BEFORE acting is inert as-of the action time.", - "case": "fold_issue", - "input": { - "events": [ - { - "id": "e1", - "targetId": "ISSUE", - "kind": "close", - "actor": "maint", - "value": null, - "oid": null, - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "maint", - "token": "maintain", - "op": "mint", - "createdAt": 50 - }, - { - "id": "t2", - "identity": "maint", - "token": "maintain", - "op": "freeze", - "createdAt": 80 - } - ] - }, - "expected": { - "open": true, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_issue__issue_close_by_author.json b/forge-contracts/vectors/fold_issue__issue_close_by_author.json deleted file mode 100644 index 0709ef8c2..000000000 --- a/forge-contracts/vectors/fold_issue__issue_close_by_author.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "issue_close_by_author", - "description": "The author may close their own issue.", - "case": "fold_issue", - "input": { - "events": [ - { - "id": "e1", - "targetId": "ISSUE", - "kind": "close", - "actor": "alice", - "value": null, - "oid": null, - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [] - }, - "expected": { - "open": false, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_issue__issue_close_by_since_frozen_maintainer_valid.json b/forge-contracts/vectors/fold_issue__issue_close_by_since_frozen_maintainer_valid.json deleted file mode 100644 index 4fd812fb0..000000000 --- a/forge-contracts/vectors/fold_issue__issue_close_by_since_frozen_maintainer_valid.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "issue_close_by_since_frozen_maintainer_valid", - "description": "A maintainer's PAST close stays valid even though they were frozen later.", - "case": "fold_issue", - "input": { - "events": [ - { - "id": "e1", - "targetId": "ISSUE", - "kind": "close", - "actor": "maint", - "value": null, - "oid": null, - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "maint", - "token": "maintain", - "op": "mint", - "createdAt": 50 - }, - { - "id": "t2", - "identity": "maint", - "token": "maintain", - "op": "freeze", - "createdAt": 200 - } - ] - }, - "expected": { - "open": false, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_issue__issue_close_by_stranger_inert.json b/forge-contracts/vectors/fold_issue__issue_close_by_stranger_inert.json deleted file mode 100644 index 5ea918ddf..000000000 --- a/forge-contracts/vectors/fold_issue__issue_close_by_stranger_inert.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "issue_close_by_stranger_inert", - "description": "A stranger's close is inert.", - "case": "fold_issue", - "input": { - "events": [ - { - "id": "e1", - "targetId": "ISSUE", - "kind": "close", - "actor": "eve", - "value": null, - "oid": null, - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [] - }, - "expected": { - "open": true, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_issue__issue_close_reopen_by_author.json b/forge-contracts/vectors/fold_issue__issue_close_reopen_by_author.json deleted file mode 100644 index c2667488a..000000000 --- a/forge-contracts/vectors/fold_issue__issue_close_reopen_by_author.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "issue_close_reopen_by_author", - "description": "Author close then reopen leaves it open.", - "case": "fold_issue", - "input": { - "events": [ - { - "id": "e1", - "targetId": "ISSUE", - "kind": "close", - "actor": "alice", - "value": null, - "oid": null, - "createdAt": 100 - }, - { - "id": "e2", - "targetId": "ISSUE", - "kind": "reopen", - "actor": "alice", - "value": null, - "oid": null, - "createdAt": 200 - } - ], - "targetAuthor": "alice", - "tokenRecords": [] - }, - "expected": { - "open": true, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_issue__issue_default_open.json b/forge-contracts/vectors/fold_issue__issue_default_open.json deleted file mode 100644 index 8938abe2d..000000000 --- a/forge-contracts/vectors/fold_issue__issue_default_open.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "issue_default_open", - "description": "An issue with no events is open with no labels.", - "case": "fold_issue", - "input": { - "events": [], - "targetAuthor": "alice", - "tokenRecords": [] - }, - "expected": { - "open": true, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_issue__issue_label_by_author_inert.json b/forge-contracts/vectors/fold_issue__issue_label_by_author_inert.json deleted file mode 100644 index fe8ce2aa5..000000000 --- a/forge-contracts/vectors/fold_issue__issue_label_by_author_inert.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "issue_label_by_author_inert", - "description": "The author cannot label (needs a token); the label event is inert.", - "case": "fold_issue", - "input": { - "events": [ - { - "id": "e1", - "targetId": "ISSUE", - "kind": "labelAdd", - "actor": "alice", - "value": "bug", - "oid": null, - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [] - }, - "expected": { - "open": true, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_issue__issue_label_churn_by_maintainer.json b/forge-contracts/vectors/fold_issue__issue_label_churn_by_maintainer.json deleted file mode 100644 index c9b12c553..000000000 --- a/forge-contracts/vectors/fold_issue__issue_label_churn_by_maintainer.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "issue_label_churn_by_maintainer", - "description": "Label add/add/remove by a MAINTAIN holder folds to the net set.", - "case": "fold_issue", - "input": { - "events": [ - { - "id": "e1", - "targetId": "ISSUE", - "kind": "labelAdd", - "actor": "maint", - "value": "bug", - "oid": null, - "createdAt": 100 - }, - { - "id": "e2", - "targetId": "ISSUE", - "kind": "labelAdd", - "actor": "maint", - "value": "urgent", - "oid": null, - "createdAt": 200 - }, - { - "id": "e3", - "targetId": "ISSUE", - "kind": "labelRemove", - "actor": "maint", - "value": "bug", - "oid": null, - "createdAt": 300 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "maint", - "token": "maintain", - "op": "mint", - "createdAt": 50 - } - ] - }, - "expected": { - "open": true, - "labels": [ - "urgent" - ], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_pr__pr_close_by_author.json b/forge-contracts/vectors/fold_pr__pr_close_by_author.json deleted file mode 100644 index 943aa4313..000000000 --- a/forge-contracts/vectors/fold_pr__pr_close_by_author.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "pr_close_by_author", - "description": "The author may close their own PR (not merged).", - "case": "fold_pr", - "input": { - "events": [ - { - "id": "e1", - "targetId": "PR", - "kind": "close", - "actor": "alice", - "value": null, - "oid": null, - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [], - "baseTip": null, - "ancestry": [] - }, - "expected": { - "open": false, - "merged": false, - "draft": false, - "baseRef": null, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_pr__pr_draft_then_ready.json b/forge-contracts/vectors/fold_pr__pr_draft_then_ready.json deleted file mode 100644 index d924d844b..000000000 --- a/forge-contracts/vectors/fold_pr__pr_draft_then_ready.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "pr_draft_then_ready", - "description": "Draft then ready clears the draft flag.", - "case": "fold_pr", - "input": { - "events": [ - { - "id": "e1", - "targetId": "PR", - "kind": "draft", - "actor": "dev", - "value": null, - "oid": null, - "createdAt": 100 - }, - { - "id": "e2", - "targetId": "PR", - "kind": "ready", - "actor": "dev", - "value": null, - "oid": null, - "createdAt": 200 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "dev", - "token": "write", - "op": "mint", - "createdAt": 50 - } - ], - "baseTip": null, - "ancestry": [] - }, - "expected": { - "open": true, - "merged": false, - "draft": false, - "baseRef": null, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_pr__pr_merge_by_maintainer_valid.json b/forge-contracts/vectors/fold_pr__pr_merge_by_maintainer_valid.json deleted file mode 100644 index 2afa10668..000000000 --- a/forge-contracts/vectors/fold_pr__pr_merge_by_maintainer_valid.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "pr_merge_by_maintainer_valid", - "description": "A MAINTAIN holder's merge with a reachable oid merges and closes the PR.", - "case": "fold_pr", - "input": { - "events": [ - { - "id": "e1", - "targetId": "PR", - "kind": "merge", - "actor": "maint", - "value": null, - "oid": "M", - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "maint", - "token": "maintain", - "op": "mint", - "createdAt": 50 - } - ], - "baseTip": "T", - "ancestry": [ - [ - "M", - "T" - ] - ] - }, - "expected": { - "open": false, - "merged": true, - "draft": false, - "baseRef": null, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_pr__pr_merge_by_nonholder_inert.json b/forge-contracts/vectors/fold_pr__pr_merge_by_nonholder_inert.json deleted file mode 100644 index 8e2b5abad..000000000 --- a/forge-contracts/vectors/fold_pr__pr_merge_by_nonholder_inert.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "pr_merge_by_nonholder_inert", - "description": "A non-holder's merge is inert.", - "case": "fold_pr", - "input": { - "events": [ - { - "id": "e1", - "targetId": "PR", - "kind": "merge", - "actor": "eve", - "value": null, - "oid": "M", - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [], - "baseTip": "T", - "ancestry": [ - [ - "M", - "T" - ] - ] - }, - "expected": { - "open": true, - "merged": false, - "draft": false, - "baseRef": null, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_pr__pr_merge_by_writer_valid.json b/forge-contracts/vectors/fold_pr__pr_merge_by_writer_valid.json deleted file mode 100644 index 33e307bdb..000000000 --- a/forge-contracts/vectors/fold_pr__pr_merge_by_writer_valid.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "pr_merge_by_writer_valid", - "description": "A WRITE holder may also merge (MAINTAIN-or-WRITE).", - "case": "fold_pr", - "input": { - "events": [ - { - "id": "e1", - "targetId": "PR", - "kind": "merge", - "actor": "dev", - "value": null, - "oid": "M", - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "dev", - "token": "write", - "op": "mint", - "createdAt": 50 - } - ], - "baseTip": "T", - "ancestry": [ - [ - "M", - "T" - ] - ] - }, - "expected": { - "open": false, - "merged": true, - "draft": false, - "baseRef": null, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_pr__pr_merge_cannot_reopen.json b/forge-contracts/vectors/fold_pr__pr_merge_cannot_reopen.json deleted file mode 100644 index c3634b43d..000000000 --- a/forge-contracts/vectors/fold_pr__pr_merge_cannot_reopen.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "pr_merge_cannot_reopen", - "description": "A merged PR cannot be reopened.", - "case": "fold_pr", - "input": { - "events": [ - { - "id": "e1", - "targetId": "PR", - "kind": "merge", - "actor": "maint", - "value": null, - "oid": "M", - "createdAt": 100 - }, - { - "id": "e2", - "targetId": "PR", - "kind": "reopen", - "actor": "alice", - "value": null, - "oid": null, - "createdAt": 200 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "maint", - "token": "maintain", - "op": "mint", - "createdAt": 50 - } - ], - "baseTip": "T", - "ancestry": [ - [ - "M", - "T" - ] - ] - }, - "expected": { - "open": false, - "merged": true, - "draft": false, - "baseRef": null, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_pr__pr_merge_unreachable_oid_inert.json b/forge-contracts/vectors/fold_pr__pr_merge_unreachable_oid_inert.json deleted file mode 100644 index e4f89fc56..000000000 --- a/forge-contracts/vectors/fold_pr__pr_merge_unreachable_oid_inert.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "pr_merge_unreachable_oid_inert", - "description": "A merge whose oid is not reachable from base is inert.", - "case": "fold_pr", - "input": { - "events": [ - { - "id": "e1", - "targetId": "PR", - "kind": "merge", - "actor": "maint", - "value": null, - "oid": "X", - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "maint", - "token": "maintain", - "op": "mint", - "createdAt": 50 - } - ], - "baseTip": "T", - "ancestry": [] - }, - "expected": { - "open": true, - "merged": false, - "draft": false, - "baseRef": null, - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/fold_pr__pr_retarget_by_maintainer.json b/forge-contracts/vectors/fold_pr__pr_retarget_by_maintainer.json deleted file mode 100644 index 90c8e22e3..000000000 --- a/forge-contracts/vectors/fold_pr__pr_retarget_by_maintainer.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "pr_retarget_by_maintainer", - "description": "Retarget updates the PR base ref.", - "case": "fold_pr", - "input": { - "events": [ - { - "id": "e1", - "targetId": "PR", - "kind": "retarget", - "actor": "maint", - "value": "refs/heads/release", - "oid": null, - "createdAt": 100 - } - ], - "targetAuthor": "alice", - "tokenRecords": [ - { - "id": "t1", - "identity": "maint", - "token": "maintain", - "op": "mint", - "createdAt": 50 - } - ], - "baseTip": null, - "ancestry": [] - }, - "expected": { - "open": true, - "merged": false, - "draft": false, - "baseRef": "refs/heads/release", - "labels": [], - "assignees": [] - } -} diff --git a/forge-contracts/vectors/holdings__holdings_before_freeze_valid.json b/forge-contracts/vectors/holdings__holdings_before_freeze_valid.json deleted file mode 100644 index 1c1d4af64..000000000 --- a/forge-contracts/vectors/holdings__holdings_before_freeze_valid.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "holdings_before_freeze_valid", - "description": "Before a freeze, the token is still spendable.", - "case": "holdings", - "input": { - "records": [ - { - "id": "r1", - "identity": "bob", - "token": "write", - "op": "mint", - "createdAt": 100 - }, - { - "id": "r2", - "identity": "bob", - "token": "write", - "op": "freeze", - "createdAt": 200 - } - ], - "identity": "bob", - "at": 150 - }, - "expected": { - "write": true, - "maintain": false - } -} diff --git a/forge-contracts/vectors/holdings__holdings_destroyed.json b/forge-contracts/vectors/holdings__holdings_destroyed.json deleted file mode 100644 index f4b8a28e8..000000000 --- a/forge-contracts/vectors/holdings__holdings_destroyed.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "holdings_destroyed", - "description": "A destroyed (revoked) balance is gone.", - "case": "holdings", - "input": { - "records": [ - { - "id": "r1", - "identity": "bob", - "token": "write", - "op": "mint", - "createdAt": 100 - }, - { - "id": "r2", - "identity": "bob", - "token": "write", - "op": "freeze", - "createdAt": 200 - }, - { - "id": "r3", - "identity": "bob", - "token": "write", - "op": "destroy", - "createdAt": 300 - } - ], - "identity": "bob", - "at": 350 - }, - "expected": { - "write": false, - "maintain": false - } -} diff --git a/forge-contracts/vectors/holdings__holdings_frozen_not_spendable.json b/forge-contracts/vectors/holdings__holdings_frozen_not_spendable.json deleted file mode 100644 index f405f9a67..000000000 --- a/forge-contracts/vectors/holdings__holdings_frozen_not_spendable.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "holdings_frozen_not_spendable", - "description": "A frozen identity cannot spend.", - "case": "holdings", - "input": { - "records": [ - { - "id": "r1", - "identity": "bob", - "token": "write", - "op": "mint", - "createdAt": 100 - }, - { - "id": "r2", - "identity": "bob", - "token": "write", - "op": "freeze", - "createdAt": 200 - } - ], - "identity": "bob", - "at": 250 - }, - "expected": { - "write": false, - "maintain": false - } -} diff --git a/forge-contracts/vectors/holdings__holdings_minted_write.json b/forge-contracts/vectors/holdings__holdings_minted_write.json deleted file mode 100644 index 8737dd81f..000000000 --- a/forge-contracts/vectors/holdings__holdings_minted_write.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "holdings_minted_write", - "description": "A minted WRITE token is spendable.", - "case": "holdings", - "input": { - "records": [ - { - "id": "r1", - "identity": "bob", - "token": "write", - "op": "mint", - "createdAt": 100 - } - ], - "identity": "bob", - "at": 150 - }, - "expected": { - "write": true, - "maintain": false - } -} diff --git a/forge-contracts/vectors/holdings__holdings_none.json b/forge-contracts/vectors/holdings__holdings_none.json deleted file mode 100644 index 21bd6b780..000000000 --- a/forge-contracts/vectors/holdings__holdings_none.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "holdings_none", - "description": "An identity with no records holds nothing.", - "case": "holdings", - "input": { - "records": [], - "identity": "bob", - "at": 100 - }, - "expected": { - "write": false, - "maintain": false - } -} diff --git a/forge-contracts/vectors/holdings__holdings_tie_at_timestamp.json b/forge-contracts/vectors/holdings__holdings_tie_at_timestamp.json deleted file mode 100644 index 0087cbeb7..000000000 --- a/forge-contracts/vectors/holdings__holdings_tie_at_timestamp.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "holdings_tie_at_timestamp", - "description": "At equal $createdAt, records apply in $id order (mint then freeze -> frozen).", - "case": "holdings", - "input": { - "records": [ - { - "id": "r1", - "identity": "bob", - "token": "write", - "op": "mint", - "createdAt": 100 - }, - { - "id": "r2", - "identity": "bob", - "token": "write", - "op": "freeze", - "createdAt": 100 - } - ], - "identity": "bob", - "at": 100 - }, - "expected": { - "write": false, - "maintain": false - } -} diff --git a/forge-contracts/vectors/holdings__holdings_unfreeze_readmits.json b/forge-contracts/vectors/holdings__holdings_unfreeze_readmits.json deleted file mode 100644 index 85c378257..000000000 --- a/forge-contracts/vectors/holdings__holdings_unfreeze_readmits.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "holdings_unfreeze_readmits", - "description": "Unfreezing restores spend.", - "case": "holdings", - "input": { - "records": [ - { - "id": "r1", - "identity": "bob", - "token": "write", - "op": "mint", - "createdAt": 100 - }, - { - "id": "r2", - "identity": "bob", - "token": "write", - "op": "freeze", - "createdAt": 200 - }, - { - "id": "r3", - "identity": "bob", - "token": "write", - "op": "unfreeze", - "createdAt": 300 - } - ], - "identity": "bob", - "at": 350 - }, - "expected": { - "write": true, - "maintain": false - } -} diff --git a/forge-contracts/vectors/holdings__holdings_write_and_maintain.json b/forge-contracts/vectors/holdings__holdings_write_and_maintain.json deleted file mode 100644 index 54b36ff95..000000000 --- a/forge-contracts/vectors/holdings__holdings_write_and_maintain.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "holdings_write_and_maintain", - "description": "Independent WRITE and MAINTAIN holdings.", - "case": "holdings", - "input": { - "records": [ - { - "id": "r1", - "identity": "bob", - "token": "write", - "op": "mint", - "createdAt": 100 - }, - { - "id": "r2", - "identity": "bob", - "token": "maintain", - "op": "mint", - "createdAt": 100 - } - ], - "identity": "bob", - "at": 150 - }, - "expected": { - "write": true, - "maintain": true - } -} diff --git a/forge-web/app/explore/page.tsx b/forge-web/app/explore/page.tsx index 357abc397..1be694dc6 100644 --- a/forge-web/app/explore/page.tsx +++ b/forge-web/app/explore/page.tsx @@ -14,7 +14,7 @@ import { AppShell } from '@/components/app-shell' import { RepoCard } from '@/components/repo-card' import { Button } from '@/components/ui/button' import { ErrorState, Spinner } from '@/components/ui/states' -import { NotDeployedState, isV2Deployed } from '@/components/ui/network-badge' +import { NotDeployedState, isForgeDeployed } from '@/components/ui/network-badge' import { useAuth } from '@/contexts/auth-context' import { useAsync, type AsyncState } from '@/hooks/use-async' import { repoHref } from '@/hooks/use-query-param' @@ -49,8 +49,8 @@ export default function ExplorePage(): JSX.Element { const on = ready && sdk !== null && forge !== null const recent = useAsync(() => listRecentRepos(sdk!, { network, limit: 24 }), [ready, network], { enabled: on }) - const recentV2 = recent.data?.v2 ?? [] - const releases = useAsync(() => latestReleases(sdk!, forge!, recentV2.map(repoLite)), [recentV2.map((r) => r.key).join(',')], { + const recentRepos = recent.data ?? [] + const releases = useAsync(() => latestReleases(sdk!, forge!, recentRepos.map(repoLite)), [recentRepos.map((r) => r.key).join(',')], { enabled: on && recent.data !== null, }) @@ -69,8 +69,8 @@ export default function ExplorePage(): JSX.Element { { enabled: signedIn }, ) // Assigned / mentioned: no index, so scan the repos I own or belong to (the inbox's set). - const ownedV2 = mine.data?.owned.filter((r) => r.kind === 'v2') ?? [] - const memberOf = [...ownedV2, ...(mine.data?.member ?? [])] + const owned = mine.data?.owned ?? [] + const memberOf = [...owned, ...(mine.data?.member ?? [])] const watched = memberOf.slice(0, SCAN_REPOS_MAX) const scan = useAsync( async () => scanAssignedAndMentions(sdk!, forge!, me, await resolveDpnsName(sdk!, me, network), watched.map(repoLite)), @@ -78,7 +78,7 @@ export default function ExplorePage(): JSX.Element { { enabled: signedIn && mine.data !== null }, ) - if (!isV2Deployed()) { + if (!isForgeDeployed()) { return ( @@ -115,11 +115,11 @@ export default function ExplorePage(): JSX.Element {
}> {() => ( <> - - + + )} - {() => ownedV2.length === 0} + {() => owned.length === 0}
{(d) => ( @@ -171,8 +171,8 @@ export default function ExplorePage(): JSX.Element { ) : null}
}> - {(d) => } - {(d) => d.v2.length === 0} + {(d) => } + {(d) => d.length === 0}
" on the next visit instead of leaving a half-made repo. On success * the repo's empty state shows the push commands (`ux-dx-spec.md` §5.5). * - * On a network without forge-v2 (testnet today) repos are not created from the browser: a v1 - * repo was its own ~1.18 DASH contract, and that path is gone. + * On a network without forge-v2 the page shows "not deployed". */ import { useCallback, useEffect, useMemo, useState } from 'react' import { useRouter } from 'next/navigation' -import { Check, GitBranch, Hammer, Loader2, Lock, Terminal } from 'lucide-react' +import { Check, GitBranch, Hammer, Loader2, Lock } from 'lucide-react' import { AppShell } from '@/components/app-shell' import { Button } from '@/components/ui/button' import { Field, Input, Textarea } from '@/components/ui/input' import { CostPreview } from '@/components/ui/cost-preview' import { ConfirmDialog } from '@/components/confirm-dialog' import { EmptyState } from '@/components/ui/states' -import { NotDeployedState, isV2Deployed } from '@/components/ui/network-badge' +import { NotDeployedState, isForgeDeployed } from '@/components/ui/network-badge' import { ACTIVE_NETWORK, DEFAULT_NETWORK } from '@/lib/constants' import { useAuth } from '@/contexts/auth-context' import { useUiStore } from '@/hooks/use-ui-store' @@ -28,7 +27,7 @@ import { useSdk } from '@/hooks/use-sdk' import { useWriteGuard } from '@/hooks/use-write-guard' import { checkRepoInput, - createRepoV2, + createRepo, discardRepoCreation, normalizeRepoName, pendingRepoCreations, @@ -106,7 +105,7 @@ export default function NewRepoPage(): JSX.Element { setProgress(INITIAL_PROGRESS) let result try { - result = await createRepoV2(sdk, signer, forge, i, (step, state) => + result = await createRepo(sdk, signer, forge, i, (step, state) => setProgress((p) => ({ ...(p ?? INITIAL_PROGRESS), [step]: state === 'start' ? 'running' : 'done' })), ) } catch (e) { @@ -118,18 +117,10 @@ export default function NewRepoPage(): JSX.Element { router.push(`/repo?owner=${encodeURIComponent(identity ?? '')}&name=${encodeURIComponent(result.name)}&created=1`) } - if (!isV2Deployed()) { + if (!isForgeDeployed()) { return ( - {ACTIVE_NETWORK.registryContractId !== null ? ( - - ) : ( - - )} + ) } diff --git a/forge-web/app/notifications/page.tsx b/forge-web/app/notifications/page.tsx index 282b56394..dc638143c 100644 --- a/forge-web/app/notifications/page.tsx +++ b/forge-web/app/notifications/page.tsx @@ -13,7 +13,7 @@ import { AppShell } from '@/components/app-shell' import { Author } from '@/components/author' import { Button } from '@/components/ui/button' import { EmptyState, ErrorState, Spinner } from '@/components/ui/states' -import { NotDeployedState, isV2Deployed } from '@/components/ui/network-badge' +import { NotDeployedState, isForgeDeployed } from '@/components/ui/network-badge' import { useAuth } from '@/contexts/auth-context' import { useInboxActions, useInboxStore } from '@/hooks/use-inbox' import { repoHref } from '@/hooks/use-query-param' @@ -46,7 +46,7 @@ export default function NotificationsPage(): JSX.Element { const shown = filter === 'unread' ? items.filter((i) => !i.read) : items const unread = items.filter((i) => !i.read).length - if (!isV2Deployed()) { + if (!isForgeDeployed()) { return ( diff --git a/forge-web/app/page.tsx b/forge-web/app/page.tsx index 76a4dc023..5032e4d2c 100644 --- a/forge-web/app/page.tsx +++ b/forge-web/app/page.tsx @@ -3,8 +3,8 @@ /** * Landing + discovery. The foundry hero states the thesis (no server to trust), the signature * verification chip sits under it — reporting whether this session's Platform connection - * actually proof-checks reads — and the discovery feed lists recent registry repos from the - * active network when the SDK connects, a clear empty/error state otherwise. + * actually proof-checks reads — and the discovery feed lists recent repos from the active + * network's forge-core when the SDK connects, a clear empty/error state otherwise. */ import Link from 'next/link' @@ -15,13 +15,7 @@ import { RepoCard } from '@/components/repo-card' import { Button } from '@/components/ui/button' import { VerificationChip } from '@/components/ui/verification-chip' import { EmptyState, ErrorState, Spinner } from '@/components/ui/states' -import { - NotDeployedState, - V2NotDeployedNote, - isForgeDeployed, - isRegistryDeployed, - isV2Deployed, -} from '@/components/ui/network-badge' +import { NotDeployedState, isForgeDeployed } from '@/components/ui/network-badge' import { useSdk } from '@/hooks/use-sdk' import { useAsync } from '@/hooks/use-async' import { useQuorumCheck } from '@/hooks/use-quorum-check' @@ -32,13 +26,11 @@ export default function LandingPage(): JSX.Element { const quorum = useQuorumCheck(network, ready && trusted) const proofs = deriveConnectionTrust(network, connectionTrust(ready, trusted), quorum) const deployed = isForgeDeployed() - const v2 = isV2Deployed() const feed = useAsync( () => listRecentRepos(sdk!, { network, limit: 24 }), [ready, network], { enabled: deployed && ready && sdk !== null }, ) - const total = feed.data ? feed.data.v2.length + feed.data.v1.length : 0 return ( @@ -87,12 +79,10 @@ export default function LandingPage(): JSX.Element {

Recent repos

- {feed.loading ? : null} - {v2 ? ( - - Explore more - - ) : null} + {feed.loading ? : null} + + Explore more +
@@ -102,10 +92,10 @@ export default function LandingPage(): JSX.Element { ) : feed.error ? ( - ) : feed.data && total === 0 ? ( + ) : feed.data && feed.data.length === 0 ? ( @@ -116,14 +106,7 @@ export default function LandingPage(): JSX.Element { } /> ) : feed.data ? ( -
- {!v2 && isRegistryDeployed() ? : null} - - {feed.data.v1.length > 0 && feed.data.v2.length > 0 ? ( -

v1 repos

- ) : null} - -
+ ) : (
{[0, 1, 2].map((i) => ( diff --git a/forge-web/app/repo/settings/page.tsx b/forge-web/app/repo/settings/page.tsx index 87cb5135f..f66be6fcf 100644 --- a/forge-web/app/repo/settings/page.tsx +++ b/forge-web/app/repo/settings/page.tsx @@ -2,7 +2,7 @@ import { Suspense } from 'react' import { RouteLoading } from '@/components/route-loading' import { SettingsClient } from './client' -/** `/repo/settings?owner=&name=` — backend, collaborators (token admin), danger zone. */ +/** `/repo/settings?owner=&name=` — backend, members, Platform details. */ export default function SettingsPage(): JSX.Element { return ( }> diff --git a/forge-web/components/app-header.tsx b/forge-web/components/app-header.tsx index 9a8b45d68..a6e51373b 100644 --- a/forge-web/components/app-header.tsx +++ b/forge-web/components/app-header.tsx @@ -44,7 +44,8 @@ export function AppHeader(): JSX.Element { Dash Forge - + {/* A devnet (resettable, test funds only) is flagged at every width. */} +
@@ -238,7 +239,7 @@ const MENU_ITEM = 'flex w-full items-start gap-2 rounded-md px-3 py-2 text-left function NewMenu(): JSX.Element | null { const { open, setOpen, ref, trigger } = usePopover() // No "New" on a network without Forge (spec §6.3: no New repo button in that state). - if (ACTIVE_NETWORK.v2 === null && ACTIVE_NETWORK.registryContractId === null) return null + if (ACTIVE_NETWORK.v2 === null) return null return (
} /> diff --git a/forge-web/components/repo/settings-content.tsx b/forge-web/components/repo/settings-content.tsx index 2f7a8e1c8..69c3ad53e 100644 --- a/forge-web/components/repo/settings-content.tsx +++ b/forge-web/components/repo/settings-content.tsx @@ -1,33 +1,24 @@ 'use client' /** - * SettingsContent — repo administration: the storage backend, the collaborator ACL (which IS - * the token balances), and the raw Platform identifiers. Grant mints a WRITE/MAINTAIN token; - * suspend freezes; revoke freezes + destroys — all CRITICAL-key token ops, each with a - * pre-sign cost + confirm. Consensus is the real gate; the UI shows the controls and surfaces - * the on-chain result. + * SettingsContent — repo administration: the storage backend, the members (the repo's + * `maintainer` / `writer` documents), and the raw Platform identifiers. Each member write has + * a pre-sign cost + confirm. Consensus is the real gate; the UI shows the controls and + * surfaces the on-chain result. * * There is deliberately no "Archive" control: the web app has no config write, and the - * config `archived` flag is display-only (token holders can still write), so a button here - * could only pretend. + * config `archived` flag is display-only (members can still write), so a button here could + * only pretend. */ import { useState } from 'react' -import { Fingerprint, HardDrive, ShieldPlus, Snowflake, UserCog } from 'lucide-react' +import { Fingerprint, HardDrive, ShieldPlus, UserCog } from 'lucide-react' import type { RepoHome } from '@/lib/view' -import type { Collaborator, V1RepoRef, V2RepoRef } from '@/lib/repo' -import { - adminCollaborator, - grantMember, - invalidateMembers, - readCollaborators, - readMembershipsCached, - revokeMember, -} from '@/lib/repo' -import type { Membership, Role as V2Role } from '@/lib/rules/v2' -import { ACTIVE_NETWORK } from '@/lib/constants' +import type { RepoRef } from '@/lib/repo' +import { grantMember, invalidateMembers, readMembershipsCached, revokeMember } from '@/lib/repo' +import type { Membership, Role as MemberRole } from '@/lib/rules/v2' import { NetworkBadge } from '@/components/ui/network-badge' -import { previewCreate, previewCredits, previewDelete, TOKEN_ADMIN_CREDITS } from '@/lib/sdk' +import { previewCreate, previewDelete } from '@/lib/sdk' import { decodeIdentifier } from '@/lib/auth' import { useWriteGuard } from '@/hooks/use-write-guard' import { useSdk } from '@/hooks/use-sdk' @@ -43,183 +34,16 @@ import { ConfirmDialog } from '@/components/confirm-dialog' import { ErrorState, LoadingBlock } from '@/components/ui/states' import { RepoStoragePolicy } from '@/components/storage/repo-storage-policy' -type Role = 'write' | 'maintain' -type Action = { kind: 'grant' | 'suspend' | 'revoke'; member: string; role: Role } - export function SettingsContent({ home }: { home: RepoHome }): JSX.Element { - if (home.repo.kind === 'v2') return - return -} - -function V1Settings({ home, repo }: { home: RepoHome; repo: V1RepoRef }): JSX.Element { - const { sdk, ready } = useSdk([repo.contractId]) - const { identity, signer } = useAuth() - const isOwner = identity === repo.ownerId - - const collabs = useAsync( - () => readCollaborators(sdk!, repo), - [ready, repo.contractId], - { enabled: ready && sdk !== null }, - ) - - const [grantId, setGrantId] = useState('') - const [grantChoice, setGrantChoice] = useState('write') - const [action, setAction] = useState(null) - - const runAction = async (): Promise => { - if (!sdk || !signer || !action) throw new Error('sign in to continue') - await adminCollaborator(sdk, signer, repo, action.kind, action.member, action.role === 'maintain') - collabs.reload() - } - - const cost = previewCredits(TOKEN_ADMIN_CREDITS) - const registryContractId = ACTIVE_NETWORK.registryContractId - - return ( -
- {/* Backend */} -
}> - -

- Change it with dg repo backend set (an owner-signed config write). It records a preference: git push currently stores packs on Platform whatever it says, and dg repack / dg reseed move them. -

-
- - {/* Collaborators */} -
}> - {collabs.loading ? ( - - ) : collabs.error ? ( - - ) : ( - <> -
- {(collabs.data ?? []).length === 0 ? ( -
- Only the owner holds tokens so far. -
- ) : ( - (collabs.data ?? []).map((c) => ( -
- -
- {c.maintain ? : null} - {c.write ? : null} - {c.frozen ? ( - - frozen - - ) : null} -
- {isOwner && c.identity !== home.repo.ownerId ? ( -
- - -
- ) : null} -
- )) - )} -
- - {isOwner ? ( -
-

Grant access

-
-
- - setGrantId(e.target.value)} placeholder="base58 identity id" className="font-mono" spellCheck={false} /> - -
-
- {(['write', 'maintain'] as Role[]).map((r) => ( - - ))} -
- -
-
- ) : ( -

Only the repo owner can mint or freeze collaborator tokens.

- )} - - )} -
- - {/* Platform details */} -
}> -
- - - - - - - - {home.listingId !== null ? : } - - - {registryContractId !== null ? : } - - - - -
-

- Raw Platform identifiers for CLI / SDK use (query the repo contract directly, or the listing on the registry). Click an id to copy the full value. -

-
- - setAction(null)} - title={ - action?.kind === 'grant' - ? `Grant ${action.role.toUpperCase()}` - : action?.kind === 'suspend' - ? 'Suspend collaborator' - : 'Revoke collaborator' - } - description={ - action?.kind === 'grant' - ? 'Mints one role token to this identity (CRITICAL key).' - : action?.kind === 'suspend' - ? 'Freezes the role token — the collaborator cannot spend it until unfrozen. Their existing docs stay valid.' - : 'Freezes then destroys the role token. Irreversible for this grant.' - } - cost={cost} - confirmLabel={action?.kind === 'grant' ? 'Sign & grant' : action?.kind === 'suspend' ? 'Sign & suspend' : 'Sign & revoke'} - onConfirm={runAction} - /> -
- ) + return } /** - * forge-v2 settings: the repo's members (its current `maintainer` / `writer` documents — the + * The repo's members (its current `maintainer` / `writer` documents — the * ACL consensus enforces), and the ids a CLI or SDK user needs. The owner adds a member by * creating their document and removes one by deleting it; consensus refuses anyone else. */ -function V2Settings({ home, repo }: { home: RepoHome; repo: V2RepoRef }): JSX.Element { +function RepoSettings({ home, repo }: { home: RepoHome; repo: RepoRef }): JSX.Element { const { sdk, ready, network } = useSdk([repo.forge.core, repo.forge.collab]) const { identity, signer } = useAuth() const guard = useWriteGuard() @@ -231,8 +55,8 @@ function V2Settings({ home, repo }: { home: RepoHome; repo: V2RepoRef }): JSX.El ) const memberRows = members.data ?? [] const [memberId, setMemberId] = useState('') - const [role, setRole] = useState('writer') - const [action, setAction] = useState<{ kind: 'grant' | 'revoke'; member: string; role: V2Role } | null>(null) + const [role, setRole] = useState('writer') + const [action, setAction] = useState<{ kind: 'grant' | 'revoke'; member: string; role: MemberRole } | null>(null) const idError = (() => { if (memberId.trim() === '') return null try { @@ -318,7 +142,7 @@ function V2Settings({ home, repo }: { home: RepoHome; repo: V2RepoRef }): JSX.El
- {(['writer', 'maintainer'] as V2Role[]).map((r) => ( + {(['writer', 'maintainer'] as MemberRole[]).map((r) => (