From d0aa1dc0a1e1923160ab58e6b7f2c77e5e44b122 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 16:20:22 -0500 Subject: [PATCH 1/8] refactor(contracts): delete the forge-v1 templates, registry and testnet deployment Removes templates/repo-v1.json (and the unused repo-core/repo-collab split), contracts/registry.json, scripts/deploy.mjs with its evo-sdk 4.0 package, deployments/testnet.json (testnet has no forge-v2 yet, so it now shows not deployed) and the registry block of devnet-moutai.json. The token-ACL conformance vectors (holdings, v1 issue/PR folds) go with the token model; the shared base-rule vectors stay. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-contracts/contracts/registry.json | 283 ---- .../deployments/devnet-moutai.json | 6 - forge-contracts/deployments/testnet.json | 18 - forge-contracts/node_modules | 1 - forge-contracts/package.json | 7 - forge-contracts/scripts/deploy-v2.mjs | 5 +- forge-contracts/scripts/deploy.mjs | 123 -- forge-contracts/sdk-v2/package.json | 2 +- forge-contracts/templates/repo-collab.json | 1019 ----------- forge-contracts/templates/repo-core.json | 777 --------- forge-contracts/templates/repo-v1.json | 1483 ----------------- ...__issue_assign_unassign_by_maintainer.json | 53 - ...se_by_already_frozen_maintainer_inert.json | 40 - .../fold_issue__issue_close_by_author.json | 25 - ...lose_by_since_frozen_maintainer_valid.json | 40 - ..._issue__issue_close_by_stranger_inert.json | 25 - ...d_issue__issue_close_reopen_by_author.json | 34 - .../fold_issue__issue_default_open.json | 15 - ...ld_issue__issue_label_by_author_inert.json | 25 - ...ssue__issue_label_churn_by_maintainer.json | 53 - .../vectors/fold_pr__pr_close_by_author.json | 30 - .../vectors/fold_pr__pr_draft_then_ready.json | 47 - ...fold_pr__pr_merge_by_maintainer_valid.json | 43 - .../fold_pr__pr_merge_by_nonholder_inert.json | 35 - .../fold_pr__pr_merge_by_writer_valid.json | 43 - .../fold_pr__pr_merge_cannot_reopen.json | 52 - ...ld_pr__pr_merge_unreachable_oid_inert.json | 38 - .../fold_pr__pr_retarget_by_maintainer.json | 38 - ...oldings__holdings_before_freeze_valid.json | 29 - .../vectors/holdings__holdings_destroyed.json | 36 - ...ldings__holdings_frozen_not_spendable.json | 29 - .../holdings__holdings_minted_write.json | 22 - .../vectors/holdings__holdings_none.json | 14 - .../holdings__holdings_tie_at_timestamp.json | 29 - .../holdings__holdings_unfreeze_readmits.json | 36 - ...holdings__holdings_write_and_maintain.json | 29 - 36 files changed, 3 insertions(+), 4581 deletions(-) delete mode 100644 forge-contracts/contracts/registry.json delete mode 100644 forge-contracts/deployments/testnet.json delete mode 120000 forge-contracts/node_modules delete mode 100644 forge-contracts/package.json delete mode 100644 forge-contracts/scripts/deploy.mjs delete mode 100644 forge-contracts/templates/repo-collab.json delete mode 100644 forge-contracts/templates/repo-core.json delete mode 100644 forge-contracts/templates/repo-v1.json delete mode 100644 forge-contracts/vectors/fold_issue__issue_assign_unassign_by_maintainer.json delete mode 100644 forge-contracts/vectors/fold_issue__issue_close_by_already_frozen_maintainer_inert.json delete mode 100644 forge-contracts/vectors/fold_issue__issue_close_by_author.json delete mode 100644 forge-contracts/vectors/fold_issue__issue_close_by_since_frozen_maintainer_valid.json delete mode 100644 forge-contracts/vectors/fold_issue__issue_close_by_stranger_inert.json delete mode 100644 forge-contracts/vectors/fold_issue__issue_close_reopen_by_author.json delete mode 100644 forge-contracts/vectors/fold_issue__issue_default_open.json delete mode 100644 forge-contracts/vectors/fold_issue__issue_label_by_author_inert.json delete mode 100644 forge-contracts/vectors/fold_issue__issue_label_churn_by_maintainer.json delete mode 100644 forge-contracts/vectors/fold_pr__pr_close_by_author.json delete mode 100644 forge-contracts/vectors/fold_pr__pr_draft_then_ready.json delete mode 100644 forge-contracts/vectors/fold_pr__pr_merge_by_maintainer_valid.json delete mode 100644 forge-contracts/vectors/fold_pr__pr_merge_by_nonholder_inert.json delete mode 100644 forge-contracts/vectors/fold_pr__pr_merge_by_writer_valid.json delete mode 100644 forge-contracts/vectors/fold_pr__pr_merge_cannot_reopen.json delete mode 100644 forge-contracts/vectors/fold_pr__pr_merge_unreachable_oid_inert.json delete mode 100644 forge-contracts/vectors/fold_pr__pr_retarget_by_maintainer.json delete mode 100644 forge-contracts/vectors/holdings__holdings_before_freeze_valid.json delete mode 100644 forge-contracts/vectors/holdings__holdings_destroyed.json delete mode 100644 forge-contracts/vectors/holdings__holdings_frozen_not_spendable.json delete mode 100644 forge-contracts/vectors/holdings__holdings_minted_write.json delete mode 100644 forge-contracts/vectors/holdings__holdings_none.json delete mode 100644 forge-contracts/vectors/holdings__holdings_tie_at_timestamp.json delete mode 100644 forge-contracts/vectors/holdings__holdings_unfreeze_readmits.json delete mode 100644 forge-contracts/vectors/holdings__holdings_write_and_maintain.json 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/testnet.json b/forge-contracts/deployments/testnet.json deleted file mode 100644 index 0d3e1ed3b..000000000 --- a/forge-contracts/deployments/testnet.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "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." - } - ] -} 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/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 - } -} From 2f4f6cfd4caa68c88d9f42b8c19f4f5d9e05267c Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 16:56:09 -0500 Subject: [PATCH 2/8] refactor(core,cli)!: remove forge-v1 read-compat, the registry and token ACLs RepoRef is now a plain forge-v2 struct: no V1 variant, no registry fallback in resolve, no dash://. Removes tokens.rs, the v1 collab services (issues, PRs, releases, labels, social on the registry), the token reads and token-payment plumbing in platform.rs, the registry from the network model (FORGE_REGISTRY_CONTRACT_ID, registry_contract_id, dash.registryContractId), Error::V1ReadOnly/TokenFrozen/Unauthorized and the registry NotDeployed, dg collab suspend/unsuspend, and the v1 branches of dg issue/pr/label/release/repo/collab/doctor. The rules keep the shared base rules (ref resolution, protected globs, display names, overlay, verdicts, per-kind event effects) that FORGE_RULES_V2 builds on; the token-ACL folds and holdings go. E602 and E605 are retired and stay reserved in docs/errors.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../{testnet-nightly.yml => nightly.yml} | 0 crates/dg/src/auth.rs | 9 - crates/dg/src/collab.rs | 64 +- crates/dg/src/common.rs | 17 +- crates/dg/src/config.rs | 24 +- crates/dg/src/context.rs | 45 +- crates/dg/src/cost.rs | 5 +- crates/dg/src/doctor.rs | 133 +- crates/dg/src/errors.rs | 8 +- crates/dg/src/issue.rs | 86 +- crates/dg/src/label.rs | 12 +- crates/dg/src/main.rs | 47 +- crates/dg/src/maint.rs | 2 - crates/dg/src/pr.rs | 66 +- crates/dg/src/release.rs | 9 +- crates/dg/src/repo.rs | 33 +- crates/dg/src/webhook.rs | 1 - crates/forge-core/Cargo.toml | 2 +- crates/forge-core/src/backends/live_tests.rs | 49 - crates/forge-core/src/backends/platform.rs | 80 +- crates/forge-core/src/collab/mod.rs | 1426 +---------------- crates/forge-core/src/collab/v2.rs | 13 +- crates/forge-core/src/create.rs | 2 +- crates/forge-core/src/error.rs | 37 +- crates/forge-core/src/fork.rs | 5 +- crates/forge-core/src/keystore.rs | 22 +- crates/forge-core/src/lib.rs | 11 +- crates/forge-core/src/members.rs | 7 +- crates/forge-core/src/network.rs | 320 +--- crates/forge-core/src/platform.rs | 183 +-- crates/forge-core/src/refs.rs | 19 +- crates/forge-core/src/repo.rs | 38 +- crates/forge-core/src/resolve.rs | 204 +-- crates/forge-core/src/rules.rs | 414 +---- crates/forge-core/src/rules/v2.rs | 17 +- crates/forge-core/src/scope.rs | 317 +--- crates/forge-core/src/tokens.rs | 313 ---- crates/forge-core/src/user_error.rs | 129 +- crates/forge-core/src/webhooks.rs | 7 +- crates/forge-core/tests/collab_tokens.rs | 270 ---- crates/forge-import/src/dest.rs | 3 - crates/forge-import/src/sink.rs | 2 +- crates/forge-relay/examples/ci_consumer.rs | 2 +- crates/forge-relay/src/config.rs | 3 +- crates/forge-relay/src/daemon.rs | 19 +- crates/git-remote-dash/src/helper.rs | 23 +- crates/git-remote-dash/src/url.rs | 11 +- docs/errors.md | 20 +- e2e/cli/scenarios/08-v1-read-compat.sh | 53 - e2e/cli/seed-read-fixture.sh | 112 -- 50 files changed, 524 insertions(+), 4170 deletions(-) rename .github/workflows/{testnet-nightly.yml => nightly.yml} (100%) delete mode 100644 crates/forge-core/src/tokens.rs delete mode 100644 crates/forge-core/tests/collab_tokens.rs delete mode 100755 e2e/cli/scenarios/08-v1-read-compat.sh delete mode 100644 e2e/cli/seed-read-fixture.sh diff --git a/.github/workflows/testnet-nightly.yml b/.github/workflows/nightly.yml similarity index 100% rename from .github/workflows/testnet-nightly.yml rename to .github/workflows/nightly.yml 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..077a90585 100644 --- a/crates/dg/src/common.rs +++ b/crates/dg/src/common.rs @@ -52,9 +52,9 @@ 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. + /// 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 contract_id(&self) -> Option<&str> { (self.owner.is_none() && looks_like_identity_id(&self.name) @@ -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,8 +82,7 @@ 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, @@ -128,11 +127,9 @@ impl Session { }) } - /// [`Self::open`], refusing a (read-only) v1 repository before anything is signed. + /// [`Self::open`] (every repository is a forge-v2 repository). 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) + Self::open(ctx, repo).await } /// The forge-v2 collaboration service, signing as this session's identity. 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..4b142f632 100644 --- a/crates/dg/src/issue.rs +++ b/crates/dg/src/issue.rs @@ -6,11 +6,10 @@ //! `authorEvent`). v1 repositories are read only: `list` and `view` still read them, every //! write is refused (E605) before anything is signed. -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 +53,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 +107,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!({ diff --git a/crates/dg/src/label.rs b/crates/dg/src/label.rs index ee87ef526..a8aa5375a 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!({ 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..314adbbef 100644 --- a/crates/dg/src/pr.rs +++ b/crates/dg/src/pr.rs @@ -20,7 +20,7 @@ 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::Verdict; use forge_core::create::default_journal_dir; use forge_core::rules::v2::Role; use forge_core::rules::EventKind; @@ -120,7 +120,7 @@ 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 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?; @@ -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..cf0ce54cb 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::{ @@ -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..6bc0dafb1 100644 --- a/crates/dg/src/repo.rs +++ b/crates/dg/src/repo.rs @@ -17,7 +17,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; @@ -314,16 +313,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 +328,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 +340,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 +370,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 +382,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 +392,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 +404,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 d4c8db69d..c9a25f1fb 100644 --- a/crates/forge-core/Cargo.toml +++ b/crates/forge-core/Cargo.toml @@ -32,7 +32,7 @@ hmac = "0.12" 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 0e7c138af..b30e2b58d 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. @@ -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,869 +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 })) - } - - /// Collect every oid that was ever a tip of `base_ref_name` (the monotonic merge- - /// reachability set) plus the newest such tip. Walks the ref's full `refUpdate` + - /// `protectedRefUpdate` history — [`crate::refs::read_ref_history`], an equality read on - /// one `refNameHash`, so its cost is this ref's pushes, not the repo's — taking every - /// non-null `newOid`. - async fn base_ref_tips( - &self, - contract: &LoadedContract, - base_ref_name: &str, - ) -> Result<(std::collections::BTreeSet, Option)> { - let ref_name_hash = sha256(base_ref_name.as_bytes()); - // 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 updates = - crate::refs::read_ref_history(self.client, contract, &scope, ref_name_hash).await?; - let mut tips: std::collections::BTreeSet = std::collections::BTreeSet::new(); - let mut newest: Option<(u64, String, String)> = None; // (created_at, id, oid) - for u in updates { - if u.new_oid.is_empty() || u.new_oid.bytes().all(|b| b == b'0') { - continue; // null oid = ref deletion, never a reachable tip - } - tips.insert(u.new_oid.clone()); - let better = match &newest { - None => true, - Some(n) => (n.0, &n.1) < (u.created_at, &u.id), - }; - if better { - newest = Some((u.created_at, u.id, u.new_oid)); - } - } - Ok((tips, newest.map(|(_, _, oid)| oid))) - } - - /// 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")] @@ -1144,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). @@ -1181,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 @@ -1332,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 { @@ -1420,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 edc33a04e..9ebaf77d3 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}; @@ -725,11 +722,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 { @@ -759,10 +755,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. diff --git a/crates/forge-core/src/create.rs b/crates/forge-core/src/create.rs index 876562368..18fc4aae8 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 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..6afae03f0 100644 --- a/crates/forge-core/src/fork.rs +++ b/crates/forge-core/src/fork.rs @@ -171,9 +171,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())?); @@ -272,7 +271,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 a08641057..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,48 +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() { - // Becomes vacuous (and should be deleted) once deployments/mainnet.json lands. - if deployment("mainnet").unwrap().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)); @@ -709,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] @@ -768,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()), @@ -792,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] @@ -820,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()), @@ -831,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] @@ -891,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); @@ -905,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()), @@ -938,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] @@ -982,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| { @@ -991,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] @@ -1011,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(); @@ -1019,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] @@ -1039,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.rs b/crates/forge-core/src/platform.rs index df567b3e4..5315ddf12 100644 --- a/crates/forge-core/src/platform.rs +++ b/crates/forge-core/src/platform.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; @@ -108,7 +96,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}; /// The `dashcore` network the SDK and its context provider use for `network`. fn to_dashcore(network: &Network) -> DashcoreNetwork { @@ -133,9 +121,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) } @@ -284,7 +270,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 @@ -316,9 +302,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); @@ -381,9 +366,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 } @@ -393,23 +377,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) @@ -656,7 +628,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 @@ -709,88 +681,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` @@ -1217,11 +1107,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, @@ -1229,7 +1114,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, @@ -1312,17 +1198,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, @@ -1851,10 +1733,8 @@ 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 requires `$createdAt`, 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; @@ -1982,25 +1862,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). @@ -2054,13 +1915,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 { @@ -2095,21 +1956,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). diff --git a/crates/forge-core/src/refs.rs b/crates/forge-core/src/refs.rs index dfb68b492..fd07de564 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}; @@ -109,10 +107,9 @@ pub(crate) trait RefDocSource { async fn full_scan(&self, doc_type: &str) -> Result>; } -/// [`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, @@ -169,7 +166,7 @@ impl RefDocSource for PlatformRefSource<'_> { } /// 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, @@ -389,7 +386,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, } diff --git a/crates/forge-core/src/repo.rs b/crates/forge-core/src/repo.rs index 4adad07ec..604231c95 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). const DOC_CONFIG: &str = "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 } @@ -631,8 +628,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 +717,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?; @@ -1592,7 +1584,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( @@ -1976,7 +1968,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..37eb7b0fb 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,25 +40,22 @@ pub fn repo_ref_from_doc(forge: &ForgeIds, doc: &FetchedDocument) -> Result Result<&ForgeIds> { + let target = client.target(); + target.v2.as_ref().ok_or_else(|| Error::V2NotDeployed { + network: target.network.key(), + }) +} + +/// Resolve `owner/name` (owner a base58 identity id). pub async fn resolve_named(client: &PlatformClient, owner: &str, name: &str) -> 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 = deployed(client)?; + find_v2(client, forge, owner_bytes, &slug) + .await? + .ok_or(Error::NotFound) } /// The forge-v2 repo `owner` named `slug`, if it exists (proved either way). @@ -94,73 +84,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 = deployed(client)?; + 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 +127,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 = deployed(client)?; + 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 +168,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 @@ -372,7 +364,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 @@ -395,7 +387,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 { @@ -460,7 +452,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 @@ -507,7 +499,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 } } @@ -534,7 +526,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: @@ -597,151 +589,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) // =========================================================================== @@ -784,7 +631,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)] @@ -849,35 +696,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>, @@ -889,31 +709,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 { @@ -943,32 +739,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, @@ -1017,13 +788,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 @@ -1159,25 +923,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, overlay_tree, resolve_ref, v2, Ancestry, AuthzResolver, ConfigDoc, - Event, EventKind, FlatIndex, Holdings, IssueState, PrState, RefState, RefUpdate, TokenKind, - TokenOp, TokenRecord, TreeDiff, Verdict, + display_ref_name, is_legal_ref_name, matches_protected, overlay_tree, resolve_ref, v2, + Ancestry, ConfigDoc, Event, EventKind, FlatIndex, IssueState, 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 { @@ -1197,23 +949,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)" @@ -1225,7 +975,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(), @@ -1244,12 +993,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"), @@ -1257,32 +1004,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")] @@ -1291,7 +1012,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, @@ -1318,36 +1040,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, - } - #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct OverlayInput { @@ -1415,38 +1107,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"); @@ -1460,7 +1120,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)] @@ -1683,7 +1343,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() { @@ -1700,15 +1360,15 @@ 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) .unwrap_or_else(|e| panic!("parse {}: {e}", path.display())); match v.rules.as_deref() { - None | Some("v1") => { + None => { run_case(&v); - ran_v1 += 1; + ran_base += 1; } Some("v2") => { run_case_v2(&v); @@ -1717,9 +1377,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 9962feb2e..5b7e08f04 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: @@ -17,12 +17,11 @@ //! * [`is_well_formed`] — plaintext xor `enc`, and no plaintext in a private repo (§5). //! * [`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; @@ -120,7 +119,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>( @@ -145,7 +144,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], @@ -162,7 +161,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/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/src/dest.rs b/crates/forge-import/src/dest.rs index fd52fc9cb..84907bb0a 100644 --- a/crates/forge-import/src/dest.rs +++ b/crates/forge-import/src/dest.rs @@ -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(), diff --git a/crates/forge-import/src/sink.rs b/crates/forge-import/src/sink.rs index dc501858c..47bb0eb02 100644 --- a/crates/forge-import/src/sink.rs +++ b/crates/forge-import/src/sink.rs @@ -457,7 +457,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-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..a4cdeca5f 100644 --- a/crates/forge-relay/src/daemon.rs +++ b/crates/forge-relay/src/daemon.rs @@ -300,16 +300,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 +571,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/git-remote-dash/src/helper.rs b/crates/git-remote-dash/src/helper.rs index f46c984a4..3e3cc7a75 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); @@ -1214,11 +1210,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 +1457,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/errors.md b/docs/errors.md index c1c05c17e..0d68886b4 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 | |---|---|---| @@ -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/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 From 28d39052303230eb5c8bcbd6a1b59652550e309b Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 16:56:09 -0500 Subject: [PATCH 3/8] ci: run the nightly on devnet moutai and build Pages for moutai Testnet Nightly becomes Devnet Nightly: Playwright runs against a moutai build using the forge-v2 read fixture, seeded idempotently by seed-v2-fixture.mjs (which now leaves an existing on-chain fixture alone on a fresh runner), and the CLI suite runs on moutai without the testnet v1 read-compat scenario 08 or the testnet read fixture. Testnet runs resume once protocol 14 and forge-v2 reach testnet. The Pages build targets devnet moutai by default, switchable with the PAGES_NETWORK / PAGES_DEVNET_NAME repository variables. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/mirror-action.yml | 6 +- .github/workflows/nightly.yml | 147 ++++++++++---------- .github/workflows/pages.yml | 12 +- Makefile | 11 +- e2e/README.md | 12 +- e2e/cli/config.sh | 22 +-- e2e/cli/run.sh | 6 +- forge-contracts/scripts/seed-v2-fixture.mjs | 26 +++- 8 files changed, 130 insertions(+), 112 deletions(-) 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/nightly.yml b/.github/workflows/nightly.yml index 7270fb20e..252cec829 100644 --- a/.github/workflows/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,45 +137,41 @@ 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 + timeout-minutes: 20 env: - ID_DEPLOYER_JSON: ${{ secrets.FORGE_TEST_IDENTITY_DEPLOYER }} + 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 }} 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 + working-directory: forge-contracts/sdk-v2 + - name: Materialize the fixture identities 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) @@ -179,7 +184,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 +214,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/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/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/forge-contracts/scripts/seed-v2-fixture.mjs b/forge-contracts/scripts/seed-v2-fixture.mjs index 9c4b31235..6c23394ef 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,26 @@ 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) { + 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`); From 37dfc9854ecedd1cefd0323960b9ec6ca9171417 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 16:56:28 -0500 Subject: [PATCH 4/8] docs: describe forge-v2 on devnet moutai as the only model The README, guides, FAQ, architecture, economics, BUILDING, the mainnet runbook (now: register the forge-v2 pair and contract group with deploy-v2.mjs) and the test plan describe forge-v2 only; the roadmap records the owner decision as D-M. data-contracts.md, design-freeze-2.md, EXECUTION.md, the PRDs and research notes carry a historical banner. Co-Authored-By: Claude Opus 5.5 (1M context) --- EXECUTION.md | 2 + README.md | 54 ++++++++------- docs/BUILDING.md | 98 ++++++++++++++------------- docs/FAQ.md | 10 +-- docs/architecture.md | 75 ++++++++++---------- docs/contracts/data-contracts.md | 2 +- docs/contracts/forge-v2.md | 42 ++++++------ docs/design-freeze-2.md | 2 + docs/design/style-guide.md | 12 ++-- docs/design/ux-dx-spec.md | 2 +- docs/economics.md | 54 ++++++++------- docs/guides/README.md | 8 ++- docs/guides/bring-your-own-storage.md | 2 +- docs/guides/collaborating.md | 61 ++++++----------- docs/guides/costs.md | 55 ++++++++------- docs/guides/identity-and-keys.md | 19 +++--- docs/guides/mirror-a-github-repo.md | 9 ++- docs/guides/quick-start.md | 52 +++++++------- docs/guides/verify-forge.md | 8 +-- docs/implementation-plan.md | 2 + docs/init-reconciliation.md | 2 + docs/mainnet-runbook.md | 81 +++++++++++++--------- docs/prd/01-product-overview.md | 2 + docs/prd/02-git-remote-helper-cli.md | 2 + docs/prd/03-web-app.md | 2 + docs/prd/04-storage-adapters.md | 4 +- docs/prd/05-forge-relay.md | 4 +- docs/prd/06-forge-import.md | 2 + docs/research/platform-constraints.md | 2 + docs/research/spike-results.md | 2 + docs/roadmap.md | 29 ++++---- docs/testing/e2e-test-plan.md | 86 ++++++++++++----------- 32 files changed, 421 insertions(+), 366 deletions(-) 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/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/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 c0d64c825..b8c619f3b 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.) @@ -149,17 +149,17 @@ A private repo is a `repo` with `visibility: "private"`; `visibility` is immutab The concrete AEAD layout, key derivation and test vectors are Phase 3 work and need their own security review (roadmap Phase 3). The contract fields above are what that design writes into. -## 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 | -| 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 | +| 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) | @@ -175,7 +175,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 | |---|---|---| @@ -190,8 +190,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 Phase 3 work and has no vectors yet. -**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. @@ -206,7 +204,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 (2026-09-25)**, as the deployer's balance change: 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/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. From ac13e4c5fcf6c34d552d47da3271ca6e73acaf89 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 16:59:19 -0500 Subject: [PATCH 5/8] chore: drop the last forge-v1 mentions from the crates Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/rust.yml | 5 ++--- crates/dg/src/common.rs | 4 ++-- crates/forge-import/Cargo.toml | 2 +- crates/forge-import/src/claim.rs | 15 +++++++-------- crates/forge-import/src/dest.rs | 2 +- crates/forge-relay/README.md | 2 +- 6 files changed, 14 insertions(+), 16 deletions(-) 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/crates/dg/src/common.rs b/crates/dg/src/common.rs index 077a90585..171e0969f 100644 --- a/crates/dg/src/common.rs +++ b/crates/dg/src/common.rs @@ -177,9 +177,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] 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 84907bb0a..75e6dc3c4 100644 --- a/crates/forge-import/src/dest.rs +++ b/crates/forge-import/src/dest.rs @@ -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>, 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 From 55808de41a5fd8a7953c7426d991968868f1461d Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 17:19:30 -0500 Subject: [PATCH 6/8] fix: address the v1-removal review Drops the last stale v1 text (relay error, dg module docs, E302/E102), the v1 JSON-string UriBudget, Session::open_v2 (now open) and resolve's duplicate of NetworkTarget::require_v2; renames the bare-id accessor to repo_id. The seeder refuses a fixture whose seed never finished, and the nightly keeps fixture keys in one step's env, runs npm ci without scripts, and serializes the CLI suite after the seed job (both sign as OWNER). Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/ci.yml | 2 +- .github/workflows/nightly.yml | 19 ++++---- crates/dg/src/common.rs | 17 +++---- crates/dg/src/issue.rs | 11 +++-- crates/dg/src/label.rs | 2 +- crates/dg/src/pr.rs | 12 ++--- crates/dg/src/release.rs | 2 +- crates/dg/src/repo.rs | 7 ++- crates/forge-core/src/collab/mod.rs | 2 +- crates/forge-core/src/fork.rs | 8 +--- crates/forge-core/src/platform.rs | 3 +- crates/forge-core/src/repo.rs | 3 +- crates/forge-core/src/resolve.rs | 14 ++---- crates/forge-core/src/storage/targets.rs | 49 +++++---------------- crates/forge-import/src/summary.rs | 2 +- crates/forge-relay/src/daemon.rs | 3 +- crates/forge-relay/src/main.rs | 2 - crates/git-remote-dash/src/helper.rs | 7 ++- docs/errors.md | 4 +- forge-contracts/scripts/seed-v2-fixture.mjs | 12 +++++ 20 files changed, 73 insertions(+), 108 deletions(-) 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/nightly.yml b/.github/workflows/nightly.yml index 252cec829..daa85ee01 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -146,11 +146,6 @@ jobs: if: needs.fixtures.outputs.seeder == 'true' runs-on: ubuntu-latest timeout-minutes: 20 - 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 }} steps: - uses: actions/checkout@v5 - uses: actions/setup-node@v5 @@ -158,9 +153,15 @@ jobs: node-version: 22 cache: npm cache-dependency-path: forge-contracts/sdk-v2/package-lock.json - - run: npm ci + - 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/devnet-moutai" mkdir -p "$dir" && chmod 700 "$dir" @@ -175,8 +176,10 @@ jobs: 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 diff --git a/crates/dg/src/common.rs b/crates/dg/src/common.rs index 171e0969f..850b06611 100644 --- a/crates/dg/src/common.rs +++ b/crates/dg/src/common.rs @@ -55,7 +55,7 @@ impl RepoRef { /// 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 contract_id(&self) -> Option<&str> { + 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())) @@ -88,7 +88,7 @@ pub async fn resolve( 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}")); @@ -127,11 +127,6 @@ impl Session { }) } - /// [`Self::open`] (every repository is a forge-v2 repository). - pub async fn open_v2(ctx: &crate::context::Ctx, repo: &str) -> Result { - Self::open(ctx, repo).await - } - /// 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) @@ -193,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/issue.rs b/crates/dg/src/issue.rs index 4b142f632..37310b6f0 100644 --- a/crates/dg/src/issue.rs +++ b/crates/dg/src/issue.rs @@ -3,8 +3,7 @@ //! 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::Result; use serde_json::json; @@ -152,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() @@ -201,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 @@ -216,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") @@ -267,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 a8aa5375a..563f7a069 100644 --- a/crates/dg/src/label.rs +++ b/crates/dg/src/label.rs @@ -60,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/pr.rs b/crates/dg/src/pr.rs index 314adbbef..49b2752c5 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 @@ -118,7 +118,7 @@ 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.forge(); let cwd = std::env::current_dir().context("reading the current directory")?; @@ -447,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()); @@ -481,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" }; @@ -533,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?; @@ -970,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, diff --git a/crates/dg/src/release.rs b/crates/dg/src/release.rs index cf0ce54cb..59164ed36 100644 --- a/crates/dg/src/release.rs +++ b/crates/dg/src/release.rs @@ -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. diff --git a/crates/dg/src/repo.rs b/crates/dg/src/repo.rs index 6bc0dafb1..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}; @@ -147,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!( @@ -267,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!( diff --git a/crates/forge-core/src/collab/mod.rs b/crates/forge-core/src/collab/mod.rs index b30e2b58d..6d4075bdb 100644 --- a/crates/forge-core/src/collab/mod.rs +++ b/crates/forge-core/src/collab/mod.rs @@ -25,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, diff --git a/crates/forge-core/src/fork.rs b/crates/forge-core/src/fork.rs index 6afae03f0..d3f08c2db 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); } diff --git a/crates/forge-core/src/platform.rs b/crates/forge-core/src/platform.rs index 5315ddf12..149e16f43 100644 --- a/crates/forge-core/src/platform.rs +++ b/crates/forge-core/src/platform.rs @@ -1733,7 +1733,8 @@ 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. /// -/// Every forge-v2 type requires `$createdAt`, so a proved query returns the boundary row's +/// 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 { diff --git a/crates/forge-core/src/repo.rs b/crates/forge-core/src/repo.rs index 604231c95..8f72dcc76 100644 --- a/crates/forge-core/src/repo.rs +++ b/crates/forge-core/src/repo.rs @@ -523,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 ))); } } diff --git a/crates/forge-core/src/resolve.rs b/crates/forge-core/src/resolve.rs index 37eb7b0fb..499a8cdfc 100644 --- a/crates/forge-core/src/resolve.rs +++ b/crates/forge-core/src/resolve.rs @@ -40,19 +40,11 @@ pub fn repo_ref_from_doc(forge: &ForgeIds, doc: &FetchedDocument) -> Result Result<&ForgeIds> { - let target = client.target(); - target.v2.as_ref().ok_or_else(|| Error::V2NotDeployed { - network: target.network.key(), - }) -} - /// Resolve `owner/name` (owner a base58 identity id). pub async fn resolve_named(client: &PlatformClient, owner: &str, name: &str) -> Result { let slug = repo_slug(name)?; let owner_bytes = platform::decode_identifier(owner)?; - let forge = deployed(client)?; + let forge = client.target().require_v2()?; find_v2(client, forge, owner_bytes, &slug) .await? .ok_or(Error::NotFound) @@ -87,7 +79,7 @@ pub async fn find_v2( /// 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 forge = deployed(client)?; + let forge = client.target().require_v2()?; 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 \ @@ -140,7 +132,7 @@ pub async fn fork_parent(client: &PlatformClient, repo: &RepoRef) -> Result Result> { let owner_bytes = platform::decode_identifier(owner)?; - let forge = deployed(client)?; + let forge = client.target().require_v2()?; let core = client.fetch_contract(&forge.core).await?; let docs = client .query_all_documents( 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-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/src/daemon.rs b/crates/forge-relay/src/daemon.rs index a4cdeca5f..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 )) })?; 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 3e3cc7a75..05549cb21 100644 --- a/crates/git-remote-dash/src/helper.rs +++ b/crates/git-remote-dash/src/helper.rs @@ -872,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) @@ -1102,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") diff --git a/docs/errors.md b/docs/errors.md index 0d68886b4..5dc784365 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -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. diff --git a/forge-contracts/scripts/seed-v2-fixture.mjs b/forge-contracts/scripts/seed-v2-fixture.mjs index 6c23394ef..2c41fc971 100644 --- a/forge-contracts/scripts/seed-v2-fixture.mjs +++ b/forge-contracts/scripts/seed-v2-fixture.mjs @@ -232,6 +232,18 @@ async function main() { }); 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)); From bee3d0275625aba5d245cb133dc1af08054e7b73 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 17:26:00 -0500 Subject: [PATCH 7/8] refactor(web)!: remove forge-v1; forge-v2 is the only model Drops the v1 RepoRef and RepoSource, registry reads and writes (listings, stars, follows), token ACLs and token history, token-admin, the V1 badge and every v1 branch in the components, ?contract= routes, the v1 rule folds and holdings, the NEXT_PUBLIC_REGISTRY_CONTRACT_ID override and the testnet deployment import. A network without forge-v2 shows the not-deployed state, including in the sign-in chooser; the header badge says devnet in the caution colour on a devnet build. Playwright runs on a moutai build by default: read-paths and auth-write (testnet v1 fixtures) are gone, a11y and zero-backend read the forge-v2 fixture, and fallback-browse forces the in-browser clone by failing the locator reads. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/app/new/page.tsx | 19 +- forge-web/app/page.tsx | 29 +- forge-web/app/repo/settings/page.tsx | 2 +- forge-web/components/app-header.tsx | 4 +- forge-web/components/login-modal.tsx | 53 +--- forge-web/components/profile-content.tsx | 28 +- forge-web/components/repo-card.tsx | 19 +- forge-web/components/repo/clone-box.tsx | 2 +- forge-web/components/repo/issue-content.tsx | 9 +- forge-web/components/repo/issues-content.tsx | 2 +- forge-web/components/repo/pull-content.tsx | 19 +- forge-web/components/repo/pull-diff.tsx | 38 +-- forge-web/components/repo/pulls-content.tsx | 2 +- forge-web/components/repo/repo-header.tsx | 6 +- forge-web/components/repo/repo-rail.tsx | 1 - forge-web/components/repo/repo-scaffold.tsx | 2 +- .../components/repo/settings-content.tsx | 204 +------------ forge-web/components/repo/star-button.tsx | 27 +- .../components/repo/stargazers-content.tsx | 31 +- forge-web/components/repo/timeline.tsx | 4 +- forge-web/components/ui/cost-preview.tsx | 13 +- forge-web/components/ui/network-badge.tsx | 68 ++--- forge-web/components/ui/trust-panel.tsx | 2 +- forge-web/components/ui/v1-badge.tsx | 11 - forge-web/e2e/a11y.spec.ts | 59 ++-- forge-web/e2e/auth-write.spec.ts | 74 ----- forge-web/e2e/fallback-browse.spec.ts | 124 ++++++-- forge-web/e2e/helpers.ts | 98 ++++--- forge-web/e2e/read-paths.spec.ts | 166 ----------- forge-web/e2e/v2-auth.spec.ts | 13 +- forge-web/e2e/v2-reads.spec.ts | 90 +++--- forge-web/e2e/v2-writes.spec.ts | 6 +- forge-web/e2e/zero-backend.spec.ts | 39 ++- forge-web/hooks/use-query-param.ts | 9 +- forge-web/hooks/use-relation-toggle.ts | 2 +- forge-web/hooks/use-repo.ts | 12 +- forge-web/hooks/use-sdk.ts | 8 +- forge-web/lib/auth/base58.ts | 2 +- forge-web/lib/auth/identity-file.ts | 2 +- forge-web/lib/browse/flatindex.ts | 2 +- forge-web/lib/browse/locator.ts | 2 +- forge-web/lib/constants.test.ts | 58 ++-- forge-web/lib/constants.ts | 66 ++--- forge-web/lib/deployments.ts | 10 +- forge-web/lib/design/contrast.test.ts | 2 +- forge-web/lib/repo/collab.ts | 198 ------------- forge-web/lib/repo/config.ts | 14 +- forge-web/lib/repo/contract.ts | 76 ++--- forge-web/lib/repo/index.ts | 48 +--- forge-web/lib/repo/issues.ts | 154 ++++------ forge-web/lib/repo/live.test.ts | 53 ---- forge-web/lib/repo/members.ts | 37 ++- forge-web/lib/repo/packs.test.ts | 115 ++------ forge-web/lib/repo/packs.ts | 98 ++----- forge-web/lib/repo/pagination.test.ts | 93 ++---- forge-web/lib/repo/refs.test.ts | 24 +- forge-web/lib/repo/refs.ts | 12 +- forge-web/lib/repo/resolveRepo.ts | 219 ++------------ forge-web/lib/repo/social.ts | 4 +- forge-web/lib/repo/source.test.ts | 1 - forge-web/lib/repo/source.ts | 56 +--- forge-web/lib/repo/token-history.live.test.ts | 42 --- forge-web/lib/repo/tokens.test.ts | 244 ---------------- forge-web/lib/repo/tokens.ts | 271 ------------------ forge-web/lib/repo/v2.live.test.ts | 7 +- forge-web/lib/repo/v2.test.ts | 76 ++--- forge-web/lib/repo/write.live.test.ts | 123 -------- forge-web/lib/repo/writes.ts | 235 ++++----------- forge-web/lib/rules/conformance.test.ts | 98 +++---- forge-web/lib/rules/fold.ts | 74 +---- forge-web/lib/rules/holdings.ts | 73 ----- forge-web/lib/rules/index.ts | 11 +- forge-web/lib/rules/matchesProtected.ts | 2 +- forge-web/lib/rules/oid.ts | 2 +- forge-web/lib/rules/resolveRef.ts | 6 +- forge-web/lib/rules/types.ts | 34 +-- forge-web/lib/rules/v2.ts | 5 +- forge-web/lib/sdk/cost.ts | 20 +- forge-web/lib/sdk/index.ts | 20 +- forge-web/lib/sdk/query.ts | 80 +----- forge-web/lib/sdk/service.ts | 8 +- forge-web/lib/sdk/token-admin.ts | 191 ------------ forge-web/lib/sdk/write-engine.test.ts | 1 - forge-web/lib/sdk/write.test.ts | 59 +--- forge-web/lib/sdk/write.ts | 90 +----- forge-web/lib/view/browse-fallback.test.ts | 55 ++-- forge-web/lib/view/browse-source.test.ts | 142 +++++---- forge-web/lib/view/browse-source.ts | 111 ++----- forge-web/lib/view/content-checks.ts | 2 +- forge-web/lib/view/discovery.ts | 138 ++------- forge-web/lib/view/fallback-cache.ts | 4 +- forge-web/lib/view/index.ts | 3 +- forge-web/lib/view/issues-view.ts | 33 +-- forge-web/lib/view/pull-actions.test.ts | 55 ++-- forge-web/lib/view/pull-actions.ts | 37 +-- forge-web/lib/view/pull-diff.ts | 3 +- forge-web/lib/view/repo-view.ts | 35 +-- forge-web/lib/view/trust.test.ts | 7 +- forge-web/lib/view/trust.ts | 10 +- forge-web/playwright.config.ts | 23 +- 100 files changed, 1118 insertions(+), 3953 deletions(-) delete mode 100644 forge-web/components/ui/v1-badge.tsx delete mode 100644 forge-web/e2e/auth-write.spec.ts delete mode 100644 forge-web/e2e/read-paths.spec.ts delete mode 100644 forge-web/lib/repo/collab.ts delete mode 100644 forge-web/lib/repo/live.test.ts delete mode 100644 forge-web/lib/repo/token-history.live.test.ts delete mode 100644 forge-web/lib/repo/tokens.test.ts delete mode 100644 forge-web/lib/repo/tokens.ts delete mode 100644 forge-web/lib/repo/write.live.test.ts delete mode 100644 forge-web/lib/rules/holdings.ts delete mode 100644 forge-web/lib/sdk/token-admin.ts diff --git a/forge-web/app/new/page.tsx b/forge-web/app/new/page.tsx index c3c51af0a..51d44d709 100644 --- a/forge-web/app/new/page.tsx +++ b/forge-web/app/new/page.tsx @@ -7,20 +7,19 @@ * "Finish creating " 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' @@ -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/page.tsx b/forge-web/app/page.tsx index 0570dfa39..cd10f206b 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 { connectionTrust, deriveConnectionTrust, listRecentRepos, type DiscoveredRepo } from '@/lib/view' @@ -30,13 +24,11 @@ export default function LandingPage(): JSX.Element { const { sdk, ready, trusted, error: sdkError, network } = useSdk() const proofs = deriveConnectionTrust(network, connectionTrust(ready, trusted)) 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 ( @@ -79,7 +71,7 @@ export default function LandingPage(): JSX.Element {

Recent repos

- {feed.loading ? : null} + {feed.loading ? : null}
{!deployed ? ( @@ -88,10 +80,10 @@ export default function LandingPage(): JSX.Element { ) : feed.error ? ( - ) : feed.data && total === 0 ? ( + ) : feed.data && feed.data.length === 0 ? ( @@ -102,14 +94,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 ffbd4c902..bb1a1339d 100644 --- a/forge-web/components/app-header.tsx +++ b/forge-web/components/app-header.tsx @@ -16,6 +16,7 @@ import { Button } from '@/components/ui/button' import { IdentityPill } from '@/components/ui/identity-pill' import { ThemeToggle } from '@/components/theme-toggle' import { NetworkBadge } from '@/components/ui/network-badge' +import { ACTIVE_NETWORK } from '@/lib/constants' import { creditsToDash } from '@/lib/sdk' import { balanceToDash, dashToUsd } from '@/lib/view/format' import { FundsPill } from '@/components/funds-pill' @@ -52,7 +53,8 @@ export function AppHeader(): JSX.Element { - + {/* A devnet (resettable, test funds only) is flagged at every width. */} +
diff --git a/forge-web/components/login-modal.tsx b/forge-web/components/login-modal.tsx index fde8ded7a..487868649 100644 --- a/forge-web/components/login-modal.tsx +++ b/forge-web/components/login-modal.tsx @@ -12,8 +12,8 @@ * * When this device already holds an encrypted key, the sheet opens on "Unlock" instead * (callers can open it on a view directly: Renew opens Import). On a network without forge-v2 - * (no contract group to bind a key to, testnet today) only the v1 path exists: the identity - * file signs with its HIGH/CRITICAL key for this tab. + * (no contract group to bind a key to) there is nothing to sign for: Import shows "not + * deployed". */ import { useEffect, useRef, useState } from 'react' @@ -28,7 +28,8 @@ import { CreateIdentityFlow } from '@/components/auth/create-identity-flow' import { WalletConnectFlow } from '@/components/auth/wallet-connect-flow' import { FORGET_CONFIRM } from '@/components/keys-panel' import { ACTIVE_NETWORK } from '@/lib/constants' -import { BROWSER_KEY_DEFAULTS, masterMaterialFromFile, parseIdentityFileText } from '@/lib/auth' +import { NotDeployedState } from '@/components/ui/network-badge' +import { BROWSER_KEY_DEFAULTS, masterMaterialFromFile } from '@/lib/auth' import { appConnectAvailable } from '@/lib/auth/app-connect' import { ensureSdk } from '@/lib/sdk' import { formatDate } from '@/lib/view/format' @@ -72,7 +73,7 @@ export function LoginModal(): JSX.Element { ? 'A pasted key signs for this tab only, with whatever power it has.' : limitedKeys ? `Forge signs with a limited key: at most ${BROWSER_KEY_DEFAULTS.budgetDash} DASH, only on Forge, for ${BROWSER_KEY_DEFAULTS.days} days.` - : `Your key signs writes on ${ACTIVE_NETWORK.key}. It stays in this tab, never sent anywhere.` + : `Dash Forge is not deployed on ${ACTIVE_NETWORK.key}, so there is nothing to sign in to here.` return ( @@ -93,7 +94,7 @@ export function LoginModal(): JSX.Element { }} /> ) : ( - + ) ) : null} {view === 'create' ? : null} @@ -124,23 +125,19 @@ function ChooseView({ onPick }: { onPick: (v: View) => void }): JSX.Element { const { limitedKeys } = useAuth() const walletAvailable = useWalletAvailability(limitedKeys) const [advanced, setAdvanced] = useState(false) + // No forge-v2 here means no contract group to bind a key to: nothing to sign in to. + if (!limitedKeys) return return (
- {limitedKeys && walletAvailable ? ( + {walletAvailable ? ( onPick('wallet')} /> ) : null} - {limitedKeys ? ( - onPick('create')} /> - ) : null} + onPick('create')} /> onPick('import')} />
@@ -407,32 +404,6 @@ function ImportView({ onDone, onStored }: { onDone: () => void; onStored: (ident ) } -/** Networks without forge-v2 (testnet): an identity file's HIGH/CRITICAL key, this tab only. */ -function V1FileView({ onDone }: { onDone: () => void }): JSX.Element { - const { loginWithRawKey, isLoading, controller } = useAuth() - const [error, setError] = useState(null) - const onFile = async (file: File): Promise => { - setError(null) - try { - const parsed = parseIdentityFileText(await file.text()) - controller.checkFileNetwork(parsed.networkKey) - await loginWithRawKey(parsed.identityId, parsed.signingKeyWif) - onDone() - } catch (e) { - setError(errorMessage(e)) - } - } - return ( -
- void onFile(f)} disabled={isLoading} /> -

- {ACTIVE_NETWORK.key} has no Forge contract group yet, so there are no limited keys here: the file's signing key is held in this tab and forgotten on reload. -

- -
- ) -} - function AdvancedView({ onDone }: { onDone: () => void }): JSX.Element { const { loginWithRawKey, isLoading } = useAuth() const [identityId, setIdentityId] = useState('') diff --git a/forge-web/components/profile-content.tsx b/forge-web/components/profile-content.tsx index ad71cc86b..389ad9fa6 100644 --- a/forge-web/components/profile-content.tsx +++ b/forge-web/components/profile-content.tsx @@ -2,7 +2,7 @@ /** * ProfileContent — an identity's profile: the identity pill (DPNS-resolved), follower/following - * counts (O(1) registry count trees), a follow/unfollow toggle, and the repos it owns. The + * counts (O(1) forge-collab count trees), a follow/unfollow toggle, and the repos it owns. The * `name` address is an identity id (what authors + search resolve to). * * The follow toggle reads whether the viewer already follows this identity before offering an @@ -12,13 +12,7 @@ import { GitBranch, UserPlus, Users } from 'lucide-react' import type { DiscoveredRepo } from '@/lib/view' import { listReposByOwner, resolveDpnsName } from '@/lib/view' -import { - followRelation, - readFollowerCount, - readFollowingCount, - readV2FollowCounts, - resolveOwner, -} from '@/lib/repo' +import { followRelation, readV2FollowCounts, resolveOwner } from '@/lib/repo' import { NETWORKS } from '@/lib/constants' import { useSdk } from '@/hooks/use-sdk' import { useAsync } from '@/hooks/use-async' @@ -29,14 +23,14 @@ import { IdentityPill } from '@/components/ui/identity-pill' import { RepoCard } from '@/components/repo-card' import { Button } from '@/components/ui/button' import { EmptyState, ErrorState, LoadingBlock } from '@/components/ui/states' -import { NotDeployedState, isForgeDeployed, isRegistryDeployed } from '@/components/ui/network-badge' +import { NotDeployedState, isForgeDeployed } from '@/components/ui/network-badge' interface ProfileData { /** The identity id the address resolved to (it may have been a DPNS name). */ readonly identityId: string readonly name: string | null readonly repos: DiscoveredRepo[] - /** forge-v2 repos this identity is a maintainer or writer of (and does not own). */ + /** Repos this identity is a maintainer or writer of (and does not own). */ readonly memberOf: DiscoveredRepo[] /** `null` when the count read failed — shown as unknown, never as a false 0. */ readonly followers: number | null @@ -63,14 +57,8 @@ export function ProfileContent({ identityId: address }: { identityId: string }): const identityId = await resolveOwner(sdk!, address) if (identityId === null) return null const forge = NETWORKS[network].v2 - // Follows live in forge-collab where forge-v2 is deployed, else in the v1 registry. const noCounts = { followers: null, following: null } - const follows = forge !== null - ? readV2FollowCounts(sdk!, forge, identityId).catch(() => noCounts) - : Promise.all([ - readFollowerCount(sdk!, identityId, { network }).catch(() => null), - readFollowingCount(sdk!, identityId, { network }).catch(() => null), - ]).then(([followers, following]) => ({ followers, following })) + const follows = forge !== null ? readV2FollowCounts(sdk!, forge, identityId).catch(() => noCounts) : noCounts const [name, repos, counts] = await Promise.all([ resolveDpnsName(sdk!, identityId, network), listReposByOwner(sdk!, identityId, { network }), @@ -82,15 +70,15 @@ export function ProfileContent({ identityId: address }: { identityId: string }): { enabled: isForgeDeployed() && ready && sdk !== null && address !== '' }, ) const identityId = data?.identityId ?? address - // forge-v2 follows live in forge-collab; networks without it use the v1 registry. + // Follows live in forge-collab. const forge = NETWORKS[network].v2 - const canFollow = forge !== null || isRegistryDeployed() + const canFollow = forge !== null const isSelf = identity === identityId const follow = useRelationToggle({ enabled: canFollow && ready && sdk !== null && identity !== null && identityId !== '' && !isSelf, key: `${network}:${identity ?? ''}:${identityId}`, - ...followRelation(sdk!, signer, identity ?? '', forge, identityId, network), + ...followRelation(sdk!, signer, identity ?? '', forge, identityId), }) const toggleFollow = (): void => { diff --git a/forge-web/components/repo-card.tsx b/forge-web/components/repo-card.tsx index dd9ed51eb..1f85386fd 100644 --- a/forge-web/components/repo-card.tsx +++ b/forge-web/components/repo-card.tsx @@ -1,8 +1,8 @@ 'use client' /** - * RepoCard — a discovery/profile row: a forge-v2 repo (with its provable star and issue - * counts when read) or a v1 registry listing (marked, since v1 repos are read-only here). + * RepoCard — a discovery/profile row: a repo with its provable star and issue counts when + * read. */ import Link from 'next/link' @@ -11,16 +11,11 @@ import type { DiscoveredRepo } from '@/lib/view' import { timeAgo } from '@/lib/view' import { repoHref } from '@/hooks/use-query-param' import { Author } from '@/components/author' -import { V1Badge } from '@/components/ui/v1-badge' export function RepoCard({ repo }: { repo: DiscoveredRepo }): JSX.Element { - // Every card pins the repo it shows (v1 its contract, v2 its repo id), so another repo - // answering to the same owner and name can never stand in for it. - const href = repoHref('/repo', { - owner: repo.ownerId, - name: repo.slug, - ...(repo.kind === 'v2' ? { repoId: repo.key } : repo.contractId ? { contractId: repo.contractId } : {}), - }) + // Every card pins the repo it shows by its repo id, so another repo answering to the same + // owner and name can never stand in for it. + const href = repoHref('/repo', { owner: repo.ownerId, name: repo.slug, repoId: repo.key }) return (
@@ -32,9 +27,7 @@ export function RepoCard({ repo }: { repo: DiscoveredRepo }): JSX.Element { {repo.name} - {repo.kind === 'v1' ? ( - - ) : repo.role ? ( + {repo.role ? ( {repo.role} diff --git a/forge-web/components/repo/clone-box.tsx b/forge-web/components/repo/clone-box.tsx index a2fac79d7..8aae318bb 100644 --- a/forge-web/components/repo/clone-box.tsx +++ b/forge-web/components/repo/clone-box.tsx @@ -47,7 +47,7 @@ export function CloneBox({ home, addr }: { home: RepoHome; addr: RepoAddress }):

Push and pull with the git-remote-dash helper.{' '} - {home.repo.kind === 'v1' ? 'Contract' : 'Repo'} + Repo

diff --git a/forge-web/components/repo/issue-content.tsx b/forge-web/components/repo/issue-content.tsx index 841af32b0..306e6bab2 100644 --- a/forge-web/components/repo/issue-content.tsx +++ b/forge-web/components/repo/issue-content.tsx @@ -7,14 +7,13 @@ * * Who may do what (`forge-v2.md` §3): the author closes and reopens their own issue with an * `authorEvent`; maintainers and writers close, reopen and label with an `event`. Consensus - * refuses anyone else on forge-v2, so the controls are offered only to them. On v1 the author's - * or a WRITE/MAINTAIN holder's plain `event` is what the fold honours. + * refuses anyone else, so the controls are offered only to them. */ import { useState } from 'react' import { CheckCircle2, CircleDot, Tag, X } from 'lucide-react' import type { RepoHome, IssueThread } from '@/lib/view' -import { aclName, loadIssueThread, timeAgo } from '@/lib/view' +import { ACL_NAME, loadIssueThread, timeAgo } from '@/lib/view' import { addEvent, createComment, readViewerPermissions, repoContractIds, repoKey, setTargetState } from '@/lib/repo' import type { Holdings } from '@/lib/rules' import { previewCreate, type CostPreview as Cost } from '@/lib/sdk' @@ -54,7 +53,7 @@ export function IssueContent({ home, number }: { home: RepoHome; number: number { enabled: ready && sdk !== null && Number.isFinite(number) }, ) - // v1: WRITE/MAINTAIN token holdings; forge-v2: a current maintainer/writer document. + // A current maintainer/writer document. const holdings = useAsync( () => readViewerPermissions(sdk!, home.repo, identity!, network), [ready, repoKey(home.repo), identity ?? '', network], @@ -80,7 +79,7 @@ export function IssueContent({ home, number }: { home: RepoHome; number: number const canToggle = identity !== null && (isAuthor || isMember) const toggleHint = !canToggle && identity !== null && holdings.settled && holdings.data === null - ? `Couldn't read this repo's ${aclName(home.repo.kind)}, so close/reopen permission is unknown.` + ? `Couldn't read this repo's ${ACL_NAME}, so close/reopen permission is unknown.` : null const target = { id: issue.id, number: issue.number } const commentCost = previewCreate('comment', { body: comment.trim() }) diff --git a/forge-web/components/repo/issues-content.tsx b/forge-web/components/repo/issues-content.tsx index c1a50166a..aa95b90f0 100644 --- a/forge-web/components/repo/issues-content.tsx +++ b/forge-web/components/repo/issues-content.tsx @@ -41,7 +41,7 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres const router = useRouter() const { data, loading, error, reload } = useAsync>( - () => listIssues(sdk!, home.repo, undefined, 100), + () => listIssues(sdk!, home.repo, 100), [ready, repoKey(home.repo)], { enabled: ready && sdk !== null }, ) diff --git a/forge-web/components/repo/pull-content.tsx b/forge-web/components/repo/pull-content.tsx index 824e40872..19995ca47 100644 --- a/forge-web/components/repo/pull-content.tsx +++ b/forge-web/components/repo/pull-content.tsx @@ -6,9 +6,9 @@ * review verdicts), a comment composer, and mark-as-merged / close / reopen. * * **It cannot merge code**, stated here because the name suggests otherwise. "Mark as merged" - * appends a `merge` event carrying the PR head oid. The fold accepts that event only from a - * WRITE or MAINTAIN holder, and only once the head has been a tip of the base ref — which a - * push must do. So the control is shown only to WRITE/MAINTAIN holders ({@link pullActions}) + * appends a `merge` event carrying the PR head oid. Consensus accepts that event only from a + * maintainer or writer, and the fold applies it only once the head has been a tip of the base + * ref — which a push must do. So the control is shown only to members ({@link pullActions}) * and says whether the head is already on the base branch. For a base branch that has moved * on, the merge commit is not the head oid at all; that merge is recorded with the CLI * (`dg pr merge --merge-oid`). @@ -59,9 +59,8 @@ export function PullContent({ home, addr, number }: { home: RepoHome; addr: Repo { enabled: ready && sdk !== null && Number.isFinite(number) }, ) - // What the PR controls are gated on: v1, the viewer's current WRITE/MAINTAIN holdings (the - // token-history cache the fold reads, so usually free); forge-v2, a current maintainer or - // writer document (the membership cache approvals read). + // What the PR controls are gated on: a current maintainer or writer document (the + // membership cache approvals read). const holdings = useAsync( () => readViewerPermissions(sdk!, home.repo, identity!, network), [ready, repoKey(home.repo), identity ?? '', network], @@ -87,7 +86,6 @@ export function PullContent({ home, addr, number }: { home: RepoHome; addr: Repo viewer: identity, // Signed in but not yet read: withhold the controls without a "can't" message. holdings: identity !== null && !holdings.settled ? 'loading' : holdings.data, - model: home.repo.kind, }) const base = pull.baseRefName || 'the base branch' @@ -159,16 +157,15 @@ export function PullContent({ home, addr, number }: { home: RepoHome; addr: Repo
{/* Where the PR's objects actually live. Without this a reviewer has a commit id with no stated home: a PR's head normally sits in the contributor's own repo, and - the patch document's source pointer (v1 sourceContractId, v2 sourceRepoId) is the - only pointer to it. */} + the patch document's source pointer (sourceRepoId) is the only pointer to it. */} {pull.sourceId ? (
- {home.repo.kind === 'v2' && pull.sourceId === home.repo.repoId ? ( + {pull.sourceId === home.repo.repoId ? ( <>Objects live in this repo ) : ( <> - Objects live in {home.repo.kind === 'v1' ? 'contract' : 'repo'}{' '} + Objects live in repo{' '} {pull.sourceId} )} diff --git a/forge-web/components/repo/pull-diff.tsx b/forge-web/components/repo/pull-diff.tsx index 944cc4312..29056968c 100644 --- a/forge-web/components/repo/pull-diff.tsx +++ b/forge-web/components/repo/pull-diff.tsx @@ -4,8 +4,8 @@ * PullDiff — the PR's "Files changed": its head against the merge base with the base branch. * * Two repos are involved. The base history is read from the repo being viewed; the head is - * read from the repo it was pushed to (the patch's source pointer — v1 `sourceContractId`, - * forge-v2 `sourceRepoId` — usually the contributor's own repo or fork). Each is resolved + * read from the repo it was pushed to (the patch's source pointer `sourceRepoId` — usually the + * contributor's own repo or fork). Each is resolved * through the same browse states as any other view — published index, else the in-browser * fallback clone — and reads prefer their own side's * repo while falling back to the other, since objects are content-addressed and verified. @@ -29,38 +29,28 @@ import { Oid } from '@/components/ui/oid' import { Spinner } from '@/components/ui/states' /** - * The PR's source repo when it is not the base repo. v1: the source contract — browse reads - * are keyed by contract alone, and the owner is the PR author, who pushed it. forge-v2: the - * `repo` document `sourceRepoId` names (a fork, in the same forge contracts), read so its - * owner and visibility are real; null while loading or when it cannot be found. + * The PR's source repo when it is not the base repo: the `repo` document `sourceRepoId` names + * (a fork, in the same forge contracts), read so its owner and visibility are real. */ type SourceRepo = | { readonly kind: 'none' } | { readonly kind: 'loading' } | { readonly kind: 'found'; readonly repo: RepoRef } - /** The v2 `sourceRepoId` names no readable repo: the diff reads the base repo alone. */ + /** `sourceRepoId` names no readable repo: the diff reads the base repo alone. */ | { readonly kind: 'missing'; readonly message: string; readonly retry?: () => void } -function useSourceRepo(base: RepoRef, sourceId: string | null, author: string): SourceRepo { +function useSourceRepo(base: RepoRef, sourceId: string | null): SourceRepo { const { sdk, ready } = useSdk() - const v1Source = useMemo( - () => - base.kind === 'v1' && sourceId !== null - ? { kind: 'v1', contractId: sourceId, ownerId: author, name: '' } - : null, - [base.kind, sourceId, author], - ) - const forge = base.kind === 'v2' ? base.forge : null + const { forge } = base const v2Source = useAsync( async () => { - const doc = await readV2RepoById(sdk!, forge!, sourceId!) - return doc === null ? null : v2RefOf(forge!, doc) + const doc = await readV2RepoById(sdk!, forge, sourceId!) + return doc === null ? null : v2RefOf(forge, doc) }, - [ready, forge?.core ?? '', sourceId ?? ''], - { enabled: ready && sdk !== null && forge !== null && sourceId !== null }, + [ready, forge.core, sourceId ?? ''], + { enabled: ready && sdk !== null && sourceId !== null }, ) if (sourceId === null) return { kind: 'none' } - if (base.kind === 'v1') return v1Source === null ? { kind: 'none' } : { kind: 'found', repo: v1Source } if (v2Source.error) { return { kind: 'missing', message: `The source repo could not be read (${v2Source.error}).`, retry: v2Source.reload } } @@ -180,12 +170,12 @@ export function PullDiff({ pull, home }: { pull: PullView; home: RepoHome }): JS const baseKey = repoKey(baseRepo) const sourceKey = pull.sourceId || baseKey const crossRepo = sourceKey !== baseKey - const source = useSourceRepo(baseRepo, crossRepo ? sourceKey : null, pull.author) + const source = useSourceRepo(baseRepo, crossRepo ? sourceKey : null) const baseState = useBrowseReader(baseRepo) const sourceState = useBrowseReader(source.kind === 'found' ? source.repo : null) - // A source that does not resolve falls back to the base repo's reader (as a v1 PR does when - // its source is unreadable), with a visible note, instead of waiting forever. + // A source that does not resolve falls back to the base repo's reader, with a visible note, + // instead of waiting forever. const sourceMissing = source.kind === 'missing' const headState = crossRepo && !sourceMissing ? sourceState : baseState diff --git a/forge-web/components/repo/pulls-content.tsx b/forge-web/components/repo/pulls-content.tsx index 5671111bf..47e7db713 100644 --- a/forge-web/components/repo/pulls-content.tsx +++ b/forge-web/components/repo/pulls-content.tsx @@ -42,7 +42,7 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress const { sdk, ready } = useSdk(repoContractIds(home.repo)) const [filter, setFilter] = useState('open') const { data, loading, error, reload } = useAsync>( - () => listPulls(sdk!, home.repo, undefined, 100), + () => listPulls(sdk!, home.repo, 100), [ready, repoKey(home.repo)], { enabled: ready && sdk !== null }, ) diff --git a/forge-web/components/repo/repo-header.tsx b/forge-web/components/repo/repo-header.tsx index b82ba41de..22600392e 100644 --- a/forge-web/components/repo/repo-header.tsx +++ b/forge-web/components/repo/repo-header.tsx @@ -13,7 +13,6 @@ import type { RepoHome } from '@/lib/view' import { BackendBadge } from '@/components/ui/backend-badge' import { Author } from '@/components/author' import { StarButton } from '@/components/repo/star-button' -import { V1Badge } from '@/components/ui/v1-badge' import { repoHref, useParam, type RepoAddress } from '@/hooks/use-query-param' import { cn } from '@/lib/utils' @@ -38,16 +37,15 @@ export function RepoHeader({ home, addr }: { home: RepoHome; addr: RepoAddress } {home.repo.name || addr.name} - {home.repo.kind === 'v2' && home.repo.visibility === 'private' ? ( + {home.repo.visibility === 'private' ? ( private ) : null} - {home.repo.kind === 'v1' ? : null}
- +
diff --git a/forge-web/components/repo/repo-rail.tsx b/forge-web/components/repo/repo-rail.tsx index 049f11d22..8f0b763d8 100644 --- a/forge-web/components/repo/repo-rail.tsx +++ b/forge-web/components/repo/repo-rail.tsx @@ -54,7 +54,6 @@ export function RepoRail({ tip: selected.ref?.state ?? 'missing', checks, configuredBackend: home.backend.label, - model: home.repo.kind, }) return ( diff --git a/forge-web/components/repo/repo-scaffold.tsx b/forge-web/components/repo/repo-scaffold.tsx index 98977670e..eccc82dfe 100644 --- a/forge-web/components/repo/repo-scaffold.tsx +++ b/forge-web/components/repo/repo-scaffold.tsx @@ -88,7 +88,7 @@ export function RepoScaffold({ } /> diff --git a/forge-web/components/repo/settings-content.tsx b/forge-web/components/repo/settings-content.tsx index e6f776c67..125e134ec 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, ShieldPlus, Snowflake, UserCog } from 'lucide-react' +import { Fingerprint, 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 { V2RepoRef } from '@/lib/repo' +import { grantMember, invalidateMembers, readMembershipsCached, revokeMember } from '@/lib/repo' import type { Membership, Role as V2Role } from '@/lib/rules/v2' -import { ACTIVE_NETWORK } from '@/lib/constants' 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' @@ -42,179 +33,12 @@ import { Field, Input } from '@/components/ui/input' import { ConfirmDialog } from '@/components/confirm-dialog' import { ErrorState, LoadingBlock } from '@/components/ui/states' -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. */ @@ -440,10 +264,6 @@ function DetailRow({ label, children }: { label: string; children: React.ReactNo ) } -function NotSet(): JSX.Element { - return — -} - function RoleTag({ role }: { role: string }): JSX.Element { return ( diff --git a/forge-web/components/repo/star-button.tsx b/forge-web/components/repo/star-button.tsx index cd88515a5..950cde3f9 100644 --- a/forge-web/components/repo/star-button.tsx +++ b/forge-web/components/repo/star-button.tsx @@ -1,9 +1,8 @@ 'use client' /** - * Star button — toggles the viewer's star on a repo: a forge-v2 `star` (indexOnly; unstar is - * an index-only delete that returns its storage) or a v1 registry `star` on the listing. The - * starred/unstarred state is read from the viewer's own star before the button offers an + * Star button — toggles the viewer's star on a repo: a forge-collab `star` (indexOnly; unstar + * is an index-only delete that returns its storage). The starred/unstarred state is read from the viewer's own star before the button offers an * action, and a failed read or write is shown rather than swallowed. */ @@ -19,24 +18,20 @@ import { creditsAsDash } from '@/lib/view/format' export function StarButton({ repo, - listingId, count, }: { repo: RepoRef - /** v1: the registry listing (null = no listing, cannot be starred). */ - listingId: string | null /** The public star count; `null` when it could not be read. */ count: number | null }): JSX.Element { const { sdk, ready, network } = useSdk() const { identity, signer } = useAuth() const guard = useWriteGuard() - const target = repo.kind === 'v2' ? repo.repoId : listingId const star = useRelationToggle({ - enabled: ready && sdk !== null && identity !== null && target !== null, - key: `${network}:${identity ?? ''}:${target ?? ''}`, - ...starRelation(sdk!, signer, identity ?? '', repo, listingId, network), + enabled: ready && sdk !== null && identity !== null, + key: `${network}:${identity ?? ''}:${repo.repoId}`, + ...starRelation(sdk!, signer, identity ?? '', repo), }) const starred = star.on === true @@ -49,7 +44,7 @@ export function StarButton({ const signedIn = identity !== null && signer !== null // Signed in but the current state is not known yet (or could not be read): no action to offer. - const unknown = signedIn && target !== null && star.on === null + const unknown = signedIn && star.on === null return ( @@ -63,14 +58,8 @@ export function StarButton({ size="sm" onClick={onClick} loading={star.busy || (unknown && star.error === null)} - disabled={!target || (unknown && star.error !== null) || (!starred && guard.disabledReason !== null)} - title={ - !target - ? 'This repo has no registry listing, so it cannot be starred.' - : starred - ? 'Unstar (returns the star’s storage)' - : `Star · ~${creditsAsDash(cost.credits)} DASH` - } + disabled={(unknown && star.error !== null) || (!starred && guard.disabledReason !== null)} + title={starred ? 'Unstar (returns the star’s storage)' : `Star · ~${creditsAsDash(cost.credits)} DASH`} > {starred ? 'Starred' : 'Star'} diff --git a/forge-web/components/repo/stargazers-content.tsx b/forge-web/components/repo/stargazers-content.tsx index da6854f1a..835ca5fe0 100644 --- a/forge-web/components/repo/stargazers-content.tsx +++ b/forge-web/components/repo/stargazers-content.tsx @@ -1,14 +1,13 @@ 'use client' /** - * StargazersContent — who starred this repo: v1 registry `star` docs (newest first), or - * forge-v2 forge-collab `star` docs (index order; `star` is indexOnly and carries no time). + * StargazersContent — who starred this repo: its forge-collab `star` docs (index order; `star` + * is indexOnly and carries no time). */ import { Star } from 'lucide-react' import type { RepoHome } from '@/lib/view' -import { timeAgo } from '@/lib/view' -import { readStargazers, readV2Stargazers, type Stargazer } from '@/lib/repo' +import { readV2Stargazers } from '@/lib/repo' import { useSdk } from '@/hooks/use-sdk' import { useAsync } from '@/hooks/use-async' import { Author } from '@/components/author' @@ -16,21 +15,14 @@ import { EmptyState, ErrorState, LoadingBlock } from '@/components/ui/states' export function StargazersContent({ home }: { home: RepoHome }): JSX.Element { const { sdk, ready, network } = useSdk() - const listingId = home.listingId - const v2 = home.repo.kind === 'v2' ? home.repo : null + const { repo } = home - const { data, loading, error, reload } = useAsync( - async () => - v2 !== null - ? (await readV2Stargazers(sdk!, v2.forge, v2.repoId)).map((identity) => ({ identity, starredAt: 0 })) - : readStargazers(sdk!, listingId!, { network }), - [ready, listingId, v2?.repoId ?? '', network], - { enabled: ready && sdk !== null && (listingId !== null || v2 !== null) }, + const { data, loading, error, reload } = useAsync( + () => readV2Stargazers(sdk!, repo.forge, repo.repoId), + [ready, repo.repoId, network], + { enabled: ready && sdk !== null }, ) - if (!listingId && v2 === null) { - return - } if (loading) return if (error) return if (!data) return @@ -40,15 +32,14 @@ export function StargazersContent({ home }: { home: RepoHome }): JSX.Element { return (
- {data.map((s) => ( + {data.map((identity) => (
- +
- {s.starredAt > 0 ? starred {timeAgo(s.starredAt)} : null}
))}
diff --git a/forge-web/components/repo/timeline.tsx b/forge-web/components/repo/timeline.tsx index fe4cff7ee..e42abd02e 100644 --- a/forge-web/components/repo/timeline.tsx +++ b/forge-web/components/repo/timeline.tsx @@ -4,8 +4,8 @@ * Timeline — the interleaved comment + event + review stream of an issue/PR. Comments render * the author pill + markdown body; events render a compact, git-native one-liner ("closed * this", "added the bug label"); reviews render their verdict and the commit they were made - * against. Spam events from non-holders are already folded out of state, but appear here as - * the audit trail they are. + * against. An `authorEvent` the fold ignores (not a close/reopen by the author) still appears + * here as the audit trail it is. */ import { Check, GitMerge, Lock, LockOpen, MessageSquare, Tag, UserPlus, X } from 'lucide-react' diff --git a/forge-web/components/ui/cost-preview.tsx b/forge-web/components/ui/cost-preview.tsx index fc72f4d20..4aec5e004 100644 --- a/forge-web/components/ui/cost-preview.tsx +++ b/forge-web/components/ui/cost-preview.tsx @@ -1,15 +1,13 @@ /** * Cost preview — signature element (style guide §A.2, `ux-dx-spec.md` §4 rule 1). Every - * signing button shows its price before the click: DASH primary, USD secondary, plus any v1 - * WRITE/MAINTAIN token spend. A delete that returns storage shows the refund in green. + * signing button shows its price before the click: DASH primary, USD secondary. A delete that + * returns storage shows the refund in green. */ import type { CostPreview as Cost } from '@/lib/sdk' import { dashToUsd, formatDash } from '@/lib/view' import { cn } from '@/lib/utils' -const TOKEN_LABEL: Readonly> = { 0: 'WRITE', 1: 'MAINTAIN' } - export function CostPreview({ cost, refund = false, @@ -22,8 +20,6 @@ export function CostPreview({ }): JSX.Element { const isRefund = refund || cost.credits < 0 const dash = Math.abs(cost.dash) - const token = - cost.tokenAmount > 0 && cost.tokenPosition !== undefined ? TOKEN_LABEL[cost.tokenPosition] : undefined return (
≈ {dashToUsd(dash)} - {token ? ( - - + {cost.tokenAmount} {token} token - - ) : null}
) } diff --git a/forge-web/components/ui/network-badge.tsx b/forge-web/components/ui/network-badge.tsx index a6a7906aa..bb30ef843 100644 --- a/forge-web/components/ui/network-badge.tsx +++ b/forge-web/components/ui/network-badge.tsx @@ -2,9 +2,10 @@ * Network badge + "not deployed" state — both driven by the build's network config. * * - NetworkBadge: which network this build reads and writes. Shown in the header whenever - * the network is not mainnet, in the caution color when it is a devnet (resettable, - * test-only funds) and when no Dash Forge registry exists on it. - * - NotDeployedState: the one honest state for a network with no registry — never a + * the network is not mainnet: a devnet as `devnet · ` in the caution color + * (resettable, test funds only), and in the caution color too when forge-v2 is not + * deployed on the network. + * - NotDeployedState: the one honest state for a network without forge-v2 — never a * silent fallback to another network's contracts. */ @@ -12,19 +13,16 @@ import { AlertTriangle } from 'lucide-react' import { ACTIVE_NETWORK, NotDeployedError, type NetworkConfig } from '@/lib/constants' import { cn } from '@/lib/utils' -/** Whether the active network has a v1 Dash Forge registry to read from. */ -export function isRegistryDeployed(config: NetworkConfig = ACTIVE_NETWORK): boolean { - return config.registryContractId !== null -} - -/** Whether the active network has the forge-v2 contracts (protocol 14). */ -export function isV2Deployed(config: NetworkConfig = ACTIVE_NETWORK): boolean { +/** Whether Dash Forge (the forge-v2 contracts) is deployed on the network. */ +export function isForgeDeployed(config: NetworkConfig = ACTIVE_NETWORK): boolean { return config.v2 !== null } -/** Whether there is anything Dash Forge to read here: a v1 registry, forge-v2, or both. */ -export function isForgeDeployed(config: NetworkConfig = ACTIVE_NETWORK): boolean { - return isRegistryDeployed(config) || isV2Deployed(config) +/** The badge label: `devnet · moutai`, `testnet`, `mainnet`. */ +export function networkLabel(config: NetworkConfig = ACTIVE_NETWORK): string { + return config.network === 'devnet' && config.devnetName !== null + ? `devnet · ${config.devnetName}` + : config.network } export function NetworkBadge({ @@ -38,48 +36,30 @@ export function NetworkBadge({ className?: string }): JSX.Element | null { if (config.network === 'mainnet' && !always) return null - const warn = config.network === 'devnet' || !isForgeDeployed(config) - const parts = [ - config.v2 !== null ? `forge-v2 ${config.v2.core} / ${config.v2.collab}` : 'forge-v2 not deployed', - isRegistryDeployed(config) - ? `v1 registry ${config.registryContractId} (${config.registrySource})` - : 'no v1 registry', - ] - const title = isForgeDeployed(config) - ? `Connected to ${config.key}. ${parts.join('; ')}.` - : `Connected to ${config.key}. Dash Forge is not deployed on this network.` + const deployed = isForgeDeployed(config) + const devnet = config.network === 'devnet' + const where = devnet + ? `Connected to devnet ${config.devnetName ?? ''}, a development network that can be reset at any time; its funds are test funds only.` + : `Connected to ${config.key}.` + const title = deployed + ? `${where} forge-core ${config.v2?.core}, forge-collab ${config.v2?.collab}.` + : `${where} Dash Forge is not deployed on this network.` return ( - {config.key} - {isForgeDeployed(config) ? null : · not deployed} + {networkLabel(config)} + {deployed ? null : · not deployed} ) } -/** - * The honest note a forge-v2 surface shows on a network without the v2 contracts (testnet - * until protocol 14): v1 repos still read, v2 ones do not exist here yet. - */ -export function V2NotDeployedNote({ config = ACTIVE_NETWORK }: { config?: NetworkConfig }): JSX.Element { - return ( -

- - - forge-v2 is not deployed on {config.key} yet (it needs Platform protocol 14). The repos - below are v1 repos: readable here, with their own contracts. - -

- ) -} - /** Full-width state for a view that needs Dash Forge on a network without it. */ export function NotDeployedState({ config = ACTIVE_NETWORK }: { config?: NetworkConfig }): JSX.Element { return ( @@ -91,7 +71,7 @@ export function NotDeployedState({ config = ACTIVE_NETWORK }: { config?: Network

- Dash Forge is not deployed on {config.key} yet + Dash Forge is not deployed on {config.key}

{new NotDeployedError(config.key).message}. Nothing here is read from another network. diff --git a/forge-web/components/ui/trust-panel.tsx b/forge-web/components/ui/trust-panel.tsx index f7122d9f2..bc1cbcec6 100644 --- a/forge-web/components/ui/trust-panel.tsx +++ b/forge-web/components/ui/trust-panel.tsx @@ -66,7 +66,7 @@ export function TrustPanel({ tipOid, }: { report: TrustReport - /** The repo the proofs were read for: the v1 repo contract id or the forge-v2 repo id. */ + /** The repo the proofs were read for: its repo id. */ serial?: string /** The commit the attested ref points at. */ tipOid?: string diff --git a/forge-web/components/ui/v1-badge.tsx b/forge-web/components/ui/v1-badge.tsx deleted file mode 100644 index d94b4c9b9..000000000 --- a/forge-web/components/ui/v1-badge.tsx +++ /dev/null @@ -1,11 +0,0 @@ -/** The mark a v1 repo carries: its own contract, readable here, while new repos are forge-v2. */ -export function V1Badge({ className = '' }: { className?: string }): JSX.Element { - return ( - - v1 - - ) -} diff --git a/forge-web/e2e/a11y.spec.ts b/forge-web/e2e/a11y.spec.ts index 6eff2c84c..76754ef88 100644 --- a/forge-web/e2e/a11y.spec.ts +++ b/forge-web/e2e/a11y.spec.ts @@ -1,36 +1,35 @@ -import { test, expect } from '@playwright/test' -import { ON_TESTNET, repoUrl, runAxe, waitForRepoResolved, M1 } from './helpers' - -// The v1 read fixture lives on testnet; a devnet build runs v2-reads.spec.ts instead. -test.skip(!ON_TESTNET, 'testnet fixture; this build targets a devnet') +import { test, expect, type Locator, type Page } from '@playwright/test' +import { expectLanded, repoUrl, runAxe } from './helpers' /** - * Scenario 6 — Accessibility smoke via axe-core. + * Accessibility smoke via axe-core, on the forge-v2 read fixture (e2e/helpers.ts `DEMO`). * - * Target: 0 serious/critical violations on the landing + repo home. We report all serious & - * critical findings; moderate/minor are logged but not gated (v1 acceptance is "0 serious"). + * Target: 0 serious/critical violations on every page below, each checked once its real + * content has landed (not the loading shell). Moderate/minor findings are logged, not gated. */ -test('6a. landing has no serious/critical axe violations', async ({ page }) => { - await page.goto('/', { waitUntil: 'domcontentloaded' }) - await expect(page.getByRole('heading', { name: /no server to trust/i })).toBeVisible() - await page.waitForTimeout(3000) - const serious = await runAxe(page, 'landing') - expect( - serious, - 'serious/critical a11y violations on landing:\n' + - serious.map((v) => `${v.id}: ${v.help}`).join('\n'), - ).toEqual([]) -}) +const PAGES: [label: string, href: string, ready: (page: Page) => Locator][] = [ + [ + 'landing', + '/', + (page) => page.locator('section').filter({ hasText: 'Recent repos' }).first().locator('a[href*="/repo"]').first(), + ], + ['repo-home', repoUrl(), (page) => page.getByRole('link', { name: 'README.md' }).first()], + ['blob', repoUrl('blob', '&path=src/main.rs'), (page) => page.getByText('reads are proof-checked').first()], + ['issues', repoUrl('issues'), (page) => page.getByText('README should explain the event split')], + ['issue', repoUrl('issue', '&number=3'), (page) => page.getByText('Done in docs/rules.md; closing.')], + ['pull', repoUrl('pull', '&number=1'), (page) => page.getByRole('region', { name: 'Approvals' })], + ['settings', repoUrl('settings'), (page) => page.getByRole('heading', { name: 'Members' })], +] -test('6b. repo home has no serious/critical axe violations', async ({ page }) => { - await page.goto(repoUrl(), { waitUntil: 'domcontentloaded' }) - await waitForRepoResolved(page) - await page.getByText(M1.name, { exact: false }).first().waitFor({ timeout: 30_000 }).catch(() => {}) - const serious = await runAxe(page, 'repo-home') - expect( - serious, - 'serious/critical a11y violations on repo home:\n' + - serious.map((v) => `${v.id}: ${v.help}`).join('\n'), - ).toEqual([]) -}) +for (const [label, href, ready] of PAGES) { + test(`a11y: ${label} has no serious/critical axe violations`, async ({ page }) => { + await page.goto(href, { waitUntil: 'domcontentloaded' }) + await expectLanded(page, ready(page)) + const serious = await runAxe(page, label) + expect( + serious, + `serious/critical a11y violations on ${label}:\n` + serious.map((v) => `${v.id}: ${v.help}`).join('\n'), + ).toEqual([]) + }) +} diff --git a/forge-web/e2e/auth-write.spec.ts b/forge-web/e2e/auth-write.spec.ts deleted file mode 100644 index 5fb3dc8d3..000000000 --- a/forge-web/e2e/auth-write.spec.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { test, expect } from '@playwright/test' -import { existsSync } from 'node:fs' -import { homedir } from 'node:os' -import { join } from 'node:path' -import { repoUrl, waitForRepoResolved, shot, WRITE_FIXTURE } from './helpers' - -/** - * OPTIONAL auth / write scenario (lower priority — read paths are the gate). - * - * Gated behind E2E_AUTH=1 so the default CI run stays key-free and hermetic. When enabled it - * loads the DEPLOYER bridge identity (which owns the write fixture) from the local, gitignored - * ~/.config/dash-forge/test-identities/, drives the login modal's identity-file upload via - * setInputFiles (keys never leave this machine), and verifies the session is established. - * - * With E2E_WRITE=1 it goes further and creates a cheap issue on the WRITE fixture (helpers.ts - * WRITE_FIXTURE, never the read fixture the read specs assert on) — a real testnet write. - * Anything flaky here self-skips rather than failing the suite. - */ - -const IDENTITY_PATH = join( - homedir(), - '.config/dash-forge/test-identities/DEPLOYER.identity.json', -) -const AUTH_ENABLED = process.env.E2E_AUTH === '1' -const WRITE_ENABLED = process.env.E2E_WRITE === '1' - -test.describe('auth + write (opt-in via E2E_AUTH=1)', () => { - test.skip(!AUTH_ENABLED, 'set E2E_AUTH=1 to run the local-key login/write scenario') - test.skip(!existsSync(IDENTITY_PATH), `DEPLOYER identity not found at ${IDENTITY_PATH}`) - - test('login via identity file, then optionally create an issue on the write fixture', async ({ page }) => { - await page.goto(repoUrl('issues', WRITE_FIXTURE), { waitUntil: 'domcontentloaded' }) - await waitForRepoResolved(page) - - // Open the login modal from the header sign-in affordance. - await page.getByRole('button', { name: /sign in/i }).first().click() - await expect(page.getByText(/Sign in to Dash Forge/i)).toBeVisible() - // Testnet has no Forge contract group, so the only tile is the v1 identity-file import. - await page.getByTestId('tile-import').click() - - // Upload the identity file straight into the (visually hidden) file input. - await page.setInputFiles('input[type="file"]', IDENTITY_PATH) - - // Login runs an SDK identity fetch against testnet; the modal closes and the header - // shows the account menu with a balance on success. - await expect(page.getByText(/Sign in to Dash Forge/i)).toBeHidden({ timeout: 40_000 }) - await expect(page.getByRole('button', { name: /sign in/i })).toHaveCount(0, { - timeout: 10_000, - }) - await shot(page, '08-logged-in') - - if (!WRITE_ENABLED) { - test.info().annotations.push({ - type: 'note', - description: 'E2E_WRITE!=1 — verified login only; skipped the paid issue-create write.', - }) - return - } - - // Create a real (cheap) issue on the write fixture. - const marker = `e2e-web smoke ${new Date().toISOString()}` - await page.getByRole('button', { name: /new issue/i }).first().click() - await page.getByLabel(/title/i).fill(marker) - const body = page.getByLabel(/body|description|comment/i).first() - if (await body.count()) await body.fill('Automated Playwright e2e write scenario.') - await page.getByRole('button', { name: /submit issue/i }).click() - - // The new issue appears in the list within the poll interval. - await expect(page.getByText(marker)).toBeVisible({ timeout: 60_000 }) - await shot(page, '09-issue-created') - - expect(WRITE_FIXTURE.name).toBeTruthy() - }) -}) diff --git a/forge-web/e2e/fallback-browse.spec.ts b/forge-web/e2e/fallback-browse.spec.ts index 9c21f8bda..c210ce6be 100644 --- a/forge-web/e2e/fallback-browse.spec.ts +++ b/forge-web/e2e/fallback-browse.spec.ts @@ -1,63 +1,129 @@ -import { test, expect } from '@playwright/test' -import { collectPageErrors, ON_TESTNET, readErrorBanner, repoUrl, shot, waitForRepoResolved } from './helpers' - -// The v1 read fixture lives on testnet; a devnet build runs v2-reads.spec.ts instead. -test.skip(!ON_TESTNET, 'testnet fixture; this build targets a devnet') +import { test, expect, type Page } from '@playwright/test' +import { + collectPageErrors, + DEMO, + deployment, + expectLanded, + nodeSdk, + repoUrl, + shot, + waitForRepoResolved, +} from './helpers' /** - * In-browser fallback clone (no objectLocator). The M1 fixture repo has never published a - * browse plane, so the repo home must engage the fallback: download the live kind-0 packs - * from platform `chunk` documents, index them client-side, and serve the root tree/README - * from the locally built index. Small repos (≤ 2 MB of live packs) auto-load; larger ones - * surface an explicit "Load repo in browser (~X MB)" action — the spec handles both. - * In-app navigation and a hard reload afterwards must reuse the browser-cached context - * (no second prompt or pack download). + * In-browser fallback clone, on the forge-v2 read fixture (e2e/helpers.ts `DEMO`). + * + * The fixture publishes an objectLocator, so the fallback is forced: every `chunk` query for a + * locator artifact (kind 1) is answered with a gRPC NOT_FOUND, so the locator cannot load. + * `loadBrowseContext` treats an index that will not load as `index-behind` and routes to the + * fallback. The fallback downloads the live kind-0 packs from their Platform `chunk` documents + * (still served), indexes them client-side, and serves the root tree / README from the index it + * built. The fixture's packs are far below 2 MB, so the clone starts on its own; the spec + * still handles the explicit "Load repo in browser (~X MB)" action. In-app navigation and a hard + * reload afterwards must reuse the browser-cached clone (no second prompt or pack download). + * + * Reads travel as gRPC-web POSTs to DAPI; a `getDocuments` request body carries the queried + * `packHash` operand as base64, which is what the route below matches on. */ -test.describe('in-browser fallback clone (no objectLocator)', () => { +/** The fixture's locator packHashes, base64 as they appear in a `chunk` query's body. */ +async function locatorPackHashes(): Promise { + const sdk = await nodeSdk() + const core = deployment().v2.forgeCore.contractId + const repos = await sdk.documents.query({ + dataContractId: core, + documentTypeName: 'repo', + where: [ + ['$ownerId', '==', DEMO.owner], + ['name', '==', DEMO.name], + ], + limit: 1, + }) + const repo = [...repos.values()][0] + if (!repo) throw new Error(`fixture repo ${DEMO.name} not found: seed it with forge-contracts/scripts/seed-v2-fixture.mjs`) + const manifests = await sdk.documents.query({ + dataContractId: core, + documentTypeName: 'packManifest', + where: [['repoId', '==', repo.id.toBase58()]], + orderBy: [['$createdAt', 'desc']], + limit: 100, + }) + const hashes = [...manifests.values()] + .map((d) => d.toJSON() as { kind: number; packHash: string }) + .filter((m) => m.kind === 1) + .map((m) => m.packHash) + if (hashes.length === 0) throw new Error(`fixture repo ${DEMO.name} has no objectLocator to block`) + return hashes +} + +/** Fail every DAPI `chunk` query for one of `hashes` with NOT_FOUND; count the blocks. */ +async function blockLocatorChunks(page: Page, hashes: readonly string[]): Promise<{ blocked: number }> { + const needles = hashes.map((h) => Buffer.from(h)) + const stats = { blocked: 0 } + await page.route( + (url) => url.pathname.endsWith('/org.dash.platform.dapi.v0.Platform/getDocuments'), + async (route) => { + const body = route.request().postDataBuffer() + if (body === null || !needles.some((n) => body.includes(n))) return route.continue() + stats.blocked++ + return route.fulfill({ + status: 200, + body: '', + headers: { + 'content-type': 'application/grpc-web+proto', + 'grpc-status': '5', + 'grpc-message': 'blocked by fallback-browse.spec', + 'access-control-allow-origin': (await route.request().headerValue('origin')) ?? '*', + 'access-control-expose-headers': 'grpc-status,grpc-message', + }, + }) + }, + ) + return stats +} + +test.describe('in-browser fallback clone (locator unavailable)', () => { test('repo home clones + indexes in-browser, then navigation and reload reuse the cache', async ({ page, }) => { const { errors } = collectPageErrors(page) + const stats = await blockLocatorChunks(page, await locatorPackHashes()) await page.goto(repoUrl(), { waitUntil: 'domcontentloaded' }) await waitForRepoResolved(page) // The fallback must engage: auto-load progress, the explicit load action, or (already - // done) the local-index notice. The app's read-error state is a meaningful failure. + // done) the local-copy notice. The app's read-error state is a meaningful failure. const loadButton = page.getByRole('button', { name: /load repo in browser/i }) const engaged = page .getByText(/preparing in-browser clone|downloading packs|indexing objects|copy loaded into your browser/i) .first() - await expect(loadButton.or(engaged).or(readErrorBanner(page))).toBeVisible({ timeout: 45_000 }) - if (await readErrorBanner(page).isVisible()) { - throw new Error( - 'Repo home is in the read-error state before the fallback could engage — ' + - 'manifest/chunk reads are failing against testnet.', - ) - } + await expectLanded(page, loadButton.or(engaged)) if (await loadButton.isVisible().catch(() => false)) { await loadButton.click() // > 2 MB of live packs: the explicit opt-in path } - // The fallback completes: quiet notice + a real root tree (file links) rendered from - // the locally built index. + // The fallback completes: quiet notice + the real root tree rendered from the index it built. await expect(page.getByText(/copy loaded into your browser/i)).toBeVisible({ timeout: 60_000 }) - const fileLink = page.locator('a[href*="/repo/blob"], a[href*="/repo/tree"]').first() - await expect(fileLink).toBeVisible({ timeout: 30_000 }) - await shot(page, '08-fallback-home') + const readme = page.getByRole('link', { name: 'README.md', exact: true }).first() + await expect(readme).toBeVisible({ timeout: 30_000 }) + expect(stats.blocked, 'the locator was never requested, so nothing forced the fallback').toBeGreaterThan(0) + await shot(page, 'fallback-01-home') // In-app navigation (SPA route change) reuses the module-level session cache: content // renders again with no re-download prompt. - await fileLink.click() - await expect(page.getByText(/copy loaded into your browser/i)).toBeVisible({ timeout: 30_000 }) + await page.getByRole('link', { name: 'src', exact: true }).first().click() + await page.getByRole('link', { name: 'main.rs', exact: true }).first().click() + await expect(page.getByText('reads are proof-checked').first()).toBeVisible({ timeout: 30_000 }) + await expect(page.getByText(/copy loaded into your browser/i)).toBeVisible() await expect(loadButton).toHaveCount(0) - await shot(page, '09-fallback-blob') + await shot(page, 'fallback-02-blob') // A full document reload clears module state. The persisted verified packs + locator must // restore the reader without returning to the download opt-in state. await page.reload({ waitUntil: 'domcontentloaded' }) await waitForRepoResolved(page) await expect(page.getByText(/copy loaded into your browser/i)).toBeVisible({ timeout: 30_000 }) + await expect(page.getByText('reads are proof-checked').first()).toBeVisible({ timeout: 30_000 }) await expect(loadButton).toHaveCount(0) expect(errors, `uncaught page errors:\n${errors.join('\n')}`).toEqual([]) diff --git a/forge-web/e2e/helpers.ts b/forge-web/e2e/helpers.ts index 0176d324a..3f6aa043f 100644 --- a/forge-web/e2e/helpers.ts +++ b/forge-web/e2e/helpers.ts @@ -1,45 +1,66 @@ import AxeBuilder from '@axe-core/playwright' -import { expect, type Browser, type Page, type ConsoleMessage } from '@playwright/test' +import { expect, type Browser, type Locator, type Page, type ConsoleMessage } from '@playwright/test' import { homedir } from 'node:os' -import { existsSync, mkdirSync } from 'node:fs' -import { join } from 'node:path' +import { existsSync, mkdirSync, readFileSync } from 'node:fs' +import { join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' /** - * Real testnet fixture: the nightly READ fixture, written only by - * `e2e/cli/seed-read-fixture.sh` (reserved in e2e/README.md). `main` holds one deterministic - * commit (README.md, src/, lib/) stored on Platform with no browse index, so the fallback - * clone is what the browse specs exercise. Never point these specs at a repo another suite - * writes: the storage e2e once left packs on a laptop's MinIO in the shared CLI repo, and - * every browse spec failed on them. Override with E2E_FIXTURE_OWNER / E2E_FIXTURE_NAME. + * The devnet the build under test reads (`E2E_DEVNET`, default moutai). Must match the + * default in playwright.config.ts, which builds the app for it. */ -export const M1 = { - owner: process.env['E2E_FIXTURE_OWNER'] ?? '8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB', - // The seeder's override (NIGHTLY_FIXTURE_REPO) applies here too, so a renamed fixture is - // seeded and read as the same repo. - name: process.env['E2E_FIXTURE_NAME'] ?? process.env['NIGHTLY_FIXTURE_REPO'] ?? 'm1-5124', -} as const - -/** The devnet this run's build targets (`E2E_DEVNET`), or '' for the default testnet build. */ -export const E2E_DEVNET = process.env['E2E_DEVNET'] ?? '' +export const E2E_DEVNET = process.env['E2E_DEVNET'] || 'moutai' -/** Skip a testnet-fixture spec on a devnet build (and vice versa). */ -export const ON_TESTNET = E2E_DEVNET === '' +/** The MAINTAINER test identity: a maintainer of {@link DEMO} and the owner of {@link EMPTY}. */ +export const MAINTAINER = 'GKBTXUdo3MpRYAUqgZvTZGTav9mXGqfJfR5822K2tp79' /** - * The repo the opt-in WRITE spec (auth-write, E2E_WRITE=1) creates issues on — never the read - * fixture above, which only its seeder may write (its issues page is asserted on). This is - * the CLI suite's DEPLOYER-owned repo, which test runs already write to. Override with - * E2E_WRITE_FIXTURE_NAME. See e2e/README.md. + * The forge-v2 READ fixture, written only by `forge-contracts/scripts/seed-v2-fixture.mjs`: + * repo `forge-v2-demo` owned by OWNER (maintainers OWNER + MAINTAINER, writer COLLAB); main = + * README.md, src/main.rs, lib/util.ts, docs/rules.md; branch feature/greeting; tag v0.1.0; a + * published objectLocator; issue #1 open + labelled `question`, #2 closed by its author, #3 + * closed + labelled `docs`; PR #1 open with MAINTAINER's approval, PR #2 merged; one star. + * Only its seeder writes it (v2-writes w6 adds OWNER's approval to PR #1, nothing else). + * Override with E2E_V2_OWNER / E2E_V2_NAME. */ -export const WRITE_FIXTURE = { - owner: M1.owner, - name: process.env['E2E_WRITE_FIXTURE_NAME'] ?? 'm1-75299', +export const DEMO = { + owner: process.env['E2E_V2_OWNER'] ?? '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD', + name: process.env['E2E_V2_NAME'] ?? 'forge-v2-demo', } as const -export function repoUrl(path = '', repo: { owner: string; name: string } = M1): string { - const q = `owner=${repo.owner}&name=${repo.name}` - if (path === '') return `/repo/?${q}` - return `/repo/${path}/?${q}` +/** The fixture's `forge-v2-empty`: a repo with nothing pushed (the empty-repo state). */ +export const EMPTY = { owner: MAINTAINER, name: 'forge-v2-empty' } as const + +/** A repo route: `repoUrl('issue', '&number=2')` → `/repo/issue/?owner=…&name=…&number=2`. */ +export function repoUrl( + path = '', + extra = '', + repo: { readonly owner: string; readonly name: string } = DEMO, +): string { + const q = `owner=${repo.owner}&name=${repo.name}${extra}` + return path === '' ? `/repo/?${q}` : `/repo/${path}/?${q}` +} + +const ROOT = resolve(__dirname, '../..') + +/** The deployment record the build under test is made from (DAPI addresses, contract ids). */ +export function deployment(): { + dapiAddresses: string[] + v2: { forgeCore: { contractId: string; contractGroupId: string }; forgeCollab: { contractId: string } } +} { + return JSON.parse(readFileSync(join(ROOT, `forge-contracts/deployments/devnet-${E2E_DEVNET}.json`), 'utf8')) +} + +/** + * A connected evo-sdk in Node, for reading Platform independently of the app (`any`: the + * module is imported by path at runtime, outside the app's typed import graph). + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export async function nodeSdk(): Promise { + const evo = await import(pathToFileURL(join(ROOT, 'forge-web/node_modules/@dashevo/evo-sdk/dist/evo-sdk.module.js')).href) + const sdk = new evo.EvoSDK({ network: 'devnet', trusted: true, devnetName: E2E_DEVNET, addresses: deployment().dapiAddresses }) + await sdk.connect() + return sdk } export const SCREENSHOT_DIR = join(__dirname, 'screenshots') @@ -51,7 +72,7 @@ export function shot(page: Page, name: string) { /** * Collect console errors. Some noise is expected and benign in a WASM SPA hitting a live - * testnet (transient DAPI request failures, favicon 404s, dev warnings). We only fail on + * devnet (transient DAPI request failures, favicon 404s, dev warnings). We only fail on * errors that indicate the *page itself* broke. */ export function collectPageErrors(page: Page): { errors: string[]; consoleErrors: string[] } { @@ -74,10 +95,19 @@ export function readErrorBanner(page: Page) { .first() } +/** Wait for `success`, failing fast with the app's read-error text instead of a bare timeout. */ +export async function expectLanded(page: Page, success: Locator, timeout = 45_000): Promise { + await expect(success.or(readErrorBanner(page))).toBeVisible({ timeout }) + if (await readErrorBanner(page).isVisible()) { + throw new Error(`read error: ${await readErrorBanner(page).innerText()}`) + } +} + /** * Wait until the repo scaffold has finished the "Connecting to Platform" / "Resolving …" - * loading shell — i.e. the WASM SDK connected and the registry listing resolved. Resolves - * when either real content or an explicit terminal state (error / not-found) is on screen. + * loading shell — i.e. the WASM SDK connected and the forge-v2 `repo` document resolved. + * Resolves when either real content or an explicit terminal state (error / not-found) is on + * screen. */ export async function waitForRepoResolved(page: Page, timeout = 60_000): Promise { await page diff --git a/forge-web/e2e/read-paths.spec.ts b/forge-web/e2e/read-paths.spec.ts deleted file mode 100644 index ee8ff2471..000000000 --- a/forge-web/e2e/read-paths.spec.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { test, expect } from '@playwright/test' -import { - M1, - repoUrl, - shot, - collectPageErrors, - waitForRepoResolved, - readErrorBanner, - ON_TESTNET, -} from './helpers' - -// The v1 read fixture lives on testnet; a devnet build runs v2-reads.spec.ts instead. -test.skip(!ON_TESTNET, 'testnet fixture; this build targets a devnet') - -/** - * Logged-out read-path scenarios (no keys required). These exercise the deployed foundry - * design against real Dash Platform testnet data via the lazily-loaded WASM SDK. - * - * These are expected to PASS. A note here used to say they failed by design, documenting a - * bug where the explicit `documents.queryWithProof(...)` facade rejected in a real browser - * with a wasm-bindgen object. That bug was fixed — `queryDocumentsWithProof` in - * `lib/sdk/query.ts` now delegates to the plain, still-proof-verified `.query()` (the - * connection is `testnetTrusted()`, which verifies proofs internally) — but the note - * outlived it, which left a permanently-red suite looking intentional. If a scenario here - * fails, that is a real regression in the read path, not a documented condition. - */ - -test.describe('logged-out read paths', () => { - test('1. landing renders the foundry hero, header, and testnet badge', async ({ page }) => { - const { errors } = collectPageErrors(page) - await page.goto('/', { waitUntil: 'domcontentloaded' }) - - // Foundry hero headline. - await expect(page.getByRole('heading', { name: /no server to trust/i })).toBeVisible() - - // Header chrome: wordmark link, network badge, sign-in affordance, search. - await expect(page.locator('header a[href="/"]').first()).toBeVisible() - await expect(page.getByText('testnet', { exact: false }).first()).toBeVisible() - await expect(page.getByRole('button', { name: /sign in/i })).toBeVisible() - await expect(page.getByPlaceholder(/Jump to owner/i)).toBeVisible() - - // The signature verification chip is present on the landing hero. - await expect(page.getByRole('group', { name: /verification status/i })).toBeVisible() - - // The discovery feed must actually LAND, not just fail quietly. A broken registry - // query renders inside the section and throws no uncaught exception, so - // the error-only assertion below stays green while the landing page is visibly - // broken — that is exactly how a registry contract missing its `$createdAt` index - // shipped unnoticed. Assert the rendered outcome: repo rows, or the honest empty - // state, but never the error state. - // Order matters: wait for the feed to SETTLE on a success outcome first. A bare - // "no error state" check would resolve instantly, long before the SDK has connected - // and the query could have failed, and would pass on a broken registry. - const feed = page.locator('section').filter({ hasText: 'Recent repos' }).first() - await expect( - feed.locator('a[href*="/repo/"]').or(feed.getByText(/the registry is quiet/i)).first(), - ).toBeVisible({ timeout: 45_000 }) - await expect(feed.getByText(/that read did not land|could not reach platform/i)).toHaveCount(0) - - await shot(page, '01-landing') - - // No fatal page errors (uncaught exceptions that break rendering). - expect(errors, `uncaught page errors:\n${errors.join('\n')}`).toEqual([]) - }) - - test('2. repo home hydrates real testnet data with trust panel + clone box', async ({ page }) => { - await page.goto(repoUrl(), { waitUntil: 'domcontentloaded' }) - await waitForRepoResolved(page) - - // Race the success signal (repo name in the header) against the app's read-error state so - // the test fails fast with a meaningful message instead of a 30s timeout. - const nameLoc = page.getByText(M1.name, { exact: false }).first() - await expect(nameLoc.or(readErrorBanner(page))).toBeVisible({ timeout: 30_000 }) - await shot(page, '02-repo-home') - - if (await readErrorBanner(page).isVisible()) { - throw new Error( - 'Repo home did not render real testnet data — the app is showing its read-error state ' + - '("That read did not land"). DAPI returns 200 but the proof-verified read rejects with a ' + - 'wasm-bindgen error object. Real data / branches / trust panel could not be asserted.', - ) - } - - // Real data rendered — assert the required surfaces. - await expect(nameLoc).toBeVisible() - await expect(page.getByText(/\bmain\b/).first()).toBeVisible() - await expect(page.getByText(`dash://${M1.owner}/${M1.name}`)).toBeVisible() - await expect(page.getByText(/assay|proof|sha256|verif|trust/i).first()).toBeVisible() - }) - - test('3. issues list renders folded open/closed state', async ({ page }) => { - await page.goto(repoUrl('issues'), { waitUntil: 'domcontentloaded' }) - await waitForRepoResolved(page) - - const openClosed = page.getByText(/\bOpen\b|\bClosed\b/i).first() - const emptyState = page.getByText(/no (open )?issues/i).first() - await expect(openClosed.or(emptyState).or(readErrorBanner(page)).first()).toBeVisible({ - timeout: 30_000, - }) - await shot(page, '03-issues') - - if (await readErrorBanner(page).isVisible()) { - throw new Error( - 'Issues list did not render — app is in the read-error state (proof-verified read ' + - 'rejects with a wasm-bindgen error). Open/closed issue folding could not be asserted.', - ) - } - await expect(openClosed.or(emptyState).first()).toBeVisible() - }) - - test('4. tree browse reaches an honest terminal state (best-effort)', async ({ page }) => { - // Best-effort: a real file listing, an honest "not indexed for browsing" degradation, OR the - // app's honest read-error state (retry offered, no crash) all count as a non-crashing pass. - const { errors } = collectPageErrors(page) - await page.goto(repoUrl('tree'), { waitUntil: 'domcontentloaded' }) - await waitForRepoResolved(page) - - const fileListing = page.getByRole('link').filter({ hasText: /\.\w+$|src|lib|README/i }) - const degraded = page.getByText( - /not indexed|no browse|degrad|object walk|browse artifact|cannot browse|unavailable/i, - ) - await expect( - fileListing.first().or(degraded.first()).or(readErrorBanner(page)), - ).toBeVisible({ timeout: 30_000 }) - await shot(page, '04-tree') - - // Annotate which terminal state we actually observed (visibility into the real behavior). - const state = (await fileListing.first().isVisible().catch(() => false)) - ? 'file-listing' - : (await degraded.first().isVisible().catch(() => false)) - ? 'graceful-degradation' - : 'read-error (honest, retryable)' - test.info().annotations.push({ type: 'observed-state', description: state }) - - // The one hard requirement: the page must not have crashed with an uncaught exception. - expect(errors, `uncaught page errors:\n${errors.join('\n')}`).toEqual([]) - }) - - test('7. landing is usable at a 375px mobile viewport with no horizontal overflow', async ({ - page, - }) => { - await page.setViewportSize({ width: 375, height: 812 }) - await page.goto('/', { waitUntil: 'domcontentloaded' }) - - await expect(page.getByRole('heading', { name: /no server to trust/i })).toBeVisible() - // Header stays usable at mobile width: the icon-only home link and sign-in are reachable - // (the "Dash Forge" wordmark text is intentionally hidden below the sm breakpoint). - await expect(page.locator('header a[href="/"]').first()).toBeVisible() - await expect(page.getByRole('button', { name: /sign in/i })).toBeVisible() - - // Let the layout settle (feed skeleton → terminal state) before measuring. - await page.waitForTimeout(5000) - - // No horizontal overflow: the document is not wider than the viewport. - const overflow = await page.evaluate(() => { - const de = document.documentElement - return { scrollW: de.scrollWidth, clientW: de.clientWidth } - }) - expect( - overflow.scrollW, - `horizontal overflow: scrollWidth ${overflow.scrollW} > clientWidth ${overflow.clientW}`, - ).toBeLessThanOrEqual(overflow.clientW + 1) - - await shot(page, '07-landing-mobile') - }) -}) diff --git a/forge-web/e2e/v2-auth.spec.ts b/forge-web/e2e/v2-auth.spec.ts index 49651cfeb..1abdebda0 100644 --- a/forge-web/e2e/v2-auth.spec.ts +++ b/forge-web/e2e/v2-auth.spec.ts @@ -2,7 +2,7 @@ import { test, expect } from '@playwright/test' import { existsSync, readFileSync } from 'node:fs' import { join, resolve } from 'node:path' import { pathToFileURL } from 'node:url' -import { E2E_DEVNET, PASSPHRASE, idFile, importIdentity, shot, unlock } from './helpers' +import { E2E_DEVNET, PASSPHRASE, deployment, idFile, importIdentity, nodeSdk, shot, unlock } from './helpers' /** * Limited-key sign-in, live on a devnet (real spend): @@ -20,22 +20,17 @@ import { E2E_DEVNET, PASSPHRASE, idFile, importIdentity, shot, unlock } from './ * lock, its chain-lock proof and the IdentityCreate. Skipped without a funding key. */ -test.skip(E2E_DEVNET === '' || process.env['E2E_WRITE'] !== '1', 'live devnet writes: set E2E_DEVNET=moutai E2E_WRITE=1') +test.skip(process.env['E2E_WRITE'] !== '1', 'live devnet writes: set E2E_WRITE=1') test.skip(!existsSync(idFile('CI-RUNNER')), 'devnet test identities not found') test.describe.configure({ mode: 'serial', timeout: 30 * 60_000 }) const ROOT = resolve(__dirname, '../..') /** The group the app binds keys to: the one in the deployment file it is built with. */ -const GROUP: string = E2E_DEVNET - ? JSON.parse(readFileSync(join(ROOT, `forge-contracts/deployments/devnet-${E2E_DEVNET}.json`), 'utf8')).v2.forgeCore.contractGroupId - : '' +const GROUP: string = deployment().v2.forgeCore.contractGroupId /** Read an identity's keys straight from Platform (evo-sdk in Node), independent of the app. */ async function onChainKeys(identityId: string): Promise<{ id: number; level: string; budget: bigint | null; expiresAt: number | null; bound: string | null; remaining: bigint | null }[]> { - const evo = await import(pathToFileURL(join(ROOT, 'forge-web/node_modules/@dashevo/evo-sdk/dist/evo-sdk.module.js')).href) - const dep = (await import(pathToFileURL(join(ROOT, `forge-contracts/deployments/devnet-${E2E_DEVNET}.json`)).href, { with: { type: 'json' } })).default - const sdk = new evo.EvoSDK({ network: 'devnet', trusted: true, devnetName: E2E_DEVNET, addresses: dep.dapiAddresses }) - await sdk.connect() + const sdk = await nodeSdk() const identity = await sdk.identities.fetch(identityId) const keys = identity.publicKeys as { keyId: number; securityLevel: string; totalBudget?: bigint; expiresAt?: bigint; contractBounds?: { toJSON(): { id: string } } }[] const budgets = await sdk.identities.keysRemainingBudgets(identityId, keys.map((k) => k.keyId)) diff --git a/forge-web/e2e/v2-reads.spec.ts b/forge-web/e2e/v2-reads.spec.ts index 53e3a5b1e..be2083315 100644 --- a/forge-web/e2e/v2-reads.spec.ts +++ b/forge-web/e2e/v2-reads.spec.ts @@ -1,9 +1,19 @@ -import { test, expect, type Page } from '@playwright/test' -import { collectPageErrors, E2E_DEVNET, readErrorBanner, runAxe, shot, waitForRepoResolved } from './helpers' +import { test, expect } from '@playwright/test' +import { + collectPageErrors, + DEMO, + E2E_DEVNET, + EMPTY, + expectLanded, + MAINTAINER, + repoUrl as url, + shot, + waitForRepoResolved, +} from './helpers' /** * forge-v2 read paths against a real devnet (protocol 14): the fixture - * `forge-contracts/scripts/seed-v2-fixture.mjs` seeds on moutai. Runs only on a devnet build: + * `forge-contracts/scripts/seed-v2-fixture.mjs` seeds on moutai (e2e/helpers.ts `DEMO`): * * E2E_DEVNET=moutai pnpm exec playwright test v2-reads.spec.ts * @@ -11,33 +21,23 @@ import { collectPageErrors, E2E_DEVNET, readErrorBanner, runAxe, shot, waitForRe * COLLAB), main = 3 files + docs/, a feature branch, tag v0.1.0; issue #1 open + labelled by a * writer, #2 closed by its author (`authorEvent`), #3 closed + labelled by a maintainer; PR #1 * open with a maintainer approval, PR #2 merged; one star. `forge-v2-empty` (MAINTAINER) has - * nothing pushed. + * nothing pushed. The axe checks over these pages live in a11y.spec.ts. */ -test.skip(E2E_DEVNET === '', 'the forge-v2 fixture lives on a devnet; set E2E_DEVNET=moutai') - -const OWNER = process.env['E2E_V2_OWNER'] ?? '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' -const MAINTAINER = 'GKBTXUdo3MpRYAUqgZvTZGTav9mXGqfJfR5822K2tp79' -const NAME = process.env['E2E_V2_NAME'] ?? 'forge-v2-demo' - -function url(path = '', extra = '', owner = OWNER, name = NAME): string { - const q = `owner=${owner}&name=${name}${extra}` - return path === '' ? `/repo/?${q}` : `/repo/${path}/?${q}` -} - -/** Fail fast with the app's read-error text instead of a bare timeout. */ -async function expectLanded(page: Page, success: ReturnType): Promise { - await expect(success.or(readErrorBanner(page))).toBeVisible({ timeout: 45_000 }) - if (await readErrorBanner(page).isVisible()) { - throw new Error(`read error: ${await readErrorBanner(page).innerText()}`) - } -} +const { owner: OWNER, name: NAME } = DEMO test.describe('forge-v2 read paths (devnet fixture)', () => { - test('v2-1. landing lists forge-v2 repos with provable counts', async ({ page }) => { + test('v2-1. landing: hero, header chrome, forge-v2 repos with provable counts', async ({ page }) => { const { errors } = collectPageErrors(page) await page.goto('/', { waitUntil: 'domcontentloaded' }) - await expect(page.getByText(`devnet-${E2E_DEVNET}`).first()).toBeVisible() + // Foundry hero, header chrome (wordmark link, network badge, sign-in, search) and the + // verification chip. + await expect(page.getByRole('heading', { name: /no server to trust/i })).toBeVisible() + await expect(page.locator('header a[href="/"]').first()).toBeVisible() + await expect(page.getByTestId('network-badge')).toContainText(E2E_DEVNET) + await expect(page.getByRole('button', { name: /sign in/i })).toBeVisible() + await expect(page.getByPlaceholder(/Jump to owner/i)).toBeVisible() + await expect(page.getByRole('group', { name: /verification status/i })).toBeVisible() const feed = page.locator('section').filter({ hasText: 'Recent repos' }).first() // The live write specs keep creating repos, so the fixture may have scrolled off the // newest 24: assert on whatever is newest, then on the fixture's counts by name. @@ -62,13 +62,14 @@ test.describe('forge-v2 read paths (devnet fixture)', () => { const { errors } = collectPageErrors(page) await page.goto(url(), { waitUntil: 'domcontentloaded' }) await waitForRepoResolved(page) - await expectLanded(page, page.getByRole('heading', { name: 'forge-v2-demo' })) + await expectLanded(page, page.getByRole('heading', { name: NAME })) // The published locator serves the root tree and README from Platform chunks. for (const entry of ['README.md', 'src', 'lib', 'docs']) { await expect(page.getByRole('link', { name: entry, exact: true }).first()).toBeVisible() } await expect(page.getByText(/code, issues and pull requests in the shared contracts/i).first()).toBeVisible() await expect(page.getByText(`dash://${OWNER}/${NAME}`)).toBeVisible() + await expect(page.getByText(/\bmain\b/).first()).toBeVisible() // The assay panel attests the ref by FORGE_RULES_V2 and names the repo id. await page.getByRole('button', { name: /assay/i }).click() await expect(page.getByText(/FORGE_RULES_V2/).first()).toBeVisible() @@ -139,28 +140,37 @@ test.describe('forge-v2 read paths (devnet fixture)', () => { test('v2-8. profile lists owned and member repos; ?repo= pins; empty repo', async ({ page }) => { await page.goto(`/u/?name=${MAINTAINER}`, { waitUntil: 'domcontentloaded' }) await expectLanded(page, page.getByRole('heading', { name: 'Member of' })) - await expect(page.getByRole('link', { name: 'forge-v2-empty' })).toBeVisible() + await expect(page.getByRole('link', { name: EMPTY.name })).toBeVisible() await expect(page.getByRole('link', { name: 'forge-v2 demo' })).toBeVisible() await shot(page, 'v2-08-profile') - await page.goto(url('', '', MAINTAINER, 'forge-v2-empty'), { waitUntil: 'domcontentloaded' }) + await page.goto(url('', '', EMPTY), { waitUntil: 'domcontentloaded' }) await waitForRepoResolved(page) await expectLanded(page, page.getByRole('region', { name: 'Empty repository' })) await expect(page.getByText(/remote add origin dash:\/\//)).toBeVisible() }) - test('v2-9. a11y: no serious/critical violations on the v2 pages', async ({ page }) => { - const pages: [string, string, ReturnType][] = [ - ['landing', '/', page.locator('section').filter({ hasText: 'Recent repos' }).first().locator('a[href*="/repo"]').first()], - ['repo-home', url(), page.getByRole('link', { name: 'README.md' }).first()], - ['issues', url('issues'), page.getByText('README should explain the event split')], - ['pull', url('pull', '&number=1'), page.getByRole('region', { name: 'Approvals' })], - ] - for (const [label, href, ready] of pages) { - await page.goto(href, { waitUntil: 'domcontentloaded' }) - await expectLanded(page, ready) - const serious = await runAxe(page, `v2-${label}`) - expect(serious, `${label}:\n${serious.map((v) => `${v.id}: ${v.help}`).join('\n')}`).toEqual([]) - } + test('v2-9. landing is usable at a 375px mobile viewport with no horizontal overflow', async ({ page }) => { + await page.setViewportSize({ width: 375, height: 812 }) + await page.goto('/', { waitUntil: 'domcontentloaded' }) + await expect(page.getByRole('heading', { name: /no server to trust/i })).toBeVisible() + // Header stays usable at mobile width: the icon-only home link and sign-in are reachable + // (the "Dash Forge" wordmark text is intentionally hidden below the sm breakpoint); a + // devnet badge shows at every width. + await expect(page.locator('header a[href="/"]').first()).toBeVisible() + await expect(page.getByRole('button', { name: /sign in/i })).toBeVisible() + await expect(page.getByTestId('network-badge')).toBeVisible() + // Measure once the feed has settled on its terminal state (cards, not the skeleton). + const feed = page.locator('section').filter({ hasText: 'Recent repos' }).first() + await expectLanded(page, feed.locator('a[href*="/repo"]').first()) + const overflow = await page.evaluate(() => { + const de = document.documentElement + return { scrollW: de.scrollWidth, clientW: de.clientWidth } + }) + expect( + overflow.scrollW, + `horizontal overflow: scrollWidth ${overflow.scrollW} > clientWidth ${overflow.clientW}`, + ).toBeLessThanOrEqual(overflow.clientW + 1) + await shot(page, 'v2-09-landing-mobile') }) }) diff --git a/forge-web/e2e/v2-writes.spec.ts b/forge-web/e2e/v2-writes.spec.ts index 64afb7b9d..4c5ed81ab 100644 --- a/forge-web/e2e/v2-writes.spec.ts +++ b/forge-web/e2e/v2-writes.spec.ts @@ -1,6 +1,6 @@ import { test, expect, type Page } from '@playwright/test' import { existsSync } from 'node:fs' -import { E2E_DEVNET, idFile, shot, signedIn, unlock } from './helpers' +import { idFile, repoUrl, shot, signedIn, unlock } from './helpers' /** * forge-v2 WRITES, live on a devnet (real spend, a few thousandths of a DASH per run): @@ -20,7 +20,7 @@ const COLLAB = '6jAyDGGcc6fgA7bsraQPriTAZ73Lkq5QgnenaRhqteHd' const REPO = `e2e-${Date.now().toString(36)}` const ISSUE_TITLE = `Browser-written issue ${REPO}` -test.skip(E2E_DEVNET === '' || process.env['E2E_WRITE'] !== '1', 'live devnet writes: set E2E_DEVNET=moutai E2E_WRITE=1') +test.skip(process.env['E2E_WRITE'] !== '1', 'live devnet writes: set E2E_WRITE=1') test.skip(!existsSync(idFile('OWNER')), 'devnet test identities not found') test.describe.configure({ mode: 'serial', timeout: 240_000 }) @@ -101,7 +101,7 @@ test('w5. contributor stars and unstars the repo (index-only delete)', async ({ }) test('w6. owner approves the fixture PR, then removes the writer', async ({ browser }) => { - const page = await signedIn(browser, 'OWNER', `/repo/pull/?owner=${OWNER}&name=forge-v2-demo&number=1`) + const page = await signedIn(browser, 'OWNER', repoUrl('pull', '&number=1')) await page.getByRole('button', { name: /^approve$/i }).click() await confirmWrite(page, /submit review/i) await expect(page.getByRole('region', { name: 'Approvals' })).toBeVisible() diff --git a/forge-web/e2e/zero-backend.spec.ts b/forge-web/e2e/zero-backend.spec.ts index c57771b09..43e64ef41 100644 --- a/forge-web/e2e/zero-backend.spec.ts +++ b/forge-web/e2e/zero-backend.spec.ts @@ -1,11 +1,8 @@ import { test, expect } from '@playwright/test' -import { ON_TESTNET, repoUrl, waitForRepoResolved } from './helpers' - -// The v1 read fixture lives on testnet; a devnet build runs v2-reads.spec.ts instead. -test.skip(!ON_TESTNET, 'testnet fixture; this build targets a devnet') +import { expectLanded, repoUrl, waitForRepoResolved } from './helpers' /** - * Scenario 5 — Zero-backend proof. + * Scenario 5 — Zero-backend proof, on the forge-v2 read fixture (e2e/helpers.ts `DEMO`). * * Record every network request made during a repo browse and assert each one goes only to an * allowed class of host: @@ -29,7 +26,7 @@ function isDashPlatform(host: string): boolean { host.endsWith('.networks.dash.org') || host.endsWith('.dash.org') || host === 'dash.org' || - // testnet masternodes are frequently addressed by raw IPv4. + // devnet masternodes (DAPI) are addressed by raw IPv4. /^\d{1,3}(\.\d{1,3}){3}$/.test(host) ) } @@ -54,27 +51,31 @@ test('5. repo browse contacts only app-origin + DAPI + declared backends (zero-b const unexpected = new Set() page.on('request', (req) => { - let host: string + let url: URL try { - host = new URL(req.url()).hostname + url = new URL(req.url()) } catch { - return // data:, blob:, about: — not network egress + return } - const url = new URL(req.url()) - if (url.protocol === 'data:' || url.protocol === 'blob:') return + // data:, blob:, about: — not network egress. + if (url.protocol !== 'http:' && url.protocol !== 'https:') return + const host = url.hostname contacted.set(host, (contacted.get(host) ?? 0) + 1) if (!isAppOrigin(host) && !isDashPlatform(host) && !isKnownBackend(host)) { unexpected.add(host) } }) - // Browse the repo home — this triggers SDK connect + quorum-key fetch + registry + document - // reads. The zero-backend claim is about *which hosts* are contacted; it holds whether or not - // the proof-verified read ultimately renders data, so we don't gate on successful hydration. + // Browse the repo home (SDK connect + quorum keys + repo/ref/manifest reads + the locator + // and pack chunks behind the root tree and README), then a blob. Both must actually render: + // a browse that never reached the chunk reads would make the host check vacuous. await page.goto(repoUrl(), { waitUntil: 'domcontentloaded' }) await waitForRepoResolved(page) + await expectLanded(page, page.getByRole('link', { name: 'README.md' }).first()) + await page.goto(repoUrl('blob', '&path=src/main.rs'), { waitUntil: 'domcontentloaded' }) + await expectLanded(page, page.getByText('reads are proof-checked').first()) // Let late/lazy fetches (WASM chunk, DAPI round-trips, artifacts) settle. - await page.waitForTimeout(8000) + await page.waitForTimeout(5000) const hosts = [...contacted.entries()].sort((a, b) => b[1] - a[1]) // Surface the evidence in the test output regardless of pass/fail. @@ -91,11 +92,7 @@ test('5. repo browse contacts only app-origin + DAPI + declared backends (zero-b [...unexpected].join('\n'), ).toEqual([]) - // Sanity: we actually exercised the Platform network (otherwise the assertion is vacuous) — - // at least one Dash Platform host (quorum endpoint or a DAPI masternode) must have been hit. + // Sanity: the browse went over the Platform network (otherwise the assertion is vacuous). const platformHosts = [...contacted.keys()].filter(isDashPlatform) - expect( - platformHosts.length, - 'no Dash Platform host was contacted — the browse did not reach testnet', - ).toBeGreaterThan(0) + expect(platformHosts.length, 'no Dash Platform host was contacted').toBeGreaterThan(0) }) diff --git a/forge-web/hooks/use-query-param.ts b/forge-web/hooks/use-query-param.ts index bff479c2f..e1838e790 100644 --- a/forge-web/hooks/use-query-param.ts +++ b/forge-web/hooks/use-query-param.ts @@ -16,15 +16,13 @@ export function useParam(name: string, fallback = ''): string { /** * How a route addresses a repo: `(owner, name)` — owner an identity id or DPNS name — plus an - * optional pin: `repo` (a forge-v2 `repo` document id) or `contract` (a v1 repo contract). + * optional pin, `repo` (the `repo` document id). */ export interface RepoAddress { readonly owner: string readonly name: string - /** `?repo=` — pins a forge-v2 repo. */ + /** `?repo=` — pins the repo by id. */ readonly repoId?: string - /** `?contract=` — pins a v1 repo contract. */ - readonly contractId?: string } /** Read the repo address from the URL. */ @@ -36,12 +34,10 @@ export function useRepoAddress(): RepoAddress { /** The {@link RepoAddress} a query string names. */ export function addressFromParams(params: { get(name: string): string | null }): RepoAddress { const repoId = params.get('repo') ?? '' - const contractId = params.get('contract') ?? '' return { owner: params.get('owner') ?? '', name: params.get('name') ?? '', ...(repoId !== '' ? { repoId } : {}), - ...(contractId !== '' ? { contractId } : {}), } } @@ -53,7 +49,6 @@ export function repoHref( ): string { const q = new URLSearchParams({ owner: addr.owner, name: addr.name }) if (addr.repoId) q.set('repo', addr.repoId) - if (addr.contractId) q.set('contract', addr.contractId) for (const [k, v] of Object.entries(extra)) q.set(k, v) return `${path}?${q.toString()}` } diff --git a/forge-web/hooks/use-relation-toggle.ts b/forge-web/hooks/use-relation-toggle.ts index 0677ecc2c..81d837d28 100644 --- a/forge-web/hooks/use-relation-toggle.ts +++ b/forge-web/hooks/use-relation-toggle.ts @@ -2,7 +2,7 @@ /** * useRelationToggle — the viewer's own on/off relation (a star on a repo, a follow of an - * identity; forge-collab on v2, the registry on v1) with an honest initial state and honest failures. + * identity, in forge-collab) with an honest initial state and honest failures. * * The initial state is READ, not assumed: until the viewer's own documents have been checked * the toggle reports `on: null` and callers must not offer an action. A read failure or a write diff --git a/forge-web/hooks/use-repo.ts b/forge-web/hooks/use-repo.ts index 3d41c47d9..91db8758c 100644 --- a/forge-web/hooks/use-repo.ts +++ b/forge-web/hooks/use-repo.ts @@ -3,12 +3,12 @@ /** * useRepoHome — resolve + compose a repo's home view-model from its route address. * - * Connects the SDK (registry, DPNS and the forge-v2 contracts preloaded), resolves the repo — - * a forge-v2 `repo` document by `($ownerId, name)`, else the v1 registry with - * listing-authenticity verification — and loads config + refs + star count. Returns the async + * Connects the SDK (DPNS and the forge-v2 contracts preloaded), resolves the repo — its + * forge-core `repo` document by `($ownerId, name)` or `?repo=` — and loads config + refs + + * star count. Returns the async * state the repo chrome renders. `notFound` distinguishes an unresolved repo from a read error. * - * Resolution is cached per `(network, owner, name, ?repo=, ?contract=)` with the settled value kept alongside the + * Resolution is cached per `(network, owner, name, ?repo=)` with the settled value kept alongside the * promise, so navigating between a repo's pages (code → issues → commits …) renders the * composed home on the first paint — no "Resolving…" shell on warm navigations. Hits older * than {@link HOME_REVALIDATE_MS} serve the cached value and refresh in the background @@ -35,7 +35,7 @@ export interface UseRepoResult extends AsyncState { } // NOTE for future write flows: anything that mutates what RepoHome composes (refs, config, -// stars, the listing) must call the hook's `reload()` — or delete the cache key — after the +// stars, the repo document) must call the hook's `reload()` — or delete the cache key — after the // write lands, or the page can serve up-to-TTL-stale data on the next navigation. const HOME_CACHE_TTL_MS = 5 * 60_000 /** Age beyond which a hit is served stale and refreshed in the background. */ @@ -50,7 +50,7 @@ interface HomeCacheEntry { const homeCache = new Map() function homeCacheKey(network: Network, addr: RepoAddress): string { - return `${network}/${addr.owner}/${addr.name}/${addr.repoId ?? ''}/${addr.contractId ?? ''}` + return `${network}/${addr.owner}/${addr.name}/${addr.repoId ?? ''}` } function startLoad(sdk: EvoSDK, key: string, network: Network, addr: RepoAddress): HomeCacheEntry { diff --git a/forge-web/hooks/use-sdk.ts b/forge-web/hooks/use-sdk.ts index dd3d3fdb3..89b3a2260 100644 --- a/forge-web/hooks/use-sdk.ts +++ b/forge-web/hooks/use-sdk.ts @@ -5,8 +5,8 @@ * * The WASM SDK cannot run during SSG (S0.3), so every data page mounts a loading shell on the * server and calls this hook after hydration. It initializes the process-wide {@link evoSdkService} - * on the active network with the registry, DPNS and forge-v2 contracts preloaded, and - * (optionally) a v1 repo contract in view. Idempotent: repeated mounts share the one connection. + * on the active network with the DPNS and forge-v2 contracts preloaded (plus any extra ids the + * caller names). Idempotent: repeated mounts share the one connection. */ import { useEffect, useState } from 'react' @@ -43,11 +43,11 @@ export function useSdk(extraContractIds: readonly string[] = []): SdkState { useEffect(() => { let cancelled = false - const { registryContractId: registry, dpnsContractId: dpns, v2 } = NETWORKS[network] + const { dpnsContractId: dpns, v2 } = NETWORKS[network] const extras = key.length > 0 ? key.split(',') : [] const contractIds = [ ...new Set( - [registry, dpns, v2?.core, v2?.collab, ...extras].filter( + [dpns, v2?.core, v2?.collab, ...extras].filter( (id): id is string => typeof id === 'string' && id.length > 0, ), ), diff --git a/forge-web/lib/auth/base58.ts b/forge-web/lib/auth/base58.ts index 618bf7a73..8108b1fec 100644 --- a/forge-web/lib/auth/base58.ts +++ b/forge-web/lib/auth/base58.ts @@ -88,7 +88,7 @@ export function base58CheckEncode(payload: Uint8Array): string { /** * Decode a base58 identity/document id into its raw 32-byte form — the encoding a typed - * `Document`'s identifier-typed property (e.g. `targetId`, `listingId`, `repoContractId`) + * `Document`'s identifier-typed property (e.g. `targetId`, `repoId`, `memberId`) * must carry. Throws if the decoded value is not 32 bytes. */ export function decodeIdentifier(id: string): Uint8Array { diff --git a/forge-web/lib/auth/identity-file.ts b/forge-web/lib/auth/identity-file.ts index 54eec6d55..f920f7235 100644 --- a/forge-web/lib/auth/identity-file.ts +++ b/forge-web/lib/auth/identity-file.ts @@ -13,7 +13,7 @@ * Login imports one of these (or a manually pasted WIF + identity id). We extract the identity * id, the file's declared network, and the single AUTHENTICATION signing key to store — * preferring the highest-privilege usable key (CRITICAL, which can sign both HIGH-gated - * document ops and CRITICAL-gated token-admin ops) and falling back to HIGH. + * document ops and CRITICAL-gated identity ops) and falling back to HIGH. */ import { isLikelyWif } from './wif' diff --git a/forge-web/lib/browse/flatindex.ts b/forge-web/lib/browse/flatindex.ts index 22fee7154..61131ebf9 100644 --- a/forge-web/lib/browse/flatindex.ts +++ b/forge-web/lib/browse/flatindex.ts @@ -1,6 +1,6 @@ /** * flatIndex reader — a tip commit's full recursive file listing (GitHub's tree API as one - * static artifact, data-contracts §2.3). + * static artifact, `forge-v2.md` §4). * * Read-side port of `crates/forge-core/src/pack/flatindex.rs`. gzip-compressed body: * tipOid(20) || varint(nrows) || row* diff --git a/forge-web/lib/browse/locator.ts b/forge-web/lib/browse/locator.ts index 39cdaf8bc..bd5fddaa2 100644 --- a/forge-web/lib/browse/locator.ts +++ b/forge-web/lib/browse/locator.ts @@ -1,5 +1,5 @@ /** - * objectLocator reader — the git-MIDX analog (data-contracts §2.3, S0.5). + * objectLocator reader — the git-MIDX analog (`forge-v2.md` §4, S0.5). * * Read-side port of `crates/forge-core/src/pack/locator.rs`. Layout: * fanout(256 × u32 BE) || rows diff --git a/forge-web/lib/constants.test.ts b/forge-web/lib/constants.test.ts index 37f48ca41..3482f3699 100644 --- a/forge-web/lib/constants.test.ts +++ b/forge-web/lib/constants.test.ts @@ -1,5 +1,5 @@ /** - * Network resolution — which network a build targets and which registry it reads. + * Network resolution — which network a build targets and which forge-v2 contracts it reads. * * Precedence per field: NEXT_PUBLIC_* env > `forge-contracts/deployments/.json` > * testnet default. A network without a deployment resolves to "not deployed", never to @@ -17,7 +17,7 @@ import { NotDeployedError, parseDapiAddresses, quorumEndpoint, - requireRegistryContractId, + requireForge, resolveNetworks, } from './constants' import { DEPLOYMENTS, forgeV2Ids, recordedDapiAddresses } from './deployments' @@ -25,7 +25,9 @@ import { identityFileMatchesNetwork } from './auth/identity-file' const DEPLOYMENTS_DIR = resolve(process.cwd(), '..', 'forge-contracts', 'deployments') -function onDisk(key: string): { registry?: { contractId?: string | null } } { +function onDisk(key: string): { + v2: { forgeCore: { contractId: string }; forgeCollab: { contractId: string }; contractGroupId: string } +} { return JSON.parse(readFileSync(resolve(DEPLOYMENTS_DIR, `${key}.json`), 'utf8')) } @@ -40,24 +42,21 @@ describe('deployments bundle', () => { }) describe('resolveNetworks', () => { - it('defaults to testnet with the registry from testnet.json', () => { + it('defaults to testnet, which has no forge-v2 deployment', () => { const { active, networks } = resolveNetworks({}, DEPLOYMENTS) expect(active).toBe('testnet') - expect(networks.testnet.registryContractId).toBe(onDisk('testnet').registry?.contractId) - expect(networks.testnet.registrySource).toBe('forge-contracts/deployments/testnet.json') + if (DEPLOYMENTS['testnet'] === undefined) expect(networks.testnet.v2).toBeNull() }) - it('never borrows testnet ids for mainnet', () => { - const { active, networks } = resolveNetworks({ network: 'mainnet' }, DEPLOYMENTS) + it('never borrows another network\'s ids', () => { + const { active, networks } = resolveNetworks({ network: 'mainnet', devnetName: '' }, DEPLOYMENTS) expect(active).toBe('mainnet') - if (DEPLOYMENTS['mainnet'] === undefined) { - expect(networks.mainnet.registryContractId).toBeNull() - expect(networks.mainnet.registrySource).toBeNull() - } - expect(networks.mainnet.registryContractId).not.toBe(networks.testnet.registryContractId) + if (DEPLOYMENTS['mainnet'] === undefined) expect(networks.mainnet.v2).toBeNull() + const moutai = resolveNetworks({ devnetName: 'moutai' }, DEPLOYMENTS).networks.devnet.v2 + expect(networks.mainnet.v2).not.toEqual(moutai) }) - it('resolves a named devnet from its deployment file (no v1 registry)', () => { + it('resolves a named devnet from its deployment file', () => { const { active, networks } = resolveNetworks( { network: 'devnet', devnetName: 'moutai' }, DEPLOYMENTS, @@ -67,11 +66,10 @@ describe('resolveNetworks', () => { expect(networks.devnet.devnetName).toBe('moutai') expect(networks.devnet.dapiAddresses).toHaveLength(10) expect(networks.devnet.dapiAddresses).toContain('https://68.67.122.84:1443') - expect(networks.devnet.registryContractId).toBeNull() }) it('exposes the forge-v2 ids devnet-moutai.json records, and none for testnet', () => { - const file = JSON.parse(readFileSync(resolve(DEPLOYMENTS_DIR, 'devnet-moutai.json'), 'utf8')) + const file = onDisk('devnet-moutai') const { networks } = resolveNetworks({ devnetName: 'moutai' }, DEPLOYMENTS) expect(networks.devnet.v2).toEqual({ core: file.v2.forgeCore.contractId, @@ -93,21 +91,10 @@ describe('resolveNetworks', () => { expect(networks.devnet.dapiAddresses).toEqual(['https://10.0.0.1:1443', 'https://10.0.0.2:2443']) }) - it('lets NEXT_PUBLIC_REGISTRY_CONTRACT_ID beat the deployment, on the active network only', () => { - const { networks } = resolveNetworks( - { network: 'devnet', devnetName: 'moutai', registryContractId: 'OVERRIDE' }, - DEPLOYMENTS, - ) - expect(networks.devnet.registryContractId).toBe('OVERRIDE') - expect(networks.devnet.registrySource).toBe('NEXT_PUBLIC_REGISTRY_CONTRACT_ID') - // The override does not leak onto testnet. - expect(networks.testnet.registryContractId).toBe(onDisk('testnet').registry?.contractId) - }) - - it('an unknown devnet has no addresses (SDK discovery) and no registry', () => { + it('an unknown devnet has no addresses (SDK discovery) and no forge-v2 deployment', () => { const { networks } = resolveNetworks({ network: 'devnet', devnetName: 'paloma' }, DEPLOYMENTS) expect(networks.devnet.dapiAddresses).toEqual([]) - expect(networks.devnet.registryContractId).toBeNull() + expect(networks.devnet.v2).toBeNull() }) it('fails the build on a malformed network env', () => { @@ -119,17 +106,14 @@ describe('resolveNetworks', () => { }) describe('module-level config (default build env)', () => { - it('targets testnet and exposes its registry', () => { + it('targets testnet by default', () => { expect(DEFAULT_NETWORK).toBe('testnet') - expect(requireRegistryContractId('testnet')).toBe(onDisk('testnet').registry?.contractId) }) - it('throws the actionable NotDeployedError for a network without a registry', () => { - if (NETWORKS.mainnet.registryContractId !== null) return - expect(() => requireRegistryContractId('mainnet')).toThrow(NotDeployedError) - expect(() => requireRegistryContractId('mainnet')).toThrow( - /no Dash Forge registry is deployed on mainnet yet; see docs\/mainnet-runbook\.md/, - ) + it('throws the actionable NotDeployedError for a network without forge-v2', () => { + if (NETWORKS.mainnet.v2 !== null) return + expect(() => requireForge('mainnet')).toThrow(NotDeployedError) + expect(() => requireForge('mainnet')).toThrow(/forge-v2 is not deployed on mainnet/) }) }) diff --git a/forge-web/lib/constants.ts b/forge-web/lib/constants.ts index 88cbb060c..361c2b0b5 100644 --- a/forge-web/lib/constants.ts +++ b/forge-web/lib/constants.ts @@ -3,12 +3,13 @@ * * PARITY SOURCE OF TRUTH: `forge-contracts/vectors/` and `forge-contracts/deployments/*.json`. * Ref-resolution / event-fold / chunking rules exist twice (Rust forge-core + this TS) by - * necessity — both implement `FORGE_RULES_V1` against the shared JSON conformance vectors. + * necessity — both implement FORGE_RULES / FORGE_RULES_V2 against the shared JSON conformance + * vectors. * Any value here that mirrors forge-core MUST stay byte-for-byte in sync with those vectors; * CI runs both suites on every vector change. Per-network contract ids are never written here: * they come from `forge-contracts/deployments/*.json` (see `./deployments`), selected by the * build-time `NEXT_PUBLIC_NETWORK` / `NEXT_PUBLIC_DEVNET_NAME` / `NEXT_PUBLIC_DAPI_ADDRESSES` / - * `NEXT_PUBLIC_QUORUM_URL` / `NEXT_PUBLIC_REGISTRY_CONTRACT_ID`. + * `NEXT_PUBLIC_QUORUM_URL`. */ import { @@ -28,18 +29,10 @@ import storageDefaults from '../../forge-contracts/config/storage-defaults.json' export type Network = 'testnet' | 'mainnet' | 'devnet' /** - * Platform **system** contracts. Their ids are fixed by rs-dpp (`dpns_contract::ID_BYTES`, - * `token_history_contract::ID_BYTES`) and identical on every network — protocol constants, - * not deployment values. + * The Platform **DPNS** system contract. Its id is fixed by rs-dpp (`dpns_contract::ID_BYTES`) + * and identical on every network — a protocol constant, not a deployment value. */ export const DPNS_CONTRACT_ID = 'GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec' -/** - * The system **TokenHistory** contract holding the `mint` / `freeze` / `unfreeze` / - * `destroyFrozenFunds` audit documents with consensus `$createdAt` (parity with forge-core - * `tokens.rs::TOKEN_HISTORY_CONTRACT_ID`, S0.7). Its records reconstruct as-of-time WRITE / - * MAINTAIN holdings for the issue/PR event fold. - */ -export const TOKEN_HISTORY_CONTRACT_ID = '43gujrzZgXqcKBiScLa4T8XTDnRhenR9BLx8GWVHjPxF' /** The DAPI port assumed when a configured address omits one (Platform HTTPS gateway). */ export const DEFAULT_DAPI_PORT = 1443 @@ -55,17 +48,12 @@ export interface NetworkConfig { readonly dapiAddresses: readonly string[] /** Devnet quorum service URL; null = `https://quorums..networks.dash.org`. */ readonly quorumBaseUrl: string | null - /** - * Global registry contract id (discovery + social graph), from - * `forge-contracts/deployments/.json` or `NEXT_PUBLIC_REGISTRY_CONTRACT_ID`. Null = - * no Dash Forge registry on this network — see {@link NotDeployedError}. - */ - readonly registryContractId: string | null - /** Where {@link registryContractId} came from (shown in the UI and the error). */ - readonly registrySource: string | null /** DPNS system contract id — supplies human-readable identity names. */ readonly dpnsContractId: string - /** The forge-v2 contracts registered here (`deployments/.json` `v2`), else null. */ + /** + * The forge-v2 contracts registered here (`deployments/.json` `v2`). Null = Dash Forge + * is not deployed on this network — see {@link NotDeployedError}. + */ readonly v2: ForgeIds | null } @@ -76,15 +64,14 @@ export interface NetworkEnv { readonly dapiAddresses?: string /** Devnet quorum service URL (`NEXT_PUBLIC_QUORUM_URL`; parity with `DASH_FORGE_QUORUM_URL`). */ readonly quorumBaseUrl?: string - readonly registryContractId?: string } -/** Thrown by registry-backed reads/writes on a network with no Dash Forge registry. */ +/** Thrown by reads/writes on a network where forge-v2 is not deployed ({@link NetworkConfig.v2} null). */ export class NotDeployedError extends Error { constructor(readonly networkKey: string) { super( - `no Dash Forge registry is deployed on ${networkKey} yet; see docs/mainnet-runbook.md ` + - `(or build with NEXT_PUBLIC_REGISTRY_CONTRACT_ID set to a registry deployed there)`, + `forge-v2 is not deployed on ${networkKey}; see docs/contracts/forge-v2.md §8 ` + + `(a network is deployed once forge-contracts/deployments/${networkKey}.json records it)`, ) this.name = 'NotDeployedError' } @@ -129,9 +116,8 @@ function validateDevnetName(name: string): void { /** * Resolve the active network and every network's config from the build env and the * embedded deployment files. Precedence per field: env > `deployments/.json` > - * testnet default. The registry override applies to the active network only. A network - * without a deployment resolves with `registryContractId: null` — never another network's. - * Throws on a malformed env (unknown network, devnet without a name) so the BUILD fails. + * testnet default. A network without a deployment resolves with `v2: null` — never another + * network's. Throws on a malformed env (unknown network, devnet without a name) so the BUILD fails. */ export function resolveNetworks( env: NetworkEnv, @@ -154,8 +140,6 @@ export function resolveNetworks( const key = network === 'devnet' ? `devnet-${name ?? ''}` : network const file = name !== null || network !== 'devnet' ? deployments[key] : undefined const isActive = network === active - const override = isActive ? nonEmpty(env.registryContractId) : null - const deployed = nonEmpty(file?.registry?.contractId) const envAddresses = isActive ? nonEmpty(env.dapiAddresses) : null const envQuorum = isActive ? nonEmpty(env.quorumBaseUrl) : null return { @@ -167,13 +151,6 @@ export function resolveNetworks( ? parseDapiAddresses(envAddresses) : parseDapiAddresses(recordedDapiAddresses(file).join(',')), quorumBaseUrl: envQuorum ?? nonEmpty(file?.quorumBaseUrl), - registryContractId: override ?? deployed, - registrySource: - override !== null - ? 'NEXT_PUBLIC_REGISTRY_CONTRACT_ID' - : deployed !== null - ? `forge-contracts/deployments/${key}.json` - : null, dpnsContractId: DPNS_CONTRACT_ID, v2: forgeV2Ids(file), } @@ -196,7 +173,6 @@ const RESOLVED = resolveNetworks( devnetName: process.env.NEXT_PUBLIC_DEVNET_NAME, dapiAddresses: process.env.NEXT_PUBLIC_DAPI_ADDRESSES, quorumBaseUrl: process.env.NEXT_PUBLIC_QUORUM_URL, - registryContractId: process.env.NEXT_PUBLIC_REGISTRY_CONTRACT_ID, }, DEPLOYMENTS, ) @@ -246,17 +222,17 @@ export const IPFS_GATEWAYS: readonly string[] = storageDefaults.ipfsGateways /** The config of the network this build targets. */ export const ACTIVE_NETWORK: NetworkConfig = NETWORKS[DEFAULT_NETWORK] -/** The registry id for `network`, or a {@link NotDeployedError}. */ -export function requireRegistryContractId(network: Network): string { +/** The forge-v2 contracts of `network`, or a {@link NotDeployedError}. */ +export function requireForge(network: Network): ForgeIds { const config = NETWORKS[network] - if (config.registryContractId === null) throw new NotDeployedError(config.key) - return config.registryContractId + if (config.v2 === null) throw new NotDeployedError(config.key) + return config.v2 } // --------------------------------------------------------------------------- // Chunk / browse constants — MIRROR forge-core (parity via forge-contracts/vectors). -// See docs/contracts/data-contracts.md for the normative `chunk` / `manifestPart` / -// `packManifest` field definitions. +// See docs/contracts/forge-v2.md and forge-contracts/contracts/forge-core.json for the +// normative `chunk` / `manifestPart` / `packManifest` field definitions. // --------------------------------------------------------------------------- /** Max bytes per byteArray field on `chunk` (d0..d2) and per `manifestPart` entry column. */ @@ -290,7 +266,7 @@ export const MANIFEST_MAX_TIPS = 16 export const MANIFEST_MAX_SUPERSEDES = 32 /** - * flatIndex publication policy (config-tunable in FORGE_RULES_V1; S0.5 tunes constants): + * flatIndex publication policy (S0.5 tunes constants): * republish after N default-branch pushes or the staleness window, whichever comes first. * Readers overlay the ≤ FLATINDEX_OVERLAY_MAX commits since the indexed tip. */ diff --git a/forge-web/lib/deployments.ts b/forge-web/lib/deployments.ts index c9f5b170d..7f371c5b9 100644 --- a/forge-web/lib/deployments.ts +++ b/forge-web/lib/deployments.ts @@ -9,9 +9,8 @@ */ import devnetMoutai from '../../forge-contracts/deployments/devnet-moutai.json' -import testnet from '../../forge-contracts/deployments/testnet.json' -/** One contract's record: `status` is `registered` once confirmed (v2 records only). */ +/** One contract's record: `status` is `registered` once confirmed. */ export interface ContractRecord { readonly contractId?: string | null readonly ownerId?: string | null @@ -22,7 +21,6 @@ export interface ContractRecord { export interface DeploymentFile { readonly dapiAddresses?: readonly string[] readonly quorumBaseUrl?: string | null - readonly registry?: ContractRecord | null /** The forge-v2 record `forge-contracts/scripts/deploy-v2.mjs` read-modify-writes. */ readonly v2?: { readonly forgeCore?: ContractRecord @@ -68,8 +66,10 @@ export function forgeV2Ids(file: DeploymentFile | undefined): ForgeIds | null { return core && collab && group ? { core, collab, group } : null } -/** Deployment key (`testnet`, `mainnet`, `devnet-`) → file contents. */ +/** + * Deployment key (`testnet`, `mainnet`, `devnet-`) → file contents. A network with no + * file here has no forge-v2 deployment and shows "not deployed". + */ export const DEPLOYMENTS: Readonly> = { - testnet, 'devnet-moutai': devnetMoutai, } diff --git a/forge-web/lib/design/contrast.test.ts b/forge-web/lib/design/contrast.test.ts index c5303454c..ecd31de83 100644 --- a/forge-web/lib/design/contrast.test.ts +++ b/forge-web/lib/design/contrast.test.ts @@ -7,7 +7,7 @@ import { avatarFill, hslToRgb, whiteContrast } from './avatar' /** * WCAG 2 AA contrast for the design tokens, checked without a browser. * - * The nightly axe run (e2e/a11y.spec.ts) is the end-to-end check, but it needs live testnet + * The nightly axe run (e2e/a11y.spec.ts) is the end-to-end check, but it needs live devnet * data to render the elements that fail — the landing only showed the DPNS-name identity * pill in dash blue once a repo card resolved its owner's name. These tests pin the token * pairs so a regression fails in `pnpm test`, offline. diff --git a/forge-web/lib/repo/collab.ts b/forge-web/lib/repo/collab.ts deleted file mode 100644 index 99f7a82a8..000000000 --- a/forge-web/lib/repo/collab.ts +++ /dev/null @@ -1,198 +0,0 @@ -/** - * Collaborators + social reads (data-contracts §2.1, §3). - * - * Collaborators ARE the token balances: an identity holding an unfrozen WRITE / MAINTAIN - * balance is a collaborator. Platform has no "list all holders" query, so the candidate - * set is discovered (distinct pushers + the repo owner) and then balance/freeze-checked. - * Star / follower / following counts are O(1) count-tree reads on the registry. - */ - -import type { EvoSDK } from '@dashevo/evo-sdk' - -import { DEFAULT_NETWORK, requireRegistryContractId, type Network } from '../constants' -import { - countDocuments, - queryDocuments, - skipScanDistinct, - base64ToBytes, - type PlainDocument, -} from '../sdk' -import { REGISTRY_DOC, TOKEN_POSITION, DOC, type V1RepoRef } from './contract' - -interface TokensFacadeLike { - calculateId: (contractId: string, tokenPosition: number) => Promise - balances: (identityIds: string[], tokenId: string) => Promise> - identitiesTokenInfos: (identityIds: string[], tokenId: string) => Promise> -} -interface SdkTokensLike { - tokens: TokensFacadeLike -} - -/** One collaborator row (the on-chain ACL). */ -export interface Collaborator { - readonly identity: string - /** Holds a (nonzero) WRITE balance. */ - readonly write: boolean - /** Holds a (nonzero) MAINTAIN balance. */ - readonly maintain: boolean - /** Frozen on either token (suspended — cannot spend at consensus). */ - readonly frozen: boolean -} - -/** Derive the WRITE / MAINTAIN token ids for a repo contract. */ -export async function repoTokenIds( - sdk: EvoSDK, - repo: V1RepoRef, -): Promise<{ write: string; maintain: string }> { - const tokens = (sdk as unknown as SdkTokensLike).tokens - const [write, maintain] = await Promise.all([ - tokens.calculateId(repo.contractId, TOKEN_POSITION.write), - tokens.calculateId(repo.contractId, TOKEN_POSITION.maintain), - ]) - return { write, maintain } -} - -/** - * Discover candidate collaborator identities: the distinct pushers (distinct `$ownerId` - * across `refUpdate`) plus the repo owner. Platform cannot enumerate token holders, so this - * candidate set bounds the balance lookups. - */ -export async function candidateCollaborators(sdk: EvoSDK, repo: V1RepoRef): Promise { - const pushers = await skipScanDistinct(sdk, { - dataContractId: repo.contractId, - documentTypeName: DOC.refUpdate, - keyField: '$ownerId', - maxKeys: 500, - }) - return [...new Set([repo.ownerId, ...pushers])] -} - -function isFrozen(info: unknown): boolean { - if (info != null && typeof info === 'object') { - const rec = info as Record - if (rec['frozen'] === true) return true - const status = rec['frozenStatus'] ?? rec['status'] - if (typeof status === 'string' && status.toLowerCase().includes('frozen')) return true - } - return false -} - -/** - * The collaborator list: balance + freeze-check every candidate against both tokens. - * `candidates` defaults to {@link candidateCollaborators}. Returns only identities that - * hold at least one of the two tokens. - */ -export async function readCollaborators( - sdk: EvoSDK, - repo: V1RepoRef, - candidates?: readonly string[], -): Promise { - const ids = candidates ? [...candidates] : await candidateCollaborators(sdk, repo) - if (ids.length === 0) return [] - const tokens = (sdk as unknown as SdkTokensLike).tokens - const { write, maintain } = await repoTokenIds(sdk, repo) - - const [writeBal, maintainBal, writeInfo, maintainInfo] = await Promise.all([ - tokens.balances(ids, write), - tokens.balances(ids, maintain), - tokens.identitiesTokenInfos(ids, write), - tokens.identitiesTokenInfos(ids, maintain), - ]) - - const out: Collaborator[] = [] - for (const id of ids) { - const hasWrite = (writeBal.get(id) ?? 0n) > 0n - const hasMaintain = (maintainBal.get(id) ?? 0n) > 0n - if (!hasWrite && !hasMaintain) continue - const frozen = isFrozen(writeInfo.get(id)) || isFrozen(maintainInfo.get(id)) - out.push({ identity: id, write: hasWrite, maintain: hasMaintain, frozen }) - } - return out -} - -// --------------------------------------------------------------------------- -// Social counts (registry count trees — O(1)) -// --------------------------------------------------------------------------- - -function registryId(network: Network | undefined, override?: string): string { - return override ?? requireRegistryContractId(network ?? DEFAULT_NETWORK) -} - -/** Star count for a repo listing (countable `star(listingId)`). `listingId` is base58. */ -export async function readStarCount( - sdk: EvoSDK, - listingId: string, - opts: { network?: Network; registryContractId?: string } = {}, -): Promise { - return countDocuments(sdk, { - dataContractId: registryId(opts.network, opts.registryContractId), - documentTypeName: REGISTRY_DOC.star, - where: [['listingId', '==', listingId]], - }) -} - -/** One stargazer row: the starring identity and when the star was created. */ -export interface Stargazer { - readonly identity: string - readonly starredAt: number -} - -/** - * The stargazer list for a repo listing — the `star(listingId)` documents, newest first. - * Traverses the `(listingId, $createdAt)` index descending so the limit keeps the newest - * rows, not the oldest. - */ -export async function readStargazers( - sdk: EvoSDK, - listingId: string, - opts: { network?: Network; registryContractId?: string; limit?: number } = {}, -): Promise { - const docs = await queryDocuments(sdk, { - dataContractId: registryId(opts.network, opts.registryContractId), - documentTypeName: REGISTRY_DOC.star, - where: [['listingId', '==', listingId]], - orderBy: [ - ['listingId', 'asc'], - ['$createdAt', 'desc'], - ], - limit: opts.limit ?? 100, - }) - return docs - .map((doc: PlainDocument) => ({ - identity: typeof doc['$ownerId'] === 'string' ? doc['$ownerId'] : '', - starredAt: typeof doc['$createdAt'] === 'number' ? doc['$createdAt'] : 0, - })) - .filter((s) => s.identity !== '') -} - -/** Follower count for an identity (countable `follow(identityId)`). */ -export async function readFollowerCount( - sdk: EvoSDK, - identityId: string, - opts: { network?: Network; registryContractId?: string } = {}, -): Promise { - return countDocuments(sdk, { - dataContractId: registryId(opts.network, opts.registryContractId), - documentTypeName: REGISTRY_DOC.follow, - where: [['identityId', '==', identityId]], - }) -} - -/** Following count for an identity (countable `follow($ownerId)`). */ -export async function readFollowingCount( - sdk: EvoSDK, - identityId: string, - opts: { network?: Network; registryContractId?: string } = {}, -): Promise { - return countDocuments(sdk, { - dataContractId: registryId(opts.network, opts.registryContractId), - documentTypeName: REGISTRY_DOC.follow, - where: [['$ownerId', '==', identityId]], - }) -} - -/** Whether the given base64 token-balance encoding is nonzero (utility for callers). */ -export function balanceIsNonzero(b64: string): boolean { - const bytes = base64ToBytes(b64) - return bytes.some((b) => b !== 0) -} diff --git a/forge-web/lib/repo/config.ts b/forge-web/lib/repo/config.ts index f29ef1ae2..1d7cd9272 100644 --- a/forge-web/lib/repo/config.ts +++ b/forge-web/lib/repo/config.ts @@ -1,5 +1,5 @@ /** - * Repo config reads — the `config` append-only timeline (data-contracts §2.2/§4). + * Repo config reads — the `config` append-only timeline (`forge-v2.md` §2, §5). * * Current config = newest doc; historical configs resolve protected-ref protection as-of * any past update (fed into {@link resolveRef}). `config` is non-deletable, so the history @@ -10,7 +10,7 @@ import type { EvoSDK } from '@dashevo/evo-sdk' import { compareKey, type ConfigDoc } from '../rules' import { queryAllDocuments, queryDocumentsWithProof, type PlainDocument } from '../sdk' -import { DOC, parseJsonList, wellFormed, type RepoRef } from './contract' +import { DOC, stringArray, wellFormed, type RepoRef } from './contract' import { repoSource } from './source' /** The current repo config surface most views need. */ @@ -26,7 +26,7 @@ function toConfigDoc(doc: PlainDocument): ConfigDoc { return { id: typeof doc['$id'] === 'string' ? doc['$id'] : '', createdAt: typeof doc['$createdAt'] === 'number' ? doc['$createdAt'] : 0, - protectedPatterns: parseJsonList(doc, 'protectedPatterns'), + protectedPatterns: stringArray(doc, 'protectedPatterns') ?? [], } } @@ -44,7 +44,7 @@ function toRepoConfig(doc: PlainDocument): RepoConfig { } return { defaultBranch: typeof doc['defaultBranch'] === 'string' ? doc['defaultBranch'] : 'main', - protectedPatterns: parseJsonList(doc, 'protectedPatterns'), + protectedPatterns: stringArray(doc, 'protectedPatterns') ?? [], archived: doc['archived'] === true, backendUris, backendMode, @@ -117,13 +117,13 @@ export async function readConfigHistory(sdk: EvoSDK, repo: RepoRef): Promise { - // forge-v2 skips a malformed config (`forge-v2.md` §5), so read a few to find the newest - // well-formed one; v1 has no such rule and one row answers. + // A malformed config is skipped (`forge-v2.md` §5), so read a few to find the newest + // well-formed one. const { documents } = await queryDocumentsWithProof( sdk, repoSource(repo).repoQuery(DOC.config, { orderBy: [['$createdAt', 'desc']], - limit: repo.kind === 'v1' ? 1 : 10, + limit: 10, }), ) const doc = documents.find((d) => wellFormed(repo, 'config', d)) diff --git a/forge-web/lib/repo/contract.ts b/forge-web/lib/repo/contract.ts index 8ec8e5efb..eff416d6f 100644 --- a/forge-web/lib/repo/contract.ts +++ b/forge-web/lib/repo/contract.ts @@ -1,19 +1,19 @@ /** * Repo-contract shape constants + on-chain-document → FORGE_RULES conversions. * - * The document type names and field names mirror the repo-v1 template (data-contracts - * §2.2/§2.3), which forge-v2 kept (`docs/contracts/forge-v2.md` §2). Platform stores + * The document type names and field names are forge-v2's (`docs/contracts/forge-v2.md` §2, + * `forge-contracts/contracts/forge-core.json` / `forge-collab.json`). Platform stores * oids/hashes as byteArray (returned base64 in wasm queries); the rules layer works in hex, * so conversions normalize base64 → hex here. */ import type { ForgeIds } from '../deployments' -import type { Event, EventKind, RefUpdate, TokenKind } from '../rules' +import type { Event, EventKind, RefUpdate } from '../rules' import { isWellFormed, type ContentKind, type Visibility } from '../rules/v2' import { base58Decode, base58Encode } from '../auth/base58' import { base64ToBytes, base64ToHex, type PlainDocument } from '../sdk' -/** Repo-contract document type names (data-contracts §2.2; forge-v2 keeps them). */ +/** The per-repo document type names forge-core and forge-collab share (`forge-v2.md` §2). */ export const DOC = { config: 'config', refUpdate: 'refUpdate', @@ -32,7 +32,7 @@ export const DOC = { webhook: 'webhook', } as const -/** The forge-v2-only document types (`forge-v2.md` §2). */ +/** The forge-v2 repo, membership, author-event and social document types (`forge-v2.md` §2). */ export const V2_DOC = { repo: 'repo', maintainer: 'maintainer', @@ -42,18 +42,7 @@ export const V2_DOC = { follow: 'follow', } as const -/** Registry-contract document type names (data-contracts §1). */ -export const REGISTRY_DOC = { - repoListing: 'repoListing', - profile: 'profile', - star: 'star', - follow: 'follow', -} as const - -/** Repo token positions (§2.1). Position 0 = WRITE, 1 = MAINTAIN. */ -export const TOKEN_POSITION: Record = { write: 0, maintain: 1 } - -/** `event.kind` integer → FORGE_RULES {@link EventKind} (data-contracts §2.3). */ +/** `event.kind` integer → FORGE_RULES {@link EventKind} (`forge-v2.md` §3). */ const EVENT_KIND_BY_INT: Readonly> = { 1: 'close', 2: 'reopen', @@ -67,24 +56,11 @@ const EVENT_KIND_BY_INT: Readonly> = { 10: 'ready', } -/** - * A v1 repository: its own repo contract (template `repo-v1.json`, token ACL). Readable on - * the networks that have them (testnet); the web app's v1 writes are unchanged. - */ -export interface V1RepoRef { - readonly kind: 'v1' - readonly contractId: string - readonly ownerId: string - /** The listing's name (`''` when the repo was addressed by contract id alone). */ - readonly name: string -} - /** * A forge-v2 repository: a `repo` document in the network's shared forge-core contract, * with everything else keyed by its id (`forge-v2.md` §2). */ export interface V2RepoRef { - readonly kind: 'v2' readonly forge: ForgeIds /** The `repo` document id (base58). */ readonly repoId: string @@ -93,21 +69,20 @@ export interface V2RepoRef { readonly visibility: Visibility } -/** A repo reference: a v1 repo contract, or a forge-v2 `repo` document. */ -export type RepoRef = V1RepoRef | V2RepoRef +/** A repo reference: a forge-v2 `repo` document. */ +export type RepoRef = V2RepoRef /** The contracts a repo's reads touch, for the SDK's contract preload (none for `null`). */ export function repoContractIds(repo: RepoRef | null): string[] { - if (repo === null) return [] - return repo.kind === 'v1' ? [repo.contractId] : [repo.forge.core, repo.forge.collab] + return repo === null ? [] : [repo.forge.core, repo.forge.collab] } /** - * The stable identity of a repo within a network — the v1 contract id or the v2 `repoId`. - * Session caches (browse context, content checks, fallback clones) key by it. + * The stable identity of a repo within a network — its `repoId`. Session caches (browse + * context, content checks, fallback clones) key by it. */ export function repoKey(repo: RepoRef): string { - return repo.kind === 'v1' ? repo.contractId : repo.repoId + return repo.repoId } /** A string field, or `''` when absent or not a string. */ @@ -149,11 +124,10 @@ export function byteFieldToHex(doc: PlainDocument, field: string): string { /** * Whether a raw document is well-formed for its repo (`isWellFormed`, `forge-v2.md` §5: - * plaintext xor `enc`, the visibility says which). v1 has no such rule, so every v1 document - * passes. Every forge-v2 reader skips a malformed document before any other rule sees it. + * plaintext xor `enc`, the visibility says which). Every reader skips a malformed document + * before any other rule sees it. */ export function wellFormed(repo: RepoRef, kind: ContentKind, doc: PlainDocument): boolean { - if (repo.kind === 'v1') return true const text = (field: string): string | null => (typeof doc[field] === 'string' ? str(doc, field) : null) return isWellFormed( { @@ -211,13 +185,12 @@ export function toEvent(doc: PlainDocument): Event | null { } /** - * Normalize a document field that holds a 32-byte identifier (e.g. a repo listing's - * `repoContractId`) to its **base58** string — the form Platform contract/document APIs + * Normalize a document field that holds a 32-byte identifier (e.g. a membership's + * `memberId`) to its **base58** string — the form Platform contract/document APIs * require. A CONTENT identifier stored as a `byteArray` comes back from the SDK's `toJSON` * as **base64**, and feeding that straight to `contracts.fetch()` / a query's * `dataContractId` throws "Invalid data contract ID: … invalid character … at byte 9" (a - * browser-only failure the Playwright suite caught — `resolveRepo` fetched the repo contract - * with a base64 id and every downstream read died). Accepts an already-base58 id unchanged; + * browser-only failure the Playwright suite caught). Accepts an already-base58 id unchanged; * re-encodes a base64 32-byte value to base58; otherwise returns the raw string. */ export function asIdentifierString(v: unknown): string { @@ -235,18 +208,3 @@ export function asIdentifierString(v: unknown): string { } return v } - -/** Parse a JSON-in-string list field (data-contracts §0: no native arrays on v12). */ -export function parseJsonList(doc: PlainDocument, field: string): string[] { - const v = doc[field] - if (Array.isArray(v)) return v.filter((x): x is string => typeof x === 'string') - if (typeof v === 'string' && v.length > 0) { - try { - const parsed: unknown = JSON.parse(v) - if (Array.isArray(parsed)) return parsed.filter((x): x is string => typeof x === 'string') - } catch { - return [] - } - } - return [] -} diff --git a/forge-web/lib/repo/index.ts b/forge-web/lib/repo/index.ts index 79b637b65..eb3fc809e 100644 --- a/forge-web/lib/repo/index.ts +++ b/forge-web/lib/repo/index.ts @@ -1,25 +1,20 @@ /** * Repo read services — the TS mirror of forge-core's RepoService read API. * - * Composes the evo-sdk query layer + FORGE_RULES_V1/V2 into the reads a repo view needs: - * resolve a repo (forge-v2 `repo` document, else the v1 registry), enumerate + resolve refs, - * read config / default branch, locate browse-plane pack manifests, fold issue/PR state, - * and derive the collaborators (v2 membership documents, v1 token balances). Every query is - * built by a {@link RepoSource}, the one place the two data models differ. + * Composes the evo-sdk query layer + FORGE_RULES / FORGE_RULES_V2 into the reads a repo view + * needs: resolve a repo (its forge-core `repo` document), enumerate + resolve refs, read + * config / default branch, locate browse-plane pack manifests, fold issue/PR state, and read + * the membership documents. Every query is scoped to the repo by a {@link RepoSource}. * - * WRITE paths (forge-v2 repo creation and membership, issues, comments, events, author events, - * reviews, releases, stars, follows; v1 issue/comment/event/star/follow and token admin) sign - * + broadcast via the `./writes` WriteEngine. + * WRITE paths (repo creation and membership, issues, comments, events, author events, + * reviews, releases, stars, follows) sign + broadcast via the `./writes` WriteEngine. */ export { DOC, - REGISTRY_DOC, - TOKEN_POSITION, V2_DOC, asIdentifierString, num, - parseJsonList, str, stringArray, repoContractIds, @@ -28,24 +23,17 @@ export { toRefUpdate, wellFormed, type RepoRef, - type V1RepoRef, type V2RepoRef, } from './contract' export { CHUNK_QUERY_MAX, repoSource } from './source' export { - fetchContractOwner, readV2RepoById, resolveAnyRepo, resolveAnyRepoWith, resolveOwner, - resolveRepo, - resolveRepoByContractId, - resolveRepoListing, - resolveRepoWithListing, toV2RepoDoc, v2RefOf, type RepoAddressParams, - type RepoListing, type ResolvedRepo, type V2RepoDoc, } from './resolveRepo' @@ -82,13 +70,10 @@ export { type ResolvedRef, } from './refs' export { - liveGitPackManifests, - liveLocatorManifests, readNewestFlatIndexManifest, readNewestLocatorManifest, readNewestManifestOfKind, readPackManifests, - isV2Copies, readRepoPackManifests, readV2PackCopies, v2PacksOfKind, @@ -96,14 +81,6 @@ export { type PackManifest, } from './packs' export { - currentHoldings, - invalidateAuthz, - readTokenHistory, - readViewerHoldings, - resolveAuthz, -} from './tokens' -export { - emptyAuthz, historicalTipsPredicate, listIssues, listPulls, @@ -122,22 +99,9 @@ export { type TargetLog, type VerdictName, } from './issues' -export { - balanceIsNonzero, - candidateCollaborators, - readCollaborators, - readFollowerCount, - readFollowingCount, - readStarCount, - readStargazers, - repoTokenIds, - type Collaborator, - type Stargazer, -} from './collab' export { addAuthorEvent, addEvent, - adminCollaborator, checkRepoInput, createComment, createIssue, diff --git a/forge-web/lib/repo/issues.ts b/forge-web/lib/repo/issues.ts index 74951327b..bfef16c27 100644 --- a/forge-web/lib/repo/issues.ts +++ b/forge-web/lib/repo/issues.ts @@ -1,34 +1,20 @@ /** - * Issue / PR reads — list + fold (data-contracts §2.3, §4; `forge-v2.md` §3, §5, §6). + * Issue / PR reads — list + fold (`forge-v2.md` §3, §5, §6). * - * forge-v2 repos fold `event` + `authorEvent` through FORGE_RULES_V2 (`foldIssueStateV2` / - * `foldPrStateV2`): an event's existence is its authorization, so no ACL history is read. - * Lists read the repo's two feeds (`(repoId, $createdAt)`) once and fold every row from them, - * rather than two queries per row. Documents that are not well-formed for the repo's - * visibility (`isWellFormed`: plaintext xor `enc`) are skipped everywhere. The rest of this - * note describes v1. - * - * Issue/PR *state* is not an on-chain field (mutation ownership forbids a maintainer - * editing an author-owned doc); it is a deterministic fold of the append-only `event` log - * via {@link foldIssueState} / {@link foldPrState}. Spam events from non-holders exist but - * are inert. Actor authorization is evaluated **as-of** each event's `$createdAt` from the - * token-history — supplied here as an {@link AuthzResolver}. - * - * TOKEN-HISTORY WIRING: the as-of WRITE/MAINTAIN holdings come from the system token-history - * contract (mint/freeze/unfreeze/destroy), reconstructed by {@link resolveAuthz} / - * {@link readTokenHistory}. Each read below resolves that history once (when the caller does - * not supply an {@link AuthzResolver}) so holder-gated actions — a non-author maintainer's - * close / label / merge — fold correctly. If the history read fails the resolver is empty and - * the fold still honors the target author's own close/reopen (graceful degradation). + * Issue/PR *state* is not an on-chain field (mutation ownership forbids a maintainer editing + * an author-owned doc); it is a deterministic fold of the append-only `event` + `authorEvent` + * logs through FORGE_RULES_V2 (`foldIssueStateV2` / `foldPrStateV2`). `event` is member-gated + * and `authorEvent` author-gated at consensus, so an event's existence is its authorization + * and no ACL history is read. Lists read the repo's two feeds (`(repoId, $createdAt)`) once + * and fold every row from them, rather than two queries per row. Documents that are not + * well-formed for the repo's visibility (`isWellFormed`: plaintext xor `enc`) are skipped + * everywhere. */ import type { EvoSDK } from '@dashevo/evo-sdk' import { - AuthzResolver, compareKey, - foldIssueState, - foldPrState, isNullOid, type Event, type IsAncestor, @@ -53,19 +39,12 @@ import { V2_DOC, wellFormed, type RepoRef, - type V2RepoRef, } from './contract' import { readRefUpdates } from './refs' import { readRoleOracle } from './members' import { repoSource } from './source' -import { resolveAuthz } from './tokens' import { base64ToHex } from '../sdk' -/** An empty authorization resolver (target-author actions only; token history unavailable). */ -export function emptyAuthz(): AuthzResolver { - return new AuthzResolver([]) -} - /** A row's title; ciphertext (a private repo's, which this client cannot decrypt) says so. */ function titleOf(doc: PlainDocument): string { const title = str(doc, 'title') @@ -121,8 +100,8 @@ export interface PullView { readonly baseOidAtOpen: string readonly headOid: string /** - * Where the PR's objects actually live: the **source** repo contract id (v1) or `repo` - * document id (v2 `sourceRepoId`), base58. + * Where the PR's objects actually live: the **source** `repo` document id + * (`sourceRepoId`), base58. * * Surfaced because a reviewer cannot fetch a PR without it: a PR's head commit usually * sits in a different repo (a fork) from the one it targets, and this is the only pointer @@ -134,7 +113,7 @@ export interface PullView { /** * Whether {@link headOid} has been a tip of the base ref — the exact test the fold applies * to a `merge` event naming the head, so a merge mark will count iff this is true (and the - * marker holds WRITE or MAINTAIN). False when the base history or head is unknown. + * marker is a writer or maintainer). False when the base history or head is unknown. */ readonly headOnBase: boolean /** Archived from another forge (`imported` provenance present) rather than opened here. */ @@ -193,13 +172,11 @@ export interface ReviewView { * * COMPLETENESS IS LOAD-BEARING, not a nicety. `foldIssueState` / `foldPrState` are folds * over the whole log: a close at row 101 that never arrives leaves the issue open forever. - * `event` carries no `tokenCost` in the repo contract template, so anyone can append — - * a stranger padding a fresh issue with 100 inert events would permanently freeze its - * displayed state if this read stopped at one page. It pages to exhaustion, and + * It pages to exhaustion, and * {@link queryAllDocuments} throws rather than returning a short answer if it cannot * prove it reached the end. Parity: forge-core `CollabEngine::fetch_events` uses - * `query_all_documents` for exactly this reason. On forge-v2 the log is `event` and - * `authorEvent` merged in `($createdAt, $id)` order ({@link readTargetLog} keeps them apart). + * `query_all_documents` for exactly this reason. The log is `event` and `authorEvent` merged + * in `($createdAt, $id)` order ({@link readTargetLog} keeps them apart). */ export async function readEvents(sdk: EvoSDK, repo: RepoRef, targetId: string): Promise { const log = await readTargetLog(sdk, repo, targetId) @@ -207,9 +184,9 @@ export async function readEvents(sdk: EvoSDK, repo: RepoRef, targetId: string): } /** - * A target's state documents, by the type that admitted them. v1 has only `event`; forge-v2 - * splits member events (`event`) from the author's own close/reopen (`authorEvent`, - * `forge-v2.md` §3), and the v2 fold needs to know which is which. + * A target's state documents, by the type that admitted them: member events (`event`) and + * the author's own close/reopen (`authorEvent`, `forge-v2.md` §3). The fold needs to know + * which is which. */ export interface TargetLog { readonly events: Event[] @@ -229,7 +206,7 @@ const FEED_TTL_MS = 30_000 const feedCache = new Map | null> }>() /** {@link readRepoFeed} through a short per-repo cache (issues and pulls pages share it). */ -function readRepoFeedCached(sdk: EvoSDK, repo: V2RepoRef): Promise | null> { +function readRepoFeedCached(sdk: EvoSDK, repo: RepoRef): Promise | null> { const key = `${repo.forge.collab}:${repo.repoId}` const hit = feedCache.get(key) if (hit !== undefined && Date.now() - hit.at < FEED_TTL_MS) return hit.promise @@ -241,8 +218,8 @@ function readRepoFeedCached(sdk: EvoSDK, repo: V2RepoRef): Promise | null> { +async function readRepoFeed(sdk: EvoSDK, repo: RepoRef): Promise | null> { const source = repoSource(repo) const read = async (type: string): Promise => toEvents( @@ -318,8 +294,8 @@ async function readRepoFeed(sdk: EvoSDK, repo: V2RepoRef): Promise { @@ -348,26 +324,19 @@ export async function readReviews(sdk: EvoSDK, repo: RepoRef, patchId: string): } /** - * Read one issue and fold its state. v1 resolves the token-history authz when not supplied; - * forge-v2 needs no ACL (`log`, when given, is the target's slice of the repo feed). + * Read one issue and fold its state (`log`, when given, is the target's slice of the repo + * feed). */ export async function readIssue( sdk: EvoSDK, repo: RepoRef, issueDoc: PlainDocument, - authz?: AuthzResolver, log?: TargetLog, ): Promise { const id = str(issueDoc, '$id') const author = str(issueDoc, '$ownerId') - let state: IssueState - if (repo.kind === 'v1') { - const resolver = authz ?? (await resolveAuthz(sdk, repo)) - state = foldIssueState(await readEvents(sdk, repo, id), author, resolver) - } else { - const l = log ?? (await readTargetLog(sdk, repo, id)) - state = foldIssueStateV2(l.events, l.authorEvents, author) - } + const l = log ?? (await readTargetLog(sdk, repo, id)) + const state: IssueState = foldIssueStateV2(l.events, l.authorEvents, author) return { id, number: num(issueDoc, 'number'), @@ -385,7 +354,7 @@ const LIST_MAX_PAGES = 5 /** * The newest `limit` issues or patches of a repo, `$createdAt` descending, and how many were - * skipped on the way. forge-v2 skips documents that are not well-formed for the repo's + * skipped on the way. It skips documents that are not well-formed for the repo's * visibility (`forge-v2.md` §5), and in a private repo also ciphertext from non-members: this * client decrypts nothing yet, and §5 shows a stranger's ciphertext to no one. Skipped rows do * not shorten the page: the read continues (newest-first, by a `$createdAt <` bound, so no @@ -397,7 +366,7 @@ async function newestTargets( type: 'issue' | 'patch', limit: number, ): Promise<{ documents: PlainDocument[]; hidden: number }> { - const oracle = repo.kind === 'v2' && repo.visibility === 'private' ? await readRoleOracle(sdk, repo) : null + const oracle = repo.visibility === 'private' ? await readRoleOracle(sdk, repo) : null const shown = (d: PlainDocument): boolean => { if (!wellFormed(repo, type, d)) return false // Private: only members' ciphertext is shown (as encrypted); strangers' is hidden. @@ -425,8 +394,8 @@ async function newestTargets( if (shown(d)) out.push(d) else hidden++ } - // v1 has no hidden rows, so one page answers; a short page is the end of the list. - if (repo.kind === 'v1' || documents.length < limit) break + // A short page is the end of the list. + if (documents.length < limit) break const oldest = documents[documents.length - 1]?.['$createdAt'] if (typeof oldest !== 'number' || oldest === before) break before = oldest @@ -435,9 +404,9 @@ async function newestTargets( } /** - * Fold a page of issue or patch rows. forge-v2: from the repo feed, read once for the whole - * page. v1: one row at a time, keeping a row (state unverified) whose event log cannot be read - * to completion. + * Fold a page of issue or patch rows from the repo feed, read once for the whole page — or, + * when the feed is too large, one row at a time, keeping a row (state unverified) whose event + * log cannot be read to completion. */ async function foldRows( sdk: EvoSDK, @@ -446,14 +415,14 @@ async function foldRows( foldOne: (doc: PlainDocument, log: TargetLog | undefined) => Promise, incomplete: (doc: PlainDocument) => T, ): Promise { - // forge-v2: fold from the repo feed while it is small; otherwise (feed = null) each row - // reads its own target log, as v1 does. - const feed = repo.kind === 'v2' && documents.length > 0 ? await readRepoFeedCached(sdk, repo) : null - // Per-row tolerance. `issue`, `event` and `comment` are un-gated, so one target padded - // past the reader's completeness bound must not take down a whole page of issues — and + // Fold from the repo feed while it is small; otherwise (feed = null) each row reads its own + // target log. + const feed = documents.length > 0 ? await readRepoFeedCached(sdk, repo) : null + // Per-row tolerance. One target padded past the reader's completeness bound must not take + // down a whole page of issues — and // dropping the row silently would be the same class of bug this all fixes. The row is // kept with `stateComplete: false`; callers render the state as unverified. (A PR row also - // reads its base ref's history, which can fail the same way, on either model.) + // reads its base ref's history, which can fail the same way.) return Promise.all( documents.map((doc) => foldOne(doc, feed === null ? undefined : feed.get(str(doc, '$id')) ?? EMPTY_LOG).catch((e: unknown) => { @@ -464,20 +433,18 @@ async function foldRows( ) } -/** List issues (newest first) with folded state. Resolves the v1 authz once for the page. */ +/** List issues (newest first) with folded state. */ export async function listIssues( sdk: EvoSDK, repo: RepoRef, - authz?: AuthzResolver, limit = 50, ): Promise> { - const resolver = repo.kind === 'v1' ? authz ?? (await resolveAuthz(sdk, repo)) : undefined const { documents, hidden } = await newestTargets(sdk, repo, 'issue', limit) const rows = await foldRows( sdk, repo, documents, - (doc, log) => readIssue(sdk, repo, doc, resolver, log), + (doc, log) => readIssue(sdk, repo, doc, log), incompleteIssueView, ) return Object.assign(rows, { hidden }) @@ -498,7 +465,7 @@ function incompleteIssueView(doc: PlainDocument): IssueView { } /** - * A historical-tips merge predicate for {@link foldPrState}: a merge oid stays valid once + * A historical-tips merge predicate for `foldPrStateV2`: a merge oid stays valid once * the base ref advances past it, so the predicate tests membership in the set of every tip * the base ref has EVER had — not reflexive equality (the BLOCKER-1 fix). Built from the * base ref's full `refUpdate`/`protectedRefUpdate` history. @@ -516,9 +483,9 @@ function readImported(doc: PlainDocument): { imported: boolean; importedUrl: str return { imported: true, importedUrl: typeof url === 'string' ? url : '' } } -/** A patch's source pointer: v1 `sourceContractId`, forge-v2 `sourceRepoId`. */ -function sourceIdOf(repo: RepoRef, doc: PlainDocument): string { - return asIdentifierString(doc[repo.kind === 'v1' ? 'sourceContractId' : 'sourceRepoId']) +/** A patch's source pointer (`sourceRepoId`). */ +function sourceIdOf(doc: PlainDocument): string { + return asIdentifierString(doc['sourceRepoId']) } /** A base ref's tips, as a PR read needs them. */ @@ -556,7 +523,6 @@ export async function readPull( sdk: EvoSDK, repo: RepoRef, patchDoc: PlainDocument, - authz?: AuthzResolver, log?: TargetLog, ): Promise { const id = str(patchDoc, '$id') @@ -574,14 +540,8 @@ export async function readPull( } const baseTip = tips.tip - let state: PrState - if (repo.kind === 'v1') { - const resolver = authz ?? (await resolveAuthz(sdk, repo)) - state = foldPrState(await readEvents(sdk, repo, id), author, resolver, baseTip, isAncestor) - } else { - const l = log ?? (await readTargetLog(sdk, repo, id)) - state = foldPrStateV2(l.events, l.authorEvents, author, baseTip, isAncestor) - } + const l = log ?? (await readTargetLog(sdk, repo, id)) + const state: PrState = foldPrStateV2(l.events, l.authorEvents, author, baseTip, isAncestor) let headOid = '' if (typeof baseHeadOidRaw === 'string' && baseHeadOidRaw.length > 0) { try { @@ -602,7 +562,7 @@ export async function readPull( baseTipOid: baseTip ?? '', baseOidAtOpen: tips.atOpen ?? baseTip ?? '', headOid, - sourceId: sourceIdOf(repo, patchDoc), + sourceId: sourceIdOf(patchDoc), sourceRefName: typeof patchDoc['sourceRefName'] === 'string' ? patchDoc['sourceRefName'] : null, headOnBase: headOid !== '' && baseTip !== undefined && isAncestor(headOid, baseTip), ...readImported(patchDoc), @@ -611,27 +571,25 @@ export async function readPull( } } -/** List PRs (patches, newest first) with folded state. Resolves the v1 authz once for the page. */ +/** List PRs (patches, newest first) with folded state. */ export async function listPulls( sdk: EvoSDK, repo: RepoRef, - authz?: AuthzResolver, limit = 50, ): Promise> { - const resolver = repo.kind === 'v1' ? authz ?? (await resolveAuthz(sdk, repo)) : undefined const { documents, hidden } = await newestTargets(sdk, repo, 'patch', limit) const rows = await foldRows( sdk, repo, documents, - (doc, log) => readPull(sdk, repo, doc, resolver, log), - (doc) => incompletePullView(repo, doc), + (doc, log) => readPull(sdk, repo, doc, log), + incompletePullView, ) return Object.assign(rows, { hidden }) } /** A PR row whose event log could not be read completely: identity only, no folded state. */ -function incompletePullView(repo: RepoRef, doc: PlainDocument): PullView { +function incompletePullView(doc: PlainDocument): PullView { let headOid = '' const raw = doc['headOid'] if (typeof raw === 'string' && raw.length > 0) { @@ -655,7 +613,7 @@ function incompletePullView(repo: RepoRef, doc: PlainDocument): PullView { headOid, // The source pointer is plain document content, not a fold — it is readable even when // the event log is not, and it is what a reviewer needs to fetch the PR at all. - sourceId: sourceIdOf(repo, doc), + sourceId: sourceIdOf(doc), sourceRefName: typeof doc['sourceRefName'] === 'string' ? doc['sourceRefName'] : null, headOnBase: false, ...readImported(doc), diff --git a/forge-web/lib/repo/live.test.ts b/forge-web/lib/repo/live.test.ts deleted file mode 100644 index 4939926f0..000000000 --- a/forge-web/lib/repo/live.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Live testnet smoke test — SKIPPED by default (needs network + WASM). - * - * Run with: FORGE_LIVE=1 pnpm exec vitest run lib/repo/live.test.ts - * - * Proves the read stack talks to the deployed registry: connect via testnetTrusted(), - * query the registry `repoListing` type with a proof, and — if any listing exists — - * resolve its repo contract owner. A bonus check; never gates CI (WASM/network flaky). - */ - -import { describe, expect, it } from 'vitest' - -import { NETWORKS } from '../constants' -import { evoSdkService } from '../sdk' -import { queryDocumentsWithProof } from '../sdk' -import { REGISTRY_DOC } from './contract' -import { resolveRepoByContractId } from './resolveRepo' - -const LIVE = process.env['FORGE_LIVE'] === '1' - -describe.skipIf(!LIVE)('live testnet reads', () => { - it( - 'connects and queries the deployed registry', - async () => { - const registryId = NETWORKS.testnet.registryContractId - expect(registryId).not.toBeNull() - - await evoSdkService.initialize({ - network: 'testnet', - contractIds: registryId ? [registryId] : [], - timeoutMs: 15000, - }) - const sdk = evoSdkService.getSdk() - - const { documents } = await queryDocumentsWithProof(sdk, { - dataContractId: registryId as string, - documentTypeName: REGISTRY_DOC.repoListing, - orderBy: [['$createdAt', 'desc']], - limit: 5, - }) - // Zero listings is a valid result on a fresh registry; the point is a proof-verified - // round-trip that did not throw. - expect(Array.isArray(documents)).toBe(true) - - const first = documents[0] - if (first && typeof first['repoContractId'] === 'string') { - const repo = await resolveRepoByContractId(sdk, first['repoContractId']) - expect(repo === null || typeof repo.ownerId === 'string').toBe(true) - } - }, - 30000, - ) -}) diff --git a/forge-web/lib/repo/members.ts b/forge-web/lib/repo/members.ts index 4c57f2609..def05dc6a 100644 --- a/forge-web/lib/repo/members.ts +++ b/forge-web/lib/repo/members.ts @@ -1,13 +1,11 @@ /** * forge-v2 membership reads — who is a maintainer or writer of a repo (`forge-v2.md` §2, §6). * - * A v2 repo's ACL is its current `maintainer` and `writer` documents in forge-core: the owner + * A repo's ACL is its current `maintainer` and `writer` documents in forge-core: the owner * creates them, deleting one revokes it, and consensus gates every write-path type on them. * The client rules that still need membership — approvals, pack-copy order, and which * controls the UI offers — read it through {@link RoleOracle} (FORGE_RULES_V2). - * - * v1 repos have no membership documents; their ACL is the WRITE/MAINTAIN token history - * (`./tokens`). {@link readViewerPermissions} answers "what may this viewer do" for both. + * {@link readViewerPermissions} answers "what may this viewer do". */ import type { EvoSDK } from '@dashevo/evo-sdk' @@ -17,9 +15,8 @@ import type { ForgeIds } from '../deployments' import type { Holdings } from '../rules' import { RoleOracle, type Membership, type Role } from '../rules/v2' import { queryAllDocuments, type PlainDocument } from '../sdk' -import { V2_DOC, asIdentifierString, type RepoRef, type V2RepoRef } from './contract' +import { V2_DOC, asIdentifierString, type RepoRef } from './contract' import { repoSource } from './source' -import { readViewerHoldings } from './tokens' const ROLES: readonly Role[] = ['maintainer', 'writer'] const ROLE_DOC: Readonly> = { maintainer: V2_DOC.maintainer, writer: V2_DOC.writer } @@ -39,11 +36,11 @@ function toMembership(doc: PlainDocument, role: Role): Membership | null { } /** - * Every current membership document of a v2 repo, maintainers first. Complete (paged): + * Every current membership document of a repo, maintainers first. Complete (paged): * approvals and pack-copy order fold over it, and a member missing from it would read as a * stranger. */ -export async function readMemberships(sdk: EvoSDK, repo: V2RepoRef): Promise { +export async function readMemberships(sdk: EvoSDK, repo: RepoRef): Promise { const source = repoSource(repo) const perRole = await Promise.all( ROLES.map(async (role) => { @@ -60,18 +57,18 @@ export async function readMemberships(sdk: EvoSDK, repo: V2RepoRef): Promise }>() -function membersKey(network: Network, repo: V2RepoRef): string { +function membersKey(network: Network, repo: RepoRef): string { return `${network}:${repo.forge.core}:${repo.repoId}` } /** {@link readMemberships} through the per-repo session cache. */ export function readMembershipsCached( sdk: EvoSDK, - repo: V2RepoRef, + repo: RepoRef, network: Network = DEFAULT_NETWORK, ): Promise { const key = membersKey(network, repo) @@ -85,32 +82,31 @@ export function readMembershipsCached( return promise } -/** Drop a repo's cached membership (for tests now; for member add/revoke with v2 writes). */ -export function invalidateMembers(repo: V2RepoRef, network: Network = DEFAULT_NETWORK): void { +/** Drop a repo's cached membership (tests; and after a member add/revoke). */ +export function invalidateMembers(repo: RepoRef, network: Network = DEFAULT_NETWORK): void { membersCache.delete(membersKey(network, repo)) } -/** A v2 repo's {@link RoleOracle}, from the cached membership. */ +/** A repo's {@link RoleOracle}, from the cached membership. */ export async function readRoleOracle( sdk: EvoSDK, - repo: V2RepoRef, + repo: RepoRef, network: Network = DEFAULT_NETWORK, ): Promise { return new RoleOracle(await readMembershipsCached(sdk, repo, network)) } /** - * A role as the v1-shaped {@link Holdings} the UI gates on: a writer may push and act on - * issues and PRs (`write`); a maintainer may also do what v1 reserved for MAINTAIN (protected - * refs, config, releases). + * A role as the {@link Holdings} the UI gates on: a writer may push and act on issues and PRs + * (`write`); a maintainer may also push protected refs and change config and releases + * (`maintain`). */ export function holdingsOfRole(role: Role | null): Holdings { return { write: role !== null, maintain: role === 'maintainer' } } /** - * What `identity` may do on `repo` now: v1 from the token history, v2 from the membership - * documents. `null` means the ACL could not be read — "unknown" stays distinct from "none", + * What `identity` may do on `repo` now, from its membership documents. `null` means the ACL could not be read — "unknown" stays distinct from "none", * so a read failure never strips a maintainer's controls or grants a stranger's. */ export async function readViewerPermissions( @@ -119,7 +115,6 @@ export async function readViewerPermissions( identity: string, network: Network = DEFAULT_NETWORK, ): Promise { - if (repo.kind === 'v1') return readViewerHoldings(sdk, repo, identity, network) try { const oracle = await readRoleOracle(sdk, repo, network) return holdingsOfRole(oracle.currentRole(identity)) diff --git a/forge-web/lib/repo/packs.test.ts b/forge-web/lib/repo/packs.test.ts index da887de13..6323c9097 100644 --- a/forge-web/lib/repo/packs.test.ts +++ b/forge-web/lib/repo/packs.test.ts @@ -1,25 +1,25 @@ /** - * packManifest parsing + live-set correctness. + * packManifest parsing. * * On-chain `tips` / `supersedes` are PACKED byteArrays (concatenated 20-/32-byte entries, - * surfaced as base64 — data-contracts §2.3), not JSON lists; parsing them wrong makes - * `supersedes` silently empty, which would let superseded packs leak into the fallback - * clone's live set. `liveGitPackManifests` mirrors forge-core `repo.rs::live_kind0_manifests`. + * surfaced as base64), not lists; parsing them wrong makes `supersedes` silently empty, which + * would let a superseded pack look current. `uris` is a native string array. */ import type { EvoSDK } from '@dashevo/evo-sdk' import { describe, expect, it } from 'vitest' import { bytesToBase64 } from '../sdk' -import { - liveGitPackManifests, - liveLocatorManifests, - readPackManifests, - type PackManifest, -} from './packs' -import type { V1RepoRef } from './contract' - -const REPO: V1RepoRef = { kind: 'v1', contractId: 'contract', ownerId: 'owner', name: '' } +import { readPackManifests } from './packs' +import type { RepoRef } from './contract' + +const REPO: RepoRef = { + forge: { core: 'CORE', collab: 'COLLAB', group: 'G' }, + repoId: 'R', + ownerId: 'owner', + name: 'n', + visibility: 'public', +} /** A 32-byte (or `len`-byte) hash filled with `seed`, as hex. */ function hashHex(seed: number, len = 32): string { @@ -30,24 +30,6 @@ function hashBytes(seed: number, len = 32): Uint8Array { return new Uint8Array(len).fill(seed) } -function manifest(overrides: Partial): PackManifest { - return { - packHash: 'aa', - kind: 0, - sizeBytes: 0, - objectCount: 0, - chunkCount: 0, - storage: 0, - uris: [], - tips: [], - supersedes: [], - createdAt: 0, - documentId: 'd', - uploader: 'owner', - ...overrides, - } -} - /** A mock SDK whose packManifest query returns the given raw docs. */ function mockSdk(docs: Record[]): EvoSDK { return { @@ -81,10 +63,10 @@ describe('packed byteArray parsing (tips / supersedes)', () => { expect(docs[0]?.tips).toEqual([hashHex(0x33, 20)]) }) - it('falls back to the legacy JSON-list shape and tolerates absent fields', async () => { + it('reads native uris and tolerates absent or malformed fields', async () => { const docs = await readPackManifests( mockSdk([ - { packHash: bytesToBase64(hashBytes(0xaa)), kind: 0, supersedes: '["deadbeef"]' }, + { packHash: bytesToBase64(hashBytes(0xaa)), kind: 0, uris: ['https://m/p.pack'], supersedes: bytesToBase64(new Uint8Array(5)) }, { packHash: bytesToBase64(hashBytes(0xbb)), kind: 0 }, ]), REPO, @@ -92,71 +74,10 @@ describe('packed byteArray parsing (tips / supersedes)', () => { // The read's row order is the reader's concern (it pages ascending and reverses); look // the rows up by pack instead of by position. const byPack = (b: number) => docs.find((d) => d.packHash === hashHex(b)) - expect(byPack(0xaa)?.supersedes).toEqual(['deadbeef']) + expect(byPack(0xaa)?.uris).toEqual(['https://m/p.pack']) + expect(byPack(0xaa)?.supersedes).toEqual([]) expect(byPack(0xbb)?.supersedes).toEqual([]) expect(byPack(0xbb)?.tips).toEqual([]) - }) -}) - -describe('liveGitPackManifests', () => { - it('excludes superseded kind-0 packs and non-kind-0 manifests', () => { - const old = manifest({ packHash: hashHex(0x01), documentId: 'a' }) - const repacked = manifest({ - packHash: hashHex(0x02), - supersedes: [hashHex(0x01)], - documentId: 'b', - uploader: 'owner', - }) - const locator = manifest({ packHash: hashHex(0x03), kind: 1, documentId: 'c' }) - - const live = liveGitPackManifests([locator, repacked, old]) - expect(live.map((m) => m.packHash)).toEqual([hashHex(0x02)]) - }) - - it('honors supersedes carried on a non-kind-0 manifest', () => { - const pack = manifest({ packHash: hashHex(0x01), documentId: 'a' }) - const locator = manifest({ - packHash: hashHex(0x03), - kind: 1, - supersedes: [hashHex(0x01)], - documentId: 'c', - uploader: 'owner', - }) - expect(liveGitPackManifests([pack, locator])).toEqual([]) - }) - - it('is non-transitive and case-insensitive on hashes', () => { - const a = manifest({ packHash: hashHex(0x01).toUpperCase(), documentId: 'a' }) - const b = manifest({ packHash: hashHex(0x02), supersedes: [hashHex(0x01)], documentId: 'b' }) - // b supersedes a; nothing supersedes b — b is live even though it references a chain. - expect(liveGitPackManifests([a, b]).map((m) => m.documentId)).toEqual(['b']) - }) -}) - -describe('liveLocatorManifests', () => { - it('returns live index fragments newest-first, dropping superseded ones', () => { - // A repo between repacks has several live fragments — one per push — and the reader - // merges them oldest-first, so the order this returns is load-bearing. - const first = manifest({ packHash: hashHex(0x01), kind: 1, createdAt: 100, documentId: 'a' }) - const second = manifest({ packHash: hashHex(0x02), kind: 1, createdAt: 200, documentId: 'b' }) - const folded = manifest({ - packHash: hashHex(0x03), - kind: 1, - createdAt: 300, - documentId: 'c', - uploader: 'owner', - supersedes: [hashHex(0x01)], - }) - const gitPack = manifest({ packHash: hashHex(0x04), createdAt: 400, documentId: 'd' }) - - expect(liveLocatorManifests([gitPack, first, second, folded]).map((m) => m.documentId)).toEqual( - ['c', 'b'], - ) - }) - - it('breaks $createdAt ties by documentId, descending', () => { - const a = manifest({ packHash: hashHex(0x01), kind: 1, createdAt: 100, documentId: 'aa' }) - const b = manifest({ packHash: hashHex(0x02), kind: 1, createdAt: 100, documentId: 'bb' }) - expect(liveLocatorManifests([a, b]).map((m) => m.documentId)).toEqual(['bb', 'aa']) + expect(byPack(0xbb)?.uris).toEqual([]) }) }) diff --git a/forge-web/lib/repo/packs.ts b/forge-web/lib/repo/packs.ts index 7bf1faecd..237bdf020 100644 --- a/forge-web/lib/repo/packs.ts +++ b/forge-web/lib/repo/packs.ts @@ -1,5 +1,5 @@ /** - * packManifest reads — locating browse-plane artifacts (data-contracts §2.3). + * packManifest reads — locating browse-plane artifacts (`forge-v2.md` §4). * * `packManifest.kind`: 0 = git pack, 1 = objectLocator, 2 = flatIndex. The `(kind, * $createdAt desc)` index lets a reader grab the newest locator / flatIndex in one query. @@ -13,7 +13,7 @@ import { bytesToHex } from '@noble/hashes/utils.js' import { PACK_KIND, type PackKind } from '../constants' import { queryAllDocuments, queryDocumentsWithProof, type PlainDocument } from '../sdk' import { v2PackList, type Role } from '../rules/v2' -import { DOC, parseJsonList, str, type RepoRef, type V2RepoRef } from './contract' +import { DOC, str, stringArray, type RepoRef } from './contract' import { base64ToBytes, base64ToHex, hexToBase64 } from '../sdk' import { readRoleOracle } from './members' import { repoSource } from './source' @@ -37,29 +37,28 @@ export interface PackManifest { readonly supersedes: readonly string[] /** Consensus `$createdAt` (ms) — the primary key for the packRef total order. */ readonly createdAt: number - /** Document `$id` (base58) — the `($createdAt, $id)` tiebreak (data-contracts §2.3). */ + /** Document `$id` (base58) — the `($createdAt, $id)` tiebreak. */ readonly documentId: string /** - * The manifest's `$ownerId` — who uploaded this copy. On forge-v2 chunks are keyed by it + * The manifest's `$ownerId` — who uploaded this copy. Chunks are keyed by it * (`(repoId, $ownerId, packHash, seq)`), so a chunk read must name it. */ readonly uploader: string /** - * forge-v2: every writer's copy of this pack, in the order a reader tries them - * (`orderPackCopies`: current maintainers, then writers, then everyone else; each by - * `($createdAt, $id)`), this manifest first. A read falls through to the next copy when one - * cannot be read or does not verify (`forge-v2.md` §4). Absent on v1, where `packHash` is - * unique. + * Every writer's copy of this pack, in the order a reader tries them (`orderPackCopies`: + * current maintainers, then writers, then everyone else; each by `($createdAt, $id)`), this + * manifest first. A read falls through to the next copy when one cannot be read or does not + * verify (`forge-v2.md` §4). Absent on a raw manifest row. */ readonly copies?: readonly PackManifest[] - /** forge-v2 raw copies: the uploader's current role (null: not a member). Absent on v1. */ + /** Raw copies: the uploader's current role (null: not a member). */ readonly ownerRole?: Role | null } /** - * Parse a packed byteArray field (concatenated fixed-width entries, surfaced as base64 — - * data-contracts §2.3: `tips` = 20-byte oids, `supersedes` = 32-byte pack hashes) into - * hex strings. Falls back to the legacy JSON-in-string list shape. + * Parse a packed byteArray field (concatenated fixed-width entries, surfaced as base64: + * `tips` = 20-byte oids, `supersedes` = 32-byte pack hashes) into hex strings; `[]` when + * absent or malformed. */ function parsePackedHashes(doc: PlainDocument, field: string, entryLen: number): string[] { const v = doc[field] @@ -74,10 +73,10 @@ function parsePackedHashes(doc: PlainDocument, field: string, entryLen: number): return out } } catch { - /* not base64 — fall through to the legacy JSON-list shape */ + /* not base64 */ } } - return parseJsonList(doc, field) + return [] } function toManifest(doc: PlainDocument): PackManifest { @@ -98,8 +97,7 @@ function toManifest(doc: PlainDocument): PackManifest { objectCount: num('objectCount'), chunkCount: num('chunkCount'), storage: num('storage'), - // v1: JSON-in-string; forge-v2: a typed string array. parseJsonList reads both. - uris: parseJsonList(doc, 'uris'), + uris: stringArray(doc, 'uris') ?? [], tips: parsePackedHashes(doc, 'tips', 20), supersedes: parsePackedHashes(doc, 'supersedes', 32), createdAt: num('$createdAt'), @@ -112,8 +110,8 @@ function toManifest(doc: PlainDocument): PackManifest { * List **every** pack manifest, newest first. * * Completeness is load-bearing for a nastier reason than staleness. A locator addresses - * pack bytes by `packRef` = the pack's index in oldest-first `($createdAt, $id)` order (see - * {@link orderGitPacks}). Drop the oldest manifests — which is exactly what a capped + * pack bytes by `packRef` = the pack's index in first-upload `($createdAt, $id)` order (see + * {@link v2PacksOfKind}). Drop the oldest manifests — which is exactly what a capped * newest-first page does once a repo passes one page — and every `packRef` shifts: lookups * then read a valid offset in the WRONG pack and return corrupt objects, with nothing in the * reader able to detect the misalignment. The fallback-clone path degrades the same way, @@ -131,11 +129,11 @@ export async function readPackManifests(sdk: EvoSDK, repo: RepoRef): Promise m.ownerRole !== undefined) -} - /** - * Every pack manifest of a repo, newest first: v1 as stored; forge-v2 as raw copies, each - * tagged with its uploader's current role so {@link v2PacksOfKind} can rank them. + * Every pack manifest of a repo, newest first, as raw copies — each tagged with its + * uploader's current role so {@link v2PacksOfKind} can rank them. */ export async function readRepoPackManifests(sdk: EvoSDK, repo: RepoRef): Promise { - if (repo.kind === 'v1') return readPackManifests(sdk, repo) const [manifests, oracle] = await Promise.all([ readPackManifests(sdk, repo), readRoleOracle(sdk, repo), @@ -198,13 +190,13 @@ export async function readRepoPackManifests(sdk: EvoSDK, repo: RepoRef): Promise } /** - * forge-v2: every writer's copy of `packHash` (`(repoId, packHash)` index), ranked for + * Every writer's copy of `packHash` (`(repoId, packHash)` index), ranked for * reading, as one manifest with `copies` — or null when no copy claims `kind`. Independent of * how many other packs the repo holds. */ export async function readV2PackCopies( sdk: EvoSDK, - repo: V2RepoRef, + repo: RepoRef, packHashHex: string, kind: number, ): Promise { @@ -247,50 +239,6 @@ export function readNewestLocatorManifest(sdk: EvoSDK, repo: RepoRef): Promise

() - for (const m of manifests) { - for (const h of m.supersedes) superseded.add(h.toLowerCase()) - } - return manifests.filter( - (m) => m.kind === PACK_KIND.GIT_PACK && !superseded.has(m.packHash.toLowerCase()), - ) -} - -/** - * The live (non-superseded) `objectLocator` manifests among `manifests`, NEWEST-FIRST — the - * index fragments a reader merges. Mirror of forge-core `repo.rs::live_locator_manifests`. - * - * There is normally more than one: a push publishes a locator over just the pack it stored, - * so the index accumulates fragments between repacks (see forge-core - * `RepoService::publish_push_locator` for why it is published that way). A repack — or a - * push that folds them — supersedes the fragments it consolidates. - */ -export function liveLocatorManifests(manifests: readonly PackManifest[]): PackManifest[] { - const superseded = new Set() - for (const m of manifests) { - for (const h of m.supersedes) superseded.add(h.toLowerCase()) - } - return manifests - .filter( - (m) => m.kind === PACK_KIND.OBJECT_LOCATOR && !superseded.has(m.packHash.toLowerCase()), - ) - .sort((a, b) => - a.createdAt !== b.createdAt - ? b.createdAt - a.createdAt - : a.documentId < b.documentId - ? 1 - : a.documentId > b.documentId - ? -1 - : 0, - ) -} - /** The current flatIndex manifest (kind 2) — the full recursive tree listing. */ export function readNewestFlatIndexManifest( sdk: EvoSDK, diff --git a/forge-web/lib/repo/pagination.test.ts b/forge-web/lib/repo/pagination.test.ts index 3543f1b0e..d0b0c0048 100644 --- a/forge-web/lib/repo/pagination.test.ts +++ b/forge-web/lib/repo/pagination.test.ts @@ -18,18 +18,25 @@ import { bytesToBase64, IncompleteReadError, queryAllDocuments, - skipScanDistinct, tieProbeAllowed, } from '../sdk' import { readConfigBundle } from './config' -import { DOC, type V1RepoRef } from './contract' -import { emptyAuthz, listIssues, readEvents, readIssue, readReviews } from './issues' -import { orderGitPacks } from '../view/browse-source' +import { DOC, type RepoRef } from './contract' +import { listIssues, readEvents, readIssue, readReviews } from './issues' +import { locatorPackSpace } from '../view/browse-source' import { readPackManifests } from './packs' import { readComments } from '../view/issues-view' import { readRefUpdates, resolveRefByHash } from './refs' -const REPO: V1RepoRef = { kind: 'v1', contractId: 'contract', ownerId: 'owner', name: '' } +const REPO: RepoRef = { + forge: { core: 'CORE', collab: 'COLLAB', group: 'G' }, + repoId: 'R', + ownerId: 'owner', + name: 'n', + visibility: 'public', +} +/** The `repoId ==` prefix every repo-scoped query carries. */ +const SCOPE = ['repoId', '==', 'R'] as const /** Platform's per-query document cap — the whole point of these tests. */ const PAGE = 100 @@ -61,8 +68,9 @@ function byField(field: string) { * Applying `where` is load-bearing for this suite, not realism for its own sake. With a mock * that ignores filters and a store holding rows for one target, deleting * `where: [['targetId','==',targetId]]` from a reader passes every test here while making - * every issue in a repo fold every other issue's close events — `foldIssueState` never checks - * `targetId` itself. So the fixtures below deliberately seed rows the filter MUST exclude. + * every issue in a repo fold every other issue's close events — `foldIssueStateV2` never checks + * `targetId` itself. So the fixtures below deliberately seed rows the filter MUST exclude. The + * store holds one repo, so the `repoId ==` scope every reader adds is accepted as is. */ function paginatingSdk( store: Record[]>, @@ -75,6 +83,7 @@ function paginatingSdk( let rows = [...(store[q.documentTypeName] ?? [])] for (const [field, op, value] of q.where ?? []) { + if (field === 'repoId') continue if (op === '==') rows = rows.filter((d) => d[field] === value) else if (op === 'in' && Array.isArray(value)) { rows = rows.filter((d) => (value as unknown[]).includes(d[field])) @@ -181,13 +190,14 @@ describe('ref history across a page boundary', () => { // tie-safe pager issues after every full page of a `(prefix, $createdAt)` read. const refQueries = seen.filter((q) => q.documentTypeName === DOC.refUpdate) expect(refQueries).toHaveLength(3) - expect(refQueries[0]?.where).toEqual([['refNameHash', '==', REF_HASH_B64]]) + expect(refQueries[0]?.where).toEqual([SCOPE, ['refNameHash', '==', REF_HASH_B64]]) expect(refQueries[0]?.startAfter).toBeUndefined() expect(refQueries[1]?.where).toEqual([ + SCOPE, ['refNameHash', '==', REF_HASH_B64], ['$createdAt', '==', expect.any(Number)], ]) - expect(refQueries[2]?.where).toEqual([['refNameHash', '==', REF_HASH_B64]]) + expect(refQueries[2]?.where).toEqual([SCOPE, ['refNameHash', '==', REF_HASH_B64]]) expect(refQueries[2]?.startAfter).toBe(`u-${String(PAGE - 1).padStart(4, '0')}`) }) @@ -225,7 +235,7 @@ describe('event log across a page boundary', () => { { [DOC.event]: [ ...Array.from({ length: PAGE + 1 }, (_, i) => eventDoc(i, 4)), - // `foldIssueState` never checks `targetId` itself, so a reader that drops its + // `foldIssueStateV2` never checks `targetId` itself, so a reader that drops its // filter would silently fold another issue's close events into this one. ...Array.from({ length: 5 }, (_, i) => otherTargetEventDoc(i, 1)), ], @@ -241,8 +251,8 @@ describe('event log across a page boundary', () => { }) it('folds a close that lands past the first page', async () => { - // The shape of the burying attack: `event` carries no token cost, so anyone can pad a - // target with inert events. The real close must still be seen. + // The shape of the burying attack: a long log (a busy member, or a padded one) pushes + // the close past the first page. The real close must still be seen. const events = Array.from({ length: PAGE }, (_, i) => eventDoc(i, 4)) events.push(eventDoc(PAGE, 1)) const sdk = paginatingSdk({ [DOC.event]: events }) @@ -251,7 +261,6 @@ describe('event log across a page boundary', () => { sdk, REPO, { $id: 'target-1', $ownerId: 'author', $createdAt: 1, number: 1, title: 't', body: 'b' }, - emptyAuthz(), ) expect(issue.state.open).toBe(false) @@ -265,7 +274,7 @@ describe('config timeline across a page boundary', () => { $ownerId: 'owner', $createdAt: 3_000 + i, defaultBranch: i === PAGE ? 'trunk' : 'main', - protectedPatterns: '["refs/heads/main"]', + protectedPatterns: ['refs/heads/main'], archived: false, })) const sdk = paginatingSdk({ [DOC.config]: configs }) @@ -308,14 +317,14 @@ describe('list surfaces tolerate one unreadable row', () => { } it('keeps the row and marks its state unverified instead of failing the page', async () => { - // `issue` and `event` are un-gated, so one target can be padded without limit. That - // must not take down the whole issue list — and dropping the row silently would be the - // same class of bug as truncating it. + // One target's log can outgrow the reader's completeness bound. That must not take down + // the whole issue list — and dropping the row silently would be the same class of bug as + // truncating it. const sdk = endlessEventsSdk([ { $id: 'target-1', $ownerId: 'author', $createdAt: 1, number: 1, title: 'buried' }, ]) - const issues = await listIssues(sdk, REPO, emptyAuthz(), 10) + const issues = await listIssues(sdk, REPO, 10) expect(issues).toHaveLength(1) expect(issues[0]?.title).toBe('buried') @@ -330,7 +339,6 @@ describe('list surfaces tolerate one unreadable row', () => { sdk, REPO, { $id: 'target-1', $ownerId: 'author', $createdAt: 1, number: 1, title: 't', body: '' }, - emptyAuthz(), ), ).rejects.toThrow(IncompleteReadError) }) @@ -338,8 +346,8 @@ describe('list surfaces tolerate one unreadable row', () => { describe('reviews across a page boundary', () => { it('reads every review on a patch, including a verdict past the first page', async () => { - // `review` is un-gated like `event`, so a verdict can be buried the same way — and the - // buried one is the one that matters. + // `review` is un-gated, so a verdict can be buried under noise — and the buried one is + // the one that matters. const reviews = Array.from({ length: PAGE + 1 }, (_, i) => ({ $id: `r-${String(i).padStart(4, '0')}`, $ownerId: i === PAGE ? 'maintainer' : 'noise', @@ -444,7 +452,7 @@ describe('same-block ties at a page boundary (protocol 13)', () => { return rows } - const q = { dataContractId: 'c', documentTypeName: 'repoListing', orderBy: [['$createdAt', 'asc']] as const } + const q = { dataContractId: 'c', documentTypeName: 'issue', orderBy: [['$createdAt', 'asc']] as const } it('recovers the rows the cursor alone would skip, once each and in order', async () => { const rows = straddlingTie(3) @@ -529,7 +537,7 @@ describe('packRef alignment is what completeness protects', () => { const sdk = paginatingSdk({ [DOC.packManifest]: manifests }) const read = await readPackManifests(sdk, REPO) - const ordered = orderGitPacks(read.filter((m) => m.kind === 0)) + const ordered = locatorPackSpace(read) // Under a truncated read the oldest manifests fall out and packRef 0 becomes m-0001. expect(ordered).toHaveLength(PAGE + 1) @@ -560,45 +568,6 @@ describe('comment threads across a page boundary', () => { }) }) -describe('skip-scan enumeration', () => { - /** Rows across `n` distinct keys, one row each. */ - function keyed(n: number): Record[] { - return Array.from({ length: n }, (_, i) => ({ - $id: `k-${i}`, - $createdAt: i, - refNameHash: `key-${String(i).padStart(3, '0')}`, - })) - } - - it('enumerates every distinct key when the space fits the cap exactly', async () => { - // The boundary case: a key space of exactly `maxKeys` IS complete, and must not be - // mistaken for one that overflowed. - const sdk = paginatingSdk({ [DOC.refUpdate]: keyed(3) }) - - const keys = await skipScanDistinct(sdk, { - dataContractId: 'c', - documentTypeName: DOC.refUpdate, - keyField: 'refNameHash', - maxKeys: 3, - }) - - expect(keys).toEqual(['key-000', 'key-001', 'key-002']) - }) - - it('throws rather than returning a short key list when the cap is exceeded', async () => { - const sdk = paginatingSdk({ [DOC.refUpdate]: keyed(4) }) - - await expect( - skipScanDistinct(sdk, { - dataContractId: 'c', - documentTypeName: DOC.refUpdate, - keyField: 'refNameHash', - maxKeys: 3, - }), - ).rejects.toThrow(IncompleteReadError) - }) -}) - describe('queryAllDocuments refuses to guess', () => { it('throws rather than returning a short answer when the cursor cannot advance', async () => { // A full page whose last row has no `$id`: the loop has no way to ask for the next page. diff --git a/forge-web/lib/repo/refs.test.ts b/forge-web/lib/repo/refs.test.ts index e890241a4..a0bb893aa 100644 --- a/forge-web/lib/repo/refs.test.ts +++ b/forge-web/lib/repo/refs.test.ts @@ -13,10 +13,16 @@ import { bytesToHex } from '@noble/hashes/utils.js' import { describe, expect, it } from 'vitest' import { base64ToHex, bytesToBase64 } from '../sdk' -import { DOC, type V1RepoRef } from './contract' +import { DOC, type RepoRef } from './contract' import { hasMissingParent, readRefs } from './refs' -const REPO: V1RepoRef = { kind: 'v1', contractId: 'contract', ownerId: 'owner', name: '' } +const REPO: RepoRef = { + forge: { core: 'CORE', collab: 'COLLAB', group: 'G' }, + repoId: 'R', + ownerId: 'owner', + name: 'n', + visibility: 'public', +} /** Real `sha256(refName)` — the rules layer rejects updates whose hash doesn't match. */ function refHashBytes(seed: number): Uint8Array { @@ -33,7 +39,7 @@ function oidHex(seed: number): string { type Doc = Record -/** A refUpdate row; `$createdAt` is absent, as on the deployed repo-v1 type. */ +/** A refUpdate row; `$createdAt` is left out, so rows order by `$id` alone. */ function updateDoc(id: string, refSeed: number, newSeed: number, prevSeed = 0): Doc { return { $id: id, @@ -95,7 +101,8 @@ function mockDrive(rows: Doc[], opts: { dropOnKeyset?: string; ignoreRange?: boo else if (q.documentTypeName === DOC.refUpdate) { const where = q.where ?? [] const gt = where.find((w) => w[1] === '>') - const eq = where.find((w) => w[1] === '==') + // Every query is scoped `repoId ==` (one repo here); the ref equality is the other `==`. + const eq = where.find((w) => w[1] === '==' && w[0] === 'refNameHash') let docs = sorted if (gt && !opts.ignoreRange) docs = docs.filter((d) => hexOf(d) > base64ToHex(gt[2] as string)) if (eq) docs = docs.filter((d) => hexOf(d) === base64ToHex(eq[2] as string)) @@ -179,8 +186,9 @@ describe('readRefs keyset scan', () => { oid: oidHex(150), }) expect(refs).toHaveLength(3) - const eqReads = seen.filter((q) => q.where?.some((w) => w[1] === '==') && q.documentTypeName === DOC.refUpdate) - expect(eqReads.map((q) => base64ToHex(q.where?.[0]?.[2] as string))).toContain(refHashHex(7)) + const refEq = (q: QueryLike) => q.where?.find((w) => w[0] === 'refNameHash' && w[1] === '==') + const eqReads = seen.filter((q) => refEq(q) !== undefined && q.documentTypeName === DOC.refUpdate) + expect(eqReads.map((q) => base64ToHex(refEq(q)?.[2] as string))).toContain(refHashHex(7)) }) it('falls back to the reflog read alone when a prevOid has no parent', async () => { @@ -192,7 +200,9 @@ describe('readRefs keyset scan', () => { const { sdk, seen } = mockDrive(rows, { dropOnKeyset: victim }) const refs = await readRefs(sdk, REPO) - expect(seen.some((q) => q.documentTypeName === DOC.refUpdate && q.orderBy?.[0]?.[0] === '$createdAt' && !q.where?.length)).toBe(true) + // The reflog read: `$createdAt` order, scoped to the repo and nothing else. + const scopeOnly = (q: QueryLike) => (q.where ?? []).every((w) => w[0] === 'repoId') + expect(seen.some((q) => q.documentTypeName === DOC.refUpdate && q.orderBy?.[0]?.[0] === '$createdAt' && scopeOnly(q))).toBe(true) expect(refs.find((r) => r.refNameHash === refHashHex(2))?.state).toMatchObject({ state: 'resolved', oid: oidHex(3), diff --git a/forge-web/lib/repo/refs.ts b/forge-web/lib/repo/refs.ts index b6f722bd9..93fa19121 100644 --- a/forge-web/lib/repo/refs.ts +++ b/forge-web/lib/repo/refs.ts @@ -1,5 +1,5 @@ /** - * Ref reads — branch/tag enumeration + tip resolution (data-contracts §2.3, §4). + * Ref reads — branch/tag enumeration + tip resolution (`forge-v2.md` §2). * * Every ref's complete update history comes from a **keyset scan** over the `refState` index * (`refNameHash, $createdAt`): pages of `refNameHash > last`, 100 rows each, with no @@ -8,8 +8,8 @@ * (an equality query, single-branch) and the scan moves past it. Cost: ⌈updates/100⌉ * queries per type plus one per such ref. Parity: forge-core `refs::read_all_ref_updates`. * - * WHY NO CURSOR: paging `refState` with `startAfter` loses rows on testnet (protocol 13) — - * 32 of 229 updates on the nightly repo. Drive's v0 lowering applies the cursor document's + * WHY NO CURSOR: paging `refState` with `startAfter` lost rows on protocol 13 — 32 of 229 + * updates on the old nightly repo. Drive's v0 lowering applies the cursor document's * lower-level bounds to every sibling `refNameHash` branch, not only the cursor's own, so a * page omits rows from later refs and can come back short (the only end-of-data signal a * pager has). Same family as dashpay/platform#4396; the orderBy-only shape is still unfixed @@ -26,8 +26,8 @@ * LIMITS (same as forge-core `refs`, whose module doc has the detail): the check sees only * mid-chain gaps — a missing newest update or a wholly missing ref leaves no dangling * `prevOid`. And a ref with more than a page of updates is read by `==` paged with - * `startAfter`: single-branch, so no sibling drop, but protocol 13's same-`$createdAt` - * boundary skip still applies to repo-v1 ref updates until forge-v2 on protocol 14. + * `startAfter`: single-branch, so no sibling drop (and protocol 14 no longer skips rows that + * share the boundary's `$createdAt`). * * Tip resolution folds a ref's full update history (both types, with the `protected` flag * set per source) through {@link resolveRef}, honoring as-of protected-pattern config. @@ -285,7 +285,7 @@ export async function readRefUpdates( * * The display name comes from the newest update whose `refName` actually hashes to this key, * on the `(createdAt, id)` total order. `refName` is caller-supplied content while only - * `refNameHash` is indexed, so a token holder can file an update under `main`'s hash carrying + * `refNameHash` is indexed, so a writer can file an update under `main`'s hash carrying * any legal name; `resolveRef` already ignores such an update, and naming the ref from it * would show a different branch name than a client that does not. Taking the last element of * the plain-then-protected concatenation — which is not even the newest update overall — diff --git a/forge-web/lib/repo/resolveRepo.ts b/forge-web/lib/repo/resolveRepo.ts index a8fa61538..1d7610057 100644 --- a/forge-web/lib/repo/resolveRepo.ts +++ b/forge-web/lib/repo/resolveRepo.ts @@ -1,61 +1,25 @@ /** * Repo resolution — `(owner, name)` → a `RepoRef`. * - * Order (the forge-v2 client migration, `forge-v2.md` §6: "the `repo` document is the - * listing"): - * - * 1. **forge-v2** — on a network with a v2 deployment, the `repo` document with unique - * `($ownerId, name)` in forge-core. The repo is its own listing; no authenticity check is - * needed. - * 2. **v1** — the registry `repoListing` → repo contract, believed only if the contract's - * owner is the listing's `$ownerId` (data-contracts §4); the repo-owner's newest listing - * is canonical. v1 repos are read-only in the web app's v2 world. - * - * `?repo=` pins a v2 repo and `?contract=` a v1 contract, skipping the name - * lookup. The owner may be an identity id or a DPNS name (`alice` / `alice.dash`). + * A repo is the forge-core `repo` document with unique `($ownerId, name)` on the network's + * forge-v2 deployment (`forge-v2.md` §6: "the `repo` document is the listing"), so no + * authenticity check is needed. `?repo=` pins one by id, skipping the name lookup. + * The owner may be an identity id or a DPNS name (`alice` / `alice.dash`). */ import type { EvoSDK } from '@dashevo/evo-sdk' import { base58Decode } from '../auth/base58' -import { DEFAULT_NETWORK, NETWORKS, requireRegistryContractId, type Network } from '../constants' +import { DEFAULT_NETWORK, NETWORKS, type Network } from '../constants' import type { ForgeIds } from '../deployments' import { normalizeRepoName, type Visibility } from '../rules/v2' import { queryDocumentsWithProof, type PlainDocument, type WhereClause } from '../sdk' -import { - REGISTRY_DOC, - V2_DOC, - asIdentifierString, - stringArray, - type V1RepoRef, - type V2RepoRef, -} from './contract' +import { V2_DOC, asIdentifierString, stringArray, type RepoRef } from './contract' -interface DataContractLike { - ownerId?: () => unknown - getOwnerId?: () => unknown - toJSON?: () => unknown -} -interface ContractsFacadeLike { - fetch: (contractId: string) => Promise -} -interface SdkContractsLike { - contracts: ContractsFacadeLike -} interface DpnsFacadeLike { dpns: { resolveName(name: string): Promise } } -/** A resolved repo listing (registry row). */ -export interface RepoListing { - readonly listingId: string - readonly ownerId: string - readonly name: string - readonly normalizedName: string - readonly repoContractId: string - readonly description: string -} - /** A forge-v2 `repo` document, flattened. */ export interface V2RepoDoc { readonly repoId: string @@ -80,17 +44,6 @@ function asString(v: unknown): string { return '' } -function toListing(doc: PlainDocument): RepoListing { - return { - listingId: asString(doc['$id']), - ownerId: asString(doc['$ownerId']), - name: asString(doc['name']), - normalizedName: asString(doc['normalizedName']), - repoContractId: asIdentifierString(doc['repoContractId']), - description: asString(doc['description']), - } -} - /** Flatten a forge-core `repo` document. */ export function toV2RepoDoc(doc: PlainDocument): V2RepoDoc { const forkOf = asIdentifierString(doc['forkOf']) @@ -108,10 +61,9 @@ export function toV2RepoDoc(doc: PlainDocument): V2RepoDoc { } } -/** The {@link V2RepoRef} a `repo` document addresses. */ -export function v2RefOf(forge: ForgeIds, repo: V2RepoDoc): V2RepoRef { +/** The {@link RepoRef} a `repo` document addresses. */ +export function v2RefOf(forge: ForgeIds, repo: V2RepoDoc): RepoRef { return { - kind: 'v2', forge, repoId: repo.repoId, ownerId: repo.ownerId, @@ -158,81 +110,6 @@ export function resolveOwner(sdk: EvoSDK, owner: string): Promise return promise } -/** The repo contract's owner identity (base58), fetched + normalized from the contract. */ -export async function fetchContractOwner(sdk: EvoSDK, contractId: string): Promise { - const contract = await (sdk as unknown as SdkContractsLike).contracts.fetch(contractId) - if (contract == null) return null - const c = contract as DataContractLike - if (typeof c.ownerId === 'function') { - const o = asString(c.ownerId()) - if (o) return o - } - if (typeof c.getOwnerId === 'function') { - const o = asString(c.getOwnerId()) - if (o) return o - } - if (typeof c.toJSON === 'function') { - const j = c.toJSON() - if (j && typeof j === 'object') { - const owner = (j as Record)['ownerId'] - const o = asString(owner) - if (o) return o - } - } - return null -} - -/** Look up a repo listing by `($ownerId, normalizedName)` in the registry. */ -export async function resolveRepoListing( - sdk: EvoSDK, - registryContractId: string, - ownerId: string, - normalizedName: string, -): Promise { - const { documents } = await queryDocumentsWithProof(sdk, { - dataContractId: registryContractId, - documentTypeName: REGISTRY_DOC.repoListing, - where: [ - ['$ownerId', '==', ownerId], - ['normalizedName', '==', normalizedName], - ], - limit: 1, - }) - const doc = documents[0] - return doc === undefined ? null : toListing(doc) -} - -/** - * Resolve a repo listing AND verify listing authenticity (§4): the repo contract's owner - * must equal the listing's `$ownerId`, else the listing points at a contract it does not - * own and is rejected. Returns both the {@link RepoRef} and the listing (whose id feeds - * star reads) so callers need only one registry round-trip. - */ -export async function resolveRepoWithListing( - sdk: EvoSDK, - registryContractId: string, - ownerId: string, - name: string, -): Promise<{ repo: V1RepoRef; listing: RepoListing } | null> { - const listing = await resolveRepoListing(sdk, registryContractId, ownerId, name) - if (listing === null) return null - - const contractOwner = await fetchContractOwner(sdk, listing.repoContractId) - if (contractOwner === null || contractOwner !== listing.ownerId) { - // Listing points at a contract it does not own — inauthentic, reject (§4). - return null - } - return { - repo: { - kind: 'v1', - contractId: listing.repoContractId, - ownerId: listing.ownerId, - name: listing.name || listing.normalizedName, - }, - listing, - } -} - /** The one forge-v2 `repo` document `where` selects, or null. */ async function readV2Repo( sdk: EvoSDK, @@ -262,10 +139,11 @@ export function readV2RepoById(sdk: EvoSDK, forge: ForgeIds, repoId: string): Pr return readV2Repo(sdk, forge, [['$id', '==', repoId]]) } -/** What resolved: a forge-v2 repo with its document, or a v1 repo with its listing. */ -export type ResolvedRepo = - | { readonly repo: V2RepoRef; readonly doc: V2RepoDoc } - | { readonly repo: V1RepoRef; readonly listing: RepoListing | null } +/** What resolved: the repo and its `repo` document. */ +export interface ResolvedRepo { + readonly repo: RepoRef + readonly doc: V2RepoDoc +} /** How a repo route addresses a repo. */ export interface RepoAddressParams { @@ -273,81 +151,36 @@ export interface RepoAddressParams { /** Identity id or DPNS name. */ readonly owner: string readonly name: string - /** `?repo=` — a forge-v2 repo id. */ + /** `?repo=` — the `repo` document id. */ readonly repoId?: string - /** `?contract=` — a v1 repo contract id. */ - readonly contractId?: string } /** - * Resolve a repo route to a repo: forge-v2 first, then the v1 registry. Null when nothing - * authentic resolves. An explicit `repoId` / `contractId` wins over the name, and is still - * checked against the owner the URL names. + * Resolve a repo route to a repo. Null when nothing resolves (or forge-v2 is not deployed on + * the network). An explicit `repoId` wins over the name, and is still checked against the + * owner the URL names. */ export function resolveAnyRepo(sdk: EvoSDK, params: RepoAddressParams): Promise { - const config = NETWORKS[params.network ?? DEFAULT_NETWORK] - return resolveAnyRepoWith(sdk, { forge: config.v2, registryId: config.registryContractId }, params) + return resolveAnyRepoWith(sdk, NETWORKS[params.network ?? DEFAULT_NETWORK].v2, params) } -/** {@link resolveAnyRepo} over explicit deployment ids (a network's, or a test's). */ +/** {@link resolveAnyRepo} over explicit forge-v2 ids (a network's, or a test's). */ export async function resolveAnyRepoWith( sdk: EvoSDK, - deployment: { readonly forge: ForgeIds | null; readonly registryId: string | null }, + forge: ForgeIds | null, params: RepoAddressParams, ): Promise { - const { forge, registryId } = deployment + if (forge === null) return null const ownerId = await resolveOwner(sdk, params.owner) if (ownerId === null) return null if (params.repoId) { - if (forge === null || !isIdentifier(params.repoId)) return null + if (!isIdentifier(params.repoId)) return null const doc = await readV2RepoById(sdk, forge, params.repoId) return doc !== null && doc.ownerId === ownerId ? { repo: v2RefOf(forge, doc), doc } : null } - if (params.contractId) { - const repo = await resolveRepoByContractId(sdk, params.contractId) - if (repo === null || repo.ownerId !== ownerId) return null - // No listing names it: show the contract id, never a name the URL supplied. - return { repo: { ...repo, name: params.contractId }, listing: null } - } - - if (forge !== null) { - const name = normalizeRepoName(params.name) - if (name !== null) { - const doc = await readV2RepoByName(sdk, forge, ownerId, name) - if (doc !== null) return { repo: v2RefOf(forge, doc), doc } - } - } - if (registryId === null) return null - return resolveRepoWithListing(sdk, registryId, ownerId, params.name) -} - -/** - * Resolve a v1 repo to its contract, verifying listing authenticity. Returns the - * {@link V1RepoRef} only if the repo contract's owner matches the listing owner (§4). - */ -export async function resolveRepo( - sdk: EvoSDK, - params: { - readonly network?: Network - readonly registryContractId?: string - readonly ownerId: string - readonly name: string - }, -): Promise { - const registryId = - params.registryContractId ?? requireRegistryContractId(params.network ?? DEFAULT_NETWORK) - - const resolved = await resolveRepoWithListing(sdk, registryId, params.ownerId, params.name) - return resolved === null ? null : resolved.repo -} - -/** Resolve straight from a known v1 repo contract id (skips the registry name lookup). */ -export async function resolveRepoByContractId( - sdk: EvoSDK, - contractId: string, -): Promise { - const ownerId = await fetchContractOwner(sdk, contractId) - if (ownerId === null) return null - return { kind: 'v1', contractId, ownerId, name: '' } + const name = normalizeRepoName(params.name) + if (name === null) return null + const doc = await readV2RepoByName(sdk, forge, ownerId, name) + return doc === null ? null : { repo: v2RefOf(forge, doc), doc } } diff --git a/forge-web/lib/repo/social.ts b/forge-web/lib/repo/social.ts index 0014070ff..eb566eec6 100644 --- a/forge-web/lib/repo/social.ts +++ b/forge-web/lib/repo/social.ts @@ -2,9 +2,7 @@ * forge-v2 social reads — stars, follows and profiles in forge-collab (`forge-v2.md` §2). * * `star` and `follow` are `indexOnly`: their countable indexes give star, follower and - * following counts in O(1). A star is keyed by the `repo` document id, not by a registry - * listing. v1 repos keep the registry reads in - * `./collab`. + * following counts in O(1). A star is keyed by the `repo` document id. */ import type { EvoSDK } from '@dashevo/evo-sdk' diff --git a/forge-web/lib/repo/source.test.ts b/forge-web/lib/repo/source.test.ts index 8e6c0cf36..da31dc2a8 100644 --- a/forge-web/lib/repo/source.test.ts +++ b/forge-web/lib/repo/source.test.ts @@ -13,7 +13,6 @@ import type { V2RepoRef } from './contract' import { repoSource } from './source' const V2: V2RepoRef = { - kind: 'v2', forge: { core: 'CORE', collab: 'COLLAB', group: 'G' }, repoId: 'R', ownerId: 'O', diff --git a/forge-web/lib/repo/source.ts b/forge-web/lib/repo/source.ts index 4384ba0ae..1df7c32f0 100644 --- a/forge-web/lib/repo/source.ts +++ b/forge-web/lib/repo/source.ts @@ -1,24 +1,19 @@ /** * RepoSource — where a repo's documents live and how a query is scoped to one repo. * - * Every reader in `lib/repo` and `lib/view` builds its queries here, so the two data models - * differ in exactly one place: + * Every reader in `lib/repo` and `lib/view` builds its queries here. Every repo shares + * forge-core (code: refs, config, packs, members, releases, labels) and forge-collab + * (issues, PRs, comments, reviews, events, social). Indexes that list a repo's documents lead + * with `repoId`, so {@link RepoSource.repoQuery} prefixes `repoId ==` (`forge-v2.md` §2). + * Indexes keyed by a document id (`targetId`, `patchId`) need no prefix — consensus ties + * those references to the same repo — and go through {@link RepoSource.targetQuery}. * - * - **v1**: the repo IS a contract (`repo-v1.json`). Every document type sits in it and - * every index is already per-repo, so a query needs no scoping. - * - **v2**: every repo shares forge-core (code: refs, config, packs, members, releases, - * labels) and forge-collab (issues, PRs, comments, reviews, events, social). Indexes that - * list a repo's documents lead with `repoId`, so {@link RepoSource.repoQuery} prefixes - * `repoId ==` (`forge-v2.md` §2). Indexes keyed by a document id (`targetId`, `patchId`) - * need no prefix — consensus ties those references to the same repo — and go through - * {@link RepoSource.targetQuery}. - * - * Parity: forge-core's v2 data plane scopes its reads the same way (PR C); the index shapes - * are the contract's own (`forge-contracts/contracts/forge-core.json`, `forge-collab.json`). + * Parity: forge-core's v2 data plane scopes its reads the same way; the index shapes are the + * contract's own (`forge-contracts/contracts/forge-core.json`, `forge-collab.json`). */ import { hexToBase64, type DocumentQuery, type OrderByClause, type WhereClause } from '../sdk' -import { DOC, V2_DOC, type RepoRef, type V1RepoRef, type V2RepoRef } from './contract' +import { DOC, V2_DOC, type RepoRef } from './contract' /** The forge-v2 document types held by forge-core; everything else is forge-collab. */ const CORE_TYPES: ReadonlySet = new Set([ @@ -43,7 +38,7 @@ export interface QueryShape { } export interface RepoSource { - /** A query on an index that lists this repo's documents (v2: `repoId ==` prefixed). */ + /** A query on an index that lists this repo's documents (`repoId ==` prefixed). */ repoQuery(documentType: string, shape?: QueryShape): DocumentQuery /** * A query on an index keyed by one of this repo's document ids (`targetId`, `patchId`). @@ -51,9 +46,9 @@ export interface RepoSource { */ targetQuery(documentType: string, shape?: QueryShape): DocumentQuery /** - * The `chunk` rows `seqs` of the artifact `packHashHex`. On v2 chunks are keyed by the + * The `chunk` rows `seqs` of the artifact `packHashHex`. Chunks are keyed by the * uploader too (`(repoId, $ownerId, packHash, seq)`, `forge-v2.md` §4), so `uploader` — - * the `$ownerId` of the manifest copy being read — is required there. + * the `$ownerId` of the manifest copy being read — is required. */ chunkQuery(packHashHex: string, uploader: string, seqs: readonly number[]): DocumentQuery } @@ -68,26 +63,8 @@ function build(dataContractId: string, documentTypeName: string, shape: QuerySha return { dataContractId, documentTypeName, ...shape } } -function v1Source(repo: V1RepoRef): RepoSource { - return { - repoQuery: (type, shape = {}) => build(repo.contractId, type, shape), - targetQuery: (type, shape = {}) => build(repo.contractId, type, shape), - chunkQuery: (packHashHex, _uploader, seqs) => - build(repo.contractId, DOC.chunk, { - where: [ - ['packHash', '==', hexToBase64(packHashHex)], - ['seq', 'in', [...seqs]], - ], - orderBy: [ - ['packHash', 'asc'], - ['seq', 'asc'], - ], - limit: CHUNK_QUERY_MAX, - }), - } -} - -function v2Source(repo: V2RepoRef): RepoSource { +/** The {@link RepoSource} for `repo`. Cheap: a few closures, no I/O. */ +export function repoSource(repo: RepoRef): RepoSource { const contractOf = (type: string): string => CORE_TYPES.has(type) ? repo.forge.core : repo.forge.collab const repoQuery = (type: string, shape: QueryShape = {}): DocumentQuery => @@ -110,8 +87,3 @@ function v2Source(repo: V2RepoRef): RepoSource { }), } } - -/** The {@link RepoSource} for `repo`. Cheap: a few closures, no I/O. */ -export function repoSource(repo: RepoRef): RepoSource { - return repo.kind === 'v1' ? v1Source(repo) : v2Source(repo) -} diff --git a/forge-web/lib/repo/token-history.live.test.ts b/forge-web/lib/repo/token-history.live.test.ts deleted file mode 100644 index defaece5a..000000000 --- a/forge-web/lib/repo/token-history.live.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Live testnet smoke test for the TokenHistory query shape — SKIPPED by default. - * - * Run with: FORGE_LIVE=1 pnpm exec vitest run lib/repo/token-history.live.test.ts - * - * Proves the operand encoding + index shape {@link readTokenHistory} depends on are accepted - * by the *deployed* system TokenHistory contract: `tokenId` is IDENTIFIER-typed, so the - * where-operand must be a base58 id (NOT the base64 byteArray form used for hash/oid fields), - * and `(tokenId, $createdAt)` is a valid index. A base64 operand is rejected live with - * "could not be decoded from base 58". Never gates CI (WASM/network flaky). - */ - -import { describe, expect, it } from 'vitest' - -import { base58Encode } from '../auth/base58' -import { TOKEN_HISTORY_CONTRACT_ID } from '../constants' -import { evoSdkService, queryDocumentsWithProof } from '../sdk' - -const LIVE = process.env['FORGE_LIVE'] === '1' - -describe.skipIf(!LIVE)('live TokenHistory query shape', () => { - it( - 'accepts a base58 tokenId== operand with orderBy $createdAt on the mint type', - async () => { - await evoSdkService.initialize({ network: 'testnet', contractIds: [], timeoutMs: 15000 }) - const sdk = evoSdkService.getSdk() - - // Arbitrary 32-byte tokenId as base58 — we assert only that the operand encoding + index - // are accepted by the live contract, not the (expected-empty) results. - const tokenB58 = base58Encode(new Uint8Array(32).fill(7)) - const { documents } = await queryDocumentsWithProof(sdk, { - dataContractId: TOKEN_HISTORY_CONTRACT_ID, - documentTypeName: 'mint', - where: [['tokenId', '==', tokenB58]], - orderBy: [['$createdAt', 'asc']], - limit: 5, - }) - expect(Array.isArray(documents)).toBe(true) - }, - 30000, - ) -}) diff --git a/forge-web/lib/repo/tokens.test.ts b/forge-web/lib/repo/tokens.test.ts deleted file mode 100644 index fd1b8e366..000000000 --- a/forge-web/lib/repo/tokens.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -/** - * Token-history authz reconstruction + its effect on the issue fold. - * - * Proves the ported `tokens.rs::token_history()` invariants: owner baseSupply seeding, - * mint→holder reconstruction, and owner-freeze observation — and, end to end, that a - * non-author MAINTAIN holder's `close` now folds an issue to CLOSED while a non-holder's - * does not (the gap the empty resolver left open). - */ - -import { describe, expect, it } from 'vitest' - -import type { EvoSDK } from '@dashevo/evo-sdk' - -import { base58Encode } from '../auth/base58' -import { AuthzResolver, foldIssueState, type Event } from '../rules' -import type { V1RepoRef } from './contract' -import { - currentHoldings, - invalidateAuthz, - readTokenHistory, - readViewerHoldings, - resolveAuthz, -} from './tokens' - -/** A deterministic base58 32-byte id from a seed byte. */ -function id(seed: number): string { - const b = new Uint8Array(32) - for (let i = 0; i < 32; i++) b[i] = (seed + i) & 0xff - return base58Encode(b) -} - -const OWNER = id(1) -const MAINTAINER = id(50) -const OUTSIDER = id(120) -const AUTHOR = id(200) - -const REPO: V1RepoRef = { kind: 'v1', contractId: id(9), ownerId: OWNER, name: '' } - -// Token ids the mock returns for positions 0 (write) / 1 (maintain). -const WRITE_TOKEN = id(70) -const MAINTAIN_TOKEN = id(80) - -interface Doc { - readonly $id: string - readonly $createdAt: number - readonly recipientId?: string - readonly frozenIdentityId?: string -} - -/** Build a mock EvoSDK whose token facade + document queries serve a fixed history. */ -function mockSdk(history: { - mints: Record // keyed by base58 token id - freezes?: Record -}): EvoSDK { - const opFor = (docType: string): Record => - docType === 'mint' ? history.mints : docType === 'freeze' ? (history.freezes ?? {}) : {} - - const operand = (where: readonly (readonly unknown[])[] | undefined, field: string): string | null => { - const clause = (where ?? []).find((w) => w[0] === field) - return clause && typeof clause[2] === 'string' ? clause[2] : null - } - - return { - tokens: { - calculateId: (_contractId: string, position: number): Promise => - Promise.resolve(position === 0 ? WRITE_TOKEN : MAINTAIN_TOKEN), - }, - documents: { - query: (q: { - documentTypeName: string - where?: readonly (readonly unknown[])[] - }): Promise> => { - // Operands are base58 identifiers (tokenId / frozenIdentityId are identifier-typed). - const tokenB58 = operand(q.where, 'tokenId') - const frozenB58 = operand(q.where, 'frozenIdentityId') - let docs = (tokenB58 && opFor(q.documentTypeName)[tokenB58]) || [] - if (frozenB58 !== null) { - docs = docs.filter((d) => d.frozenIdentityId === frozenB58) - } - const map = new Map() - for (const d of docs) map.set(d.$id, d) - return Promise.resolve(map) - }, - }, - } as unknown as EvoSDK -} - -describe('readTokenHistory', () => { - it('seeds the owner baseSupply on both tokens at createdAt 0', async () => { - const sdk = mockSdk({ mints: {} }) - const records = await readTokenHistory(sdk, REPO) - const ownerSeeds = records.filter((r) => r.identity === OWNER && r.createdAt === 0 && r.op === 'mint') - expect(ownerSeeds.map((r) => r.token).sort()).toEqual(['maintain', 'write']) - }) - - it('reconstructs a MAINTAIN mint as a holder record', async () => { - const sdk = mockSdk({ - mints: { - [MAINTAIN_TOKEN]: [{ $id: 'mint1', $createdAt: 100, recipientId: MAINTAINER }], - }, - }) - const records = await readTokenHistory(sdk, REPO) - const m = records.find((r) => r.identity === MAINTAINER) - expect(m).toMatchObject({ token: 'maintain', op: 'mint', createdAt: 100 }) - }) - - it('degrades to empty history when the history read fails', async () => { - const sdk = { - tokens: { calculateId: (): Promise => Promise.reject(new Error('offline')) }, - } as unknown as EvoSDK - expect(await readTokenHistory(sdk, REPO)).toEqual([]) - }) -}) - -describe('issue fold with reconstructed authz', () => { - const issueClosedBy = (actor: string, at: number): Event => ({ - id: `e-${actor}-${at}`, - targetId: 'issue-1', - kind: 'close', - actor, - createdAt: at, - }) - - it('folds a non-author MAINTAINER close to CLOSED, but ignores a non-holder close', async () => { - const sdk = mockSdk({ - mints: { - [MAINTAIN_TOKEN]: [{ $id: 'mint1', $createdAt: 100, recipientId: MAINTAINER }], - }, - }) - const resolver = new AuthzResolver(await readTokenHistory(sdk, REPO)) - - // Maintainer (holds MAINTAIN since t=100) closes at t=200 → applies. - expect(foldIssueState([issueClosedBy(MAINTAINER, 200)], AUTHOR, resolver).open).toBe(false) - - // Outsider (never minted) closes at t=200 → inert, stays open. - expect(foldIssueState([issueClosedBy(OUTSIDER, 200)], AUTHOR, resolver).open).toBe(true) - - // Maintainer's action BEFORE its mint (t=50 < 100) is not yet authorized. - expect(foldIssueState([issueClosedBy(MAINTAINER, 50)], AUTHOR, resolver).open).toBe(true) - }) - - it('observes an owner freeze: the owner cannot close while frozen', async () => { - const sdk = mockSdk({ - mints: {}, - freezes: { - [MAINTAIN_TOKEN]: [{ $id: 'fz1', $createdAt: 100, frozenIdentityId: OWNER }], - [WRITE_TOKEN]: [{ $id: 'fz2', $createdAt: 100, frozenIdentityId: OWNER }], - }, - }) - const resolver = new AuthzResolver(await readTokenHistory(sdk, REPO)) - - // Owner acts before the freeze (t=50) → holds baseSupply, close applies. - expect(foldIssueState([issueClosedBy(OWNER, 50)], AUTHOR, resolver).open).toBe(false) - - // Owner acts after the freeze (t=200) → frozen on both tokens, close is inert. - expect(foldIssueState([issueClosedBy(OWNER, 200)], AUTHOR, resolver).open).toBe(true) - }) -}) - -describe('resolveAuthz caching', () => { - /** Wrap a mock sdk with a document-query counter. */ - function counting(sdk: EvoSDK): { sdk: EvoSDK; queries: () => number } { - const inner = sdk as unknown as { documents: { query: (q: unknown) => Promise } } - let n = 0 - const wrapped = { - ...(sdk as unknown as Record), - documents: { - query: (q: unknown): Promise => { - n += 1 - return inner.documents.query(q) - }, - }, - } as unknown as EvoSDK - return { sdk: wrapped, queries: () => n } - } - - it('caches a successful resolver per contract; invalidateAuthz drops it', async () => { - const repo: V1RepoRef = { kind: 'v1', contractId: id(30), ownerId: OWNER, name: '' } - const { sdk, queries } = counting( - mockSdk({ mints: { [MAINTAIN_TOKEN]: [{ $id: 'm1', $createdAt: 100, recipientId: MAINTAINER }] } }), - ) - - await resolveAuthz(sdk, repo) - const afterFirst = queries() - expect(afterFirst).toBeGreaterThan(0) - - await resolveAuthz(sdk, repo) - expect(queries()).toBe(afterFirst) // served from cache — no new reads - - invalidateAuthz(repo.contractId) - await resolveAuthz(sdk, repo) - expect(queries()).toBeGreaterThan(afterFirst) - invalidateAuthz(repo.contractId) - }) - - it('does not cache a failed (degraded) reconstruction', async () => { - const repo: V1RepoRef = { kind: 'v1', contractId: id(31), ownerId: OWNER, name: '' } - let calculateCalls = 0 - const sdk = { - tokens: { - calculateId: (): Promise => { - calculateCalls += 1 - return Promise.reject(new Error('unreachable')) - }, - }, - documents: { query: (): Promise> => Promise.resolve(new Map()) }, - } as unknown as EvoSDK - - const degraded = await resolveAuthz(sdk, repo) - expect(degraded.holdingsAsOf(OWNER, 1).write).toBe(false) // empty resolver - expect(calculateCalls).toBeGreaterThan(0) - - const before = calculateCalls - await resolveAuthz(sdk, repo) // failure was NOT pinned — the read retries - expect(calculateCalls).toBeGreaterThan(before) - invalidateAuthz(repo.contractId) - }) -}) - -describe('viewer holdings (the PR/issue control gate)', () => { - it('reads the owner, a granted maintainer, and a stranger correctly', async () => { - const repo: V1RepoRef = { kind: 'v1', contractId: id(40), ownerId: OWNER, name: '' } - const sdk = mockSdk({ mints: { [MAINTAIN_TOKEN]: [{ $id: 'm1', $createdAt: 100, recipientId: MAINTAINER }] } }) - - expect(await readViewerHoldings(sdk, repo, OWNER)).toEqual({ write: true, maintain: true }) - expect(await readViewerHoldings(sdk, repo, MAINTAINER)).toEqual({ write: false, maintain: true }) - expect(await readViewerHoldings(sdk, repo, OUTSIDER)).toEqual({ write: false, maintain: false }) - invalidateAuthz(repo.contractId) - }) - - it('sees a freeze: a suspended maintainer holds nothing spendable', async () => { - const repo: V1RepoRef = { kind: 'v1', contractId: id(41), ownerId: OWNER, name: '' } - const sdk = mockSdk({ - mints: { [MAINTAIN_TOKEN]: [{ $id: 'm1', $createdAt: 100, recipientId: MAINTAINER }] }, - freezes: { [MAINTAIN_TOKEN]: [{ $id: 'f1', $createdAt: 200, frozenIdentityId: MAINTAINER }] }, - }) - expect(await readViewerHoldings(sdk, repo, MAINTAINER)).toEqual({ write: false, maintain: false }) - invalidateAuthz(repo.contractId) - }) - - it('returns null (unknown, not "holds nothing") when the history read failed', () => { - expect(currentHoldings([], OWNER)).toBeNull() - }) -}) diff --git a/forge-web/lib/repo/tokens.ts b/forge-web/lib/repo/tokens.ts deleted file mode 100644 index 55cc4e385..000000000 --- a/forge-web/lib/repo/tokens.ts +++ /dev/null @@ -1,271 +0,0 @@ -/** - * Token-history reconstruction (data-contracts §2.1, §4) — the as-of-time WRITE / MAINTAIN - * authorization source for the issue/PR event fold. - * - * A TS port of forge-core `tokens.rs::token_history()`. A repo's two tokens ARE its ACL, so - * the folded state of an issue/PR must honor *who held which token when each event landed*. - * Platform emits an audit document on the system **TokenHistory** contract for every - * `mint` / `freeze` / `unfreeze` / `destroyFrozenFunds`; replaying those (as {@link TokenRecord}s) - * through {@link holdingsAsOf} reconstructs spendable holdings at any past `$createdAt`. - * - * Faithful to the hardened Rust after its review fixes: - * 1. **Seed the owner** — the repo owner is auto-credited both tokens' `baseSupply` at - * contract creation, which emits NO `mint` document. Without a synthetic genesis mint - * (`createdAt = 0`) the owner would read as a non-holder and its legitimate actions - * would fold as unauthorized. - * 2. **Paginate to exhaustion** (`query_all`) — a repo with >100 grants would otherwise drop - * late collaborators from the resolver. - * 3. **Observe owner freeze** — the owner is always in the affected set so its freeze / - * unfreeze / destroy history is reconstructed (org joint-ownership can freeze the owner); - * otherwise the owner reads as perpetually unfrozen. - * - * Best-effort: any read failure (contract unreachable, index shape, mainnet not deployed) - * degrades to an empty history — the fold then honors only the target author's own - * close/reopen, exactly the prior behavior, never a hard error in the UI. - */ - -import type { EvoSDK } from '@dashevo/evo-sdk' - -import { base58Decode, base58Encode } from '../auth/base58' -import { DEFAULT_NETWORK, TOKEN_HISTORY_CONTRACT_ID, type Network } from '../constants' -import { - AuthzResolver, - holdingsAsOf, - type Holdings, - type TokenKind, - type TokenOp, - type TokenRecord, -} from '../rules' -import { base64ToBytes, queryAllDocuments } from '../sdk' -import { repoTokenIds } from './collab' -import type { V1RepoRef } from './contract' - -/** TokenHistory document type names (parity with `tokens.rs`). */ -const TH = { - mint: 'mint', - freeze: 'freeze', - unfreeze: 'unfreeze', - destroy: 'destroyFrozenFunds', -} as const - -/** The two repo token positions, in the fixed WRITE-then-MAINTAIN order. */ -const ROLES: ReadonlyArray<{ readonly kind: TokenKind; readonly key: 'write' | 'maintain' }> = [ - { kind: 'write', key: 'write' }, - { kind: 'maintain', key: 'maintain' }, -] - -/** The freeze-lifecycle doc types mapped to their {@link TokenOp}. */ -const FREEZE_OPS: ReadonlyArray<{ readonly doc: string; readonly op: TokenOp }> = [ - { doc: TH.freeze, op: 'freeze' }, - { doc: TH.unfreeze, op: 'unfreeze' }, - { doc: TH.destroy, op: 'destroy' }, -] - -/** - * Normalize an identifier-typed result field to base58. The SDK's `toJSON` serializes - * identifier fields as base58, but a byteArray-typed field would arrive base64 — accept - * either so a schema nuance on the system contract cannot silently drop records. - */ -function toIdentityB58(v: unknown): string | null { - if (typeof v !== 'string' || v.length === 0) return null - try { - if (base58Decode(v).length === 32) return v - } catch { - // Not base58 — fall through to base64. - } - try { - const bytes = base64ToBytes(v) - if (bytes.length === 32) return base58Encode(bytes) - } catch { - // Not base64 either. - } - return null -} - -function num(doc: Record, field: string): number { - const v = doc[field] - if (typeof v === 'bigint') return Number(v) - return typeof v === 'number' ? v : 0 -} - -/** - * Read the repo's full token history as {@link TokenRecord}s (both tokens), ready to feed - * {@link AuthzResolver} / {@link holdingsAsOf}. See the module note for the three parity - * invariants (owner seed, pagination, owner-freeze). Returns `[]` on any failure. - */ -export async function readTokenHistory(sdk: EvoSDK, repo: V1RepoRef): Promise { - // A system contract: the same id on every network. - const historyContractId = TOKEN_HISTORY_CONTRACT_ID - - try { - const owner = repo.ownerId - const tokenIds = await repoTokenIds(sdk, repo) - const records: TokenRecord[] = [] - - // (1) Synthetic genesis mint for the owner on both tokens (baseSupply, no mint doc). - for (const role of ROLES) { - records.push({ - id: `baseSupply:${owner}:${role.key}`, - identity: owner, - token: role.kind, - op: 'mint', - createdAt: 0, - }) - } - - // Two waves per role (the affected set depends on the mints), roles in parallel and - // every freeze/unfreeze/destroy read of a wave in parallel — the fold is - // order-independent (AuthzResolver sorts by createdAt), so only completeness matters. - const perRole = await Promise.all( - ROLES.map(async (role) => { - const roleRecords: TokenRecord[] = [] - // `tokenId` / `frozenIdentityId` on the TokenHistory contract are IDENTIFIER-typed, - // so the wasm query operand is the base58 id itself — NOT the base64 byteArray form - // used for hash/oid fields (verified live against the deployed testnet contract: a - // base64 operand is rejected with "could not be decoded from base 58"). - const tokenIdB58 = tokenIds[role.key] - - // Mints (byDate index: tokenId, $createdAt), paginated to exhaustion. - const mints = await queryAllDocuments(sdk, { - dataContractId: historyContractId, - documentTypeName: TH.mint, - where: [['tokenId', '==', tokenIdB58]], - orderBy: [['$createdAt', 'asc']], - }) - - // (3) Always include the owner so its freeze history is reconstructed. - const affected = new Set([owner]) - for (const m of mints) { - const recipient = toIdentityB58(m['recipientId']) - if (recipient === null) continue - affected.add(recipient) - roleRecords.push({ - id: typeof m['$id'] === 'string' ? (m['$id'] as string) : undefined, - identity: recipient, - token: role.kind, - op: 'mint', - createdAt: num(m, '$createdAt'), - }) - } - - // Freeze / unfreeze / destroy per affected identity (byFrozenIdentityId index). - const freezeWaves = await Promise.all( - [...affected].flatMap((identity) => - FREEZE_OPS.map(async ({ doc, op }): Promise => { - const docs = await queryAllDocuments(sdk, { - dataContractId: historyContractId, - documentTypeName: doc, - where: [ - ['tokenId', '==', tokenIdB58], - ['frozenIdentityId', '==', identity], - ], - orderBy: [['$createdAt', 'asc']], - }) - return docs.map((d) => ({ - id: typeof d['$id'] === 'string' ? (d['$id'] as string) : undefined, - identity, - token: role.kind, - op, - createdAt: num(d, '$createdAt'), - })) - }), - ), - ) - for (const wave of freezeWaves) roleRecords.push(...wave) - return roleRecords - }), - ) - for (const roleRecords of perRole) records.push(...roleRecords) - - return records - } catch { - return [] - } -} - -// Grants change rarely, but every issues/pulls page needs the resolver — cache the history per -// contract. A failed reconstruction returns [] (degraded author-only folds); a SUCCESSFUL -// run always contains at least the two synthetic genesis records, so a short history marks -// a failure and is evicted immediately rather than pinning the degraded resolver for the TTL. -const AUTHZ_TTL_MS = 5 * 60_000 -const authzCache = new Map }>() - -/** Fewer records than the two synthetic genesis mints means the history read failed. */ -function historyComplete(records: readonly TokenRecord[]): boolean { - return records.length >= 2 -} - -function authzKey(network: Network, contractId: string): string { - return `${network}:${contractId}` -} - -/** Drop a repo's cached authz resolver (call after a grant / suspend / revoke lands). */ -export function invalidateAuthz(contractId: string): void { - for (const key of authzCache.keys()) { - if (key.endsWith(`:${contractId}`)) authzCache.delete(key) - } -} - -/** {@link readTokenHistory} through the per-contract session cache (failures not cached). */ -function tokenHistoryCached( - sdk: EvoSDK, - repo: V1RepoRef, - network: Network, -): Promise { - const key = authzKey(network, repo.contractId) - const hit = authzCache.get(key) - if (hit !== undefined && Date.now() - hit.at < AUTHZ_TTL_MS) return hit.promise - const promise: Promise = readTokenHistory(sdk, repo).then( - (records) => { - if (!historyComplete(records) && authzCache.get(key)?.promise === promise) { - authzCache.delete(key) - } - return records - }, - ) - // readTokenHistory never rejects today, but a rejected entry must not be pinned for the - // TTL — evict it like every other session cache does. - promise.catch(() => { - if (authzCache.get(key)?.promise === promise) authzCache.delete(key) - }) - authzCache.set(key, { at: Date.now(), promise }) - return promise -} - -/** - * Build an {@link AuthzResolver} from the repo's reconstructed token history — the as-of-time - * WRITE/MAINTAIN source the issue/PR fold consumes. Degrades to an empty resolver (author-only - * actions) if the history is unavailable. Cached per contract for {@link AUTHZ_TTL_MS}; - * failures are not cached. - */ -export async function resolveAuthz( - sdk: EvoSDK, - repo: V1RepoRef, - network: Network = DEFAULT_NETWORK, -): Promise { - return new AuthzResolver(await tokenHistoryCached(sdk, repo, network)) -} - -/** - * An identity's current WRITE / MAINTAIN holdings, or `null` when the token history could not - * be read — "unknown" must stay distinguishable from "holds nothing", or a read failure would - * silently strip a maintainer's controls (or, inverted, grant a stranger's). - */ -export function currentHoldings( - records: readonly TokenRecord[], - identity: string, -): Holdings | null { - if (!historyComplete(records)) return null - // As of "now": every record so far counts, which is what an event signed now is judged by. - return holdingsAsOf(records, identity, Number.MAX_SAFE_INTEGER) -} - -/** {@link currentHoldings} for `identity`, read through the shared history cache. */ -export async function readViewerHoldings( - sdk: EvoSDK, - repo: V1RepoRef, - identity: string, - network: Network = DEFAULT_NETWORK, -): Promise { - return currentHoldings(await tokenHistoryCached(sdk, repo, network), identity) -} diff --git a/forge-web/lib/repo/v2.live.test.ts b/forge-web/lib/repo/v2.live.test.ts index cb026d01d..2fc6adcb1 100644 --- a/forge-web/lib/repo/v2.live.test.ts +++ b/forge-web/lib/repo/v2.live.test.ts @@ -35,8 +35,7 @@ describe.skipIf(!LIVE)('live forge-v2 reads (moutai fixture)', () => { const sdk = evoSdkService.getSdk() const home = await loadRepoHome(sdk, { network: 'devnet', owner: OWNER, name: 'forge-v2-demo' }) - expect(home?.repo.kind).toBe('v2') - if (home === null || home.repo.kind !== 'v2') throw new Error('unreachable') + if (home === null) throw new Error('forge-v2-demo did not resolve') expect(home.defaultBranch).toBe('main') expect(home.starCount).toBe(1) const main = home.branches.find((b) => b.refName === 'refs/heads/main') @@ -50,7 +49,7 @@ describe.skipIf(!LIVE)('live forge-v2 reads (moutai fixture)', () => { name: 'ignored', repoId: home.repo.repoId, }) - expect(pinned?.repo.kind).toBe('v2') + expect(pinned?.repo.repoId).toBe(home.repo.repoId) expect( await loadRepoHome(sdk, { network: 'devnet', owner: MAINTAINER, name: 'x', repoId: home.repo.repoId }), ).toBeNull() @@ -86,7 +85,7 @@ describe.skipIf(!LIVE)('live forge-v2 reads (moutai fixture)', () => { const feed = await listRecentRepos(sdk, { network: 'devnet' }) const repoId = home.repo.repoId - const demo = feed.v2.find((r) => r.key === repoId) + const demo = feed.find((r) => r.key === repoId) expect(demo).toMatchObject({ stars: 1, issues: 3 }) const profile = await listReposByOwner(sdk, MAINTAINER, { network: 'devnet' }) diff --git a/forge-web/lib/repo/v2.test.ts b/forge-web/lib/repo/v2.test.ts index 6c2ea182e..e7520f952 100644 --- a/forge-web/lib/repo/v2.test.ts +++ b/forge-web/lib/repo/v2.test.ts @@ -3,7 +3,7 @@ * every `where` clause (so a reader that forgets `repoId ==` reads another repo's documents * and fails here), honours `in`, caps pages at 100 and pages by `startAfter`. * - * Covers: resolution (v2 first, v1 fallback, DPNS owners, `?repo=` pins), the RepoSource + * Covers: resolution (the `repo` document, DPNS owners, `?repo=` pins), the RepoSource * query shapes, the issue/PR folds over `event` + `authorEvent` (lists read the repo feed once * instead of per row), the well-formedness filter, membership-derived permissions and * approvals, pack-copy selection, and the chunk reads that must name the uploader. @@ -34,7 +34,6 @@ import { v2PacksOfKind, wellFormed, type PackManifest, - type V1RepoRef, type V2RepoRef, } from './index' @@ -51,7 +50,6 @@ const HEAD = 'ab'.repeat(20) const REPO_ISSUE2 = 'EiaSVsG5gm6aLBXjodmJNmQRVcmwUbvon1YiFGKc64by' const V2: V2RepoRef = { - kind: 'v2', forge: FORGE, repoId: REPO, ownerId: OWNER, @@ -107,7 +105,6 @@ function mockSdk(store: Store, seen: DocumentQuery[] = [], dpns: Record new Map([['', BigInt((await query({ ...q, limit: 100 })).size)]]), }, - contracts: { fetch: async (id: string) => (store[id] ? { ownerId: () => store[id]?.['$owner']?.[0]?.['id'] } : null) }, dpns: { resolveName: async (name: string) => dpns[name] }, } as unknown as EvoSDK } @@ -213,73 +210,49 @@ describe('RepoSource', () => { expect(s.targetQuery('comment', { where: [['targetId', '==', 't']] }).where).toEqual([['targetId', '==', 't']]) }) - it('names the uploader in a v2 chunk read, and not in a v1 one', () => { - const v2 = repoSource(V2).chunkQuery('aa'.repeat(32), MAINT, [0, 1]) - expect(v2.where).toEqual([ + it('names the uploader in a chunk read', () => { + const q = repoSource(V2).chunkQuery('aa'.repeat(32), MAINT, [0, 1]) + expect(q.where).toEqual([ ['repoId', '==', REPO], ['$ownerId', '==', MAINT], ['packHash', '==', hexToBase64('aa'.repeat(32))], ['seq', 'in', [0, 1]], ]) - const v1: V1RepoRef = { kind: 'v1', contractId: 'C1', ownerId: OWNER, name: 'x' } - expect(repoSource(v1).chunkQuery('aa'.repeat(32), MAINT, [0]).where?.map((w) => w[0])).toEqual([ - 'packHash', - 'seq', - ]) }) - it('keys and preloads by the model', () => { + it('keys by repo id and preloads both forge contracts', () => { expect(repoKey(V2)).toBe(REPO) expect(repoContractIds(V2)).toEqual(['CORE', 'COLLAB']) - expect(repoContractIds({ kind: 'v1', contractId: 'C1', ownerId: OWNER, name: '' })).toEqual(['C1']) expect(repoContractIds(null)).toEqual([]) }) }) describe('resolveAnyRepo', () => { - const store = (): Store => ({ - ...fixture(), - REG: { - repoListing: [ - doc({ $ownerId: OWNER, normalizedName: 'legacy', name: 'Legacy', repoContractId: 'V1C' }), - ], - }, - V1C: { $owner: [{ id: OWNER }] }, - }) const params = { network: 'devnet' as const } // resolveAnyRepo reads the build's NETWORKS; these tests hand resolveAnyRepoWith the ids. - it('prefers the forge-v2 repo document, then falls back to the v1 registry', async () => { - const sdk = mockSdk(store()) - const v2 = await resolveAnyRepoWith(sdk, { forge: FORGE, registryId: 'REG' }, { ...params, owner: OWNER, name: 'Demo' }) - expect(v2?.repo).toMatchObject({ kind: 'v2', repoId: REPO, name: 'demo' }) - const v1 = await resolveAnyRepoWith(sdk, { forge: FORGE, registryId: 'REG' }, { ...params, owner: OWNER, name: 'legacy' }) - expect(v1?.repo).toMatchObject({ kind: 'v1', contractId: 'V1C' }) - expect( - await resolveAnyRepoWith(sdk, { forge: FORGE, registryId: 'REG' }, { ...params, owner: OWNER, name: 'nope' }), - ).toBeNull() + it('resolves the repo document by (owner, normalized name)', async () => { + const sdk = mockSdk(fixture()) + const found = await resolveAnyRepoWith(sdk, FORGE, { ...params, owner: OWNER, name: 'Demo' }) + expect(found?.repo).toMatchObject({ repoId: REPO, name: 'demo' }) + expect(await resolveAnyRepoWith(sdk, FORGE, { ...params, owner: OWNER, name: 'nope' })).toBeNull() }) it('resolves a DPNS owner name and rejects a repo pin owned by someone else', async () => { - const sdk = mockSdk(store(), [], { 'alice.dash': OWNER }) - const byName = await resolveAnyRepoWith(sdk, { forge: FORGE, registryId: null }, { ...params, owner: 'Alice', name: 'demo' }) - expect(byName?.repo).toMatchObject({ kind: 'v2', ownerId: OWNER }) - const pinned = await resolveAnyRepoWith(sdk, { forge: FORGE, registryId: null }, { ...params, owner: OWNER, name: 'x', repoId: REPO }) - expect(pinned?.repo).toMatchObject({ kind: 'v2', repoId: REPO }) - expect( - await resolveAnyRepoWith(sdk, { forge: FORGE, registryId: null }, { ...params, owner: MAINT, name: 'x', repoId: REPO }), - ).toBeNull() - expect( - await resolveAnyRepoWith(sdk, { forge: FORGE, registryId: null }, { ...params, owner: 'nobody', name: 'demo' }), - ).toBeNull() + const sdk = mockSdk(fixture(), [], { 'alice.dash': OWNER }) + const byName = await resolveAnyRepoWith(sdk, FORGE, { ...params, owner: 'Alice', name: 'demo' }) + expect(byName?.repo).toMatchObject({ ownerId: OWNER }) + const pinned = await resolveAnyRepoWith(sdk, FORGE, { ...params, owner: OWNER, name: 'x', repoId: REPO }) + expect(pinned?.repo).toMatchObject({ repoId: REPO }) + expect(await resolveAnyRepoWith(sdk, FORGE, { ...params, owner: MAINT, name: 'x', repoId: REPO })).toBeNull() + expect(await resolveAnyRepoWith(sdk, FORGE, { ...params, owner: 'nobody', name: 'demo' })).toBeNull() }) - it('never reads forge-v2 on a network without it', async () => { + it('reads nothing on a network without forge-v2', async () => { const seen: DocumentQuery[] = [] - const sdk = mockSdk(store(), seen) - const v1 = await resolveAnyRepoWith(sdk, { forge: null, registryId: 'REG' }, { ...params, owner: OWNER, name: 'legacy' }) - expect(v1?.repo.kind).toBe('v1') - expect(seen.some((q) => q.dataContractId === 'CORE')).toBe(false) + const sdk = mockSdk(fixture(), seen) + expect(await resolveAnyRepoWith(sdk, null, { ...params, owner: OWNER, name: 'demo' })).toBeNull() + expect(seen).toEqual([]) // The exported entry point is the same function over the build's network config. expect(typeof resolveAnyRepo).toBe('function') }) @@ -310,7 +283,7 @@ describe('forge-v2 issue and PR folds', () => { const eventReads = seen.filter((q) => q.documentTypeName === 'event' || q.documentTypeName === 'authorEvent') expect(eventReads.every((q) => q.where?.[0]?.[0] === 'repoId')).toBe(true) expect(eventReads).toHaveLength(2) - // …and no token-history reads either. + // …and nothing outside the two forge contracts. expect(seen.some((q) => q.dataContractId !== 'CORE' && q.dataContractId !== 'COLLAB')).toBe(false) }) @@ -344,7 +317,7 @@ describe('forge-v2 issue and PR folds', () => { ) } invalidateRepoFeed(V2) - const issues = await listIssues(mockSdk(store), V2, undefined, 3) + const issues = await listIssues(mockSdk(store), V2, 3) expect(issues.map((i) => i.number).sort()).toEqual([1, 2, 3]) expect(issues.hidden).toBe(6) // the five spam rows and the fixture's malformed #4 invalidateRepoFeed(V2) @@ -393,12 +366,11 @@ describe('forge-v2 permissions', () => { describe('wellFormed', () => { const PRIVATE: V2RepoRef = { ...V2, visibility: 'private' } const enc = bytesToBase64(new Uint8Array(32)) - it('applies plaintext-xor-enc by visibility, and passes every v1 document', () => { + it('applies plaintext-xor-enc by visibility', () => { expect(wellFormed(V2, 'issue', { title: 't' })).toBe(true) expect(wellFormed(V2, 'issue', { title: '' })).toBe(false) expect(wellFormed(PRIVATE, 'issue', { enc, epoch: 0 })).toBe(true) expect(wellFormed(PRIVATE, 'refUpdate', { enc, epoch: 0, refName: 'refs/heads/main' })).toBe(false) - expect(wellFormed({ kind: 'v1', contractId: 'c', ownerId: 'o', name: '' }, 'issue', {})).toBe(true) }) }) diff --git a/forge-web/lib/repo/write.live.test.ts b/forge-web/lib/repo/write.live.test.ts deleted file mode 100644 index 4a99d7c9d..000000000 --- a/forge-web/lib/repo/write.live.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Live testnet WRITE smoke test — SKIPPED by default (needs network + WASM + real spend). - * - * Run with: - * FORGE_LIVE=1 pnpm exec vitest run lib/repo/write.live.test.ts - * - * Proves the browser signing path interoperates with the CLI-created world: it loads the - * DEPLOYER testnet identity, connects via `testnetTrusted()`, creates an `issue` on the m1 repo - * through the WriteEngine (build → sign HIGH key → broadcast-only → poll), reads it back and - * folds its state, then stars the m1 repo listing in the registry and confirms the star landed. - * - * Spend is a few cents (two ungated document creates). Never gates CI. - */ - -import { readFileSync } from 'node:fs' -import { homedir } from 'node:os' -import { join } from 'node:path' - -import { describe, expect, it } from 'vitest' - -import { NETWORKS } from '../constants' -import { evoSdkService, queryDocumentsWithProof, type WriteAuth } from '../sdk' -import { parseIdentityFileText } from '../auth' -import { REGISTRY_DOC, type V1RepoRef } from './contract' -import { createIssue, starRelation } from './writes' -import { asIdentifierString, fetchContractOwner, listIssues } from './index' - -const LIVE = process.env['FORGE_LIVE'] === '1' -const M1_REPO_CONTRACT = '5rrwgjjVUqMghnessfiXPXubpiM2QLNNXH142Hv4PDyX' -const IDENTITY_FILE = join(homedir(), '.config/dash-forge/test-identities/DEPLOYER.identity.json') - -describe.skipIf(!LIVE)('live testnet browser-path writes', () => { - it( - 'creates an issue, reads it back, and stars the repo', - async () => { - // 1. Load the DEPLOYER identity file the way the browser login would (bridge format). - const parsed = parseIdentityFileText(readFileSync(IDENTITY_FILE, 'utf8')) - const auth: WriteAuth = { - identityId: parsed.identityId, - network: 'testnet', - getSigningKeyWif: () => parsed.signingKeyWif, - } - - const registryId = NETWORKS.testnet.registryContractId as string - await evoSdkService.initialize({ - network: 'testnet', - contractIds: [registryId, M1_REPO_CONTRACT], - timeoutMs: 20000, - }) - const sdk = evoSdkService.getSdk() - const repo: V1RepoRef = { kind: 'v1', contractId: M1_REPO_CONTRACT, ownerId: parsed.identityId, name: '' } - - // 2. Create an issue via the browser write path. - const title = `web-path smoke ${new Date().toISOString()}` - const created = await createIssue(sdk, auth, repo, { - title, - body: 'Created by forge-web WriteEngine (browser signing path).', - }) - // eslint-disable-next-line no-console - console.log('issue created:', { - documentId: created.documentId, - uploader: 'owner', - number: created.number, - confirmed: created.confirmed, - costDash: created.cost.dash, - }) - expect(created.documentId.length).toBeGreaterThan(0) - - // 3. Read it back and fold its state — proves a web-created doc is readable + folds. - const issues = await listIssues(sdk, repo, undefined, 50) - const mine = issues.find((i) => i.id === created.documentId) - expect(mine, 'the web-created issue should be listable').toBeDefined() - expect(mine?.title).toBe(title) - expect(mine?.author).toBe(parsed.identityId) - expect(mine?.state.open).toBe(true) - // eslint-disable-next-line no-console - console.log('issue read back + folded:', { number: mine?.number, open: mine?.state.open }) - - // 4. Resolve the m1 listing id (repoContractId is not indexed on repoListing, so query by - // the repo owner via the ownerName index and match the contract id client-side), then star it. - const repoOwner = await fetchContractOwner(sdk, M1_REPO_CONTRACT) - expect(repoOwner, 'm1 repo contract must have an owner').not.toBeNull() - const { documents } = await queryDocumentsWithProof(sdk, { - dataContractId: registryId, - documentTypeName: REGISTRY_DOC.repoListing, - where: [['$ownerId', '==', repoOwner as string]], - orderBy: [['$ownerId', 'asc'], ['normalizedName', 'asc']], - limit: 100, - }) - // repoListing.repoContractId is an identifier-typed byteArray: evo-sdk 4.0 serialized - // it as base64, 4.2 as base58. Normalize through the same helper the app uses. - const listing = documents.find( - (d) => asIdentifierString(d['repoContractId']) === M1_REPO_CONTRACT, - ) - expect(listing, 'm1 repo must have a registry listing').toBeDefined() - const listingId = listing?.['$id'] as string - - // The deployed registry's `star.listing` index is a compound (listingId, $createdAt) - // countable index, so the O(1) count-tree (readStarCount) is rejected by the proof helper - // (documented in forge-core star_count). Count star rows directly instead. - const countStars = async (): Promise => { - const { documents: stars } = await queryDocumentsWithProof(sdk, { - dataContractId: registryId, - documentTypeName: REGISTRY_DOC.star, - where: [['listingId', '==', listingId]], - orderBy: [['listingId', 'asc'], ['$createdAt', 'desc']], - limit: 100, - }) - return stars.length - } - const before = await countStars() - const confirmed = await starRelation(sdk, auth, auth.identityId, repo, listingId, 'testnet').add() - const after = await countStars() - // eslint-disable-next-line no-console - console.log('star:', { listingId, confirmed, before, after }) - // Idempotent: a fresh star increments; a re-star leaves the count unchanged (already ours). - expect(confirmed).toBe(true) - expect(after).toBeGreaterThanOrEqual(before) - expect(after).toBeGreaterThanOrEqual(1) - }, - 180000, - ) -}) diff --git a/forge-web/lib/repo/writes.ts b/forge-web/lib/repo/writes.ts index 1c6bb9612..0e3afa6a0 100644 --- a/forge-web/lib/repo/writes.ts +++ b/forge-web/lib/repo/writes.ts @@ -1,27 +1,23 @@ /** - * Write paths — the browser signing surface, for forge-v2 repos and (where still cheap) v1. + * Write paths — the browser signing surface for forge-v2 repos. * * Every write builds a document whose on-chain encoding matches forge-core byte for byte * (identifier fields as raw 32-byte values, `refNameHash = sha256(refName)`, event `kind` * integers), signs it through the {@link createDocumentIdempotent} WriteEngine, and returns * the estimate shown before signing plus the balance change it caused. * - * forge-v2 (`docs/contracts/forge-v2.md`): a repo is three documents in forge-core (`repo`, + * `docs/contracts/forge-v2.md`: a repo is three documents in forge-core (`repo`, * the owner's `maintainer`, the first `config`), created resumably; members are `maintainer` / * `writer` documents the owner creates and deletes; issues, comments, reviews, `event` * (members) and `authorEvent` (the author's close/reopen) live in forge-collab, and consensus * enforces every gate. `star` and `follow` are `indexOnly`: a delete carries the document's * values (the SDK's index-only delete). Issue numbers follow the `allocateNumber` rule (§6). - * - * v1 (testnet): issue, comment, event, review, release, star, follow and the collaborator - * token admin keep working for existing repos. Creating a v1 repo from the browser is gone: - * new repos are forge-v2 (a v1 repo was a ~1.18 DASH contract). */ import type { EvoSDK } from '@dashevo/evo-sdk' import { hexToBytes } from '@noble/hashes/utils.js' -import { requireRegistryContractId, type Network } from '../constants' +import type { Network } from '../constants' import type { ForgeIds } from '../deployments' import { decodeIdentifier } from '../auth/base58' import { idbDelete, idbEntries, idbGet, idbPut } from '../idb' @@ -31,26 +27,19 @@ import { DUPLICATE_UNIQUE_CODE, GATE_REFUSED_CODE, UnconfirmedWriteError, - serialized, - createGateFor, countDocuments, createDocumentIdempotent, deleteDocumentIdempotent, - grantRole, previewCredits, - queryAllDocuments, queryDocumentsWithProof, - revokeRole, - suspendRole, type DeleteResult, type WriteAuth, type WriteResult, } from '../sdk' -import { DOC, REGISTRY_DOC, V2_DOC, asIdentifierString, num, str, type RepoRef, type V1RepoRef, type V2RepoRef } from './contract' +import { DOC, V2_DOC, num, str, type RepoRef } from './contract' import { invalidateMembers } from './members' import { invalidateRepoFeed } from './issues' import { repoSource } from './source' -import { invalidateAuthz } from './tokens' // --------------------------------------------------------------------------- // event kind name → integer (parity with forge-core `event_kind_to_u64`) @@ -99,27 +88,25 @@ function isDuplicate(e: unknown): boolean { return e instanceof ConsensusRefusal && e.code === DUPLICATE_UNIQUE_CODE } -/** The contract a write of `documentType` targets, for either data model. */ +/** The contract (forge-core or forge-collab) a write of `documentType` targets. */ function contractFor(repo: RepoRef, documentType: string): string { - return repo.kind === 'v1' ? repo.contractId : repoSource(repo).repoQuery(documentType).dataContractId + return repoSource(repo).repoQuery(documentType).dataContractId } -/** `data` plus, on forge-v2, the `repoId` every repo-scoped type carries. */ +/** `data` plus the `repoId` every repo-scoped type carries. */ function scoped(repo: RepoRef, data: Record): Record { - return repo.kind === 'v1' ? data : { repoId: decodeIdentifier(repo.repoId), ...data } + return { repoId: decodeIdentifier(repo.repoId), ...data } } /** Drop the caches a write to `repo` invalidates, so the next read shows it. */ function afterWrite(repo: RepoRef, network: Network): void { - if (repo.kind === 'v2') { - invalidateRepoFeed(repo) - invalidateMembers(repo, network) - } + invalidateRepoFeed(repo) + invalidateMembers(repo, network) } /** - * Create one repo-scoped document: the right contract, `repoId` on v2, the v1 token gate on - * v1 (forge-v2 types carry none), then drop the caches the write invalidates. + * Create one repo-scoped document: the right contract, `repoId` set, then drop the caches + * the write invalidates. */ async function writeRepoDoc( sdk: EvoSDK, @@ -134,7 +121,6 @@ async function writeRepoDoc( contractId: contractFor(repo, documentType), documentType, data: scoped(repo, data), - gate: repo.kind === 'v1' ? createGateFor(documentType) ?? null : null, ...(intent ? { intent } : {}), }) } finally { @@ -167,7 +153,7 @@ function firstId(documents: readonly Record[]): string | null { } // --------------------------------------------------------------------------- -// Issue numbering (forge-v2.md §6 `allocate_number`; v1 keeps max + 1) +// Issue numbering (forge-v2.md §6 `allocate_number`) // --------------------------------------------------------------------------- /** The `number` field of a result row, or null. */ @@ -177,12 +163,12 @@ function numberOf(doc: Record): number | null { } /** - * The number the allocation rule gives the next issue (or PR) of a forge-v2 repo: + * The number the allocation rule gives the next issue (or PR) of a repo: * `n` = the provable count, `base` = the largest taken number at or below the ceiling, then * — only when `base` sits at the ceiling — the contiguous run of taken numbers above it, * paged to its end. Null when nothing is left to allocate. */ -export async function nextNumberV2(sdk: EvoSDK, repo: V2RepoRef, type: 'issue' | 'patch'): Promise { +export async function nextNumberV2(sdk: EvoSDK, repo: RepoRef, type: 'issue' | 'patch'): Promise { const source = repoSource(repo) const count = await countDocuments(sdk, source.repoQuery(DOC[type])) const ceiling = numberCeiling(count) @@ -228,17 +214,6 @@ export async function nextNumberV2(sdk: EvoSDK, repo: V2RepoRef, type: 'issue' | return allocateNumber(count, taken.sort((a, b) => b - a)) } -/** v1: the newest number + 1 (a v1 repo contract has no numbering rule beyond uniqueness). */ -async function nextNumberV1(sdk: EvoSDK, repo: V1RepoRef): Promise { - const { documents } = await queryDocumentsWithProof(sdk, { - dataContractId: repo.contractId, - documentTypeName: DOC.issue, - orderBy: [['number', 'desc']], - limit: 1, - }) - return (documents[0] ? numberOf(documents[0]) ?? 0 : 0) + 1 -} - // --------------------------------------------------------------------------- // Issues / comments / events / reviews // --------------------------------------------------------------------------- @@ -261,7 +236,7 @@ export async function createIssue( input: { title: string; body: string; intent?: string }, onRetry?: (taken: number, next: number) => void, ): Promise { - let number = repo.kind === 'v2' ? await nextNumberV2(sdk, repo, 'issue') : await nextNumberV1(sdk, repo) + let number = await nextNumberV2(sdk, repo, 'issue') for (let attempt = 0; attempt < 4; attempt++) { if (number === null) throw new Error('this repo has no issue numbers left to allocate') const data: Record = { number, title: input.title } @@ -277,7 +252,7 @@ export async function createIssue( if (holder === undefined || holder === null || holder === auth.identityId) throw e } else if (!isDuplicate(e)) throw e const taken: number = number - number = repo.kind === 'v2' ? await nextNumberV2(sdk, repo, 'issue') : taken + 1 + number = await nextNumberV2(sdk, repo, 'issue') if (number !== null && number <= taken) number = taken + 1 if (number !== null) onRetry?.(taken, number) } @@ -306,22 +281,23 @@ export async function createComment( /** The document data of a state event on `target`. */ function eventData( - repo: RepoRef, target: WriteTarget, kind: EventKindName, extra: { value?: string; oidHex?: string } = {}, ): Record { - const data: Record = { targetId: decodeIdentifier(target.id), kind: EVENT_KIND_INT[kind] } - if (repo.kind === 'v2') data['targetNumber'] = target.number + const data: Record = { + targetId: decodeIdentifier(target.id), + targetNumber: target.number, + kind: EVENT_KIND_INT[kind], + } if (extra.value !== undefined && extra.value.length > 0) data['value'] = extra.value if (extra.oidHex !== undefined && extra.oidHex.length > 0) data['oid'] = hexToBytes(extra.oidHex) return data } /** - * Append a member `event` (close / reopen / label / assign / merge mark, …). On forge-v2 - * consensus admits it only from a current maintainer or writer (40120 otherwise); on v1 it - * lands for anyone and the fold decides whether it counts. + * Append a member `event` (close / reopen / label / assign / merge mark, …). Consensus admits + * it only from a current maintainer or writer (40120 otherwise). */ export async function addEvent( sdk: EvoSDK, @@ -329,12 +305,12 @@ export async function addEvent( repo: RepoRef, input: { target: WriteTarget; kind: EventKindName; value?: string; oidHex?: string; intent?: string }, ): Promise { - return writeRepoDoc(sdk, auth, repo, DOC.event, eventData(repo, input.target, input.kind, input), input.intent) + return writeRepoDoc(sdk, auth, repo, DOC.event, eventData(input.target, input.kind, input), input.intent) } /** - * The issue or PR author's own close / reopen. forge-v2 has a type for it (`authorEvent`, - * gated to the target's author, `forge-v2.md` §3); v1 folds the author's plain `event`. + * The issue or PR author's own close / reopen: an `authorEvent`, gated to the target's author + * (`forge-v2.md` §3). */ export async function addAuthorEvent( sdk: EvoSDK, @@ -342,8 +318,7 @@ export async function addAuthorEvent( repo: RepoRef, input: { target: WriteTarget; kind: 'close' | 'reopen'; intent?: string }, ): Promise { - if (repo.kind === 'v1') return addEvent(sdk, auth, repo, input) - return writeRepoDoc(sdk, auth, repo, V2_DOC.authorEvent, eventData(repo, input.target, input.kind), input.intent) + return writeRepoDoc(sdk, auth, repo, V2_DOC.authorEvent, eventData(input.target, input.kind), input.intent) } /** Which state-event type a close/reopen by the viewer should be. */ @@ -394,7 +369,7 @@ export async function createReview( } // --------------------------------------------------------------------------- -// Releases (maintainer-only on v2; MAINTAIN-gated on v1) +// Releases (maintainer-only) // --------------------------------------------------------------------------- /** A release asset (hash-verified download; stored as a JSON string). */ @@ -405,7 +380,7 @@ export interface ReleaseAsset { readonly uri: string } -/** Create a `release`: newest per tag wins. Maintainers only (consensus on v2). */ +/** Create a `release`: newest per tag wins. Maintainers only (consensus-gated). */ export async function createRelease( sdk: EvoSDK, auth: WriteAuth, @@ -420,7 +395,7 @@ export async function createRelease( } // --------------------------------------------------------------------------- -// forge-v2 social: star / follow (indexOnly) +// Social: star / follow (indexOnly) // --------------------------------------------------------------------------- interface RawDocumentsFacade { @@ -488,39 +463,28 @@ export interface Relation { remove(): Promise } -/** - * The viewer's star on a repo: forge-collab `star` on v2, the registry `star` on the v1 - * listing (`listingId`) otherwise. - */ -export function starRelation(sdk: EvoSDK, auth: WriteAuth | null, viewer: string, repo: RepoRef, listingId: string | null, network: Network): Relation { - if (repo.kind === 'v2') { - return { - read: async () => (await findOwnIndexOnly(sdk, repo.forge, 'star', viewer, repo.repoId)) !== null, - add: async () => (await createIndexOnly(sdk, need(auth), repo.forge, 'star', repo.repoId)).confirmed, - remove: async () => (await deleteIndexOnly(sdk, need(auth), repo.forge, 'star', repo.repoId)).deleted, - } - } - const listing = listingId ?? '' +/** The viewer's star on a repo (forge-collab `star`). */ +export function starRelation(sdk: EvoSDK, auth: WriteAuth | null, viewer: string, repo: RepoRef): Relation { return { - read: async () => (await findOwnRegistryDoc(sdk, network, viewer, REGISTRY_DOC.star, 'listingId', listing)) !== null, - add: async () => (await createRegistryRelation(sdk, need(auth), REGISTRY_DOC.star, 'listingId', listing)).confirmed, - remove: async () => (await deleteRegistryRelation(sdk, need(auth), REGISTRY_DOC.star, 'listingId', listing)).deleted, + read: async () => (await findOwnIndexOnly(sdk, repo.forge, 'star', viewer, repo.repoId)) !== null, + add: async () => (await createIndexOnly(sdk, need(auth), repo.forge, 'star', repo.repoId)).confirmed, + remove: async () => (await deleteIndexOnly(sdk, need(auth), repo.forge, 'star', repo.repoId)).deleted, } } -/** The viewer's follow of `target`: forge-collab `follow` where forge-v2 runs, else the registry. */ -export function followRelation(sdk: EvoSDK, auth: WriteAuth | null, viewer: string, forge: ForgeIds | null, target: string, network: Network): Relation { - if (forge !== null) { - return { - read: async () => (await findOwnIndexOnly(sdk, forge, 'follow', viewer, target)) !== null, - add: async () => (await createIndexOnly(sdk, need(auth), forge, 'follow', target)).confirmed, - remove: async () => (await deleteIndexOnly(sdk, need(auth), forge, 'follow', target)).deleted, - } +/** + * The viewer's follow of `target` (forge-collab `follow`). `forge` null (not deployed): every + * call refuses, so a caller can build the relation unconditionally and gate on deployment. + */ +export function followRelation(sdk: EvoSDK, auth: WriteAuth | null, viewer: string, forge: ForgeIds | null, target: string): Relation { + const f = (): ForgeIds => { + if (forge === null) throw new Error('Dash Forge is not deployed on this network') + return forge } return { - read: async () => (await findOwnRegistryDoc(sdk, network, viewer, REGISTRY_DOC.follow, 'identityId', target)) !== null, - add: async () => (await createRegistryRelation(sdk, need(auth), REGISTRY_DOC.follow, 'identityId', target)).confirmed, - remove: async () => (await deleteRegistryRelation(sdk, need(auth), REGISTRY_DOC.follow, 'identityId', target)).deleted, + read: async () => (await findOwnIndexOnly(sdk, f(), 'follow', viewer, target)) !== null, + add: async () => (await createIndexOnly(sdk, need(auth), f(), 'follow', target)).confirmed, + remove: async () => (await deleteIndexOnly(sdk, need(auth), f(), 'follow', target)).deleted, } } @@ -530,80 +494,13 @@ function need(auth: WriteAuth | null): WriteAuth { } // --------------------------------------------------------------------------- -// v1 social (registry) — stars + follows on existing v1 networks -// --------------------------------------------------------------------------- - -/** - * Resolve `ownerId`'s own registry doc (star/follow) whose `field` equals `targetId`, via the - * `$ownerId` index (filtered client-side by field — the single-field owner query matches the - * deployed registry index, mirroring forge-core `find_own`). Complete: a user past 100 stars - * could otherwise not remove an older one. - */ -async function findOwnRegistryDoc( - sdk: EvoSDK, - network: Network, - ownerId: string, - documentType: string, - field: string, - targetId: string, -): Promise { - const documents = await queryAllDocuments(sdk, { - dataContractId: requireRegistryContractId(network), - documentTypeName: documentType, - where: [['$ownerId', '==', ownerId]], - orderBy: [['$ownerId', 'asc'], ['$createdAt', 'desc']], - }) - for (const doc of documents) { - if (asIdentifierString(doc[field]) === targetId) { - const id = doc['$id'] - if (typeof id === 'string') return id - } - } - return null -} - -async function createRegistryRelation( - sdk: EvoSDK, - auth: WriteAuth, - documentType: string, - field: string, - targetId: string, -): Promise { - return createOrExisting( - () => - createDocumentIdempotent(sdk, auth, { - contractId: requireRegistryContractId(auth.network), - documentType, - data: { [field]: decodeIdentifier(targetId) }, - }), - () => findOwnRegistryDoc(sdk, auth.network, auth.identityId, documentType, field, targetId), - ) -} - -async function deleteRegistryRelation( - sdk: EvoSDK, - auth: WriteAuth, - documentType: string, - field: string, - targetId: string, -): Promise { - const existing = await findOwnRegistryDoc(sdk, auth.network, auth.identityId, documentType, field, targetId) - if (!existing) return ALREADY_GONE - return deleteDocumentIdempotent(sdk, auth, { - contractId: requireRegistryContractId(auth.network), - documentType, - documentId: existing, - }) -} - -// --------------------------------------------------------------------------- -// forge-v2 membership (owner-only) +// Membership (owner-only) // --------------------------------------------------------------------------- const ROLE_DOC: Readonly> = { maintainer: V2_DOC.maintainer, writer: V2_DOC.writer } /** The membership document `(repoId, memberId)` of `role`, or null. */ -async function findMembership(sdk: EvoSDK, repo: V2RepoRef, role: Role, memberId: string): Promise { +async function findMembership(sdk: EvoSDK, repo: RepoRef, role: Role, memberId: string): Promise { const { documents } = await queryDocumentsWithProof( sdk, repoSource(repo).repoQuery(ROLE_DOC[role], { where: [['memberId', '==', memberId]], limit: 1 }), @@ -612,13 +509,13 @@ async function findMembership(sdk: EvoSDK, repo: V2RepoRef, role: Role, memberId } /** - * Grant `memberId` a role on a forge-v2 repo: the owner creates a `maintainer` or `writer` + * Grant `memberId` a role on a repo: the owner creates a `maintainer` or `writer` * document (consensus refuses anyone else). Idempotent: an existing membership is success. */ export async function grantMember( sdk: EvoSDK, auth: WriteAuth, - repo: V2RepoRef, + repo: RepoRef, memberId: string, role: Role, intent?: string, @@ -642,7 +539,7 @@ export async function grantMember( export async function revokeMember( sdk: EvoSDK, auth: WriteAuth, - repo: V2RepoRef, + repo: RepoRef, memberId: string, role: Role, ): Promise { @@ -659,32 +556,6 @@ export async function revokeMember( return result } -// --------------------------------------------------------------------------- -// v1 collaborators (token admin — CRITICAL key) -// --------------------------------------------------------------------------- - -/** - * v1 collaborator token admin: grant (mint), suspend (freeze) or revoke (freeze + destroy) a - * WRITE (`maintain=false`) or MAINTAIN role. - */ -export async function adminCollaborator( - sdk: EvoSDK, - auth: WriteAuth, - repo: V1RepoRef, - op: 'grant' | 'suspend' | 'revoke', - memberId: string, - maintain: boolean, -): Promise { - const role = maintain ? 'maintain' : 'write' - // The token ops use this identity's nonces too: queue them behind any document write. - await serialized(auth.identityId, async () => { - if (op === 'grant') await grantRole(sdk, auth, repo.contractId, memberId, role) - else if (op === 'suspend') await suspendRole(sdk, auth, repo.contractId, memberId, role) - else await revokeRole(sdk, auth, repo.contractId, memberId, role) - }) - invalidateAuthz(repo.contractId) -} - // --------------------------------------------------------------------------- // forge-v2 repo creation (three documents, resumable) // --------------------------------------------------------------------------- @@ -818,7 +689,7 @@ export async function createRepoV2( journal.repoId = repoId await save() const R = decodeIdentifier(repoId) - const repo: V2RepoRef = { kind: 'v2', forge, repoId, ownerId, name, visibility: 'public' } + const repo: RepoRef = { forge, repoId, ownerId, name, visibility: 'public' } // 2. the owner's maintainer document (unique per repo + member) await step('maintainer', async () => { diff --git a/forge-web/lib/rules/conformance.test.ts b/forge-web/lib/rules/conformance.test.ts index 50babad18..18e9547c4 100644 --- a/forge-web/lib/rules/conformance.test.ts +++ b/forge-web/lib/rules/conformance.test.ts @@ -3,11 +3,11 @@ * * Loads every `forge-contracts/vectors/*.json` and asserts this TypeScript port produces the * vector's `expected` — the exact same suite the Rust reference runs at the bottom of - * `crates/forge-core/src/rules.rs`. A vector's `rules` field picks the rule set: absent or - * `"v1"` is FORGE_RULES_V1, `"v2"` is FORGE_RULES_V2 (`./v2`). If this is green, the two - * clients agree on ref resolution, protected-pattern matching, issue/PR folds (v1 and v2), - * token holdings, ref naming, flatIndex staleness overlay, and the v2 numbering, pack-copy, - * approval, well-formedness and repo-name rules. + * `crates/forge-core/src/rules.rs`. A vector's `rules` field picks the rule set: absent is + * the base rules forge-v2 shares (ref resolution, protected-pattern matching, ref naming, + * flatIndex staleness overlay, verdict labels), `"v2"` is FORGE_RULES_V2 (`./v2`); any other + * value fails as unknown. If this is green, the two clients agree on all of those and on the + * v2 issue/PR folds, numbering, pack-copy, approval, well-formedness and repo-name rules. * * SCOPE, stated precisely because it has been over-read: every vector hands the pure * functions a ready-made input array, so this suite proves the two ports FOLD identically @@ -23,12 +23,8 @@ import { resolve } from 'node:path' import { describe, expect, it } from 'vitest' import { - AuthzResolver, ancestryFromPairs, displayRefName, - foldIssueState, - foldPrState, - holdingsAsOf, matchesProtected, overlayTree, resolveRef, @@ -40,7 +36,6 @@ import type { Event, FlatIndex, RefUpdate, - TokenRecord, TreeDiff, } from './types' @@ -48,7 +43,7 @@ interface Vector { readonly name: string readonly description: string readonly case: string - readonly rules?: 'v1' | 'v2' + readonly rules?: string readonly input: unknown readonly expected: unknown } @@ -67,26 +62,6 @@ interface MatchesProtectedInput { readonly patterns: readonly string[] } -interface HoldingsInput { - readonly records: readonly TokenRecord[] - readonly identity: string - readonly at: number -} - -interface FoldIssueInput { - readonly events: readonly Event[] - readonly targetAuthor: string - readonly tokenRecords?: readonly TokenRecord[] -} - -interface FoldPrInput { - readonly events: readonly Event[] - readonly targetAuthor: string - readonly tokenRecords?: readonly TokenRecord[] - readonly baseTip?: string | null - readonly ancestry?: Pairs -} - interface OverlayInput { readonly base: FlatIndex readonly diffs?: readonly TreeDiff[] @@ -109,7 +84,7 @@ function loadVectors(): Vector[] { }) } -function runCase(v: Vector): void { +function runCaseBase(v: Vector): void { switch (v.case) { case 'resolve_ref': { const inp = v.input as ResolveRefInput @@ -138,43 +113,19 @@ function runCase(v: Vector): void { expect(matchesProtected(inp.refName, inp.patterns)).toEqual(v.expected) break } - case 'holdings': { - const inp = v.input as HoldingsInput - expect(holdingsAsOf(inp.records, inp.identity, inp.at)).toEqual(v.expected) - break - } - case 'fold_issue': { - const inp = v.input as FoldIssueInput - const authz = new AuthzResolver(inp.tokenRecords ?? []) - expect(foldIssueState(inp.events, inp.targetAuthor, authz)).toEqual(v.expected) - break - } - case 'fold_pr': { - const inp = v.input as FoldPrInput - const authz = new AuthzResolver(inp.tokenRecords ?? []) - const got = foldPrState( - inp.events, - inp.targetAuthor, - authz, - inp.baseTip ?? undefined, - ancestryFromPairs(inp.ancestry ?? []), - ) - expect(got).toEqual(v.expected) - break - } case 'overlay': { const inp = v.input as OverlayInput expect(overlayTree(inp.base, inp.diffs ?? [])).toEqual(v.expected) break } default: - throw new Error(`unknown vector case: ${v.case}`) + throw new Error(`unknown base vector case: ${v.case}`) } } /** * The keys each v2 input record may carry. The harness refuses any other key, at any depth, - * as the Rust harness does, so a vector cannot carry a field (v1's `tokenRecords`, a misspelt + * as the Rust harness does, so a vector cannot carry a field (a retired `tokenRecords`, a misspelt * `supersedes`) that the rules silently ignore. */ const EVENT_KEYS = ['id', 'targetId', 'kind', 'actor', 'value', 'oid', 'createdAt'] @@ -324,6 +275,13 @@ function runCaseV2(v: Vector): void { } } +/** Run one vector under the rule set its `rules` field names (absent = base). */ +function runVector(v: Vector): void { + if (v.rules === undefined) runCaseBase(v) + else if (v.rules === 'v2') runCaseV2(v) + else throw new Error(`unknown vector rule set "${v.rules}" in ${v.name}`) +} + interface V2FoldInput { readonly events?: readonly Event[] readonly authorEvents?: readonly Event[] @@ -332,23 +290,33 @@ interface V2FoldInput { describe('FORGE_RULES conformance vectors', () => { const vectors = loadVectors() - const v1 = vectors.filter((v) => (v.rules ?? 'v1') === 'v1') + const base = vectors.filter((v) => v.rules === undefined) const v2Vectors = vectors.filter((v) => v.rules === 'v2') it('loads the full vector corpus', () => { - expect(v1.length).toBeGreaterThanOrEqual(70) + expect(base.length).toBeGreaterThanOrEqual(45) expect(v2Vectors.length).toBeGreaterThanOrEqual(110) - expect(v1.length + v2Vectors.length).toBe(vectors.length) }) - for (const v of v1) { - it(`v1 ${v.case} :: ${v.name}`, () => { - runCase(v) + it('knows every vector rule set', () => { + const unknown = vectors.filter((v) => v.rules !== undefined && v.rules !== 'v2') + expect(unknown.map((v) => `${v.name} (rules: ${v.rules})`)).toEqual([]) + }) + + it('rejects a vector with an unknown rule set', () => { + expect(() => runVector({ name: 'x', description: '', case: 'resolve_ref', rules: 'v1', input: {}, expected: null })).toThrow( + /unknown vector rule set/, + ) + }) + + for (const v of base) { + it(`base ${v.case} :: ${v.name}`, () => { + runVector(v) }) } for (const v of v2Vectors) { it(`v2 ${v.case} :: ${v.name}`, () => { - runCaseV2(v) + runVector(v) }) } }) diff --git a/forge-web/lib/rules/fold.ts b/forge-web/lib/rules/fold.ts index 97f36f305..00c9e2686 100644 --- a/forge-web/lib/rules/fold.ts +++ b/forge-web/lib/rules/fold.ts @@ -1,26 +1,14 @@ /** - * Event fold — issue / PR state. + * Event fold building blocks — issue / PR state. * - * Ports `fold_issue_state` / `fold_pr_state` / `actor_authorized` / `ordered_events` - * from `crates/forge-core/src/rules.rs`. Events may be unordered and may include spam - * from non-holders; they are ordered by `(createdAt, id)` and each is applied only if - * its actor is authorized as-of the event's `createdAt`. - * - * The per-kind effects (`applyIssueEvent`, `applyPrEvent`) and merge reachability - * (`mergeReachable`) are shared with the FORGE_RULES_V2 fold in `./v2`, as in Rust. + * The per-kind effects (`applyIssueEvent`, `applyPrEvent`), merge reachability + * (`mergeReachable`) and the state accumulators the FORGE_RULES_V2 fold in `./v2` applies, + * ported from `crates/forge-core/src/rules.rs`. */ -import { AuthzResolver, holdingsAny } from './holdings' -import { compareKey, compareStrings, isLegalRefName } from './oid' +import { compareStrings, isLegalRefName } from './oid' import type { Event, IsAncestor, IssueState, PrState } from './types' -/** Order events deterministically by `(createdAt, id)`. */ -function orderedEvents(events: readonly Event[]): Event[] { - return [...events].sort(compareKey) -} - -const NO_ANCESTRY: IsAncestor = () => false - /** * 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: reachability cannot be proven, so the merge is inert. @@ -35,26 +23,6 @@ export function mergeReachable( return isAncestor(oid, baseTip) } -/** Is event `e`'s actor authorized to apply it, evaluated as-of `e.createdAt`? */ -function actorAuthorized( - e: Event, - targetAuthor: string, - authz: AuthzResolver, - baseTip: string | undefined, - isAncestor: IsAncestor, -): boolean { - const holder = holdingsAny(authz.holdingsAsOf(e.actor, e.createdAt)) - switch (e.kind) { - case 'close': - case 'reopen': - return holder || e.actor === targetAuthor - case 'merge': - return holder && mergeReachable(e, baseTip, isAncestor) - default: - return holder - } -} - /** Mutable issue state while folding. */ export interface IssueAcc { open: boolean @@ -77,7 +45,7 @@ export function newPrAcc(): PrAcc { return { ...newIssueAcc(), merged: false, draft: false, baseRef: null } } -/** Apply one authorized event to an issue (both rule versions). PR-only kinds do nothing. */ +/** Apply one authorized event to an issue. PR-only kinds do nothing. */ export function applyIssueEvent(s: IssueAcc, e: Event): void { switch (e.kind) { case 'close': @@ -106,7 +74,7 @@ export function applyIssueEvent(s: IssueAcc, e: Event): void { } } -/** Apply one authorized event to a PR (both rule versions). */ +/** Apply one authorized event to a PR. */ export function applyPrEvent(s: PrAcc, e: Event): void { switch (e.kind) { case 'reopen': @@ -147,34 +115,6 @@ export function prStateOf(s: PrAcc): PrState { } } -/** Fold an issue's `event` log into its {@link IssueState}. */ -export function foldIssueState( - events: readonly Event[], - targetAuthor: string, - authz: AuthzResolver, -): IssueState { - const s = newIssueAcc() - for (const e of orderedEvents(events)) { - if (actorAuthorized(e, targetAuthor, authz, undefined, NO_ANCESTRY)) applyIssueEvent(s, e) - } - return issueStateOf(s) -} - -/** Fold a PR's `event` log into its {@link PrState}. */ -export function foldPrState( - events: readonly Event[], - targetAuthor: string, - authz: AuthzResolver, - baseTip: string | undefined, - isAncestor: IsAncestor, -): PrState { - const s = newPrAcc() - for (const e of orderedEvents(events)) { - if (actorAuthorized(e, targetAuthor, authz, baseTip, isAncestor)) applyPrEvent(s, e) - } - return prStateOf(s) -} - /** Sort + dedupe a set into a stable array (mirrors Rust's BTreeSet ordering: code points). */ export function sorted(set: ReadonlySet): string[] { return [...set].sort(compareStrings) diff --git a/forge-web/lib/rules/holdings.ts b/forge-web/lib/rules/holdings.ts deleted file mode 100644 index 8c3f36c79..000000000 --- a/forge-web/lib/rules/holdings.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Token-history authorization (as-of-time). - * - * Ports `holdings_as_of` / `token_spendable_as_of` / `AuthzResolver` from - * `crates/forge-core/src/rules.rs`. Reconstructs an identity's *spendable* WRITE/MAINTAIN - * holdings at a point in time by replaying mint/freeze/unfreeze/destroy records with - * `createdAt <= at`, tie-broken by `id`. - */ - -import { compareKey } from './oid' -import type { Holdings, TokenKind, TokenRecord } from './types' - -/** Whether the identity holds an unfrozen balance for either token (the "holder" gate). */ -export function holdingsAny(h: Holdings): boolean { - return h.write || h.maintain -} - -/** Reconstruct an identity's spendable WRITE/MAINTAIN holdings as-of time `at`. */ -export function holdingsAsOf( - records: readonly TokenRecord[], - identity: string, - at: number, -): Holdings { - return { - write: tokenSpendableAsOf(records, identity, 'write', at), - maintain: tokenSpendableAsOf(records, identity, 'maintain', at), - } -} - -function tokenSpendableAsOf( - records: readonly TokenRecord[], - identity: string, - token: TokenKind, - at: number, -): boolean { - const relevant = records - .filter((r) => r.identity === identity && r.token === token && r.createdAt <= at) - .sort(compareKey) - - let held = false - let frozen = false - for (const r of relevant) { - switch (r.op) { - case 'mint': - held = true - frozen = false - break - case 'freeze': - frozen = true - break - case 'unfreeze': - frozen = false - break - case 'destroy': - held = false - frozen = false - break - } - } - return held && !frozen -} - -/** - * A token-history-backed authorization resolver. Thin wrapper over {@link holdingsAsOf} - * so callers can thread one object through the fold instead of the record slice. - */ -export class AuthzResolver { - constructor(private readonly records: readonly TokenRecord[]) {} - - holdingsAsOf(identity: string, at: number): Holdings { - return holdingsAsOf(this.records, identity, at) - } -} diff --git a/forge-web/lib/rules/index.ts b/forge-web/lib/rules/index.ts index 8355684cd..ff1f8d044 100644 --- a/forge-web/lib/rules/index.ts +++ b/forge-web/lib/rules/index.ts @@ -1,7 +1,7 @@ /** - * FORGE_RULES_V1 — the cross-client-parity heart of Dash Forge (TypeScript port). + * FORGE_RULES — the cross-client-parity heart of Dash Forge (TypeScript port). * - * Dash Platform enforces token spend, schema, and uniqueness at consensus, but it has no + * Dash Platform enforces the forge-v2 writer gates, schema, and uniqueness at consensus, but it has no * CAS, cannot read glob patterns, and cannot fold an append-only event log into "is this * issue open". Those decisions are made client-side, and every conforming client must * make them IDENTICALLY. This module is the TypeScript half of that shared logic; the @@ -16,16 +16,11 @@ * `createdAt` carried on every document. */ -/** The versioned rules identifier shared with forge-core and the conformance vectors. */ -export const FORGE_RULES_V1 = 'FORGE_RULES_V1' as const - export * from './types' export { compareKey, compareStrings, isLegalRefName, isNullOid } from './oid' export { matchesProtected, neutralizeWildmatch, wildmatch } from './matchesProtected' -export { AuthzResolver, holdingsAny, holdingsAsOf } from './holdings' export { displayRefName, resolveRef } from './resolveRef' -export { foldIssueState, foldPrState } from './fold' export { overlayTree } from './overlay' -// FORGE_RULES_V2 (forge-v2 shared-contract repositories) +// FORGE_RULES_V2: the forge-v2 membership, event-fold, pack and numbering rules export * as v2 from './v2' export { FORGE_RULES_V2 } from './v2' diff --git a/forge-web/lib/rules/matchesProtected.ts b/forge-web/lib/rules/matchesProtected.ts index e85f98cd7..91ed806ef 100644 --- a/forge-web/lib/rules/matchesProtected.ts +++ b/forge-web/lib/rules/matchesProtected.ts @@ -8,7 +8,7 @@ * alternation — into literals. This TS port neutralizes identically and then runs a * faithful git-`wildmatch` matcher, so it never needs the crate's extensions at all. * - * Pinned semantics (FORGE_RULES_V1): + * Pinned semantics (FORGE_RULES): * `*` matches any run of chars EXCEPT `/` (stays within one ref segment) * `**` (a whole path segment) matches across `/` (any number of segments) * `?` matches a single non-`/` char diff --git a/forge-web/lib/rules/oid.ts b/forge-web/lib/rules/oid.ts index d4a8f0416..eb2cea1a4 100644 --- a/forge-web/lib/rules/oid.ts +++ b/forge-web/lib/rules/oid.ts @@ -1,5 +1,5 @@ /** - * OID / ref-name primitives shared by the FORGE_RULES_V1 fold paths. + * OID / ref-name primitives shared by the FORGE_RULES fold paths. * * Ports the free functions at the top of `crates/forge-core/src/rules.rs` * (`is_null_oid`, `is_legal_ref_name`, `is_content_hash`, `ref_name_hash_matches`). diff --git a/forge-web/lib/rules/resolveRef.ts b/forge-web/lib/rules/resolveRef.ts index 8e62dce61..156f9edc7 100644 --- a/forge-web/lib/rules/resolveRef.ts +++ b/forge-web/lib/rules/resolveRef.ts @@ -3,7 +3,7 @@ * * Ports `resolve_ref` (+ `is_update_valid`, `config_as_of`) from * `crates/forge-core/src/rules.rs`, byte-for-byte behaviorally. Implements - * data-contracts §4 protected-ref routing plus the §2.3 same-`prevOid` divergence rule, + * protected-ref routing (`forge-v2.md` §2, §6) plus the same-`prevOid` divergence rule, * with the prevOid causal DAG authoritative over the `(createdAt, id)` clock. */ @@ -46,7 +46,7 @@ function isUpdateValid(u: RefUpdate, configHistory: readonly ConfigDoc[]): boole * * A shared rule, not a reader convenience, because the two halves of a 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 carrying any legal + * content. A writer may therefore file an update under `main`'s hash carrying any legal * name. {@link resolveRef} 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. Parity: forge-core `rules::display_ref_name`. @@ -133,7 +133,7 @@ export function resolveRef( const h = heads[0] as RefHead return { state: 'resolved', oid: h.oid, author: h.author, createdAt: h.createdAt } } - // Newest-first by (createdAt, id): heads[0] is the provisional read-only tip (§2.3). + // Newest-first by (createdAt, id): heads[0] is the provisional tip a reader shows. heads.sort((a, b) => compareKey(b, a)) return { state: 'diverged', heads } } diff --git a/forge-web/lib/rules/types.ts b/forge-web/lib/rules/types.ts index 4f4558867..c48d566fc 100644 --- a/forge-web/lib/rules/types.ts +++ b/forge-web/lib/rules/types.ts @@ -1,10 +1,10 @@ /** - * FORGE_RULES_V1 — shared type definitions. + * FORGE_RULES — shared type definitions. * * These are the TypeScript half of the cross-client-parity contract. Every type here * mirrors a struct in `crates/forge-core/src/rules.rs` and deserializes the same * `forge-contracts/vectors/*.json` shapes (camelCase, `createdAt` in ms). The rules are - * PURE: callers fetch documents (refUpdate / config / event / token-history / flatIndex) + * PURE: callers fetch documents (refUpdate / config / event / flatIndex) * and hand them in as plain objects; the only clock is the consensus `createdAt`. */ @@ -66,31 +66,13 @@ export type RefState = } | { readonly state: 'diverged'; readonly heads: readonly RefHead[] } -/** Which repo token a history record concerns (§2.1). */ -export type TokenKind = 'write' | 'maintain' - -/** A token-history operation (§2.1 grant/suspend/revoke lifecycle). */ -export type TokenOp = 'mint' | 'freeze' | 'unfreeze' | 'destroy' - -/** One record from the system token-history contract. */ -export interface TokenRecord { - /** Record `$id` — tiebreak for equal `createdAt`. */ - readonly id?: string - /** The affected identity. */ - readonly identity: string - /** Which token. */ - readonly token: TokenKind - /** What happened. */ - readonly op: TokenOp - /** Consensus `$createdAt` (ms). */ - readonly createdAt: number -} - -/** Whether an identity can *spend* WRITE / MAINTAIN at a point in time. */ +/** + * What an identity may do on a repo now, from its forge-v2 membership: `write` for a writer + * or maintainer (push, act on issues and PRs), `maintain` for a maintainer only (protected + * refs, config, releases). + */ export interface Holdings { - /** Holds an unfrozen WRITE balance (can push). */ readonly write: boolean - /** Holds an unfrozen MAINTAIN balance (can protected-push / configure). */ readonly maintain: boolean } @@ -115,7 +97,7 @@ export interface Event { readonly targetId?: string /** What happened. */ readonly kind: EventKind - /** Document `$ownerId` — the actor whose authorization is checked as-of `createdAt`. */ + /** Document `$ownerId` — the actor. */ readonly actor: string /** Kind-dependent payload: label name, assignee id, or retarget base ref. */ readonly value?: string | null diff --git a/forge-web/lib/rules/v2.ts b/forge-web/lib/rules/v2.ts index fa8b1ccd1..2dafa7447 100644 --- a/forge-web/lib/rules/v2.ts +++ b/forge-web/lib/rules/v2.ts @@ -6,8 +6,7 @@ * module and `docs/contracts/forge-v2.md` (§3 events, §4 packs, §5 private repos, §6 * numbering and approvals) for the normative text. * - * The event order and per-kind effects are v1's own (`./fold`), so the two rule versions - * cannot drift apart where they are meant to agree. + * The per-kind event effects live in `./fold`, shared with forge-core's `rules.rs`. */ import { @@ -83,7 +82,7 @@ function authorEventApplies(e: Event, targetAuthor: string): boolean { return (e.kind === 'close' || e.kind === 'reopen') && e.actor === targetAuthor } -/** Both document types, applicable ones only, in v1's `(createdAt, id)` order (stable). */ +/** Both document types, applicable ones only, in `(createdAt, id)` order (stable). */ function mergedLog( events: readonly Event[], authorEvents: readonly Event[], diff --git a/forge-web/lib/sdk/cost.ts b/forge-web/lib/sdk/cost.ts index cd471dc0c..871c9d20e 100644 --- a/forge-web/lib/sdk/cost.ts +++ b/forge-web/lib/sdk/cost.ts @@ -9,9 +9,6 @@ * with 4,000 bytes 167.7M; comments 47.6M / 74.3M / 157.2M for 10 / 1,000 / 4,000 bytes. * The post-write actual (the balance change) is recorded next to each estimate in the spend * ledger, so drift shows up there (`ux-dx-spec.md` §4 rule 2). - * - * v1 repos (testnet, protocol 13) use the same model; their token-gated types add one - * WRITE/MAINTAIN token, shown separately. */ /** 1 DASH = 1e11 credits (parity with forge-core `credits_to_dash`). */ @@ -43,8 +40,6 @@ export const BASE_CREDITS: Readonly> = { review: 34_900_000, star: 27_800_000, follow: 38_400_000, - // v1 registry - repoListing: 60_000_000, } const DEFAULT_BASE_CREDITS = 50_000_000 @@ -66,18 +61,11 @@ export const DELETE_CREDITS: Readonly> = { review: -20_000_000, } -/** The fee a v1 token-admin action (mint / freeze / destroy) is estimated at. */ -export const TOKEN_ADMIN_CREDITS = 15_000_000 - /** A pre-sign cost preview for the confirm UI. */ export interface CostPreview { /** Estimated credits; negative when the action refunds storage. */ readonly credits: number readonly dash: number - /** The token spend, when the action is v1 token-gated (1 WRITE/MAINTAIN token), else 0. */ - readonly tokenAmount: number - /** Token position spent (0 WRITE / 1 MAINTAIN), when gated. */ - readonly tokenPosition?: number } /** Credit → DASH (display). */ @@ -87,7 +75,7 @@ export function creditsToDash(credits: number): number { /** A preview for a plain credit amount. */ export function previewCredits(credits: number): CostPreview { - return { credits, dash: creditsToDash(credits), tokenAmount: 0 } + return { credits, dash: creditsToDash(credits) } } /** UTF-8 bytes of every string in `data` (the text a document stores beyond its fixed shape). */ @@ -108,7 +96,7 @@ export function estimateCreateCredits(documentType: string, data: Readonly> = {}): CostPreview { return previewCredits(estimateCreateCredits(documentType, data)) } @@ -120,7 +108,5 @@ export function previewDelete(documentType: string): CostPreview { /** The sum of several previews (a repo creation is three documents). */ export function sumPreviews(parts: readonly CostPreview[]): CostPreview { - const credits = parts.reduce((s, p) => s + p.credits, 0) - const tokenAmount = parts.reduce((s, p) => s + p.tokenAmount, 0) - return { credits, dash: creditsToDash(credits), tokenAmount } + return previewCredits(parts.reduce((s, p) => s + p.credits, 0)) } diff --git a/forge-web/lib/sdk/index.ts b/forge-web/lib/sdk/index.ts index 44cb5e2f2..2117194cd 100644 --- a/forge-web/lib/sdk/index.ts +++ b/forge-web/lib/sdk/index.ts @@ -1,9 +1,9 @@ /** * evo-sdk services — the browser Platform I/O layer. * - * `EvoSDK.testnetTrusted()` + `*WithProof` reads (the only WASM-viable path, S0.3), with - * the base64 byteArray operand encoding, skip-scan ref enumeration, and the in-batch - * completeness fallback (S0.8) that active-repo correctness depends on. + * Trusted-mode connections (`testnetTrusted()` / `mainnetTrusted()` / a devnet's) + `*WithProof` + * reads (the only WASM-viable path, S0.3), with the base64 byteArray operand encoding and the + * complete, tie-safe paging that active-repo correctness depends on. */ export { ensureSdk, evoSdkService, type EvoSdkConfig } from './service' @@ -16,7 +16,6 @@ export { isNonceUsedError, newIntent, serialized, - REPO_CREATE_GATES, SECURITY_LEVEL, WriteAuthError, asConsensusRefusal, @@ -24,21 +23,17 @@ export { isStaleDocumentIdError, measureActual, pendingWriteKey, - createGateFor, deleteDocumentIdempotent, findSigningKey, isAlreadyExistsError, - previewDocumentCreate, readIdentityBalance, type DeleteResult, type SpendEvent, - type TokenGate, type WriteAuth, type WriteResult, } from './write' export { CREDITS_PER_DASH, - TOKEN_ADMIN_CREDITS, creditsToDash, previewCreate, previewCredits, @@ -46,14 +41,6 @@ export { sumPreviews, type CostPreview, } from './cost' -export { - GRANT_AMOUNT, - ROLE_POSITION, - grantRole, - revokeRole, - suspendRole, - type Role, -} from './token-admin' export { ascendingEquivalent, base64ToBytes, @@ -67,7 +54,6 @@ export { IncompleteReadError, queryDocuments, queryDocumentsWithProof, - skipScanDistinct, tieProbeAllowed, type DocumentQuery, type OrderByClause, diff --git a/forge-web/lib/sdk/query.ts b/forge-web/lib/sdk/query.ts index 65a458a01..742bcffc9 100644 --- a/forge-web/lib/sdk/query.ts +++ b/forge-web/lib/sdk/query.ts @@ -11,9 +11,6 @@ * 2. **`in`-batches do NOT round-robin** — a single global `limit` is drawn in * orderBy-traversal order, so one hot key starves all siblings (measured 9/9 starved). * So a multi-key read is done per key, in parallel, not as one `in` batch. - * - * Plus **skip-scan** distinct-key enumeration ({@link skipScanDistinct}, used for pushers): `> lastKey` orderBy key - * `limit 1` hops to the next distinct key — O(log n) per distinct ref, not O(total pushes). */ import type { EvoSDK } from '@dashevo/evo-sdk' @@ -67,7 +64,7 @@ export type WhereOperator = export type WhereClause = readonly [field: string, operator: WhereOperator, value: unknown] /** A single `orderBy` clause: `[field, direction]`. Stored indexes are asc-only; */ -/** `desc` is query-time reverse traversal (data-contracts §0). */ +/** `desc` is query-time reverse traversal of an index. */ export type OrderByClause = readonly [field: string, direction: 'asc' | 'desc'] /** A raw document query. `byteArray` operands in `where` must already be base64 (see above). */ @@ -173,7 +170,7 @@ export async function queryDocumentsWithProof( } /** - * Provable O(1) count over a countable index (data-contracts §3). Sums the grouped result + * Provable O(1) count over a countable index (`forge-v2.md` §2). Sums the grouped result * the SDK returns for `documents.count`. Use for star / follower / issue-total surfaces. */ export async function countDocuments(sdk: EvoSDK, query: DocumentQuery): Promise { @@ -192,7 +189,7 @@ export async function countDocuments(sdk: EvoSDK, query: DocumentQuery): Promise * `platform::ascending_equivalent`. * * A complete read pages with a `startAfter` cursor. The grovedb verifier in evo-sdk 4.2 checks - * that every proof op matches the walk direction. Protocol-13 nodes (testnet today) answer a + * that every proof op matches the walk direction. Protocol-13 nodes answered a * descending page after a cursor with a proof that fails that check. It surfaced as * `packManifest` reads failing once a repo passed 100 manifests. Ascending pages verify, and * Drive's descending walk is the exact reverse of its ascending walk. Reversing also @@ -224,8 +221,8 @@ export class IncompleteReadError extends Error { * Page a query to exhaustion (the `query_all` pattern — parity with forge-core * `platform::query_all_documents`). Repeats the proof-verified query, advancing `startAfter` * past the last `$id` of each page, until a **short page** proves the end was reached. Used by - * every read that MUST be complete: the deterministic folds (`resolve_ref`, `foldIssueState`, - * `foldPrState`) are folds over a whole history, so a silently truncated input does not + * every read that MUST be complete: the deterministic folds (`resolve_ref`, `foldIssueStateV2`, + * `foldPrStateV2`) are folds over a whole history, so a silently truncated input does not * degrade the answer — it produces a confidently wrong one (a closed issue that reads open, * a branch pinned at its 100th push). * @@ -250,9 +247,8 @@ export class IncompleteReadError extends Error { * Documents created in the same block as a page's last row that sort after it would be * silently skipped. Protocol 14 bounds the cursor by document id and does not drop them. * - * Limitation: the fix 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 protocol-13 gap until they move to forge-v2 on protocol 14. + * forge-v2 runs on protocol 14, so this is a safety net there, kept for parity with forge-core. + * It needs the boundary row's `$createdAt`, which every forge-v2 history type requires. */ export function tieProbeAllowed(query: DocumentQuery): boolean { const orderBy = query.orderBy ?? [] @@ -337,65 +333,3 @@ export async function queryAllDocuments( `the ${maxPages}-page safety cap was reached before a short page proved the end`, ) } - -// --------------------------------------------------------------------------- -// Skip-scan distinct-key enumeration (branch/tag listing) -// --------------------------------------------------------------------------- - -/** - * Enumerate the distinct values of an indexed key via `limit 1` skip hops (S0.8): - * seek the first row ordered by `keyField asc`, record its key, then seek - * `keyField > lastKey limit 1` repeatedly. Cost is one cheap seek per distinct key — - * bounded by real branch/tag counts, NOT by how many times any one ref was pushed. - * - * `keyIsBase64` values are compared/advanced as base64 strings (the wasm result form). - * Returns the distinct key values (base64) in ascending order, with a hard `maxKeys` cap. - */ -export async function skipScanDistinct( - sdk: EvoSDK, - params: { - readonly dataContractId: string - readonly documentTypeName: string - readonly keyField: string - readonly maxKeys?: number - }, -): Promise { - const { dataContractId, documentTypeName, keyField } = params - const maxKeys = params.maxKeys ?? 10_000 - const keys: string[] = [] - let last: string | undefined - - // maxKeys + 1 iterations: the extra probe distinguishes "exactly maxKeys keys, and we are - // done" from "more keys remain". Without it an enumeration that WAS complete throws. - for (let i = 0; i <= maxKeys; i++) { - const where: WhereClause[] = last === undefined ? [] : [[keyField, '>', last]] - const rows = await queryDocuments(sdk, { - dataContractId, - documentTypeName, - where, - orderBy: [[keyField, 'asc']], - limit: 1, - }) - const row = rows[0] - // No further row: the strictly-increasing cursor has passed the last key. This is the - // only way out that proves the enumeration is complete. - if (row === undefined) return keys - const key = row[keyField] - if (typeof key !== 'string') { - throw new IncompleteReadError( - documentTypeName, - keys.length, - `a row has no string ${keyField}, so the skip-scan cursor cannot advance`, - ) - } - keys.push(key) - last = key - } - // A truncated ref enumeration is the same class of confidently-wrong answer as a - // truncated history: the caller would render "these are the branches" from a partial set. - throw new IncompleteReadError( - documentTypeName, - keys.length, - `more than ${maxKeys} distinct ${keyField} values exist; the safety cap was reached`, - ) -} diff --git a/forge-web/lib/sdk/service.ts b/forge-web/lib/sdk/service.ts index c7f6825df..442dfe337 100644 --- a/forge-web/lib/sdk/service.ts +++ b/forge-web/lib/sdk/service.ts @@ -17,7 +17,7 @@ import { setPlatformVersion } from './query' export interface EvoSdkConfig { readonly network: Network - /** Contract ids to preload (registry + the repo contract(s) in view + DPNS). */ + /** Contract ids to preload (DPNS + the forge-v2 contracts). */ readonly contractIds: readonly string[] /** Per-request timeout (ms). */ readonly timeoutMs?: number @@ -177,12 +177,12 @@ class EvoSdkService { export const evoSdkService = new EvoSdkService() /** - * The connected SDK for `network`, connecting first if needed (the registry, DPNS and forge-v2 + * The connected SDK for `network`, connecting first if needed (the DPNS and forge-v2 * contracts preloaded). Flows that start before any page has connected (sign-in) use this. */ export async function ensureSdk(network: Network): Promise { - const { registryContractId, dpnsContractId, v2 } = NETWORKS[network] - const contractIds = [registryContractId, dpnsContractId, v2?.core, v2?.collab].filter( + const { dpnsContractId, v2 } = NETWORKS[network] + const contractIds = [dpnsContractId, v2?.core, v2?.collab].filter( (id): id is string => typeof id === 'string' && id.length > 0, ) await evoSdkService.initialize({ network, contractIds, timeoutMs: 15000 }) diff --git a/forge-web/lib/sdk/token-admin.ts b/forge-web/lib/sdk/token-admin.ts deleted file mode 100644 index 4d60a196c..000000000 --- a/forge-web/lib/sdk/token-admin.ts +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Token-admin writes — collaborator grant (mint) / suspend (freeze) / revoke (freeze + destroy). - * - * These are the CRITICAL-key token operations (S0.7: token admin ops reject a HIGH key). Unlike - * document writes they go through the typed token facade (`tokens.mint` / `freeze` / - * `destroyFrozen`), which builds + broadcasts + waits internally — the browser is the supported - * runtime for these (the Node `waitForResponse` panic does not apply in a real browser). - * - * Parity with forge-core `tokens.rs`: grant mints `GRANT_AMOUNT` of the role token to the member - * (WRITE = position 0, MAINTAIN = position 1) and **verifies via a balance query** — the - * keepsHistory `mint()` return value is not trusted (known SDK bug, spike-results). Suspend - * freezes; revoke freezes-then-destroys. Idempotent: a grant to an existing (unfrozen) holder, - * or a freeze of an already-frozen balance, is a no-op success. - */ - -import type { EvoSDK, IdentityPublicKey, IdentitySigner } from '@dashevo/evo-sdk' - -import { findSigningKey, SECURITY_LEVEL, WriteAuthError, type WriteAuth } from './write' - -/** Amount minted per grant (a single role token confers the ACL; parity with forge-core). */ -export const GRANT_AMOUNT = 1 - -/** Repo role → token position (WRITE = 0, MAINTAIN = 1). */ -export const ROLE_POSITION = { write: 0, maintain: 1 } as const -export type Role = keyof typeof ROLE_POSITION - -interface TokensFacadeLike { - calculateId(contractId: string, tokenPosition: number): Promise - balances(identityIds: string[], tokenId: string): Promise> - identitiesTokenInfos(identityIds: string[], tokenId: string): Promise> - mint(options: unknown): Promise - freeze(options: unknown): Promise - unfreeze(options: unknown): Promise - destroyFrozen(options: unknown): Promise -} -interface IdentitiesFacadeLike { - fetch(identityId: string): Promise< - | { - readonly publicKeys: { - keyId: number - purposeNumber: number - securityLevelNumber: number - validatePrivateKey(bytes: Uint8Array, network: string): boolean - }[] - readonly balance: bigint - getPublicKeyById(keyId: number): unknown - } - | undefined - > -} -interface SdkTokenFacades { - tokens: TokensFacadeLike - identities: IdentitiesFacadeLike -} -function facades(sdk: EvoSDK): SdkTokenFacades { - return sdk as unknown as SdkTokenFacades -} - -/** Build the CRITICAL-key signer material (signer + wasm public key) for a token-admin op. */ -async function criticalSigner( - sdk: EvoSDK, - auth: WriteAuth, -): Promise<{ signer: IdentitySigner; identityKey: IdentityPublicKey }> { - const wif = auth.getSigningKeyWif() - const identity = await facades(sdk).identities.fetch(auth.identityId) - if (!identity) throw new WriteAuthError(`identity ${auth.identityId} not found`) - const signing = await findSigningKey(identity, wif, auth.network, SECURITY_LEVEL.CRITICAL) - if (!signing) { - throw new WriteAuthError( - 'token-admin operations require a CRITICAL AUTHENTICATION key that matches the stored key', - ) - } - const { IdentitySigner } = await import('@dashevo/evo-sdk') - const signer = new IdentitySigner() - signer.addKeyFromWif(wif) - return { signer, identityKey: signing.publicKey as IdentityPublicKey } -} - -function isFrozen(info: unknown): boolean { - if (info != null && typeof info === 'object') { - const rec = info as Record - if (rec['isFrozen'] === true || rec['frozen'] === true) return true - } - return false -} - -async function balanceOf(sdk: EvoSDK, tokenId: string, member: string): Promise { - const balances = await facades(sdk).tokens.balances([member], tokenId) - return balances.get(member) ?? 0n -} -async function frozenOf(sdk: EvoSDK, tokenId: string, member: string): Promise { - const infos = await facades(sdk).tokens.identitiesTokenInfos([member], tokenId) - return isFrozen(infos.get(member)) -} - -/** - * Grant a collaborator a role (mint the role token to `memberId`). Idempotent: an existing - * unfrozen holder is skipped. Verified via a post-mint balance query. Returns whether a mint - * was actually broadcast. - */ -export async function grantRole( - sdk: EvoSDK, - auth: WriteAuth, - contractId: string, - memberId: string, - role: Role, -): Promise<{ minted: boolean }> { - const position = ROLE_POSITION[role] - const tokenId = await facades(sdk).tokens.calculateId(contractId, position) - if ((await balanceOf(sdk, tokenId, memberId)) > 0n) { - return { minted: false } - } - const { Identifier } = await import('@dashevo/evo-sdk') - const { signer, identityKey } = await criticalSigner(sdk, auth) - await facades(sdk).tokens.mint({ - dataContractId: new Identifier(contractId), - tokenPosition: position, - amount: BigInt(GRANT_AMOUNT), - identityId: new Identifier(auth.identityId), - recipientId: new Identifier(memberId), - identityKey, - signer, - }) - if ((await balanceOf(sdk, tokenId, memberId)) === 0n) { - throw new Error('grant broadcast but the member balance did not increase') - } - return { minted: true } -} - -/** Suspend a collaborator (freeze the role balance). Idempotent; verified via a freeze query. */ -export async function suspendRole( - sdk: EvoSDK, - auth: WriteAuth, - contractId: string, - memberId: string, - role: Role, -): Promise<{ frozen: boolean }> { - const position = ROLE_POSITION[role] - const tokenId = await facades(sdk).tokens.calculateId(contractId, position) - if (await frozenOf(sdk, tokenId, memberId)) return { frozen: true } - const { Identifier } = await import('@dashevo/evo-sdk') - const { signer, identityKey } = await criticalSigner(sdk, auth) - await facades(sdk).tokens.freeze({ - dataContractId: new Identifier(contractId), - tokenPosition: position, - authorityId: new Identifier(auth.identityId), - frozenIdentityId: new Identifier(memberId), - identityKey, - signer, - }) - if (!(await frozenOf(sdk, tokenId, memberId))) { - throw new Error('suspend broadcast but the member token is not frozen') - } - return { frozen: true } -} - -/** Revoke a collaborator's role: freeze (if needed) then destroy the frozen balance. */ -export async function revokeRole( - sdk: EvoSDK, - auth: WriteAuth, - contractId: string, - memberId: string, - role: Role, -): Promise<{ revoked: boolean }> { - const position = ROLE_POSITION[role] - const tokenId = await facades(sdk).tokens.calculateId(contractId, position) - const { Identifier } = await import('@dashevo/evo-sdk') - const { signer, identityKey } = await criticalSigner(sdk, auth) - if (!(await frozenOf(sdk, tokenId, memberId))) { - await facades(sdk).tokens.freeze({ - dataContractId: new Identifier(contractId), - tokenPosition: position, - authorityId: new Identifier(auth.identityId), - frozenIdentityId: new Identifier(memberId), - identityKey, - signer, - }) - } - await facades(sdk).tokens.destroyFrozen({ - dataContractId: new Identifier(contractId), - tokenPosition: position, - authorityId: new Identifier(auth.identityId), - frozenIdentityId: new Identifier(memberId), - identityKey, - signer, - }) - if ((await balanceOf(sdk, tokenId, memberId)) !== 0n) { - throw new Error('revoke broadcast but the member balance is not zero') - } - return { revoked: true } -} diff --git a/forge-web/lib/sdk/write-engine.test.ts b/forge-web/lib/sdk/write-engine.test.ts index 3d752d41a..6fe33c2da 100644 --- a/forge-web/lib/sdk/write-engine.test.ts +++ b/forge-web/lib/sdk/write-engine.test.ts @@ -51,7 +51,6 @@ vi.mock('@dashevo/evo-sdk', () => { }, BatchTransition: { fromBatchedTransitions: () => ({ toStateTransition: () => new ST() }) }, PrivateKey: { fromWIF: () => ({ toBytes: () => new Uint8Array(32) }) }, - TokenPaymentInfo: class {}, IdentitySigner: class { addKeyFromWif(): void {} free(): void {} diff --git a/forge-web/lib/sdk/write.test.ts b/forge-web/lib/sdk/write.test.ts index 01fc3141e..2083653e3 100644 --- a/forge-web/lib/sdk/write.test.ts +++ b/forge-web/lib/sdk/write.test.ts @@ -1,25 +1,20 @@ /** * WriteEngine unit tests — network-free parity + encoding checks. * - * The token gate table, cost math, base58 identifier encoding, WIF parsing, identity-file - * extraction and the calibrated cost model are deterministic and verified here against the same - * `repo-v1.json` the CLI compiles in, so a drift between the browser and Rust write encodings - * fails CI without needing testnet. + * The cost math, base58 identifier encoding, WIF parsing, identity-file extraction and the + * calibrated cost model are deterministic and verified here, so a drift between the browser + * and Rust write encodings fails CI without needing a network. */ import { describe, expect, it } from 'vitest' -import repoV1 from '../../../forge-contracts/templates/repo-v1.json' import { - REPO_CREATE_GATES, asConsensusRefusal, isAlreadyExistsError, isNonceUsedError, newIntent, - createGateFor, isStaleDocumentIdError, pendingWriteKey, - previewDocumentCreate, } from './write' import { CREDITS_PER_DASH, @@ -41,41 +36,6 @@ import { decodeWif, isLikelyWif, normalizeToWif, parsePrivateKey } from '../auth import { parseIdentityFile } from '../auth/identity-file' import { normalizeRepoName } from '../repo/writes' -// --------------------------------------------------------------------------- -// Token gate table — MUST match repo-v1.json tokenCost.create declarations -// --------------------------------------------------------------------------- - -describe('token gate table (repo-v1 parity)', () => { - it('matches every tokenCost.create in the bundled template', () => { - const schemas = (repoV1 as { documentSchemas: Record }).documentSchemas - for (const [name, schemaRaw] of Object.entries(schemas)) { - const schema = schemaRaw as { tokenCost?: { create?: { tokenPosition: number; amount: number } } } - const create = schema.tokenCost?.create - if (create) { - expect(REPO_CREATE_GATES[name], `${name} should be gated`).toEqual({ - position: create.tokenPosition, - amount: create.amount, - }) - } else { - expect(REPO_CREATE_GATES[name], `${name} should be ungated`).toBeUndefined() - } - } - }) - - it('leaves ungated author-owned types without a gate', () => { - for (const t of ['issue', 'patch', 'comment', 'event', 'review']) { - expect(createGateFor(t)).toBeUndefined() - } - }) - - it('gates refUpdate at WRITE (0) and release/label/config at MAINTAIN (1)', () => { - expect(createGateFor('refUpdate')).toEqual({ position: 0, amount: 1 }) - expect(createGateFor('release')).toEqual({ position: 1, amount: 1 }) - expect(createGateFor('label')).toEqual({ position: 1, amount: 1 }) - expect(createGateFor('config')).toEqual({ position: 1, amount: 1 }) - }) -}) - // --------------------------------------------------------------------------- // Cost preview // --------------------------------------------------------------------------- @@ -112,17 +72,6 @@ describe('cost preview', () => { it('previews deletes of indexOnly types as refunds', () => { expect(previewDelete('star').credits).toBeLessThan(0) }) - - it('folds the token spend into a gated create preview', () => { - const gated = previewDocumentCreate('release') - expect(gated.tokenAmount).toBe(1) - expect(gated.tokenPosition).toBe(1) - expect(gated.dash).toBeGreaterThan(0) - - const ungated = previewDocumentCreate('issue') - expect(ungated.tokenAmount).toBe(0) - expect(ungated.tokenPosition).toBeUndefined() - }) }) // --------------------------------------------------------------------------- @@ -208,7 +157,7 @@ describe('identity-file parsing', () => { ], } - it('picks the CRITICAL auth key (highest privilege that covers doc + token ops)', () => { + it('picks the CRITICAL auth key (the highest privilege a document write accepts)', () => { const parsed = parseIdentityFile(file) expect(parsed.identityId).toBe('8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB') expect(parsed.network).toBe('testnet') diff --git a/forge-web/lib/sdk/write.ts b/forge-web/lib/sdk/write.ts index 67f4a31a0..3eeb11d19 100644 --- a/forge-web/lib/sdk/write.ts +++ b/forge-web/lib/sdk/write.ts @@ -18,10 +18,6 @@ * intent token; retrying that action re-broadcasts the *same* signed ST (no new nonce, no * double post). Only "already in mempool/chain" or the doc appearing on a poll counts as * landed; a write not seen landing throws `UnconfirmedWriteError`, never resolves. - * - **Token gating**: WRITE/MAINTAIN-gated doc types carry a `TokenPaymentInfo` pinned to the - * contract-declared `tokenCost.create` (position + amount) so a later owner-side price change - * cannot overcharge — parity with forge-core's `token_payment_for`. Ungated types (issue / - * comment / event / patch / review, and the registry's star / follow / repoListing) carry none. * * Keys never enter React state or logs: the WIF is read from the network-scoped keystore only * here, wrapped in a `PrivateKey`, used to sign, and dropped. @@ -29,7 +25,7 @@ // Type-only: every evo-sdk class is loaded via dynamic `import()` at call time so the ~9.4 MB // WASM chunk never enters the initial bundle (it is pulled on the first write / login). -import type { EvoSDK, StateTransition, TokenPaymentInfo } from '@dashevo/evo-sdk' +import type { EvoSDK, StateTransition } from '@dashevo/evo-sdk' import { sha256 } from '@noble/hashes/sha2.js' import { bytesToHex } from '@noble/hashes/utils.js' @@ -119,7 +115,7 @@ export async function findSigningKey( matches = false } if (!matches) continue - // MASTER (0) is not usable for document/token ops; require CRITICAL/HIGH range that is at + // MASTER (0) is not usable for document ops; require CRITICAL/HIGH range that is at // least as privileged as the requirement. if (key.securityLevelNumber === SECURITY_LEVEL.MASTER) continue if (key.securityLevelNumber > requiredLevel) continue @@ -130,60 +126,6 @@ export async function findSigningKey( return null } -// --------------------------------------------------------------------------- -// Token gate table (parity with forge-contracts/templates/repo-v1.json) -// --------------------------------------------------------------------------- - -/** A doc type's `tokenCost.create`: token position (0 = WRITE, 1 = MAINTAIN) + amount. */ -export interface TokenGate { - readonly position: number - readonly amount: number -} - -/** - * The repo-v1 `tokenCost.create` gates. Ungated types (issue / patch / comment / event / - * review) are absent → no `TokenPaymentInfo`. Mirrors the template exactly (verified against - * `repo-v1.json`); the registry types (star / follow / repoListing) are all ungated. - */ -export const REPO_CREATE_GATES: Readonly> = { - config: { position: 1, amount: 1 }, - refUpdate: { position: 0, amount: 1 }, - protectedRefUpdate: { position: 1, amount: 1 }, - packManifest: { position: 0, amount: 1 }, - manifestPart: { position: 0, amount: 1 }, - chunk: { position: 0, amount: 1 }, - label: { position: 1, amount: 1 }, - release: { position: 1, amount: 1 }, - checkRun: { position: 0, amount: 1 }, - webhook: { position: 1, amount: 1 }, -} - -/** The token gate for a repo doc-type create, or undefined if the type is ungated. */ -export function createGateFor(documentType: string): TokenGate | undefined { - return REPO_CREATE_GATES[documentType] -} - -// --------------------------------------------------------------------------- -// Cost preview — the calibrated model lives in `./cost` -// --------------------------------------------------------------------------- - -/** - * The preview for a v1 repo-contract document create: the calibrated estimate plus the - * WRITE/MAINTAIN token its type spends, if gated. forge-v2 types spend no tokens; their - * previews come from {@link previewCreate} directly. - */ -export function previewDocumentCreate( - documentType: string, - data: Readonly> = {}, -): CostPreview { - const gate = createGateFor(documentType) - return { - ...previewCreate(documentType, data), - tokenAmount: gate?.amount ?? 0, - ...(gate ? { tokenPosition: gate.position } : {}), - } -} - // --------------------------------------------------------------------------- // Signed-ST idempotency cache (localStorage; keyed by the action's intent) // --------------------------------------------------------------------------- @@ -421,7 +363,7 @@ export interface SpendEvent { readonly network: Network /** `create:issue`, `delete:star`, `refused:issue` (a refused write still pays its fee), … */ readonly kind: string - /** The repo the write belongs to (base58 `repoId` / v1 contract id), when it has one. */ + /** The repo the write belongs to (base58 `repoId`), when it has one. */ readonly repo: string | null readonly documentId: string readonly estimateCredits: number @@ -494,7 +436,7 @@ function crossTab(identityId: string, run: () => Promise): Promise { return locks ? locks.request(`dash-forge-writer:${identityId}`, run) : run() } -/** Run `run` as this identity's only writer. Exported for the v1 token-admin path. */ +/** Run `run` as this identity's only writer. */ export function serialized(identityId: string, run: () => Promise): Promise { const prev = writeLocks.get(identityId) ?? Promise.resolve() const next = prev.then( @@ -538,7 +480,7 @@ function pollForDocument(sdk: EvoSDK, contractId: string, documentType: string, * * evo-sdk 4.2's `new Document({ properties })` (and the `properties` setter) converts the * properties through JSON, which turns every `Uint8Array` into an array of integers — Drive - * then rejects the write with "not an array of bytes" for any byteArray field (`listingId`, + * then rejects the write with "not an array of bytes" for any byteArray field (`repoId`, * `refNameHash`, `newOid`, ...). `Document.fromObject` converts a `Uint8Array` to bytes, which * is what 4.0's constructor did: the signed transition is byte-identical to 4.0's for every * top-level field. So the system fields come from a property-less constructor call and the @@ -612,8 +554,6 @@ export interface CreateParams { readonly data: Record /** The action this write belongs to ({@link newIntent}); a fresh token when omitted. */ readonly intent?: string - /** A v1 repo contract's token payment for this type (`createGateFor`); none by default. */ - readonly gate?: TokenGate | null readonly requiredLevel?: number readonly confirmTimeoutMs?: number /** Whether the write landed, for types `documents.get` cannot fetch (indexOnly). */ @@ -630,13 +570,8 @@ async function createDocumentUnlocked( const { contractId, documentType, data } = params const requiredLevel = params.requiredLevel ?? SECURITY_LEVEL.HIGH const confirmTimeoutMs = params.confirmTimeoutMs ?? 30_000 - const gate = params.gate ?? undefined const indexOnly = params.probe !== undefined - const cost: CostPreview = { - ...previewCreate(documentType, data), - tokenAmount: gate?.amount ?? 0, - ...(gate ? { tokenPosition: gate.position } : {}), - } + const cost: CostPreview = previewCreate(documentType, data) const landed = (documentId: string, timeoutMs: number): Promise => params.probe ? pollUntil(params.probe, timeoutMs) : pollForDocument(sdk, contractId, documentType, documentId, timeoutMs) @@ -694,7 +629,7 @@ async function createDocumentUnlocked( throw new WriteAuthError('no usable AUTHENTICATION key for the stored signing key (it may be disabled or expired)') } - const build = () => signCreate(sdk, { ownerId, contractId, documentType, data, gate, wif, publicKey: signing.publicKey }) + const build = () => signCreate(sdk, { ownerId, contractId, documentType, data, wif, publicKey: signing.publicKey }) let signed = await build() for (let attempt = 0; ; attempt++) { @@ -774,13 +709,12 @@ async function signCreate( readonly contractId: string readonly documentType: string readonly data: Record - readonly gate: TokenGate | undefined readonly wif: string readonly publicKey: unknown }, ): Promise<{ st: StateTransition; bytes: Uint8Array; documentId: string; nonce: bigint }> { - const { ownerId, contractId, documentType, data, gate } = p - const { Document, DocumentCreateTransition, BatchedTransition, BatchTransition, PrivateKey, TokenPaymentInfo } = await import('@dashevo/evo-sdk') + const { ownerId, contractId, documentType, data } = p + const { Document, DocumentCreateTransition, BatchedTransition, BatchTransition, PrivateKey } = await import('@dashevo/evo-sdk') // The nonce is fetched once and used for both the id and the transition. From protocol 14 // the document id commits to it (protocol 13: entropy only), and the create transition @@ -796,11 +730,6 @@ async function signCreate( const document = documentForCreate(Document, { data, documentType, contractId, ownerId, documentId, entropy, platformVersion }) - let tokenPaymentInfo: TokenPaymentInfo | undefined - if (gate) { - tokenPaymentInfo = new TokenPaymentInfo({ tokenContractPosition: gate.position, maximumTokenCost: BigInt(gate.amount) }) - } - // `platformVersion` is load-bearing: without it the transition re-derives the id at the // SDK's latest compiled version (14), which on a protocol-13 network is an id Drive does not // recompute, and the create is rejected. @@ -808,7 +737,6 @@ async function signCreate( document, identityContractNonce: nonce, platformVersion, - ...(tokenPaymentInfo ? { tokenPaymentInfo } : {}), }) if (document.id.toBase58() !== documentId) { throw new Error( diff --git a/forge-web/lib/view/browse-fallback.test.ts b/forge-web/lib/view/browse-fallback.test.ts index da4254b2c..392694ddc 100644 --- a/forge-web/lib/view/browse-fallback.test.ts +++ b/forge-web/lib/view/browse-fallback.test.ts @@ -24,13 +24,18 @@ import { packFrame, } from '../browse/pack-fixtures' import { CHUNK_PAYLOAD_MAX } from '../constants' -import type { PackManifest, V1RepoRef } from '../repo' +import type { PackManifest, RepoRef } from '../repo' import { base64ToHex, bytesToBase64 } from '../sdk' import { cachedFallback, startFallback, type FallbackProgress } from './browse-fallback' import { externalFetchUrls, resetExternalFetchState } from './browse-source' import { contentChecks, resetContentChecks } from './content-checks' import { deriveTrust } from './trust' +/** A repo whose session caches key by `repoId` (each test uses its own). */ +function testRepo(repoId: string): RepoRef { + return { forge: { core: 'CORE', collab: 'COLLAB', group: 'G' }, repoId, ownerId: 'owner', name: '', visibility: 'public' } +} + /** Mock SDK serving each pack's bytes as `chunk` docs split at CHUNK_PAYLOAD_MAX. */ function mockSdk(packsByHash: Map): EvoSDK { return { @@ -92,7 +97,7 @@ describe('startFallback', () => { it('downloads, verifies, indexes, and serves objects through the synthesized locator', async () => { const { pack, baseOid, targetOid, base, target } = fixturePack() const manifest = manifestFor(pack, 2) - const repo: V1RepoRef = { kind: 'v1', contractId: 'fallback-ok', ownerId: 'owner', name: '' } + const repo = testRepo('fallback-ok') const sdk = mockSdk(new Map([[manifest.packHash, pack]])) const phases: FallbackProgress['phase'][] = [] @@ -104,25 +109,25 @@ describe('startFallback', () => { expect(Array.from((await ctx.reader.readObject(targetOid)).bytes)).toEqual(Array.from(target)) // The session cache holds the completed run; a second start joins it. - expect(cachedFallback(repo.contractId)).not.toBeNull() + expect(cachedFallback(repo.repoId)).not.toBeNull() await expect(startFallback(sdk, repo, [manifest])).resolves.toBe(ctx) }) it('rejects on pack hash mismatch and evicts the cache entry', async () => { const { pack } = fixturePack() const manifest = manifestFor(pack, 2, { packHash: '00'.repeat(32) }) - const repo: V1RepoRef = { kind: 'v1', contractId: 'fallback-badhash', ownerId: 'owner', name: '' } + const repo = testRepo('fallback-badhash') const sdk = mockSdk(new Map([[manifest.packHash, pack]])) await expect(startFallback(sdk, repo, [manifest])).rejects.toThrow(/hash mismatch/) await Promise.resolve() // let the eviction handler run - expect(cachedFallback(repo.contractId)).toBeNull() + expect(cachedFallback(repo.repoId)).toBeNull() }) it('rejects when the manifest objectCount disagrees with the pack header', async () => { const { pack } = fixturePack() const manifest = manifestFor(pack, 5) - const repo: V1RepoRef = { kind: 'v1', contractId: 'fallback-badcount', ownerId: 'owner', name: '' } + const repo = testRepo('fallback-badcount') const sdk = mockSdk(new Map([[manifest.packHash, pack]])) await expect(startFallback(sdk, repo, [manifest])).rejects.toThrow(/header claims/) }) @@ -167,7 +172,7 @@ describe('startFallback with external-storage packs', () => { documentId: 'b', uploader: 'owner', }) - const repo: V1RepoRef = { kind: 'v1', contractId: 'fallback-partial', ownerId: 'owner', name: '' } + const repo = testRepo('fallback-partial') const calls = stubFetch({}) const ctx = await startFallback(mockSdk(new Map([[platform.packHash, plat.pack]])), repo, [platform, external]) @@ -183,10 +188,10 @@ describe('startFallback with external-storage packs', () => { new RegExp(`${external.packHash.slice(0, 12)}.*127\\.0\\.0\\.1:9000`), ) // The trust ledger reports the gap: content is partial, never verified. - const checks = contentChecks(repo.contractId) + const checks = contentChecks(repo.repoId) expect(checks.unavailablePacks).toEqual([external.packHash]) const trust = deriveTrust({ - network: 'testnet', + network: 'devnet', connection: 'trusted', tip: 'missing', checks, @@ -205,7 +210,7 @@ describe('startFallback with external-storage packs', () => { stubFetch({}) const ctx = await startFallback( mockSdk(new Map([[platform.packHash, plat.pack]])), - { kind: 'v1', contractId: 'fallback-dup', ownerId: 'owner', name: '' }, + testRepo('fallback-dup'), [platform, external('b'), external('c')], ) expect(ctx.unavailable).toHaveLength(1) @@ -214,7 +219,7 @@ describe('startFallback with external-storage packs', () => { it('fetches an ipfs:// pack through a gateway and verifies it', async () => { const ext = blobPack('pinned on ipfs\n') const external = manifestFor(ext.pack, 1, { storage: 1, chunkCount: 0, uris: ['ipfs://bafkreitest'] }) - const repo: V1RepoRef = { kind: 'v1', contractId: 'fallback-ipfs', ownerId: 'owner', name: '' } + const repo = testRepo('fallback-ipfs') const [first, second] = externalFetchUrls(external.uris) expect(first).toBe('https://ipfs.io/ipfs/bafkreitest') // The first gateway is down; the second serves the right bytes. @@ -222,7 +227,7 @@ describe('startFallback with external-storage packs', () => { const ctx = await startFallback(mockSdk(new Map()), repo, [external]) expect(ctx.unavailable).toEqual([]) expect((await ctx.reader.readObject(ext.oid)).type).toBe('blob') - expect(contentChecks(repo.contractId).sources).toEqual(['dweb.link']) + expect(contentChecks(repo.repoId).sources).toEqual(['dweb.link']) }) it('treats a mirror serving the wrong bytes as unavailable, not as content', async () => { @@ -230,20 +235,20 @@ describe('startFallback with external-storage packs', () => { const ext = blobPack('expected\n') const platform = manifestFor(plat.pack, 1, { createdAt: 1, documentId: 'a' }) const external = manifestFor(ext.pack, 1, { storage: 1, uris: ['https://mirror.example/p'], createdAt: 2, documentId: 'b' }) - const repo: V1RepoRef = { kind: 'v1', contractId: 'fallback-liar', ownerId: 'owner', name: '' } + const repo = testRepo('fallback-liar') // Same length as the real pack, different bytes: only the sha256 check can catch it. stubFetch({ 'https://mirror.example/p': () => blobPack('forgery!\n').pack }) const ctx = await startFallback(mockSdk(new Map([[platform.packHash, plat.pack]])), repo, [platform, external]) expect(ctx.unavailable?.[0]?.reason).toMatch(/sha256/) expect(ctx.unavailable?.[0]?.corrupt).toBe(true) - expect(contentChecks(repo.contractId).corruptMirrorPacks).toEqual([external.packHash]) + expect(contentChecks(repo.repoId).corruptMirrorPacks).toEqual([external.packHash]) await expect(ctx.reader.readObject(ext.oid)).rejects.toThrow(/could not be fetched/) }) it('still fails loudly when an on-chain pack cannot be read', async () => { const plat = blobPack('on-chain\n') const platform = manifestFor(plat.pack, 1) - const repo: V1RepoRef = { kind: 'v1', contractId: 'fallback-platform-missing', ownerId: 'owner', name: '' } + const repo = testRepo('fallback-platform-missing') // The chunk documents are absent: platform storage must not be skipped. await expect(startFallback(mockSdk(new Map()), repo, [platform])).rejects.toThrow(/missing chunk/) }) @@ -253,7 +258,7 @@ describe('startFallback with external-storage packs', () => { const external = manifestFor(ext.pack, 1, { storage: 1, uris: ['http://127.0.0.1:9000/p'] }) stubFetch({}) await expect( - startFallback(mockSdk(new Map()), { kind: 'v1', contractId: 'fallback-none', ownerId: 'owner', name: '' }, [external]), + startFallback(mockSdk(new Map()), testRepo('fallback-none'), [external]), ).rejects.toThrow(/none of this repo's 1 live packs could be fetched/) }) @@ -272,7 +277,7 @@ describe('startFallback with external-storage packs', () => { const i = Number(url.slice(url.lastIndexOf('p') + 1)) return new Response(new Blob([packs[i]?.pack as BlobPart]), { status: 200 }) }) - const ctx = await startFallback(mockSdk(new Map()), { kind: 'v1', contractId: 'fallback-origin', ownerId: 'o', name: '' }, manifests) + const ctx = await startFallback(mockSdk(new Map()), testRepo('fallback-origin'), manifests) expect(ctx.unavailable).toEqual([]) expect(peak).toBeLessThanOrEqual(4) }) @@ -292,7 +297,7 @@ describe('startFallback with external-storage packs', () => { } return Promise.resolve(new Response(new Blob([ext.pack as BlobPart]), { status: 200 })) }) - const run = startFallback(mockSdk(new Map()), { kind: 'v1', contractId: 'fallback-retry', ownerId: 'o', name: '' }, [external]) + const run = startFallback(mockSdk(new Map()), testRepo('fallback-retry'), [external]) await vi.advanceTimersByTimeAsync(16_000) vi.useRealTimers() const ctx = await run @@ -309,8 +314,8 @@ describe('startFallback with external-storage packs', () => { } const calls = stubFetch({}) const sdk = mockSdk(new Map([[platform.packHash, plat.pack]])) - await startFallback(sdk, { kind: 'v1', contractId: 'fallback-dead', ownerId: 'o', name: '' }, [platform, dead(1)]) - await startFallback(sdk, { kind: 'v1', contractId: 'fallback-dead-2', ownerId: 'o', name: '' }, [platform, dead(2)]) + await startFallback(sdk, testRepo('fallback-dead'), [platform, dead(1)]) + await startFallback(sdk, testRepo('fallback-dead-2'), [platform, dead(2)]) expect(calls).toEqual(['http://127.0.0.1:9000/p']) }) @@ -331,7 +336,7 @@ describe('startFallback with external-storage packs', () => { ), ) await expect( - startFallback(mockSdk(new Map()), { kind: 'v1', contractId: 'fallback-cancel', ownerId: 'o', name: '' }, [platform, external]), + startFallback(mockSdk(new Map()), testRepo('fallback-cancel'), [platform, external]), ).rejects.toThrow(/missing chunk/) expect(aborted).toBe(true) }) @@ -349,7 +354,7 @@ describe('startFallback with external-storage packs', () => { const b = manifestFor(packB, 1, { createdAt: 1, documentId: 'b' }) stubFetch({}) await expect( - startFallback(mockSdk(new Map([[b.packHash, packB]])), { kind: 'v1', contractId: 'fallback-thin', ownerId: 'o', name: '' }, [a, b]), + startFallback(mockSdk(new Map([[b.packHash, packB]])), testRepo('fallback-thin'), [a, b]), ).rejects.toThrow(new RegExp(`${a.packHash.slice(0, 12)}.*127\\.0\\.0\\.1:9000`)) }) @@ -359,11 +364,11 @@ describe('startFallback with external-storage packs', () => { const platform = manifestFor(plat.pack, 1, { createdAt: 0, documentId: 'a' }) const ext = blobPack('later\n') const external = manifestFor(ext.pack, 1, { storage: 1, uris: ['https://flaky.example/p'], createdAt: 1, documentId: 'b' }) - const repo: V1RepoRef = { kind: 'v1', contractId: 'fallback-expiry', ownerId: 'o', name: '' } + const repo = testRepo('fallback-expiry') vi.stubGlobal('fetch', () => Promise.resolve(new Response('nope', { status: 503 }))) await startFallback(mockSdk(new Map([[platform.packHash, plat.pack]])), repo, [platform, external]) - expect(cachedFallback(repo.contractId, [platform, external])).not.toBeNull() + expect(cachedFallback(repo.repoId, [platform, external])).not.toBeNull() await vi.advanceTimersByTimeAsync(61_000) - expect(cachedFallback(repo.contractId, [platform, external])).toBeNull() + expect(cachedFallback(repo.repoId, [platform, external])).toBeNull() }) }) diff --git a/forge-web/lib/view/browse-source.test.ts b/forge-web/lib/view/browse-source.test.ts index a1b33812a..2e108c35a 100644 --- a/forge-web/lib/view/browse-source.test.ts +++ b/forge-web/lib/view/browse-source.test.ts @@ -2,8 +2,8 @@ * Browse-source correctness: the two glue assumptions the UI build documented, now pinned * by tests (a wrong assumption means wrong bytes when browsing). * - * (a) packRef → pack ordering is oldest-first by `($createdAt, $id)`, bounded to packs that - * existed when the owning locator was published. + * (a) packRef → pack ordering is oldest-first by first upload `($createdAt, $id)`, bounded + * to packs that existed when the owning locator was published (`forge-v2.md` §4). * (b) offset → seq maps as `⌊offset / CHUNK_PAYLOAD_MAX⌋` because the chunker fills every * interior chunk to exactly `CHUNK_PAYLOAD_MAX` (forge-core `pack.rs::split`). */ @@ -14,8 +14,8 @@ import { bytesToHex } from '@noble/hashes/utils.js' import { beforeEach, describe, expect, it, vi } from 'vitest' import { CHUNK_PAYLOAD_MAX } from '../constants' -import type { PackManifest, V1RepoRef, V2RepoRef } from '../repo' -import { base64ToHex, bytesToBase64 } from '../sdk' +import type { PackManifest, V2RepoRef } from '../repo' +import { base64ToHex, bytesToBase64, hexToBase64 } from '../sdk' import { DOC } from '../repo' import { serializeLocator, type IndexedObject } from '../browse/indexer' import { @@ -33,7 +33,13 @@ import { // must be dropped between tests to keep the fixtures independent. beforeEach(() => clearChunkCache()) -const REPO: V1RepoRef = { kind: 'v1', contractId: 'contract', ownerId: 'owner', name: '' } +const REPO: V2RepoRef = { + forge: { core: 'CORE', collab: 'COLLAB', group: 'GROUP' }, + repoId: 'REPO', + ownerId: 'owner', + name: 'proj', + visibility: 'public', +} function gitPack(packHashHex: string, createdAt: number, documentId: string): PackManifest { return { @@ -206,25 +212,23 @@ describe('packRef ordering (assumption a)', () => { expect((await src.fetchRange(2, 0, 1))[0]).toBe(0xc3) // id "z" }) - it('excludes superseded packs, so a surviving repacked-over manifest cannot shift indices', async () => { - // `repack` consolidates packs and marks the originals `supersedes`, but deletes only the - // CALLER's own manifests — in a multi-author repo the others survive. Counting them - // would shift every packRef by however many happened to remain, which is incidental to - // who ran the repack. `cc` here is the consolidated pack; `aa` and `bb` are superseded - // but still present. + it('keeps superseded packs in place, so a repack never shifts indices', async () => { + // A Platform-tier repack only consolidates: it writes a superseding pack and deletes + // nothing (`forge-v2.md` §4). The superseded packs keep their positions, so every older + // locator's packRefs still mean what they meant; the consolidated pack is appended. const consolidated: PackManifest = { ...gitPack('cc', 300, 'z'), supersedes: ['aa', 'bb'] } const packs = [gitPack('aa', 100, 'x'), gitPack('bb', 200, 'y'), consolidated] const src = buildPackSource(sdk, REPO, packs) - expect((await src.fetchRange(0, 0, 1))[0]).toBe(0xc3) // the consolidated pack IS packRef 0 - await expect(src.fetchRange(1, 0, 1)).rejects.toThrow(/out of range/) + expect((await src.fetchRange(0, 0, 1))[0]).toBe(0xa1) + expect((await src.fetchRange(1, 0, 1))[0]).toBe(0xb2) + expect((await src.fetchRange(2, 0, 1))[0]).toBe(0xc3) }) - it('computes liveness within the asOf bound, so a later repack cannot rewrite an older locator', async () => { + it('bounds the space as of the locator, so a later repack cannot rewrite an older locator', async () => { // A repack published AFTER the locator supersedes packs the locator legitimately - // indexed. Bounding first and computing liveness second keeps the old locator meaning - // what it meant when it was written. + // indexed; the bound keeps the old locator meaning what it meant when it was written. const laterRepack: PackManifest = { ...gitPack('cc', 500, 'z'), supersedes: ['aa', 'bb'] } const packs = [gitPack('aa', 100, 'x'), gitPack('bb', 200, 'y'), laterRepack] @@ -248,17 +252,27 @@ describe('packRef ordering (assumption a)', () => { // loadBrowseContext — index fragments, coverage, and the honest degraded state // --------------------------------------------------------------------------- -/** A 32-byte hash as the pair of encodings a manifest is read through. */ -const hashB64 = (n: number): string => bytesToBase64(new Uint8Array(32).fill(n)) +/** + * A 32-byte hash as the base64 a manifest is read through: `n` filled (a git pack, whose + * bytes these tests never fetch), or a hex digest (an index fragment, which the reader + * sha256-checks against it). + */ +const hashB64 = (h: number | string): string => + typeof h === 'string' ? hexToBase64(h) : bytesToBase64(new Uint8Array(32).fill(h)) + +/** The packHash of an artifact: sha256 of its bytes, hex. */ +const digest = (bytes: Uint8Array): string => bytesToHex(sha256(bytes)) interface ManifestSpec { readonly id: string readonly createdAt: number readonly kind: 0 | 1 - readonly hash: number + readonly hash: number | string readonly sizeBytes?: number readonly objectCount?: number readonly supersedes?: readonly number[] + /** The uploader (`$ownerId`); absent = a non-member's copy. */ + readonly owner?: string } function manifestDoc(m: ManifestSpec): Record { @@ -268,6 +282,7 @@ function manifestDoc(m: ManifestSpec): Record { return { $id: m.id, $createdAt: m.createdAt, + ...(m.owner !== undefined ? { $ownerId: m.owner } : {}), packHash: hashB64(m.hash), kind: m.kind, sizeBytes: m.sizeBytes ?? 0, @@ -275,7 +290,7 @@ function manifestDoc(m: ManifestSpec): Record { // Kind-0 packs hold objects unless a test says otherwise; coverage exempts empty ones. objectCount: m.objectCount ?? (m.kind === 0 ? 2 : 0), storage: 0, - uris: '[]', + uris: [], tips: '', supersedes: supersedes.length > 0 ? bytesToBase64(packed) : '', } @@ -301,11 +316,13 @@ const oidBytes = (n: number): Uint8Array => /** * A mock serving both halves of a browse resolve: the `packManifest` listing (with the * `$createdAt desc` order, page cap and cursor a real query applies) and the `chunk` - * documents holding each index fragment's bytes. + * documents holding each index fragment's bytes — plus the repo's `maintainer` documents, + * which rank each manifest copy by its uploader's role. */ function browseSdk( manifests: readonly Record[], artifacts: ReadonlyMap, + maintainers: readonly Record[] = [], ): EvoSDK { return { documents: { @@ -315,6 +332,9 @@ function browseSdk( limit?: number startAfter?: string }): Promise> => { + if (q.documentTypeName === 'maintainer') { + return Promise.resolve(new Map(maintainers.map((d, i) => [`mt${i}`, d]))) + } if (q.documentTypeName === DOC.packManifest) { let rows = [...manifests].sort((a, b) => { const d = (b['$createdAt'] as number) - (a['$createdAt'] as number) @@ -342,8 +362,8 @@ describe('loadBrowseContext', () => { const F0 = fragmentBytes(0, [0x11, 0x13]) const F1 = fragmentBytes(1, [0x22, 0x24]) const artifacts = new Map([ - ['b0'.repeat(32).slice(0, 64), F0], - ['b1'.repeat(32).slice(0, 64), F1], + [digest(F0), F0], + [digest(F1), F1], ]) const pack0: ManifestSpec = { id: 'p0', createdAt: 100, kind: 0, hash: 0xa0 } const pack1: ManifestSpec = { id: 'p1', createdAt: 200, kind: 0, hash: 0xa1 } @@ -351,14 +371,14 @@ describe('loadBrowseContext', () => { id: 'f0', createdAt: 110, kind: 1, - hash: 0xb0, + hash: digest(F0), sizeBytes: F0.length, } const frag1: ManifestSpec = { id: 'f1', createdAt: 210, kind: 1, - hash: 0xb1, + hash: digest(F1), sizeBytes: F1.length, } @@ -392,30 +412,9 @@ describe('loadBrowseContext', () => { }) }) - it('reports index-behind when a fragment predates a repack that renumbered the packs', async () => { - // A fragment published concurrently with a repack survives (the repack could not list - // it in `supersedes`), but it indexes a pack space the repack replaced — its packRefs - // now name the wrong packs. Caught from the manifest list, before any bytes are read. - const consolidated: ManifestSpec = { - id: 'p2', - createdAt: 300, - kind: 0, - hash: 0xa2, - supersedes: [0xa0, 0xa1], - } - const sdk = browseSdk([pack0, pack1, consolidated, frag1].map(manifestDoc), artifacts) - expect(await loadBrowseContext(sdk, REPO)).toMatchObject({ - kind: 'unindexed', - reason: 'index-behind', - }) - }) - - it('reports index-behind when a surviving fragment covers the right INDEX of the wrong pack', async () => { - // The dangerous shape a coverage count alone cannot see. After a repack the live space - // is one pack, and a fragment that predates it also indexes exactly one pack — index 0 - // in both — so coverage looks complete. But its packRef 0 means the pre-repack pack, - // and reading through it would return a valid offset in the WRONG pack. Only comparing - // the fragment's as-of space against the live one catches it. + it('reports index-behind when a pack pushed after the fragments is not covered', async () => { + // A repack appends its consolidated pack at the end of the space (superseded packs stay + // in place), so fragments that predate it cover only a prefix: the new pack is unindexed. const consolidated: ManifestSpec = { id: 'p2', createdAt: 300, @@ -423,8 +422,7 @@ describe('loadBrowseContext', () => { hash: 0xa2, supersedes: [0xa0, 0xa1], } - // frag0 (createdAt 110) indexed packRef 0 when that meant pack0. - const sdk = browseSdk([pack0, pack1, consolidated, frag0].map(manifestDoc), artifacts) + const sdk = browseSdk([pack0, pack1, consolidated, frag0, frag1].map(manifestDoc), artifacts) expect(await loadBrowseContext(sdk, REPO)).toMatchObject({ kind: 'unindexed', reason: 'index-behind', @@ -449,11 +447,11 @@ describe('loadBrowseContext', () => { id: 'f9', createdAt: 220, kind: 1, - hash: 0xb9, + hash: digest(wild), sizeBytes: wild.length, } const withWild = new Map(artifacts) - withWild.set('b9'.repeat(32).slice(0, 64), wild) + withWild.set(digest(wild), wild) const sdk = browseSdk([pack0, pack1, frag0, frag1, wildManifest].map(manifestDoc), withWild) expect(await loadBrowseContext(sdk, REPO)).toMatchObject({ kind: 'unindexed', @@ -465,7 +463,7 @@ describe('loadBrowseContext', () => { // One transient chunk-query failure out of up to 16 fragment fetches must not deny the // user a repo whose raw packs are perfectly readable. const partial = new Map(artifacts) - partial.delete('b1'.repeat(32).slice(0, 64)) + partial.delete(digest(F1)) const sdk = browseSdk([pack0, pack1, frag0, frag1].map(manifestDoc), partial) expect(await loadBrowseContext(sdk, REPO)).toMatchObject({ kind: 'unindexed', @@ -474,9 +472,12 @@ describe('loadBrowseContext', () => { }) it('falls back rather than erroring when a fragment is malformed', async () => { + // Bytes that hash to the manifest's packHash but do not parse as a locator. + const junk = new Uint8Array(17) const corrupt = new Map(artifacts) - corrupt.set('b1'.repeat(32).slice(0, 64), new Uint8Array(17)) - const sdk = browseSdk([pack0, pack1, frag0, frag1].map(manifestDoc), corrupt) + corrupt.set(digest(junk), junk) + const badFrag1: ManifestSpec = { ...frag1, hash: digest(junk), sizeBytes: junk.length } + const sdk = browseSdk([pack0, pack1, frag0, badFrag1].map(manifestDoc), corrupt) expect(await loadBrowseContext(sdk, REPO)).toMatchObject({ kind: 'unindexed', reason: 'index-behind', @@ -486,6 +487,32 @@ describe('loadBrowseContext', () => { it('reports no-packs when nothing is stored', async () => { expect(await loadBrowseContext(browseSdk([], artifacts), REPO)).toEqual({ kind: 'no-packs' }) }) + + it("reports index-behind when a maintainer's copy re-kinds a pack a fragment indexed", async () => { + // A since-revoked member uploaded pack0 as a git pack (kind 0), and the fragments were + // built over it. A maintainer later posts a kind-1 copy of the same hash: that copy now + // ranks first, so the pack's kind is 1 and it leaves the live git-pack space. As of each + // fragment the old space still starts with pack0, so the prefix check must refuse the + // index rather than let packRef 0 read the wrong pack. (Each run uses its own repo id: + // membership is cached per repo.) + const MAINT = 'maint' + const revoked = { ...pack0, owner: 'revoked' } + const pack1m = { ...pack1, owner: MAINT } + const frags = [frag0, frag1].map((f) => ({ ...f, owner: MAINT })) + const members = [{ $id: 'm1', $createdAt: 1, memberId: MAINT }] + + // Control: without the maintainer's copy the index covers both packs. + const before = [revoked, pack1m, ...frags].map(manifestDoc) + const ok = await loadBrowseContext(browseSdk(before, artifacts, members), { ...REPO, repoId: 'REKIND-OK' }) + expect(ok.kind).toBe('ready') + + const rekind: ManifestSpec = { id: 'k0', createdAt: 300, kind: 1, hash: 0xa0, owner: MAINT } + const after = [...before, manifestDoc(rekind)] + expect(await loadBrowseContext(browseSdk(after, artifacts, members), { ...REPO, repoId: 'REKIND' })).toMatchObject({ + kind: 'unindexed', + reason: 'index-behind', + }) + }) }) // --------------------------------------------------------------------------- @@ -494,7 +521,6 @@ describe('loadBrowseContext', () => { describe('fork pack via a platform:// locator', () => { const FORK: V2RepoRef = { - kind: 'v2', forge: { core: 'CORE', collab: 'COLLAB', group: 'GROUP' }, repoId: 'FORK', ownerId: 'forker', @@ -557,7 +583,7 @@ describe('fork pack via a platform:// locator', () => { it.each([ ["another network's forge-core", `platform://OTHER/PARENT/uploader/${hash}`], - ['the v1 form', `platform://CORE/${hash}`], + ['a short form', `platform://CORE/${hash}`], ['another pack', `platform://CORE/PARENT/uploader/${'0'.repeat(64)}`], ])('skips a locator into %s', async (_what, uri) => { const { sdk, scopes } = parentSdk(bytes) diff --git a/forge-web/lib/view/browse-source.ts b/forge-web/lib/view/browse-source.ts index 3a0312ea7..2d91aec10 100644 --- a/forge-web/lib/view/browse-source.ts +++ b/forge-web/lib/view/browse-source.ts @@ -27,19 +27,15 @@ import { } from '../browse' import { CHUNK_QUERY_MAX, - isV2Copies, readV2PackCopies, v2PacksOfKind, type AsOf, - liveGitPackManifests, - liveLocatorManifests, readNewestManifestOfKind, readRepoPackManifests, repoKey, repoSource, type PackManifest, type RepoRef, - type V2RepoRef, } from '../repo' import { base64ToBytes, queryDocumentsWithProof } from '../sdk' import { externalSourceName, noteContentCheck, objectObserver } from './content-checks' @@ -183,8 +179,8 @@ async function queryChunkBatch( * always resolved from the row actually returned (its real length), never assumed full. * * Chunk payloads are served through the session LRU: only the seqs absent from the cache - * are queried (one batch — the chunk index, `(packHash, seq)` on v1 and - * `(repoId, $ownerId, packHash, seq)` on forge-v2, is unique per key, so no + * are queried (one batch — the chunk index, `(repoId, $ownerId, packHash, seq)`, is unique + * per key, so no * `in`-starvation fallback is needed), and every fetched chunk is cached for later ranges. */ async function fetchPlatformRange( @@ -195,7 +191,7 @@ async function fetchPlatformRange( end: number, ): Promise { const packHashHex = manifest.packHash - // Keyed by repo and uploader, not the pack hash alone: on forge-v2 every writer has its own + // Keyed by repo and uploader, not the pack hash alone: every writer has its own // copy of a pack (`forge-v2.md` §4), and a hostile copy's chunks must never be served for // an honest one — nor one repo's for another's. const cachePrefix = `${repoKey(repo)}:${manifest.uploader}:${packHashHex}` @@ -587,7 +583,7 @@ async function firstSequential( return null } -/** A v2 chunk locator: `platform://///` (forge-core `scope.rs`). */ +/** A chunk locator: `platform://///` (forge-core `scope.rs`). */ const PLATFORM_LOCATOR_V2 = /^platform:\/\/([^/]+)\/([^/]+)\/([^/]+)\/([0-9a-f]{64})$/i /** @@ -596,19 +592,17 @@ const PLATFORM_LOCATOR_V2 = /^platform:\/\/([^/]+)\/([^/]+)\/([^/]+)\/([0-9a-f]{ * the parent's scope, keyed `(parentRepoId, uploader, packHash, seq)`. Each read is the * manifest re-pointed at that scope: the parent's `repoId`, the locator's uploader, storage 0. * - * Only forge-v2 locators into THIS network's forge-core, and only of this manifest's own pack - * (a locator naming another pack would download it in full before the hash check refused - * it). The v1 form (`platform:///`) is skipped, like any locator a - * browser cannot follow. + * Only locators into THIS network's forge-core, and only of this manifest's own pack (a + * locator naming another pack would download it in full before the hash check refused it). + * Any other form is skipped, like any locator a browser cannot follow. */ function platformLocatorReads( repo: RepoRef, manifest: PackManifest, -): { readonly repo: V2RepoRef; readonly manifest: PackManifest }[] { - if (repo.kind !== 'v2') return [] +): { readonly repo: RepoRef; readonly manifest: PackManifest }[] { const want = manifest.packHash.toLowerCase() const seen = new Set() - const out: { repo: V2RepoRef; manifest: PackManifest }[] = [] + const out: { repo: RepoRef; manifest: PackManifest }[] = [] for (const uri of manifest.uris) { const [, core, repoId, owner, hash] = PLATFORM_LOCATOR_V2.exec(uri) ?? [] if (core !== repo.forge.core || repoId === undefined || owner === undefined) continue @@ -659,7 +653,7 @@ export function artifactRangeFetch( return bytes } return async (start: number, end: number, copy?: number) => { - // forge-v2: a range cannot be hashed on its own. The reader re-hashes every object it + // A range cannot be hashed on its own. The reader re-hashes every object it // builds from one and asks for a specific `copy` when the current one fails it; without // one, a copy that cannot serve the range at all falls through to the next in order. const copies = manifest.copies ?? [manifest] @@ -718,7 +712,7 @@ export async function loadArtifactBytesProgress( cancel?: AbortSignal, ): Promise { if (manifest.copies === undefined) return loadOneCopy(sdk, repo, manifest, onProgress, cancel) - // forge-v2: every writer may hold a copy of a pack. Read them in `orderPackCopies` order + // Every writer may hold a copy of a pack. Read them in `orderPackCopies` order // and keep the first whose bytes hash to `packHash`; a copy that does not, or that cannot // be read (a missing chunk, a dead mirror), is skipped (`forge-v2.md` §4 reader rule). A // pack no copy serves is unreadable. @@ -830,77 +824,34 @@ async function loadExternalCopy( } } -/** - * Order git-pack manifests into the canonical `packRef` space. - * - * PACKREF ORDERING (VERIFIED / corrected): the objectLocator's `packRef` is "an index into - * the manifest's pack list" (forge-core `pack/locator.rs`), but no explicit pack list is - * stored on-chain — so reader and writer must share a *deterministic* ordering of the kind-0 - * pack manifests. The platform total order is `($createdAt, $id)` (data-contracts §2.3, §4), - * so packs are sorted **oldest-first by `($createdAt, documentId)`** — NOT by reversing the - * `$createdAt desc` query result, which drops the `$id` tiebreak on equal timestamps and is - * wrong past one page. When the owning locator's publish time is known, the list is bounded to - * packs that existed at/before it (`createdAt <= asOf`): a locator only indexes packs present - * when it was built, and later incremental packs are outside its `packRef` space. - */ -export function orderGitPacks( - gitPacks: readonly PackManifest[], - asOf?: number, -): PackManifest[] { - const bounded = asOf === undefined ? [...gitPacks] : gitPacks.filter((m) => m.createdAt <= asOf) - return bounded.sort((a, b) => - a.createdAt !== b.createdAt - ? a.createdAt - b.createdAt - : a.documentId < b.documentId - ? -1 - : a.documentId > b.documentId - ? 1 - : 0, - ) -} - /** * The pack list a locator's `packRef` indexes — THE normative definition, shared by both * clients and by whatever publishes a locator. * * `packRef` is "an index into the manifest's pack list", but no pack list is stored on-chain, - * so reader and writer must derive the same one. It is: **the LIVE kind-0 packs as of the - * locator's `$createdAt`, oldest-first by `($createdAt, $id)`.** Three parts, each - * load-bearing: + * so reader and writer must derive the same one. It is the kind-0 packs of `v2PackList` + * (`forge-v2.md` §4, parity with forge-core `repo.rs::locator_pack_space`): every pack once + * however many writers hold a copy, positioned by its first upload `($createdAt, $id)`, as of + * the locator (a locator only indexes packs that existed when it was built). Superseded + * packs stay in place, so a repack never renumbers what an older locator meant. * - * * *as of the locator* — a locator only indexes packs that existed when it was built; later - * incremental packs are outside its space. - * * *live* — a repack consolidates several packs into one and marks the originals - * `supersedes`. Counting superseded packs would leave every index shifted by however many - * of them happened to survive, and whether they survive is incidental: `repack` deletes - * only the CALLER's own manifests, so in a multi-author repo some remain. Liveness is - * computed within the as-of bound, so a later repack cannot retroactively change what an - * older locator meant. - * * *oldest-first by `($createdAt, $id)`* — the platform total order, not a reversed `desc` - * query, which drops the `$id` tiebreak on equal timestamps. - * - * This used to differ between the two browse paths: the indexed path counted ALL kind-0 - * packs while the fallback counted live ones, so the two disagreed about which bytes - * `packRef 0` meant — a valid offset in the wrong pack, undetectable downstream. + * The indexed path and the fallback clone both read this list, so they always agree about + * which bytes `packRef 0` means. */ export function locatorPackSpace( manifests: readonly PackManifest[], asOf?: AsOf, ): PackManifest[] { - // forge-v2: the v2 pack list's kind-0 packs (`forge-v2.md` §4), superseded ones included - // and in place — a locator's packRefs index every git pack listed as of it. - if (isV2Copies(manifests)) return v2PacksOfKind(manifests, PACK_KIND.GIT_PACK, asOf) - const bound = typeof asOf === 'object' ? asOf.createdAt : asOf - const bounded = bound === undefined ? manifests : manifests.filter((m) => m.createdAt <= bound) - return orderGitPacks(liveGitPackManifests(bounded)) + // The pack list's kind-0 packs (`forge-v2.md` §4), superseded ones included and in place — + // a locator's packRefs index every git pack listed as of it. + return v2PacksOfKind(manifests, PACK_KIND.GIT_PACK, asOf) } /** - * The live index fragments (objectLocators), newest first: v1 per `liveLocatorManifests`; - * forge-v2 from the v2 pack list's kind-1 packs, those a verified pack supersedes left out. + * The live index fragments (objectLocators), newest first: the pack list's kind-1 packs, + * those a verified pack supersedes left out. */ function locatorFragments(manifests: readonly PackManifest[]): PackManifest[] { - if (!isV2Copies(manifests)) return liveLocatorManifests(manifests) return v2PacksOfKind(manifests, PACK_KIND.OBJECT_LOCATOR) .filter((p) => !p.superseded) .reverse() @@ -961,12 +912,9 @@ export async function loadFlatIndex(sdk: EvoSDK, repo: RepoRef): Promise livePacks.length) return behind('index-behind') if (asOf.some((m, i) => m.packHash !== livePacks[i]?.packHash)) return behind('index-behind') } diff --git a/forge-web/lib/view/content-checks.ts b/forge-web/lib/view/content-checks.ts index 28796a232..89e71e7be 100644 --- a/forge-web/lib/view/content-checks.ts +++ b/forge-web/lib/view/content-checks.ts @@ -8,7 +8,7 @@ * manifest. This ledger records those outcomes where they happen so the panel can report * what was checked instead of what could be — including "nothing read yet" and a mismatch. * - * Keyed by `repoKey` (the v1 repo contract id or the forge-v2 repo id) and kept for the session, the same lifetime as the browse caches + * Keyed by `repoKey` (the repo id) and kept for the session, the same lifetime as the browse caches * whose reads it counts. Subscribable for `useSyncExternalStore`: every update replaces the * repo's record, so a snapshot is a stable reference until something changes. */ diff --git a/forge-web/lib/view/discovery.ts b/forge-web/lib/view/discovery.ts index 2e23833e7..72591fe56 100644 --- a/forge-web/lib/view/discovery.ts +++ b/forge-web/lib/view/discovery.ts @@ -1,14 +1,11 @@ /** * Discovery reads (view glue) — the repo feeds for the landing page and profiles. * - * - **forge-v2**: a repo IS a `repo` document in forge-core, so the feed is one proof-checked - * query on the `$createdAt` index, and the star and issue counts ride along in the same - * verified round trip (`documents.composite`: counts over forge-collab's `star.byRepo` and - * `issue.number` indexes, bound to the page's repo ids). A profile lists the repos an - * identity owns (`($ownerId, name)`) and the ones it is a member of (`memberId` indexes). - * - **v1**: recent `repoListing` rows from the global registry. Listing authenticity - * (repo-contract owner == listing owner, §4) is verified lazily on the repo home page; the - * feed is a discovery surface, a registry index rather than a proof-of-ownership claim. + * A repo IS a `repo` document in forge-core, so the feed is one proof-checked query on the + * `$createdAt` index, and the star and issue counts ride along in the same verified round trip + * (`documents.composite`: counts over forge-collab's `star.byRepo` and `issue.number` indexes, + * bound to the page's repo ids). A profile lists the repos an identity owns (`($ownerId, + * name)`) and the ones it is a member of (`memberId` indexes). */ import type { EvoSDK } from '@dashevo/evo-sdk' @@ -16,61 +13,30 @@ import type { EvoSDK } from '@dashevo/evo-sdk' import { DEFAULT_NETWORK, NETWORKS, type Network } from '../constants' import type { ForgeIds } from '../deployments' import type { Role } from '../rules/v2' -import { normalizeDocument, queryDocumentsWithProof, type PlainDocument } from '../sdk' -import { - DOC, - REGISTRY_DOC, - V2_DOC, - asIdentifierString, - readMemberRepoIds, - toV2RepoDoc, - type RepoListing, - type V2RepoDoc, -} from '../repo' +import { normalizeDocument, queryDocumentsWithProof } from '../sdk' +import { DOC, V2_DOC, readMemberRepoIds, toV2RepoDoc, type V2RepoDoc } from '../repo' -function asString(v: unknown): string { - return typeof v === 'string' ? v : '' -} - -/** A repo row for the discovery feed and profiles — v1 listing or forge-v2 repo. */ +/** A repo row for the discovery feed and profiles. */ export interface DiscoveredRepo { - readonly kind: 'v1' | 'v2' - /** Stable row key: the v1 listing id or the v2 repo id. */ + /** Stable row key: the `repo` document id. */ readonly key: string readonly ownerId: string - /** Display name (v1: the listing's; v2: the repo name). */ + /** Display name (`displayName`, else the repo name). */ readonly name: string - /** The URL segment that addresses it (v1 `normalizedName`, v2 `name`). */ + /** The URL segment that addresses it (the repo `name`). */ readonly slug: string readonly description: string readonly createdAt: number - /** v1 only: the repo contract (links pin it with `?contract=`). */ - readonly contractId?: string - /** forge-v2 only. */ - readonly visibility?: 'public' | 'private' - /** forge-v2: provable counts, or null when not read. */ + readonly visibility: 'public' | 'private' + /** Provable counts, or null when not read. */ readonly stars?: number | null readonly issues?: number | null /** Profile pages: the viewer's role in a repo it does not own. */ readonly role?: Role } -function fromListing(d: PlainDocument): DiscoveredRepo { - return { - kind: 'v1', - key: asString(d['$id']), - ownerId: asString(d['$ownerId']), - name: asString(d['name']) || asString(d['normalizedName']), - slug: asString(d['normalizedName']) || asString(d['name']), - contractId: asIdentifierString(d['repoContractId']), - description: asString(d['description']), - createdAt: typeof d['$createdAt'] === 'number' ? d['$createdAt'] : 0, - } -} - function fromV2(doc: V2RepoDoc, counts?: { stars?: number | null; issues?: number | null }): DiscoveredRepo { return { - kind: 'v2', key: doc.repoId, ownerId: doc.ownerId, name: doc.displayName || doc.name, @@ -148,59 +114,32 @@ async function listRecentV2Repos( } } -/** The newest v1 repo listings from the registry (empty on a network without one). */ -async function listRecentV1Repos(sdk: EvoSDK, network: Network, limit: number): Promise { - const registryId = NETWORKS[network].registryContractId - if (registryId === null) return [] - const { documents } = await queryDocumentsWithProof(sdk, { - dataContractId: registryId, - documentTypeName: REGISTRY_DOC.repoListing, - orderBy: [['$createdAt', 'desc']], - limit, - }) - return documents.map(fromListing) -} - /** - * The landing feed: forge-v2 repos first (where deployed), then v1 registry listings, each - * newest first. A network with neither returns an empty list; the caller decides what that - * means (it cannot happen where a registry or a v2 deployment exists). + * The landing feed: the newest repos, newest first. Empty on a network without a forge-v2 + * deployment (the caller shows "not deployed" before asking). */ export async function listRecentRepos( sdk: EvoSDK, opts: { network?: Network; limit?: number } = {}, -): Promise<{ v2: DiscoveredRepo[]; v1: DiscoveredRepo[] }> { - const network = opts.network ?? DEFAULT_NETWORK - const forge = NETWORKS[network].v2 - const limit = opts.limit ?? 24 - // Independent sources: one failing must not blank the other. Both failing is an error. - const [v2, v1] = await Promise.allSettled([ - forge !== null ? listRecentV2Repos(sdk, forge, limit) : Promise.resolve([]), - listRecentV1Repos(sdk, network, limit), - ]) - if (v2.status === 'rejected' && v1.status === 'rejected') throw v2.reason - return { - v2: v2.status === 'fulfilled' ? v2.value : [], - v1: v1.status === 'fulfilled' ? v1.value : [], - } +): Promise { + const forge = NETWORKS[opts.network ?? DEFAULT_NETWORK].v2 + return forge === null ? [] : listRecentV2Repos(sdk, forge, opts.limit ?? 24) } /** - * Repos an identity owns — forge-v2 `repo` documents (`($ownerId, name)` index) and v1 - * registry listings — plus, on forge-v2, repos it is a maintainer or writer of. + * Repos an identity owns (`repo` documents, `($ownerId, name)` index) and repos it is a + * maintainer or writer of, each newest first. */ export async function listReposByOwner( sdk: EvoSDK, ownerId: string, opts: { network?: Network; limit?: number } = {}, ): Promise<{ owned: DiscoveredRepo[]; member: DiscoveredRepo[] }> { - const network = opts.network ?? DEFAULT_NETWORK - const forge = NETWORKS[network].v2 - const registryId = NETWORKS[network].registryContractId + const forge = NETWORKS[opts.network ?? DEFAULT_NETWORK].v2 + if (forge === null) return { owned: [], member: [] } const limit = opts.limit ?? 50 - const v2Owned = async (): Promise => { - if (forge === null) return [] + const owned = async (): Promise => { const { documents } = await queryDocumentsWithProof(sdk, { dataContractId: forge.core, documentTypeName: V2_DOC.repo, @@ -210,22 +149,7 @@ export async function listReposByOwner( }) return documents.map((d) => fromV2(toV2RepoDoc(d))) } - const v1Owned = async (): Promise => { - if (registryId === null) return [] - const { documents } = await queryDocumentsWithProof(sdk, { - dataContractId: registryId, - documentTypeName: REGISTRY_DOC.repoListing, - where: [['$ownerId', '==', ownerId]], - // The only index carrying `$ownerId` is `ownerName` ($ownerId, normalizedName) — there - // is no ($ownerId, $createdAt) index to order on. Traverse by normalizedName and sort - // newest-first client-side; the owner's listing count is small by construction. - orderBy: [['normalizedName', 'asc']], - limit, - }) - return documents.map(fromListing) - } - const v2Member = async (): Promise => { - if (forge === null) return [] + const member = async (): Promise => { const rows = (await readMemberRepoIds(sdk, forge, ownerId)).slice(0, limit) if (rows.length === 0) return [] const { documents } = await queryDocumentsWithProof(sdk, { @@ -241,19 +165,13 @@ export async function listReposByOwner( .map((doc) => ({ ...fromV2(doc), role: roleOf.get(doc.repoId) })) } - const settled = await Promise.allSettled([v2Owned(), v1Owned(), v2Member()]) + // Independent sources: one failing must not blank the other. Both failing is an error. + const settled = await Promise.allSettled([owned(), member()]) if (settled.every((r) => r.status === 'rejected')) throw (settled[0] as PromiseRejectedResult).reason - const [ownedV2, ownedV1, member] = settled.map((r) => (r.status === 'fulfilled' ? r.value : [])) as [ - DiscoveredRepo[], + const [ownedRows, memberRows] = settled.map((r) => (r.status === 'fulfilled' ? r.value : [])) as [ DiscoveredRepo[], DiscoveredRepo[], ] const newestFirst = (x: DiscoveredRepo, y: DiscoveredRepo): number => y.createdAt - x.createdAt - return { - owned: [...ownedV2.sort(newestFirst), ...ownedV1.sort(newestFirst)], - member: member.sort(newestFirst), - } + return { owned: ownedRows.sort(newestFirst), member: memberRows.sort(newestFirst) } } - -/** Re-export the listing type for callers that only import from view glue. */ -export type { RepoListing } diff --git a/forge-web/lib/view/fallback-cache.ts b/forge-web/lib/view/fallback-cache.ts index 50a2d0eb8..bf7f35c0d 100644 --- a/forge-web/lib/view/fallback-cache.ts +++ b/forge-web/lib/view/fallback-cache.ts @@ -40,8 +40,8 @@ function openDatabase(): Promise { const request = indexedDB.open(DB_NAME, DB_VERSION) request.onupgradeneeded = () => { if (!request.result.objectStoreNames.contains(STORE_NAME)) { - // `contractId` is the persisted key name; it now holds the repo key (v1 contract id or - // forge-v2 repo id). Renaming it would change the stored schema. + // `contractId` is the persisted key name; it holds the repo key (the repo id). + // Renaming it would change the stored schema. request.result.createObjectStore(STORE_NAME, { keyPath: 'contractId' }) } } diff --git a/forge-web/lib/view/index.ts b/forge-web/lib/view/index.ts index 73943e504..7a12b5022 100644 --- a/forge-web/lib/view/index.ts +++ b/forge-web/lib/view/index.ts @@ -65,7 +65,6 @@ export { loadBrowseContext, loadBrowseContextCached, loadFlatIndex, - orderGitPacks, peekBrowseState, PackUnavailableError, type BrowseContext, @@ -95,7 +94,7 @@ export { type TrustReport, type TrustState, } from './trust' -export { aclName, pullActions, type PullActionInputs, type PullActions } from './pull-actions' +export { ACL_NAME, pullActions, type PullActionInputs, type PullActions } from './pull-actions' export { backendInfo, loadRepoHome, diff --git a/forge-web/lib/view/issues-view.ts b/forge-web/lib/view/issues-view.ts index dc20b8969..c85cea798 100644 --- a/forge-web/lib/view/issues-view.ts +++ b/forge-web/lib/view/issues-view.ts @@ -3,9 +3,9 @@ * event log into a single chronological timeline for the detail view. * * State itself (open/closed, labels) is the deterministic fold done by the core `readIssue` / - * `readPull` (v1 `foldIssueState`, forge-v2 `foldIssueStateV2` over `event` + `authorEvent`); - * this module only adds the human thread (comments + rendered events + reviews) and, on - * forge-v2, the PR's counted approvals (`countApprovals`, `forge-v2.md` §6). + * `readPull` (`foldIssueStateV2` / `foldPrStateV2` over `event` + `authorEvent`); this module + * only adds the human thread (comments + rendered events + reviews) and the PR's counted + * approvals (`countApprovals`, `forge-v2.md` §6). */ import type { EvoSDK } from '@dashevo/evo-sdk' @@ -25,7 +25,6 @@ import { type PullView, type RepoRef, type ReviewView, - type V2RepoRef, } from '../repo' import { queryAllDocuments, queryDocumentsWithProof, type PlainDocument } from '../sdk' import { compareKey, type Event } from '../rules' @@ -58,9 +57,9 @@ export async function readComments(sdk: EvoSDK, repo: RepoRef, targetId: string) ], }), ) - // Private forge-v2 repo: a stranger's ciphertext is shown to no one (`forge-v2.md` §5), - // as in the lists. - const oracle = repo.kind === 'v2' && repo.visibility === 'private' ? await readRoleOracle(sdk, repo) : null + // Private repo: a stranger's ciphertext is shown to no one (`forge-v2.md` §5), as in the + // lists. + const oracle = repo.visibility === 'private' ? await readRoleOracle(sdk, repo) : null return documents .filter((d) => wellFormed(repo, 'comment', d)) .filter((d) => oracle === null || oracle.currentRole(str(d, '$ownerId')) !== null) @@ -79,7 +78,7 @@ export type TimelineItem = readonly kind: 'event' readonly at: number readonly event: Event - /** forge-v2 `authorEvent`: the author's own close/reopen (`forge-v2.md` §3). */ + /** An `authorEvent`: the author's own close/reopen (`forge-v2.md` §3). */ readonly byAuthor?: boolean } | { readonly kind: 'review'; readonly at: number; readonly review: ReviewView } @@ -95,8 +94,6 @@ async function docByNumber( sdk, repoSource(repo).repoQuery(DOC[type], { where: [['number', '==', number]], - // v1 keeps the query shape it always sent; forge-v2's unique (repoId, number) needs none. - ...(repo.kind === 'v1' ? { orderBy: [['number', 'desc']] as const } : {}), limit: 1, }), ) @@ -120,11 +117,11 @@ export async function loadIssueThread(sdk: EvoSDK, repo: RepoRef, number: number readTargetLog(sdk, repo, id), readComments(sdk, repo, id), ]) - const issue = await readIssue(sdk, repo, doc, undefined, log) + const issue = await readIssue(sdk, repo, doc, log) return { issue, timeline: mergeTimeline(comments, log.events, log.authorEvents, []) } } -/** The counted approvals of a forge-v2 PR, and what each reviewer's role is now. */ +/** The counted approvals of a PR, and what each reviewer's role is now. */ export interface PullApprovals extends Approvals { /** Each counted reviewer's current role (null once revoked — then they do not count). */ readonly roles: ReadonlyMap @@ -135,8 +132,8 @@ export interface PullThread { readonly pull: PullView readonly timeline: TimelineItem[] /** - * forge-v2 only: the reviews that count on the current head (`countApprovals`). Null on - * v1, which has no approval rule, or when the membership could not be read. + * The reviews that count on the current head (`countApprovals`). Null when the membership + * could not be read. */ readonly approvals: PullApprovals | null } @@ -157,15 +154,15 @@ export async function loadPullThread(sdk: EvoSDK, repo: RepoRef, number: number) readComments(sdk, repo, id), readReviews(sdk, repo, id), ]) - const pull = await readPull(sdk, repo, doc, undefined, log) - const approvals = repo.kind === 'v2' ? await readApprovals(sdk, repo, reviews, pull.headOid) : null + const pull = await readPull(sdk, repo, doc, log) + const approvals = await readApprovals(sdk, repo, reviews, pull.headOid) return { pull, timeline: mergeTimeline(comments, log.events, log.authorEvents, reviews), approvals } } -/** A forge-v2 PR's counted approvals, or null when the membership could not be read. */ +/** A PR's counted approvals, or null when the membership could not be read. */ async function readApprovals( sdk: EvoSDK, - repo: V2RepoRef, + repo: RepoRef, reviews: readonly ReviewView[], headOid: string, ): Promise { diff --git a/forge-web/lib/view/pull-actions.test.ts b/forge-web/lib/view/pull-actions.test.ts index d7a639aeb..f520164b7 100644 --- a/forge-web/lib/view/pull-actions.test.ts +++ b/forge-web/lib/view/pull-actions.test.ts @@ -1,17 +1,17 @@ /** - * PR action gating — the merge control is offered only to identities whose merge event the - * fold would accept, and it says whether the mark counts now. + * PR action gating — the merge control is offered only to members (whose `event` consensus + * admits), and it says whether the mark counts now. * - * The end-to-end case at the bottom ties the gate to {@link foldPrState}: whenever the gate - * says a mark "counts now", folding that same merge event really does flip the PR to merged — - * and a non-holder (to whom the gate never offers the control) would have folded inert. + * The end-to-end case at the bottom ties the gate to `foldPrStateV2`: whenever the gate says a + * mark "counts now", folding that same merge event really does flip the PR to merged. */ import { describe, expect, it } from 'vitest' import type { PullView } from '../repo' import { historicalTipsPredicate } from '../repo' -import { AuthzResolver, foldPrState, type Event, type Holdings, type TokenRecord } from '../rules' +import type { Event, Holdings } from '../rules' +import { foldPrStateV2 } from '../rules/v2' import { pullActions, type PullActionInputs } from './pull-actions' const AUTHOR = 'author' @@ -39,21 +39,21 @@ function pull(over: Omit, 'state'> & { state?: Partial { - it('offers it to WRITE and MAINTAIN holders', () => { + it('offers it to writers and maintainers', () => { expect(pullActions({ pull: pull(), viewer: WRITER, holdings: WRITE }).canMarkMerged).toBe(true) expect(pullActions({ pull: pull(), viewer: MAINTAINER, holdings: MAINTAIN }).canMarkMerged).toBe(true) }) - it('withholds it from a signed-in non-holder, with the reason', () => { + it('withholds it from a signed-in non-member, with the reason', () => { const a = pullActions({ pull: pull(), viewer: STRANGER, holdings: NONE }) expect(a.canMarkMerged).toBe(false) - expect(a.mergeHint).toMatch(/WRITE or MAINTAIN/) + expect(a.mergeHint).toMatch(/maintainers and writers/) }) - it('withholds it from the PR author who holds no token', () => { + it('withholds it from the PR author who is not a member', () => { const a = pullActions({ pull: pull(), viewer: AUTHOR, holdings: NONE }) expect(a.canMarkMerged).toBe(false) - // …but the author may still close/reopen their own PR (the fold honors that). + // …but the author may still close/reopen their own PR (an authorEvent). expect(a.canCloseReopen).toBe(true) }) @@ -64,14 +64,14 @@ describe('pullActions — who sees "Mark as merged"', () => { expect(a.mergeHint).toBeNull() }) - it('withholds it silently while holdings load, and explains an unreadable history', () => { + it('withholds it silently while membership loads, and explains an unreadable one', () => { const loading = pullActions({ pull: pull(), viewer: WRITER, holdings: 'loading' }) expect(loading.canMarkMerged).toBe(false) expect(loading.mergeHint).toBeNull() const unknown = pullActions({ pull: pull(), viewer: WRITER, holdings: null }) expect(unknown.canMarkMerged).toBe(false) - expect(unknown.mergeHint).toMatch(/token history/) + expect(unknown.mergeHint).toMatch(/members/) }) it('withholds it on merged, closed, headless, and unverified PRs', () => { @@ -84,7 +84,7 @@ describe('pullActions — who sees "Mark as merged"', () => { }) describe('pullActions — close / reopen', () => { - it('offers close on an open PR and reopen on a closed one, to holders and the author', () => { + it('offers close on an open PR and reopen on a closed one, to members and the author', () => { expect(pullActions({ pull: pull(), viewer: WRITER, holdings: WRITE }).canCloseReopen).toBe(true) expect(pullActions({ pull: pull({ state: { open: false } }), viewer: AUTHOR, holdings: NONE }).canCloseReopen).toBe(true) }) @@ -97,27 +97,7 @@ describe('pullActions — close / reopen', () => { }) }) -describe('pullActions — forge-v2 membership', () => { - // On forge-v2 "holdings" come from membership documents (`holdingsOfRole`), so the same gate - // applies; only the wording says members rather than token holders. - it('offers merge to a maintainer or writer and names members when withholding it', () => { - expect(pullActions({ pull: pull(), viewer: WRITER, holdings: WRITE, model: 'v2' }).canMarkMerged).toBe(true) - const stranger = pullActions({ pull: pull(), viewer: STRANGER, holdings: NONE, model: 'v2' }) - expect(stranger.canMarkMerged).toBe(false) - expect(stranger.mergeHint).toMatch(/maintainers and writers/) - const unknown = pullActions({ pull: pull(), viewer: WRITER, holdings: null, model: 'v2' }) - expect(unknown.mergeHint).toMatch(/members/) - expect(unknown.mergeHint).not.toMatch(/token/) - }) - - it('lets the author close their own PR (an authorEvent) without membership', () => { - expect(pullActions({ pull: pull(), viewer: AUTHOR, holdings: NONE, model: 'v2' }).canCloseReopen).toBe(true) - }) -}) - describe('pullActions agrees with the fold', () => { - const records: TokenRecord[] = [{ identity: WRITER, token: 'write', op: 'mint', createdAt: 0 }] - const authz = new AuthzResolver(records) const mergeBy = (actor: string): Event => ({ id: 'e1', kind: 'merge', actor, oid: HEAD, createdAt: 10 }) it('"counts now" iff the head has been a base tip — and the fold then merges', () => { @@ -132,9 +112,10 @@ describe('pullActions agrees with the fold', () => { const a = pullActions({ pull: pull({ headOnBase }), viewer: WRITER, holdings: WRITE }) expect(a.canMarkMerged).toBe(true) expect(a.markCountsNow).toBe(expected) - expect(foldPrState([mergeBy(WRITER)], AUTHOR, authz, baseTip, isAncestor).merged).toBe(expected) - // A stranger's identical event is inert — which is why they are never offered it. - expect(foldPrState([mergeBy(STRANGER)], AUTHOR, authz, baseTip, isAncestor).merged).toBe(false) + // A member's `event` (consensus admitted it, so the fold applies it). + expect(foldPrStateV2([mergeBy(WRITER)], [], AUTHOR, baseTip, isAncestor).merged).toBe(expected) + // An author's merge through `authorEvent` is inert — merge is not an author action. + expect(foldPrStateV2([], [mergeBy(AUTHOR)], AUTHOR, baseTip, isAncestor).merged).toBe(false) } }) }) diff --git a/forge-web/lib/view/pull-actions.ts b/forge-web/lib/view/pull-actions.ts index 41dd58d85..254466b27 100644 --- a/forge-web/lib/view/pull-actions.ts +++ b/forge-web/lib/view/pull-actions.ts @@ -2,19 +2,15 @@ * PR action gating (view glue) — which PR state controls a viewer is shown, and what the * merge control may honestly promise. * - * The web app cannot merge code. What it can do is append a `merge` event naming the PR head, - * which {@link foldPrState} accepts only when (a) the signer held WRITE or MAINTAIN when the - * event landed and (b) the head has been a tip of the base ref. So the control is offered - * only to WRITE/MAINTAIN holders, is labelled "Mark as merged", and says up front whether - * the mark will count now (the head is already on the base branch) or stay inert until the - * code gets there by a push. + * The web app cannot merge code. What it can do is append a `merge` event naming the PR head. + * Consensus admits an `event` only from a current maintainer or writer, and `foldPrStateV2` + * applies the merge only when the head has been a tip of the base ref. So the control is + * offered only to members, is labelled "Mark as merged", and says up front whether the mark + * will count now (the head is already on the base branch) or stay inert until the code gets + * there by a push. * - * Close/reopen stay available to the PR author as well — the fold honors the author's own - * close/reopen — but not to identities whose event the fold would ignore. - * - * forge-v2 (`model: 'v2'`): "holder" means a current `maintainer` or `writer` document. The - * `event` gate is consensus there (a non-member's event is refused, not inert) and the author's - * close/reopen is an `authorEvent`, so the same rule offers the same controls. + * Close/reopen stay available to the PR author as well (an `authorEvent`), but not to anyone + * consensus would refuse. */ import type { Holdings } from '../rules' @@ -41,22 +37,17 @@ export interface PullActionInputs { /** The signed-in identity, or null when logged out. */ readonly viewer: string | null /** - * The viewer's current permissions: `'loading'` until read, `null` when the ACL (v1 token - * history, v2 membership) could not be read — permission unknown, controls withheld with a - * reason. + * The viewer's current permissions: `'loading'` until read, `null` when the membership could + * not be read — permission unknown, controls withheld with a reason. */ readonly holdings: Holdings | null | 'loading' - /** Which data model the repo uses; only the wording differs. Defaults to v1. */ - readonly model?: 'v1' | 'v2' } /** What a repo's ACL is read from, for "couldn't read …" messages. */ -export function aclName(model: 'v1' | 'v2'): string { - return model === 'v1' ? 'token history' : 'members' -} +export const ACL_NAME = 'members' /** Decide the PR controls for a viewer. Pure — the unit-tested core of the PR page gate. */ -export function pullActions({ pull, viewer, holdings, model = 'v1' }: PullActionInputs): PullActions { +export function pullActions({ pull, viewer, holdings }: PullActionInputs): PullActions { const known = holdings !== null && holdings !== 'loading' const holder = known && (holdings.write || holdings.maintain) const isAuthor = viewer !== null && viewer === pull.author @@ -70,11 +61,9 @@ export function pullActions({ pull, viewer, holdings, model = 'v1' }: PullAction let mergeHint: string | null = null if (!canMarkMerged && actionable && open && viewer !== null && holdings !== 'loading') { if (holdings === null) { - mergeHint = `Couldn't read this repo's ${aclName(model)}, so merge permission is unknown.` + mergeHint = `Couldn't read this repo's ${ACL_NAME}, so merge permission is unknown.` } else if (pull.headOid === '') { mergeHint = 'This PR records no head commit to mark as merged.' - } else if (model === 'v1') { - mergeHint = 'Only WRITE or MAINTAIN holders can mark a PR as merged.' } else { mergeHint = "Only this repo's maintainers and writers can mark a PR as merged." } diff --git a/forge-web/lib/view/pull-diff.ts b/forge-web/lib/view/pull-diff.ts index 404f1d7b0..dfc64f3ec 100644 --- a/forge-web/lib/view/pull-diff.ts +++ b/forge-web/lib/view/pull-diff.ts @@ -1,8 +1,7 @@ /** * Reconstruct a pull request comparison from its base and source repository objects. * - * A PR's head commit is pushed to the contributor's own repo (v1 `sourceContractId`, forge-v2 - * `sourceRepoId`), while + * A PR's head commit is pushed to the contributor's own repo (`sourceRepoId`), while * the base history lives in the repo being viewed. The comparison therefore reads through two * readers: head-side objects prefer the source repo, base-side objects prefer the target repo, * and each falls back to the other. Falling back is safe because objects are content-addressed diff --git a/forge-web/lib/view/repo-view.ts b/forge-web/lib/view/repo-view.ts index cf4455963..9657e4ba7 100644 --- a/forge-web/lib/view/repo-view.ts +++ b/forge-web/lib/view/repo-view.ts @@ -1,8 +1,8 @@ /** * Repo home view-model (view glue) — composes the reads a repo page needs into one shape. * - * The cold home view is size-independent: resolve the repo (a forge-v2 `repo` document, else - * the v1 registry), read its current config + default branch, resolve refs, and read the + * The cold home view is size-independent: resolve the repo (its forge-core `repo` document), + * read its current config + default branch, resolve refs, and read the * O(1) star count. The root tree / README ride the browse plane (locator) and are loaded * separately so the header can paint immediately. */ @@ -14,7 +14,6 @@ import { branchesOf, readConfigBundle, readRefs, - readStarCount, readV2StarCount, resolveAnyRepo, tagsOf, @@ -56,11 +55,9 @@ export function backendInfo(config: RepoConfig | null): BackendInfo { /** Everything the repo header + rail render (excludes browse-plane tree/README). */ export interface RepoHome { readonly repo: RepoRef - /** The v1 registry listing id (stars live on it), or null (forge-v2, or no listing). */ - readonly listingId: string | null - /** The forge-v2 `repo` document (description, display name, topics, fork), else null. */ - readonly v2: V2RepoDoc | null - /** The repo description: the v2 `repo` document's, else the v1 listing's. */ + /** The `repo` document (description, display name, topics, fork). */ + readonly v2: V2RepoDoc + /** The repo description (the `repo` document's). */ readonly description: string readonly config: RepoConfig | null readonly defaultBranch: string @@ -73,7 +70,7 @@ export interface RepoHome { /** * Resolve + compose a repo home view-model from its route address (`owner`, `name`, and an - * optional `?repo=` / `?contract=` pin). Returns null if nothing authentic resolves. + * optional `?repo=` pin). Returns null if nothing resolves. */ export async function loadRepoHome( sdk: EvoSDK, @@ -81,34 +78,22 @@ export async function loadRepoHome( ): Promise { const resolved = await resolveAnyRepo(sdk, params) if (resolved === null) return null - const { repo } = resolved - const v2 = 'doc' in resolved ? resolved.doc : null - const listing = 'listing' in resolved ? resolved.listing : null - const listingId = listing?.listingId || null - - const readStars = (): Promise => { - if (repo.kind === 'v2') return readV2StarCount(sdk, repo.forge, repo.repoId).catch(() => null) - // Stars live on the registry listing; a repo addressed without one has an unknown count. - return listingId - ? readStarCount(sdk, listingId, { network: params.network }).catch(() => null) - : Promise.resolve(null) - } + const { repo, doc: v2 } = resolved // One config query serves both the current config and the history readRefs folds with. const bundlePromise = readConfigBundle(sdk, repo) const [{ config }, refs, starCount] = await Promise.all([ bundlePromise, readRefs(sdk, repo, undefined, bundlePromise.then((b) => b.history)), - readStars(), + readV2StarCount(sdk, repo.forge, repo.repoId).catch(() => null), ]) return { repo, - listingId, v2, - description: v2?.description ?? listing?.description ?? '', + description: v2.description, config, - defaultBranch: config?.defaultBranch ?? v2?.defaultBranch ?? 'main', + defaultBranch: config?.defaultBranch ?? v2.defaultBranch ?? 'main', branches: branchesOf(refs), tags: tagsOf(refs), starCount, diff --git a/forge-web/lib/view/trust.test.ts b/forge-web/lib/view/trust.test.ts index 21d1fa955..aa47c7277 100644 --- a/forge-web/lib/view/trust.test.ts +++ b/forge-web/lib/view/trust.test.ts @@ -59,9 +59,8 @@ describe('deriveTrust — proofs and refs', () => { expect(r.refs.state).toBe('verified') }) - it('names the rules that folded the refs (v1 or forge-v2)', () => { - expect(deriveTrust(inputs()).refs.detail).toMatch(/FORGE_RULES_V1/) - expect(deriveTrust(inputs({ model: 'v2' })).refs.detail).toMatch(/FORGE_RULES_V2/) + it('names the rules that folded the refs', () => { + expect(deriveTrust(inputs()).refs.detail).toMatch(/FORGE_RULES_V2/) }) it('reports proofs and refs as unverified on a connection that does not check proofs', () => { @@ -167,7 +166,7 @@ describe('trust-anchor disclosure', () => { it('names the network by its key in copy', () => { expect(deriveTrust(inputs({ network: 'testnet' })).networkLabel).toBe('testnet') - // Unnamed in this (testnet) build's resolution; a devnet build would read `devnet-`. + // Unnamed in the default build's resolution; a devnet build would read `devnet-`. expect(deriveConnectionTrust('devnet', 'connecting').detail).toContain(NETWORKS.devnet.key) }) diff --git a/forge-web/lib/view/trust.ts b/forge-web/lib/view/trust.ts index 2957b64f2..3bab09b5a 100644 --- a/forge-web/lib/view/trust.ts +++ b/forge-web/lib/view/trust.ts @@ -61,10 +61,11 @@ export interface TrustInputs { readonly checks: ContentChecks /** The repo config's backend label — what the owner declared, not what served bytes. */ readonly configuredBackend: string - /** Which rules folded the refs (v1 `FORGE_RULES_V1`, forge-v2 `FORGE_RULES_V2`). */ - readonly model?: 'v1' | 'v2' } +/** The rules that fold a repo's refs. */ +const RULES = 'FORGE_RULES_V2' + /** * Severity order for the headline. `pending` ranks below `verified` so a page that has only * read refs so far (nothing to hash yet) reads as verified for what it showed, while any @@ -129,7 +130,6 @@ function deriveProofs(network: Network, connection: ConnectionTrust, endpoint: s } function deriveRefs(input: TrustInputs): TrustLink { - const rules = input.model === 'v2' ? 'FORGE_RULES_V2' : 'FORGE_RULES_V1' if (input.connection === 'connecting') { return { state: 'pending', summary: 'pending', detail: 'Refs have not been read yet.' } } @@ -138,7 +138,7 @@ function deriveRefs(input: TrustInputs): TrustLink { state: 'unverified', summary: 'unchecked', detail: - `The tip was folded from the refUpdate log by ${rules}, but the log itself was read without proofs.`, + `The tip was folded from the refUpdate log by ${RULES}, but the log itself was read without proofs.`, } } const tip = input.tip @@ -166,7 +166,7 @@ function deriveRefs(input: TrustInputs): TrustLink { return { state: 'verified', summary: 'proof', - detail: `The tip was folded by ${rules} from the proof-checked, append-only refUpdate log.`, + detail: `The tip was folded by ${RULES} from the proof-checked, append-only refUpdate log.`, } } } diff --git a/forge-web/playwright.config.ts b/forge-web/playwright.config.ts index 431623661..9f848dc92 100644 --- a/forge-web/playwright.config.ts +++ b/forge-web/playwright.config.ts @@ -5,27 +5,25 @@ import { defineConfig, devices } from '@playwright/test' * * Tests run headless Chromium against the LOCAL static build (`out/`) served on * port 4321 — same bytes deployed to GitHub Pages / IPFS, but local for speed and - * request-interception control. The app talks to Dash Platform **testnet** (the - * app default, `DEFAULT_NETWORK`), so read-path specs exercise real on-chain data. + * request-interception control. The build targets a forge-v2 **devnet** (`E2E_DEVNET`, + * default `moutai`), so the specs exercise real on-chain data: the read fixture that + * `forge-contracts/scripts/seed-v2-fixture.mjs` seeds there (e2e/helpers.ts `DEMO`). + * Testnet has no forge-v2 deployment, so a testnet build has nothing to read. * - * The WASM SDK loads lazily post-paint and connects to testnet DAPI, so data pages + * The WASM SDK loads lazily post-paint and connects to the devnet's DAPI, so data pages * need a generous timeout; the per-test timeout is bumped accordingly. */ const PORT = Number(process.env.E2E_PORT ?? 4321) const BASE_URL = `http://127.0.0.1:${PORT}` -/** - * The network the build under test reads: testnet (default; the v1 read fixture) or a - * devnet (`E2E_DEVNET=moutai`; the forge-v2 fixture, `v2-reads.spec.ts`). Each spec skips - * on the network its fixture does not live on, and the build below is made for this one. - */ -const DEVNET = process.env.E2E_DEVNET ?? '' -const BUILD_ENV = DEVNET ? `NEXT_PUBLIC_NETWORK=devnet NEXT_PUBLIC_DEVNET_NAME=${DEVNET} ` : '' +/** The devnet the build under test reads. Keep the default in step with e2e/helpers.ts. */ +const DEVNET = process.env.E2E_DEVNET || 'moutai' +const BUILD_ENV = `NEXT_PUBLIC_NETWORK=devnet NEXT_PUBLIC_DEVNET_NAME=${DEVNET} ` export default defineConfig({ testDir: './e2e', - // Real testnet round-trips (SDK connect + proof-verified reads) are slow; be generous. + // Real devnet round-trips (SDK connect + proof-verified reads) are slow; be generous. timeout: 90_000, expect: { timeout: 30_000 }, fullyParallel: false, @@ -49,7 +47,8 @@ export default defineConfig({ ], // Build (if needed) then serve out/ with a hermetic, dependency-free static server // (sets COOP/COEP for the WASM SDK and mirrors trailingSlash routing). If you already - // have a fresh out/, set E2E_SKIP_BUILD=1 to skip the rebuild and just serve it. + // have a fresh out/ built for the same devnet, set E2E_SKIP_BUILD=1 to skip the rebuild + // and just serve it. webServer: { command: process.env.E2E_SKIP_BUILD ? `node e2e/static-server.mjs --port ${PORT}` From 5a98fb272685e9b1df081f4e456ad868d56fa522 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 17:51:51 -0500 Subject: [PATCH 8/8] refactor: drop the V2 prefixes that only told forge-v2 apart from v1 A mechanical rename, no behaviour change. Rust: V2Issue/V2Patch/V2Comment/V2Review become Issue/Patch/Comment/Review and resolve::find_v2 becomes find_named. Web: V2RepoRef becomes RepoRef, V2RepoDoc RepoDoc, v2RefOf repoRefOf, readV2* readers lose the prefix, and V2_DOC merges into DOC. Names that mirror the FORGE_RULES_V2 rule set, the deployment file's v2 record and the conformance harness keep theirs. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dg/src/pr.rs | 4 +- crates/forge-core/src/collab/v2.rs | 62 +++++++------- crates/forge-core/src/create.rs | 6 +- crates/forge-core/src/fork.rs | 2 +- crates/forge-core/src/resolve.rs | 6 +- crates/forge-import/src/dest.rs | 4 +- forge-web/app/explore/page.tsx | 4 +- forge-web/app/new/page.tsx | 4 +- forge-web/components/profile-content.tsx | 4 +- forge-web/components/repo/pull-diff.tsx | 16 ++-- .../components/repo/repo-home-content.tsx | 4 +- forge-web/components/repo/repo-rail.tsx | 4 +- .../components/repo/settings-content.tsx | 14 ++-- .../components/repo/stargazers-content.tsx | 4 +- forge-web/hooks/use-repo-chrome.ts | 4 +- forge-web/lib/repo/contract.ts | 23 ++---- forge-web/lib/repo/index.ts | 26 +++--- forge-web/lib/repo/issues.ts | 5 +- forge-web/lib/repo/members.ts | 4 +- forge-web/lib/repo/packs.ts | 10 +-- forge-web/lib/repo/push.ts | 10 +-- forge-web/lib/repo/resolveRepo.ts | 34 ++++---- forge-web/lib/repo/social.ts | 24 +++--- forge-web/lib/repo/source.test.ts | 6 +- forge-web/lib/repo/source.ts | 8 +- forge-web/lib/repo/v2.test.ts | 82 +++++++++---------- forge-web/lib/repo/writes.ts | 22 ++--- forge-web/lib/storage/index.ts | 4 +- forge-web/lib/storage/storage.test.ts | 4 +- forge-web/lib/storage/upload.live.test.ts | 8 +- forge-web/lib/storage/upload.ts | 4 +- forge-web/lib/view/browse-source.test.ts | 8 +- forge-web/lib/view/browse-source.ts | 14 ++-- forge-web/lib/view/discovery.ts | 30 +++---- forge-web/lib/view/mine.ts | 6 +- forge-web/lib/view/repo-view.ts | 8 +- 36 files changed, 236 insertions(+), 246 deletions(-) diff --git a/crates/dg/src/pr.rs b/crates/dg/src/pr.rs index 49b2752c5..b9a66f2c1 100644 --- a/crates/dg/src/pr.rs +++ b/crates/dg/src/pr.rs @@ -19,7 +19,7 @@ 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::v2::{Collab, Patch, PatchInput, PatchView}; use forge_core::collab::Verdict; use forge_core::create::default_journal_dir; use forge_core::rules::v2::Role; @@ -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? diff --git a/crates/forge-core/src/collab/v2.rs b/crates/forge-core/src/collab/v2.rs index ce228c600..7deb5b3d8 100644 --- a/crates/forge-core/src/collab/v2.rs +++ b/crates/forge-core/src/collab/v2.rs @@ -124,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`. @@ -141,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 { @@ -155,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`. @@ -182,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 { @@ -215,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. @@ -230,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`). @@ -281,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, } @@ -290,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. @@ -373,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(), @@ -386,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(), @@ -407,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(), @@ -417,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()), @@ -829,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? @@ -838,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? @@ -889,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? @@ -897,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? @@ -910,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 @@ -967,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) @@ -979,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) @@ -993,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, @@ -1025,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( @@ -1049,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 } @@ -1066,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 5b06fa5a6..615d86537 100644 --- a/crates/forge-core/src/create.rs +++ b/crates/forge-core/src/create.rs @@ -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/fork.rs b/crates/forge-core/src/fork.rs index d3f08c2db..90d6f381d 100644 --- a/crates/forge-core/src/fork.rs +++ b/crates/forge-core/src/fork.rs @@ -177,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)?, diff --git a/crates/forge-core/src/resolve.rs b/crates/forge-core/src/resolve.rs index 499a8cdfc..2c73441e1 100644 --- a/crates/forge-core/src/resolve.rs +++ b/crates/forge-core/src/resolve.rs @@ -45,13 +45,13 @@ pub async fn resolve_named(client: &PlatformClient, owner: &str, name: &str) -> let slug = repo_slug(name)?; let owner_bytes = platform::decode_identifier(owner)?; let forge = client.target().require_v2()?; - find_v2(client, forge, owner_bytes, &slug) + 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], diff --git a/crates/forge-import/src/dest.rs b/crates/forge-import/src/dest.rs index 75e6dc3c4..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; @@ -170,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/forge-web/app/explore/page.tsx b/forge-web/app/explore/page.tsx index 81274c867..1be694dc6 100644 --- a/forge-web/app/explore/page.tsx +++ b/forge-web/app/explore/page.tsx @@ -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 ?? [] - 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, }) diff --git a/forge-web/app/new/page.tsx b/forge-web/app/new/page.tsx index 51d44d709..e250f2b40 100644 --- a/forge-web/app/new/page.tsx +++ b/forge-web/app/new/page.tsx @@ -27,7 +27,7 @@ import { useSdk } from '@/hooks/use-sdk' import { useWriteGuard } from '@/hooks/use-write-guard' import { checkRepoInput, - createRepoV2, + createRepo, discardRepoCreation, normalizeRepoName, pendingRepoCreations, @@ -105,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) { diff --git a/forge-web/components/profile-content.tsx b/forge-web/components/profile-content.tsx index 389ad9fa6..db531171a 100644 --- a/forge-web/components/profile-content.tsx +++ b/forge-web/components/profile-content.tsx @@ -12,7 +12,7 @@ import { GitBranch, UserPlus, Users } from 'lucide-react' import type { DiscoveredRepo } from '@/lib/view' import { listReposByOwner, resolveDpnsName } from '@/lib/view' -import { followRelation, readV2FollowCounts, resolveOwner } from '@/lib/repo' +import { followRelation, readFollowCounts, resolveOwner } from '@/lib/repo' import { NETWORKS } from '@/lib/constants' import { useSdk } from '@/hooks/use-sdk' import { useAsync } from '@/hooks/use-async' @@ -58,7 +58,7 @@ export function ProfileContent({ identityId: address }: { identityId: string }): if (identityId === null) return null const forge = NETWORKS[network].v2 const noCounts = { followers: null, following: null } - const follows = forge !== null ? readV2FollowCounts(sdk!, forge, identityId).catch(() => noCounts) : noCounts + const follows = forge !== null ? readFollowCounts(sdk!, forge, identityId).catch(() => noCounts) : noCounts const [name, repos, counts] = await Promise.all([ resolveDpnsName(sdk!, identityId, network), listReposByOwner(sdk!, identityId, { network }), diff --git a/forge-web/components/repo/pull-diff.tsx b/forge-web/components/repo/pull-diff.tsx index 29056968c..d1c8513aa 100644 --- a/forge-web/components/repo/pull-diff.tsx +++ b/forge-web/components/repo/pull-diff.tsx @@ -18,7 +18,7 @@ import { useMemo, type ReactNode } from 'react' import { FileDiff, Files, HardDriveDownload } from 'lucide-react' -import { readV2RepoById, repoKey, v2RefOf, type PullView, type RepoRef } from '@/lib/repo' +import { readRepoById, repoKey, repoRefOf, type PullView, type RepoRef } from '@/lib/repo' import { formatBytes, loadPullComparison, tipOidOf, type DiffSides, type RepoHome } from '@/lib/view' import { useAsync } from '@/hooks/use-async' import { useSdk } from '@/hooks/use-sdk' @@ -42,20 +42,20 @@ type SourceRepo = function useSourceRepo(base: RepoRef, sourceId: string | null): SourceRepo { const { sdk, ready } = useSdk() const { forge } = base - const v2Source = useAsync( + const sourceRepo = useAsync( async () => { - const doc = await readV2RepoById(sdk!, forge, sourceId!) - return doc === null ? null : v2RefOf(forge, doc) + const doc = await readRepoById(sdk!, forge, sourceId!) + return doc === null ? null : repoRefOf(forge, doc) }, [ready, forge.core, sourceId ?? ''], { enabled: ready && sdk !== null && sourceId !== null }, ) if (sourceId === null) return { kind: 'none' } - if (v2Source.error) { - return { kind: 'missing', message: `The source repo could not be read (${v2Source.error}).`, retry: v2Source.reload } + if (sourceRepo.error) { + return { kind: 'missing', message: `The source repo could not be read (${sourceRepo.error}).`, retry: sourceRepo.reload } } - if (v2Source.data) return { kind: 'found', repo: v2Source.data } - if (v2Source.settled && !v2Source.loading) { + if (sourceRepo.data) return { kind: 'found', repo: sourceRepo.data } + if (sourceRepo.settled && !sourceRepo.loading) { return { kind: 'missing', message: `The source repo ${sourceId.slice(0, 8)}… this PR names does not exist.` } } return { kind: 'loading' } diff --git a/forge-web/components/repo/repo-home-content.tsx b/forge-web/components/repo/repo-home-content.tsx index 60e1ac025..4bf230ea3 100644 --- a/forge-web/components/repo/repo-home-content.tsx +++ b/forge-web/components/repo/repo-home-content.tsx @@ -29,7 +29,7 @@ import { type TreeEntry, } from '@/lib/view' import { countCommits, lastCommitsForDir, type LastCommit } from '@/lib/view/commit-log' -import { readPublicRepoFacts, repoContractIds, type V2RepoRef } from '@/lib/repo' +import { readPublicRepoFacts, repoContractIds, type RepoRef } from '@/lib/repo' import { useAsync } from '@/hooks/use-async' import { useSdk } from '@/hooks/use-sdk' import { useViewerRole } from '@/hooks/use-repo-chrome' @@ -334,7 +334,7 @@ function EmptyRepoState({ home, addr, branch }: { home: RepoHome; addr: RepoAddr * (name, owner, member count, size, last activity). Nothing is decrypted or rendered from * encrypted fields, titles included. */ -function PrivateRepoState({ repo, addr }: { repo: V2RepoRef; addr: RepoAddress }): JSX.Element { +function PrivateRepoState({ repo, addr }: { repo: RepoRef; addr: RepoAddress }): JSX.Element { const { sdk, ready } = useSdk(repoContractIds(repo)) const facts = useAsync(() => readPublicRepoFacts(sdk!, repo), [ready, repo.repoId], { enabled: ready && sdk !== null }) return ( diff --git a/forge-web/components/repo/repo-rail.tsx b/forge-web/components/repo/repo-rail.tsx index 27360a4cc..6e8de6a2c 100644 --- a/forge-web/components/repo/repo-rail.tsx +++ b/forge-web/components/repo/repo-rail.tsx @@ -24,7 +24,7 @@ import { type RepoHome, type SelectedRef, } from '@/lib/view' -import { readMembershipsCached, repoContractIds, repoKey, type V2RepoRef } from '@/lib/repo' +import { readMembershipsCached, repoContractIds, repoKey, type RepoRef } from '@/lib/repo' import type { Membership } from '@/lib/rules/v2' import { useSdk } from '@/hooks/use-sdk' import { useAsync } from '@/hooks/use-async' @@ -121,7 +121,7 @@ function About({ home, addr }: { home: RepoHome; addr: RepoAddress }): JSX.Eleme ) } -function Members({ repo }: { repo: V2RepoRef }): JSX.Element { +function Members({ repo }: { repo: RepoRef }): JSX.Element { const { sdk, ready, network } = useSdk([repo.forge.core, repo.forge.collab]) const members = useAsync( () => readMembershipsCached(sdk!, repo, network), diff --git a/forge-web/components/repo/settings-content.tsx b/forge-web/components/repo/settings-content.tsx index 8a1dcc955..69c3ad53e 100644 --- a/forge-web/components/repo/settings-content.tsx +++ b/forge-web/components/repo/settings-content.tsx @@ -14,9 +14,9 @@ import { useState } from 'react' import { Fingerprint, HardDrive, ShieldPlus, UserCog } from 'lucide-react' import type { RepoHome } from '@/lib/view' -import type { V2RepoRef } from '@/lib/repo' +import type { RepoRef } from '@/lib/repo' import { grantMember, invalidateMembers, readMembershipsCached, revokeMember } from '@/lib/repo' -import type { Membership, Role as V2Role } from '@/lib/rules/v2' +import type { Membership, Role as MemberRole } from '@/lib/rules/v2' import { NetworkBadge } from '@/components/ui/network-badge' import { previewCreate, previewDelete } from '@/lib/sdk' import { decodeIdentifier } from '@/lib/auth' @@ -35,7 +35,7 @@ import { ErrorState, LoadingBlock } from '@/components/ui/states' import { RepoStoragePolicy } from '@/components/storage/repo-storage-policy' export function SettingsContent({ home }: { home: RepoHome }): JSX.Element { - return + return } /** @@ -43,7 +43,7 @@ export function SettingsContent({ home }: { home: RepoHome }): JSX.Element { * 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() @@ -55,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 { @@ -142,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) => (